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, FieldsShape, HasDataLayout, Reg, Size,
6    VariantIdx, Variants, WrappingRange,
7};
8use rustc_ast as ast;
9use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10use rustc_attr_ir::UnrollAttr;
11use rustc_attr_ir::lang_items::LangItem;
12use rustc_data_structures::packed::Pu128;
13use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
14use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
15use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
16use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement};
17use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
18use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
19use rustc_session::config::OptLevel;
20use rustc_span::{Span, Spanned, bug, span_bug};
21use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, IndirectMode, PassMode};
22use tracing::{debug, info};
23
24use super::operand::OperandRef;
25use super::operand::OperandValue::{self, Immediate, Pair, Ref, ZeroSized};
26use super::place::{PlaceRef, PlaceValue};
27use super::{CachedLlbb, FunctionCx, LocalRef};
28use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
29use crate::common::{self, IntPredicate};
30use crate::diagnostics::CompilerBuiltinsCannotCall;
31use crate::mir::IntrinsicResult;
32use crate::traits::*;
33use crate::{MemFlags, meth};
34
35// Indicates if we are in the middle of merging a BB's successor into it. This
36// can happen when BB jumps directly to its successor and the successor has no
37// other predecessors.
38#[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::marker::StructuralPartialEq for MergingSucc { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
39enum MergingSucc {
40    False,
41    True,
42}
43
44/// Indicates to the call terminator codegen whether a call
45/// is a normal call or an explicit tail call.
46#[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::marker::StructuralPartialEq for CallKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
47enum CallKind {
48    Normal,
49    Tail,
50}
51
52/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
53/// e.g., creating a basic block, calling a function, etc.
54struct TerminatorCodegenHelper<'tcx> {
55    bb: mir::BasicBlock,
56    terminator: &'tcx mir::Terminator<'tcx>,
57}
58
59impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
60    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
61    /// either already previously cached, or newly created, by `landing_pad_for`.
62    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
63        &self,
64        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
65    ) -> Option<&'b Bx::Funclet> {
66        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
67        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
68        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
69        // it has to be now. This may not seem necessary, as RPO should lead
70        // to all the unwind edges being visited (and so to `landing_pad_for`
71        // getting called for them), before building any of the blocks inside
72        // the funclet itself - however, if MIR contains edges that end up not
73        // being needed in the LLVM IR after monomorphization, the funclet may
74        // be unreachable, and we don't have yet a way to skip building it in
75        // such an eventuality (which may be a better solution than this).
76        if fx.funclets[funclet_bb].is_none() {
77            fx.landing_pad_for(funclet_bb);
78        }
79        Some(
80            fx.funclets[funclet_bb]
81                .as_ref()
82                .expect("landing_pad_for didn't also create funclets entry"),
83        )
84    }
85
86    /// Get a basic block (creating it if necessary), possibly with cleanup
87    /// stuff in it or next to it.
88    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
89        &self,
90        fx: &mut FunctionCx<'a, 'tcx, Bx>,
91        target: mir::BasicBlock,
92    ) -> Bx::BasicBlock {
93        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
94        let mut lltarget = fx.llbb(target);
95        if needs_landing_pad {
96            lltarget = fx.landing_pad_for(target);
97        }
98        if is_cleanupret {
99            // Cross-funclet jump - need a trampoline
100            if !base::wants_new_eh_instructions(&fx.cx.tcx().sess.target) {
    ::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)")
};assert!(base::wants_new_eh_instructions(&fx.cx.tcx().sess.target));
101            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:101",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(101u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
                                                    target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
102            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
103            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
104            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
105            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
106            trampoline_llbb
107        } else {
108            lltarget
109        }
110    }
111
112    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
113        &self,
114        fx: &mut FunctionCx<'a, 'tcx, Bx>,
115        target: mir::BasicBlock,
116    ) -> (bool, bool) {
117        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
118            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
119            let target_funclet = cleanup_kinds[target].funclet_bb(target);
120            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
121                (None, None) => (false, false),
122                (None, Some(_)) => (true, false),
123                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
124                (Some(_), None) => {
125                    let span = self.terminator.source_info.span;
126                    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("{0:?} - jump out of cleanup?", self.terminator),
    Location::caller());span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
127                }
128            };
129            (needs_landing_pad, is_cleanupret)
130        } else {
131            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
132            let is_cleanupret = false;
133            (needs_landing_pad, is_cleanupret)
134        }
135    }
136
137    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
138        &self,
139        fx: &mut FunctionCx<'a, 'tcx, Bx>,
140        bx: &mut Bx,
141        target: mir::BasicBlock,
142        mergeable_succ: bool,
143        loop_hint_attrs: &[UnrollAttr],
144    ) -> MergingSucc {
145        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
146        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
147            // We can merge the successor into this bb, so no need for a `br`.
148            MergingSucc::True
149        } else {
150            let mut lltarget = fx.llbb(target);
151            if needs_landing_pad {
152                lltarget = fx.landing_pad_for(target);
153            }
154            if is_cleanupret {
155                // micro-optimization: generate a `ret` rather than a jump
156                // to a trampoline.
157                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
158            } else {
159                bx.br_with_attrs(lltarget, loop_hint_attrs);
160            }
161            MergingSucc::False
162        }
163    }
164
165    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
166    /// return destination `destination` and the unwind action `unwind`.
167    /// The `return_slot` is [`ReturnSlot::Indirect`] for functions returning
168    /// via `PassMode::Indirect`, and points to a buffer where the return value
169    /// shall be stored.
170    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
171        &self,
172        fx: &mut FunctionCx<'a, 'tcx, Bx>,
173        bx: &mut Bx,
174        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
175        fn_ptr: Bx::Value,
176        return_slot: ReturnSlot<Bx::Value>,
177        llargs: &[Bx::Value],
178        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
179        mut unwind: mir::UnwindAction,
180        lifetime_ends_after_call: &[(Bx::Value, Size)],
181        instance: Option<Instance<'tcx>>,
182        kind: CallKind,
183        mergeable_succ: bool,
184    ) -> MergingSucc {
185        let tcx = bx.tcx();
186        if let Some(instance) = instance
187            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
188        {
189            if destination.is_some() {
190                let caller_def = fx.instance.def_id();
191                let e = CompilerBuiltinsCannotCall {
192                    span: tcx.def_span(caller_def),
193                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
194                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
195                };
196                tcx.dcx().emit_err(e);
197            } else {
198                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:198",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
                                                    instance.def_id()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!(
199                    "compiler_builtins call to diverging function {:?} replaced with abort",
200                    instance.def_id()
201                );
202                bx.abort_immediate();
203                bx.unreachable();
204                return MergingSucc::False;
205            }
206        }
207
208        // If there is a cleanup block and the function we're calling can unwind, then
209        // do an invoke, otherwise do a call.
210        let fn_ty = bx.fn_decl_backend_type(fn_abi);
211
212        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
213            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
214        } else {
215            None
216        };
217        let caller_attrs = caller_attrs.as_deref();
218
219        if !fn_abi.can_unwind {
220            unwind = mir::UnwindAction::Unreachable;
221        }
222
223        let unwind_block = match unwind {
224            mir::UnwindAction::Cleanup(cleanup) => {
225                if !fx.nop_landing_pads.contains(cleanup) {
226                    Some(self.llbb_with_cleanup(fx, cleanup))
227                } else {
228                    None
229                }
230            }
231            mir::UnwindAction::Continue => None,
232            mir::UnwindAction::Unreachable => None,
233            mir::UnwindAction::Terminate(reason) => {
234                if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(&fx.cx.tcx().sess.target) {
235                    // For wasm, we need to generate a nested `cleanuppad within %outer_pad`
236                    // to catch exceptions during cleanup and call `panic_in_cleanup`.
237                    Some(fx.terminate_block(reason, Some(self.bb)))
238                } else if fx.mir[self.bb].is_cleanup
239                    && base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)
240                {
241                    // MSVC SEH will abort automatically if an exception tries to
242                    // propagate out from cleanup.
243                    None
244                } else {
245                    Some(fx.terminate_block(reason, None))
246                }
247            }
248        };
249
250        if true {
    {
        match (&return_slot.is_indirect(), &fn_abi.ret.is_indirect()) {
            (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!("a return slot must be provided if and only if the return is `PassMode::Indirect`")));
                }
            }
        }
    };
};debug_assert_eq!(
251            return_slot.is_indirect(),
252            fn_abi.ret.is_indirect(),
253            "a return slot must be provided if and only if the return is `PassMode::Indirect`",
254        );
255
256        if kind == CallKind::Tail {
257            bx.tail_call(
258                fn_ty,
259                caller_attrs,
260                fn_abi,
261                fn_ptr,
262                return_slot,
263                llargs,
264                self.funclet(fx),
265                instance,
266            );
267            return MergingSucc::False;
268        }
269
270        if let Some(unwind_block) = unwind_block {
271            let ret_llbb = if let Some((_, target)) = destination {
272                self.llbb_with_cleanup(fx, target)
273            } else {
274                fx.unreachable_block()
275            };
276            let invokeret = bx.invoke(
277                fn_ty,
278                caller_attrs,
279                Some(fn_abi),
280                fn_ptr,
281                return_slot,
282                llargs,
283                ret_llbb,
284                unwind_block,
285                self.funclet(fx),
286                instance,
287            );
288            if fx.mir[self.bb].is_cleanup {
289                bx.apply_attrs_to_cleanup_callsite(invokeret);
290            }
291
292            if let Some((ret_dest, target)) = destination {
293                bx.switch_to_block(fx.llbb(target));
294                fx.set_debug_loc(bx, self.terminator.source_info);
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, invokeret);
299
300                // If the return value was retagged as it was stored,
301                // then we might be in a different basic block now.
302                // Update the cached block for `target` to point to this new
303                // block, where codegen will continue.
304                fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
305            }
306            MergingSucc::False
307        } else {
308            let llret = bx.call(
309                fn_ty,
310                caller_attrs,
311                Some(fn_abi),
312                fn_ptr,
313                return_slot,
314                llargs,
315                self.funclet(fx),
316                instance,
317            );
318            if fx.mir[self.bb].is_cleanup {
319                bx.apply_attrs_to_cleanup_callsite(llret);
320            }
321
322            if let Some((ret_dest, target)) = destination {
323                for &(tmp, size) in lifetime_ends_after_call {
324                    bx.lifetime_end(tmp, size);
325                }
326                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
327                self.funclet_br(fx, bx, target, mergeable_succ, &[])
328            } else {
329                bx.unreachable();
330                MergingSucc::False
331            }
332        }
333    }
334
335    /// Generates inline assembly with optional `destination` and `unwind`.
336    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
337        &self,
338        fx: &mut FunctionCx<'a, 'tcx, Bx>,
339        bx: &mut Bx,
340        template: &[InlineAsmTemplatePiece],
341        operands: &[InlineAsmOperandRef<'tcx, Bx>],
342        options: InlineAsmOptions,
343        line_spans: &[Span],
344        destination: Option<mir::BasicBlock>,
345        unwind: mir::UnwindAction,
346        instance: Instance<'_>,
347        mergeable_succ: bool,
348    ) -> MergingSucc {
349        let unwind_target = match unwind {
350            mir::UnwindAction::Cleanup(cleanup) => {
351                if !fx.nop_landing_pads.contains(cleanup) {
352                    Some(self.llbb_with_cleanup(fx, cleanup))
353                } else {
354                    None
355                }
356            }
357            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
358            mir::UnwindAction::Continue => None,
359            mir::UnwindAction::Unreachable => None,
360        };
361
362        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
363            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
364            let ret_llbb = if let Some(target) = destination {
365                self.llbb_with_cleanup(fx, target)
366            } else {
367                fx.unreachable_block()
368            };
369
370            bx.codegen_inline_asm(
371                template,
372                operands,
373                options,
374                line_spans,
375                instance,
376                Some(ret_llbb),
377                None,
378            );
379            MergingSucc::False
380        } else if let Some(cleanup) = unwind_target {
381            let ret_llbb = if let Some(target) = destination {
382                self.llbb_with_cleanup(fx, target)
383            } else {
384                fx.unreachable_block()
385            };
386
387            bx.codegen_inline_asm(
388                template,
389                operands,
390                options,
391                line_spans,
392                instance,
393                Some(ret_llbb),
394                Some((cleanup, self.funclet(fx))),
395            );
396            MergingSucc::False
397        } else {
398            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
399
400            if let Some(target) = destination {
401                self.funclet_br(fx, bx, target, mergeable_succ, &[])
402            } else {
403                bx.unreachable();
404                MergingSucc::False
405            }
406        }
407    }
408}
409
410/// Codegen implementations for some terminator variants.
411impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
412    /// Generates code for a `Resume` terminator.
413    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
414        if let Some(funclet) = helper.funclet(self) {
415            bx.cleanup_ret(funclet, None);
416        } else {
417            let slot = self.get_personality_slot(bx);
418            let exn0 = slot.project_field(bx, 0);
419            let exn0 = bx.load_operand(exn0).immediate();
420            let exn1 = slot.project_field(bx, 1);
421            let exn1 = bx.load_operand(exn1).immediate();
422            slot.storage_dead(bx);
423
424            bx.resume(exn0, exn1);
425        }
426    }
427
428    fn codegen_switchint_terminator(
429        &mut self,
430        helper: TerminatorCodegenHelper<'tcx>,
431        bx: &mut Bx,
432        discr: &mir::Operand<'tcx>,
433        targets: &SwitchTargets,
434    ) {
435        let discr = self.codegen_operand(bx, discr);
436        let discr_value = discr.immediate();
437        let switch_ty = discr.layout.ty;
438        // If our discriminant is a constant we can branch directly
439        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
440            let target = targets.target_for_value(const_discr);
441            bx.br(helper.llbb_with_cleanup(self, target));
442            return;
443        };
444
445        let mut target_iter = targets.iter();
446        if target_iter.len() == 1 {
447            // If there are two targets (one conditional, one fallback), emit `br` instead of
448            // `switch`.
449            let (test_value, target) = target_iter.next().unwrap();
450            let otherwise = targets.otherwise();
451            let lltarget = helper.llbb_with_cleanup(self, target);
452            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
453            let target_cold = self.cold_blocks[target];
454            let otherwise_cold = self.cold_blocks[otherwise];
455            // If `target_cold == otherwise_cold`, the branches have the same weight
456            // so there is no expectation. If they differ, the `target` branch is expected
457            // when the `otherwise` branch is cold.
458            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
459            if switch_ty == bx.tcx().types.bool {
460                // Don't generate trivial icmps when switching on bool.
461                match test_value {
462                    0 => {
463                        let expect = expect.map(|e| !e);
464                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
465                    }
466                    1 => {
467                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
468                    }
469                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
470                }
471            } else {
472                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
473                let llval = bx.const_uint_big(switch_llty, test_value);
474                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
475                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
476            }
477        } else if target_iter.len() == 2
478            && self.mir[targets.otherwise()].is_empty_unreachable()
479            && targets.all_values().contains(&Pu128(0))
480            && targets.all_values().contains(&Pu128(1))
481        {
482            // This is the really common case for `bool`, `Option`, etc.
483            // By using `trunc nuw` we communicate that other values are
484            // impossible without needing `switch` or `assume`s.
485            let true_bb = targets.target_for_value(1);
486            let false_bb = targets.target_for_value(0);
487            let true_ll = helper.llbb_with_cleanup(self, true_bb);
488            let false_ll = helper.llbb_with_cleanup(self, false_bb);
489
490            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
491                None
492            } else {
493                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
494                    // Same coldness, no expectation
495                    (true, true) | (false, false) => None,
496                    // Different coldness, expect the non-cold one
497                    (true, false) => Some(false),
498                    (false, true) => Some(true),
499                }
500            };
501
502            let bool_ty = bx.tcx().types.bool;
503            let cond = if switch_ty == bool_ty {
504                discr_value
505            } else {
506                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
507                bx.unchecked_utrunc(discr_value, bool_llty)
508            };
509            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
510        } else if self.cx.sess().opts.optimize == OptLevel::No
511            && target_iter.len() == 2
512            && self.mir[targets.otherwise()].is_empty_unreachable()
513        {
514            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
515            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
516            // BB, which will usually (but not always) be dead code.
517            //
518            // Why only in unoptimized builds?
519            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
520            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
521            //   significant compile time speedups for unoptimized builds.
522            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
523            //   worse generated code because LLVM can no longer tell that the value being switched
524            //   on can only have two values, e.g. 0 and 1.
525            //
526            let (test_value1, target1) = target_iter.next().unwrap();
527            let (_test_value2, target2) = target_iter.next().unwrap();
528            let ll1 = helper.llbb_with_cleanup(self, target1);
529            let ll2 = helper.llbb_with_cleanup(self, target2);
530            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
531            let llval = bx.const_uint_big(switch_llty, test_value1);
532            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
533            bx.cond_br(cmp, ll1, ll2);
534        } else {
535            let otherwise = targets.otherwise();
536            let otherwise_cold = self.cold_blocks[otherwise];
537            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
538            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
539            let none_cold = cold_count == 0;
540            let all_cold = cold_count == targets.iter().len();
541            if (none_cold && (!otherwise_cold || otherwise_unreachable))
542                || (all_cold && (otherwise_cold || otherwise_unreachable))
543            {
544                // All targets have the same weight,
545                // or `otherwise` is unreachable and it's the only target with a different weight.
546                bx.switch(
547                    discr_value,
548                    helper.llbb_with_cleanup(self, targets.otherwise()),
549                    target_iter
550                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
551                );
552            } else {
553                // Targets have different weights
554                bx.switch_with_weights(
555                    discr_value,
556                    helper.llbb_with_cleanup(self, targets.otherwise()),
557                    otherwise_cold,
558                    target_iter.map(|(value, target)| {
559                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
560                    }),
561                );
562            }
563        }
564    }
565
566    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
567        // Explicitly end the lifetime of the VaList if this function is c-variadic. We explicitly
568        // start the lifetime when desugaring `...`. Ending the lifetime meaningfully improves
569        // codegen.
570        if self.fn_abi.c_variadic {
571            // The `VaList` "spoofed" argument is just after all the real arguments.
572            let va_list_arg_idx = self.fn_abi.args.len();
573            match self.locals[mir::Local::arg(va_list_arg_idx)] {
574                LocalRef::Place(va_list) => {
575                    // NOTE: we don't actually call LLVM's va_end here. We know it's a no-op for
576                    // all current targets and hence don't bother
577                    // (as permitted by https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic).
578
579                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
580                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
581                }
582                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("C-variadic function must have a `VaList` place"),
    Location::caller())bug!("C-variadic function must have a `VaList` place"),
583            }
584        }
585        if self.fn_abi.ret.layout.is_uninhabited() {
586            // Functions with uninhabited return values are marked `noreturn`,
587            // so we should make sure that we never actually do.
588            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
589            // if that turns out to be helpful.
590            bx.abort_immediate();
591            // `abort` does not terminate the block, so we still need to generate
592            // an `unreachable` terminator after it.
593            bx.unreachable();
594            return;
595        }
596        let llval = match &self.fn_abi.ret.mode {
597            PassMode::Ignore | PassMode::Indirect { .. } => {
598                bx.ret_void();
599                return;
600            }
601
602            PassMode::Direct(_) | PassMode::Pair(..) => {
603                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
604                if let Ref(place_val) = op.val {
605                    bx.load_from_place(bx.backend_type(op.layout), place_val)
606                } else {
607                    op.immediate_or_packed_pair(bx)
608                }
609            }
610
611            PassMode::Cast { cast: cast_ty, pad_i32_count: _ } => {
612                let op = match self.locals[mir::RETURN_PLACE] {
613                    LocalRef::Operand(op) => op,
614                    LocalRef::PendingOperand => ::rustc_span::macros::bug_impl(None, format_args!("use of return before def"),
    Location::caller())bug!("use of return before def"),
615                    LocalRef::Place(cg_place) => OperandRef {
616                        val: Ref(cg_place.val),
617                        layout: cg_place.layout,
618                        move_annotation: None,
619                    },
620                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
621                };
622                let llslot = match op.val {
623                    Immediate(_) | Pair(..) => {
624                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
625                        op.val.store(bx, scratch);
626                        scratch.val.llval
627                    }
628                    Ref(place_val) => {
629                        {
    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!(
630                            place_val.align, op.layout.align.abi,
631                            "return place is unaligned!"
632                        );
633                        place_val.llval
634                    }
635                    ZeroSized => ::rustc_span::macros::bug_impl(None,
    format_args!("ZST return value shouldn\'t be in PassMode::Cast"),
    Location::caller())bug!("ZST return value shouldn't be in PassMode::Cast"),
636                };
637
638                if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
639                    // The return value of an `extern "cmse-nonsecure-entry"` function crosses the
640                    // secure boundary. Clear any padding bytes so information does not leak.
641                    let ret_layout = self.fn_abi.ret.layout;
642                    self.clear_padding_cmse(bx, llslot, ret_layout.size, ret_layout);
643                }
644
645                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
646            }
647            PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
    format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
648        };
649        bx.ret(llval);
650    }
651
652    {}
#[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("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                    ::tracing_core::__macro_support::Option::Some(652u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_info")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_info");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("unwind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("unwind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("mergeable_succ")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("mergeable_succ");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&mergeable_succ as
                                                            &dyn ::tracing::field::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 /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:701",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(701u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
                                                                            ty) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:702",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(702u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
                                                                            drop_fn) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:703",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(703u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
                                                                            args) as &dyn ::tracing::field::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,
                                bx.sess().pointer_authentication_functions()),
                            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, ReturnSlot::Direct,
                args, Some((ReturnDest::Nothing, target)), unwind, &[],
                Some(drop_instance), CallKind::Normal,
                !maybe_null && mergeable_succ)
        }
    }
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
653    fn codegen_drop_terminator(
654        &mut self,
655        helper: TerminatorCodegenHelper<'tcx>,
656        bx: &mut Bx,
657        source_info: &mir::SourceInfo,
658        location: mir::Place<'tcx>,
659        target: mir::BasicBlock,
660        unwind: mir::UnwindAction,
661        mergeable_succ: bool,
662    ) -> MergingSucc {
663        let ty = location.ty(self.mir, bx.tcx()).ty;
664        let ty = self.monomorphize(ty);
665        let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
666
667        if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
668            // we don't actually need to drop anything.
669            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
670        }
671
672        let place = self.codegen_place(bx, location.as_ref());
673        let (args1, args2);
674        let mut args = if let Some(llextra) = place.val.llextra {
675            args2 = [place.val.llval, llextra];
676            &args2[..]
677        } else {
678            args1 = [place.val.llval];
679            &args1[..]
680        };
681        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
682            // FIXME(eddyb) perhaps move some of this logic into
683            // `Instance::resolve_drop_glue`?
684            ty::Dynamic(_, _) => {
685                // IN THIS ARM, WE HAVE:
686                // ty = *mut (dyn Trait)
687                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
688                //                       args[0]    args[1]
689                //
690                // args = ( Data, Vtable )
691                //                  |
692                //                  v
693                //                /-------\
694                //                | ...   |
695                //                \-------/
696                //
697                let virtual_drop = Instance {
698                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
699                    args: drop_fn.args,
700                };
701                debug!("ty = {:?}", ty);
702                debug!("drop_fn = {:?}", drop_fn);
703                debug!("args = {:?}", args);
704                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
705                let vtable = args[1];
706                // Truncate vtable off of args list
707                args = &args[..1];
708                (
709                    true,
710                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
711                        .get_optional_fn(bx, vtable, ty, fn_abi),
712                    fn_abi,
713                    virtual_drop,
714                )
715            }
716            _ => (
717                false,
718                bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_functions()),
719                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
720                drop_fn,
721            ),
722        };
723
724        // We generate a null check for the drop_fn. This saves a bunch of relocations being
725        // generated for no-op drops.
726        if maybe_null {
727            let is_not_null = bx.append_sibling_block("is_not_null");
728            let llty = bx.fn_ptr_backend_type(fn_abi);
729            let null = bx.const_null(llty);
730            let non_null =
731                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
732            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
733            bx.switch_to_block(is_not_null);
734            self.set_debug_loc(bx, *source_info);
735        }
736
737        helper.do_call(
738            self,
739            bx,
740            fn_abi,
741            drop_fn,
742            ReturnSlot::Direct,
743            args,
744            Some((ReturnDest::Nothing, target)),
745            unwind,
746            &[],
747            Some(drop_instance),
748            CallKind::Normal,
749            !maybe_null && mergeable_succ,
750        )
751    }
752
753    fn codegen_assert_terminator(
754        &mut self,
755        helper: TerminatorCodegenHelper<'tcx>,
756        bx: &mut Bx,
757        terminator: &mir::Terminator<'tcx>,
758        cond: &mir::Operand<'tcx>,
759        expected: bool,
760        msg: &mir::AssertMessage<'tcx>,
761        target: mir::BasicBlock,
762        unwind: mir::UnwindAction,
763        mergeable_succ: bool,
764    ) -> MergingSucc {
765        let span = terminator.source_info.span;
766        let cond = self.codegen_operand(bx, cond).immediate();
767        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
768
769        // This case can currently arise only from functions marked
770        // with #[rustc_inherit_overflow_checks] and inlined from
771        // another crate (mostly core::num generic/#[inline] fns),
772        // while the current crate doesn't use overflow checks.
773        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
774            const_cond = Some(expected);
775        }
776
777        // Don't codegen the panic block if success if known.
778        if const_cond == Some(expected) {
779            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
780        }
781
782        // Because we're branching to a panic block (either a `#[cold]` one
783        // or an inlined abort), there's no need to `expect` it.
784
785        // Create the failure block and the conditional branch to it.
786        let lltarget = helper.llbb_with_cleanup(self, target);
787        let panic_block = bx.append_sibling_block("panic");
788        if expected {
789            bx.cond_br(cond, lltarget, panic_block);
790        } else {
791            bx.cond_br(cond, panic_block, lltarget);
792        }
793
794        // After this point, bx is the block for the call to panic.
795        bx.switch_to_block(panic_block);
796        self.set_debug_loc(bx, terminator.source_info);
797
798        // Get the location information.
799        let location = self.get_caller_location(bx, terminator.source_info).immediate();
800
801        // Put together the arguments to the panic entry point.
802        let (lang_item, args) = match msg {
803            AssertKind::BoundsCheck { len, index } => {
804                let len = self.codegen_operand(bx, len).immediate();
805                let index = self.codegen_operand(bx, index).immediate();
806                // It's `fn panic_bounds_check(index: usize, len: usize)`,
807                // and `#[track_caller]` adds an implicit third argument.
808                (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])
809            }
810            AssertKind::MisalignedPointerDereference { required, found } => {
811                let required = self.codegen_operand(bx, required).immediate();
812                let found = self.codegen_operand(bx, found).immediate();
813                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
814                // and `#[track_caller]` adds an implicit third argument.
815                (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])
816            }
817            AssertKind::NullPointerDereference => {
818                // It's `fn panic_null_pointer_dereference()`,
819                // `#[track_caller]` adds an implicit argument.
820                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
821            }
822            AssertKind::NullReferenceConstructed => {
823                // It's `fn panic_null_reference_constructed()`,
824                // `#[track_caller]` adds an implicit argument.
825                (LangItem::PanicNullReferenceConstructed, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
826            }
827            AssertKind::InvalidEnumConstruction(source) => {
828                let source = self.codegen_operand(bx, source).immediate();
829                // It's `fn panic_invalid_enum_construction(source: u128)`,
830                // `#[track_caller]` adds an implicit argument.
831                (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])
832            }
833            _ => {
834                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
835                (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])
836            }
837        };
838
839        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
840
841        // Codegen the actual panic invoke/call.
842        let merging_succ = helper.do_call(
843            self,
844            bx,
845            fn_abi,
846            llfn,
847            ReturnSlot::Direct,
848            &args,
849            None,
850            unwind,
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        MergingSucc::False
858    }
859
860    fn codegen_terminate_terminator(
861        &mut self,
862        helper: TerminatorCodegenHelper<'tcx>,
863        bx: &mut Bx,
864        terminator: &mir::Terminator<'tcx>,
865        reason: UnwindTerminateReason,
866    ) {
867        let span = terminator.source_info.span;
868        self.set_debug_loc(bx, terminator.source_info);
869
870        // Obtain the panic entry point.
871        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
872
873        // Codegen the actual panic invoke/call.
874        let merging_succ = helper.do_call(
875            self,
876            bx,
877            fn_abi,
878            llfn,
879            ReturnSlot::Direct,
880            &[],
881            None,
882            mir::UnwindAction::Unreachable,
883            &[],
884            Some(instance),
885            CallKind::Normal,
886            false,
887        );
888        {
    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);
889    }
890
891    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
892    fn codegen_panic_intrinsic(
893        &mut self,
894        helper: &TerminatorCodegenHelper<'tcx>,
895        bx: &mut Bx,
896        intrinsic: ty::IntrinsicDef,
897        instance: Instance<'tcx>,
898        source_info: mir::SourceInfo,
899        target: Option<mir::BasicBlock>,
900        unwind: mir::UnwindAction,
901        mergeable_succ: bool,
902    ) -> Option<MergingSucc> {
903        // Emit a panic or a no-op for `assert_*` intrinsics.
904        // These are intrinsics that compile to panics so that we can get a message
905        // which mentions the offending type, even from a const context.
906        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
907            return None;
908        };
909
910        let ty = instance.args.type_at(0);
911
912        let is_valid = bx
913            .tcx()
914            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
915            .expect("expect to have layout during codegen");
916
917        if is_valid {
918            // a NOP
919            let target = target.unwrap();
920            return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
921        }
922
923        let layout = bx.layout_of(ty);
924
925        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!({
926            with_no_trimmed_paths!({
927                if layout.is_uninhabited() {
928                    // Use this error even for the other intrinsics as it is more precise.
929                    format!("attempted to instantiate uninhabited type `{ty}`")
930                } else if requirement == ValidityRequirement::Zero {
931                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
932                } else {
933                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
934                }
935            })
936        });
937        let msg = bx.const_str(&msg_str);
938
939        // Obtain the panic entry point.
940        let (fn_abi, llfn, instance) =
941            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
942
943        // Codegen the actual panic invoke/call.
944        Some(helper.do_call(
945            self,
946            bx,
947            fn_abi,
948            llfn,
949            ReturnSlot::Direct,
950            &[msg.0, msg.1],
951            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
952            unwind,
953            &[],
954            Some(instance),
955            CallKind::Normal,
956            mergeable_succ,
957        ))
958    }
959
960    fn codegen_call_terminator(
961        &mut self,
962        helper: TerminatorCodegenHelper<'tcx>,
963        bx: &mut Bx,
964        terminator: &mir::Terminator<'tcx>,
965        func: &mir::Operand<'tcx>,
966        args: &[Spanned<mir::Operand<'tcx>>],
967        destination: mir::Place<'tcx>,
968        target: Option<mir::BasicBlock>,
969        unwind: mir::UnwindAction,
970        fn_span: Span,
971        kind: CallKind,
972        mergeable_succ: bool,
973    ) -> MergingSucc {
974        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
975
976        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
977        let callee = self.codegen_operand(bx, func);
978
979        let (instance, mut llfn) = match *callee.layout.ty.kind() {
980            ty::FnDef(def_id, generic_args) => {
981                let instance = ty::Instance::expect_resolve(
982                    bx.tcx(),
983                    bx.typing_env(),
984                    def_id,
985                    generic_args.no_bound_vars().unwrap(),
986                    fn_span,
987                );
988
989                match instance.def {
990                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
991                    // it is `func returning noop future`
992                    ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
993                        // Empty drop glue; a no-op.
994                        let target = target.unwrap();
995                        return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
996                    }
997                    ty::InstanceKind::Intrinsic(def_id) => {
998                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
999                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
1000                            &helper,
1001                            bx,
1002                            intrinsic,
1003                            instance,
1004                            source_info,
1005                            target,
1006                            unwind,
1007                            mergeable_succ,
1008                        ) {
1009                            return merging_succ;
1010                        }
1011
1012                        let result_layout =
1013                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1014
1015                        let (result_place, store_in_local) =
1016                            if let Some(local) = destination.as_local() {
1017                                match self.locals[local] {
1018                                    LocalRef::Place(dest) => (Some(dest.val), None),
1019                                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1020                                    LocalRef::PendingOperand => (None, Some(local)),
1021                                    LocalRef::Operand(_) => {
1022                                        if result_layout.is_zst() {
1023                                            let place = PlaceRef::new_sized(
1024                                                bx.const_undef(bx.type_ptr()),
1025                                                result_layout,
1026                                            );
1027                                            (Some(place.val), None)
1028                                        } else {
1029                                            ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
1030                                        }
1031                                    }
1032                                }
1033                            } else {
1034                                (Some(self.codegen_place(bx, destination.as_ref()).val), None)
1035                            };
1036
1037                        if let Some(place) = result_place
1038                            && place.align < result_layout.align.abi
1039                        {
1040                            // Currently, MIR code generation does not create calls
1041                            // that store directly to fields of packed structs (in
1042                            // fact, the calls it creates write only to temps).
1043                            //
1044                            // If someone changes that, please update this code path
1045                            // to create a temporary.
1046                            ::rustc_span::macros::bug_impl(Some(self.mir.span),
    format_args!("can\'t directly store to unaligned value"),
    Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
1047                        }
1048
1049                        let args: Vec<_> =
1050                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1051
1052                        let intrinsic_result = self.codegen_intrinsic_call(
1053                            bx,
1054                            instance,
1055                            &args,
1056                            result_layout,
1057                            result_place,
1058                            source_info,
1059                        );
1060
1061                        if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1062                            match (result_place, store_in_local) {
1063                                (None, Some(local)) => {
1064                                    let op = OperandRef {
1065                                        val: op_val,
1066                                        layout: result_layout,
1067                                        move_annotation: None,
1068                                    };
1069                                    self.overwrite_local(local, LocalRef::Operand(op));
1070                                    self.debug_introduce_local(bx, local);
1071                                }
1072                                (Some(place_val), None) => {
1073                                    let dest = PlaceRef { val: place_val, layout: result_layout };
1074                                    op_val.store(bx, dest);
1075                                }
1076                                _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1077                            }
1078                        }
1079
1080                        match intrinsic_result {
1081                            IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1082                                return if let Some(target) = target {
1083                                    helper.funclet_br(self, bx, target, mergeable_succ, &[])
1084                                } else {
1085                                    bx.unreachable();
1086                                    MergingSucc::False
1087                                };
1088                            }
1089                            IntrinsicResult::Err(_) => {
1090                                // Even though we're definitely going to error, we need it initialize
1091                                // the local or `maybe_codegen_consume_direct` might ICE later
1092                                // when it goes to use the result from this intrinsic.
1093                                if let Some(local) = store_in_local {
1094                                    let op = OperandRef {
1095                                        val: OperandValue::poison(bx, result_layout),
1096                                        layout: result_layout,
1097                                        move_annotation: None,
1098                                    };
1099                                    self.overwrite_local(local, LocalRef::Operand(op));
1100                                }
1101                                // Also we need to terminate the block to avoid an LLVM assertion,
1102                                // even though we're not going to actually use the IR.
1103                                bx.abort_immediate();
1104                                return MergingSucc::False;
1105                            }
1106                            IntrinsicResult::Fallback(instance) => {
1107                                if intrinsic.must_be_overridden {
1108                                    ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
        intrinsic.name), Location::caller());span_bug!(
1109                                        fn_span,
1110                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1111                                        intrinsic.name,
1112                                    );
1113                                }
1114                                (Some(instance), None)
1115                            }
1116                        }
1117                    }
1118
1119                    _ if kind == CallKind::Tail
1120                        && instance.def.requires_caller_location(bx.tcx()) =>
1121                    {
1122                        if let Some(hir_id) =
1123                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1124                        {
1125                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1126                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1127                            }));
1128                        }
1129
1130                        let instance = ty::Instance::resolve_for_fn_ptr(
1131                            bx.tcx(),
1132                            bx.typing_env(),
1133                            def_id,
1134                            generic_args.no_bound_vars().unwrap(),
1135                        )
1136                        .unwrap();
1137
1138                        (
1139                            None,
1140                            Some(bx.get_fn_addr(
1141                                instance,
1142                                bx.sess().pointer_authentication_functions(),
1143                            )),
1144                        )
1145                    }
1146                    _ => (Some(instance), None),
1147                }
1148            }
1149            ty::FnPtr(..) => (None, Some(callee.immediate())),
1150            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0} is not callable", callee.layout.ty), Location::caller())bug!("{} is not callable", callee.layout.ty),
1151        };
1152
1153        if let Some(instance) = instance
1154            && let ty::InstanceKind::LlvmIntrinsic(_) = instance.def
1155            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1156            // This is the only LLVM intrinsic we use that unwinds
1157            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1158            // this intrinsic with something else
1159            && name.as_str() != "llvm.wasm.throw"
1160        {
1161            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1162            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());
1163
1164            let result_layout =
1165                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1166
1167            let return_dest = if result_layout.is_zst() {
1168                ReturnDest::Nothing
1169            } else if let Some(index) = destination.as_local() {
1170                match self.locals[index] {
1171                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1172                    LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1173                    LocalRef::PendingOperand => {
1174                        // Handle temporary places, specifically `Operand` ones, as
1175                        // they don't have `alloca`s.
1176                        ReturnDest::DirectOperand(index)
1177                    }
1178                    LocalRef::Operand(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller())bug!("place local already assigned to"),
1179                }
1180            } else {
1181                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1182            };
1183
1184            let args =
1185                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1186
1187            self.set_debug_loc(bx, source_info);
1188
1189            let llret =
1190                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1191
1192            if let Some(target) = target {
1193                self.store_return(
1194                    bx,
1195                    return_dest,
1196                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1197                    llret,
1198                );
1199                return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1200            } else {
1201                bx.unreachable();
1202                return MergingSucc::False;
1203            }
1204        }
1205
1206        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1207        // available - right now `sig` is only needed for getting the `abi`
1208        // and figuring out how many extra args were passed to a C-variadic `fn`.
1209        let sig = callee.layout.ty.fn_sig(bx.tcx());
1210
1211        let extra_args = &args[sig.inputs().skip_binder().len()..];
1212        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1213            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1214            self.monomorphize(op_ty)
1215        }));
1216
1217        let fn_abi = match instance {
1218            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1219            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1220        };
1221
1222        // The arguments we'll be passing. Plus one to account for outptr, if used.
1223        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1224
1225        let mut llargs = Vec::with_capacity(arg_count);
1226
1227        // We still need to call `make_return_dest` even if there's no `target`, since
1228        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1229        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1230        let (destination, return_slot) = match kind {
1231            CallKind::Normal => {
1232                let (return_dest, return_slot) =
1233                    self.make_return_dest(bx, destination, &fn_abi.ret);
1234                (target.map(|target| (return_dest, target)), return_slot)
1235            }
1236            CallKind::Tail => {
1237                let return_slot = if fn_abi.ret.is_indirect() {
1238                    match self.make_return_dest(bx, destination, &fn_abi.ret) {
1239                        (ReturnDest::Nothing, return_slot) => return_slot,
1240                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("tail calls to functions with indirect returns cannot store into a destination"),
    Location::caller())bug!(
1241                            "tail calls to functions with indirect returns cannot store into a destination"
1242                        ),
1243                    }
1244                } else {
1245                    ReturnSlot::Direct
1246                };
1247                (None, return_slot)
1248            }
1249        };
1250
1251        // Split the rust-call tupled arguments off.
1252        // FIXME(splat): un-tuple splatted arguments in codegen, for performance
1253        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1254            && let Some((tup, args)) = args.split_last()
1255        {
1256            (args, Some(tup))
1257        } else {
1258            (args, None)
1259        };
1260
1261        // Special logic for tail calls with `PassMode::Indirect { mode: IndirectMode::Pointer, .. }` arguments.
1262        //
1263        // Normally an indirect argument that is allocated in the caller's stack frame
1264        // would be passed as a pointer into the callee's stack frame.
1265        // For tail calls, that would be unsound, because the caller's
1266        // stack frame is overwritten by the callee's stack frame.
1267        //
1268        // Therefore we store the argument for the callee in the corresponding caller's slot.
1269        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1270        // the corresponding slot has the correct type.
1271        //
1272        // To handle cases like the one below, the tail call arguments must first be copied to a
1273        // temporary, and only then copied to the caller's argument slots.
1274        //
1275        // ```
1276        // // A struct big enough that it is not passed via registers.
1277        // pub struct Big([u64; 4]);
1278        //
1279        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1280        //     become swapper_helper(b, a);
1281        // }
1282        // ```
1283        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1284        if kind == CallKind::Tail {
1285            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1286            // Copy the arguments that use `PassMode::Indirect { mode: IndirectMode::Pointer , ..}`
1287            // to temporary stack allocations. See the comment above.
1288            for (i, arg) in first_args.iter().enumerate() {
1289                if #[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::IndirectUnsized { .. } => true,
    _ => false,
}matches!(fn_abi.args[i].mode, PassMode::IndirectUnsized { .. }) {
1290                    ::rustc_span::macros::bug_impl(None,
    format_args!("extern \"tail\" arguments must not be unsized"),
    Location::caller());bug!("extern \"tail\" arguments must not be unsized");
1291                }
1292
1293                if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::Indirect { mode: IndirectMode::Pointer, .. } => true,
    _ => false,
}matches!(
1294                    fn_abi.args[i].mode,
1295                    PassMode::Indirect { mode: IndirectMode::Pointer, .. }
1296                ) {
1297                    continue;
1298                }
1299
1300                let op = self.codegen_operand(bx, &arg.node);
1301                let tmp = PlaceRef::alloca(bx, op.layout);
1302                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1303                op.store_with_annotation(bx, tmp);
1304
1305                tail_call_temporaries[i] = Some(tmp);
1306            }
1307        }
1308
1309        // When generating arguments we sometimes introduce temporary allocations with lifetime
1310        // that extend for the duration of a call. Keep track of those allocations and their sizes
1311        // to generate `lifetime_end` when the call returns.
1312        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1313        'make_args: for (i, arg) in first_args.iter().enumerate() {
1314            let mut op = self.codegen_operand(bx, &arg.node);
1315
1316            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1317                match op.val {
1318                    Pair(data_ptr, meta) => {
1319                        // In the case of Rc<Self>, we need to explicitly pass a
1320                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1321                        // that is understood elsewhere in the compiler as a method on
1322                        // `dyn Trait`.
1323                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1324                        // we get a value of a built-in pointer type.
1325                        //
1326                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1327                        // `Pin`.
1328                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1329                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1330                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1331                            );
1332                            op = op.extract_field(self, bx, idx.as_usize());
1333                        }
1334
1335                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1336                        // data pointer and vtable. Look up the method in the vtable, and pass
1337                        // the data pointer as the first argument.
1338                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1339                            bx,
1340                            meta,
1341                            op.layout.ty,
1342                            fn_abi,
1343                        ));
1344                        llargs.push(data_ptr);
1345                        continue 'make_args;
1346                    }
1347                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1348                        // by-value dynamic dispatch
1349                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1350                            bx,
1351                            meta,
1352                            op.layout.ty,
1353                            fn_abi,
1354                        ));
1355                        llargs.push(data_ptr);
1356                        continue;
1357                    }
1358                    _ => {
1359                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("can\'t codegen a virtual call on {0:#?}", op),
    Location::caller());span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1360                    }
1361                }
1362            }
1363
1364            let by_move = if let PassMode::Indirect { mode: IndirectMode::Pointer, .. } =
1365                fn_abi.args[i].mode
1366                && kind == CallKind::Tail
1367            {
1368                // Special logic for tail calls with `PassMode::Indirect { mode: IndirectMode::Pointer, .. }` arguments.
1369                //
1370                // Normally an indirect argument that is allocated in the caller's stack frame
1371                // would be passed as a pointer into the callee's stack frame.
1372                // For tail calls, that would be unsound, because the caller's
1373                // stack frame is overwritten by the callee's stack frame.
1374                //
1375                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1376                // temporaries, then copy back to the caller's argument slots.
1377                // Finally, we pass the caller's argument slots as arguments.
1378                //
1379                // To do that, the argument must be MUST-by-move value.
1380                let Some(tmp) = tail_call_temporaries[i].take() else {
1381                    ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("missing temporary for indirect tail call argument #{0}", i),
    Location::caller())span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1382                };
1383
1384                let local = self.mir.args_iter().nth(i).unwrap();
1385
1386                match &self.locals[local] {
1387                    LocalRef::Place(arg) => {
1388                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1389                        op.val = Ref(arg.val);
1390                    }
1391                    LocalRef::Operand(arg) => {
1392                        let Ref(place_value) = arg.val else {
1393                            ::rustc_span::macros::bug_impl(None,
    format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
        arg.val), Location::caller());bug!(
1394                                "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1395                                arg.val
1396                            );
1397                        };
1398                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1399                        op.val = arg.val;
1400                    }
1401                    LocalRef::UnsizedPlace(_) => {
1402                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("unsized types are not supported"), Location::caller())span_bug!(fn_span, "unsized types are not supported")
1403                    }
1404                    LocalRef::PendingOperand => {
1405                        ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("argument local should not be pending"), Location::caller())span_bug!(fn_span, "argument local should not be pending")
1406                    }
1407                };
1408
1409                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1410                true
1411            } else {
1412                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1413            };
1414
1415            self.codegen_argument(
1416                bx,
1417                fn_abi.conv,
1418                op,
1419                by_move,
1420                &mut llargs,
1421                &fn_abi.args[i],
1422                &mut lifetime_ends_after_call,
1423            );
1424        }
1425        let num_untupled = untuple.map(|tup| {
1426            self.codegen_arguments_untupled(
1427                bx,
1428                fn_abi.conv,
1429                &tup.node,
1430                &mut llargs,
1431                &fn_abi.args[first_args.len()..],
1432                &mut lifetime_ends_after_call,
1433            )
1434        });
1435
1436        let needs_location =
1437            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1438        if needs_location {
1439            let mir_args = if let Some(num_untupled) = num_untupled {
1440                first_args.len() + num_untupled
1441            } else {
1442                args.len()
1443            };
1444            {
    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!(
1445                fn_abi.args.len(),
1446                mir_args + 1,
1447                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1448            );
1449            let location = self.get_caller_location(bx, source_info);
1450            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:1450",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1450u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
                                                    terminator, location, fn_span) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1451                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1452                terminator, location, fn_span
1453            );
1454
1455            let last_arg = fn_abi.args.last().unwrap();
1456            self.codegen_argument(
1457                bx,
1458                fn_abi.conv,
1459                location,
1460                /* by_move */ false,
1461                &mut llargs,
1462                last_arg,
1463                &mut lifetime_ends_after_call,
1464            );
1465        }
1466
1467        let fn_ptr = match (instance, llfn) {
1468            (Some(instance), None) => {
1469                bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions())
1470            }
1471            (_, Some(llfn)) => llfn,
1472            _ => ::rustc_span::macros::bug_impl(Some(fn_span),
    format_args!("no instance or llfn for call"), Location::caller())span_bug!(fn_span, "no instance or llfn for call"),
1473        };
1474        self.set_debug_loc(bx, source_info);
1475        helper.do_call(
1476            self,
1477            bx,
1478            fn_abi,
1479            fn_ptr,
1480            return_slot,
1481            &llargs,
1482            destination,
1483            unwind,
1484            &lifetime_ends_after_call,
1485            instance,
1486            kind,
1487            mergeable_succ,
1488        )
1489    }
1490
1491    fn codegen_asm_terminator(
1492        &mut self,
1493        helper: TerminatorCodegenHelper<'tcx>,
1494        bx: &mut Bx,
1495        asm_macro: InlineAsmMacro,
1496        terminator: &mir::Terminator<'tcx>,
1497        template: &[ast::InlineAsmTemplatePiece],
1498        operands: &[mir::InlineAsmOperand<'tcx>],
1499        options: ast::InlineAsmOptions,
1500        line_spans: &[Span],
1501        targets: &[mir::BasicBlock],
1502        unwind: mir::UnwindAction,
1503        instance: Instance<'_>,
1504        mergeable_succ: bool,
1505    ) -> MergingSucc {
1506        let span = terminator.source_info.span;
1507
1508        let operands: Vec<_> = operands
1509            .iter()
1510            .map(|op| match *op {
1511                mir::InlineAsmOperand::In { reg, ref value } => {
1512                    let value = self.codegen_operand(bx, value);
1513                    InlineAsmOperandRef::In { reg, value }
1514                }
1515                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1516                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1517                    InlineAsmOperandRef::Out { reg, late, place }
1518                }
1519                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1520                    let in_value = self.codegen_operand(bx, in_value);
1521                    let out_place =
1522                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1523                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1524                }
1525                mir::InlineAsmOperand::Const { ref value } => {
1526                    let const_value = self.eval_mir_constant(value);
1527                    let mir::ConstValue::Scalar(scalar) = const_value else {
1528                        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("expected Scalar for promoted asm const, but got {0:#?}",
        const_value), Location::caller())span_bug!(
1529                            span,
1530                            "expected Scalar for promoted asm const, but got {:#?}",
1531                            const_value
1532                        )
1533                    };
1534                    InlineAsmOperandRef::Const {
1535                        value: common::asm_const_ptr_clean(bx.tcx(), scalar),
1536                        ty: value.ty(),
1537                    }
1538                }
1539                mir::InlineAsmOperand::SymFn { ref value } => {
1540                    let const_ = self.monomorphize(value.const_);
1541                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1542                        let instance = ty::Instance::resolve_for_fn_ptr(
1543                            bx.tcx(),
1544                            bx.typing_env(),
1545                            def_id,
1546                            args.no_bound_vars().unwrap(),
1547                        )
1548                        .unwrap();
1549
1550                        InlineAsmOperandRef::Const {
1551                            value: Scalar::from_pointer(
1552                                bx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
1553                                bx,
1554                            ),
1555                            ty: Ty::new_fn_ptr(bx.tcx(), const_.ty().fn_sig(bx.tcx())),
1556                        }
1557                    } else {
1558                        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid type for asm sym (fn)"), Location::caller());span_bug!(span, "invalid type for asm sym (fn)");
1559                    }
1560                }
1561                mir::InlineAsmOperand::SymStatic { def_id } => {
1562                    if bx.tcx().is_thread_local_static(def_id) {
1563                        InlineAsmOperandRef::SymThreadLocalStatic { def_id }
1564                    } else {
1565                        InlineAsmOperandRef::Const {
1566                            value: Scalar::from_pointer(
1567                                bx.tcx().reserve_and_set_static_alloc(def_id).into(),
1568                                bx,
1569                            ),
1570                            ty: bx.tcx().static_ptr_ty(def_id, bx.typing_env()),
1571                        }
1572                    }
1573                }
1574                mir::InlineAsmOperand::Label { target_index } => {
1575                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1576                }
1577            })
1578            .collect();
1579
1580        helper.do_inlineasm(
1581            self,
1582            bx,
1583            template,
1584            &operands,
1585            options,
1586            line_spans,
1587            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1588            unwind,
1589            instance,
1590            mergeable_succ,
1591        )
1592    }
1593
1594    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1595        let llbb = match self.try_llbb(bb) {
1596            Some(llbb) => llbb,
1597            None => return,
1598        };
1599        let bx = &mut Bx::build(self.cx, llbb);
1600        let mir = self.mir;
1601
1602        // MIR basic blocks stop at any function call. This may not be the case
1603        // for the backend's basic blocks, in which case we might be able to
1604        // combine multiple MIR basic blocks into a single backend basic block.
1605        loop {
1606            let data = &mir[bb];
1607
1608            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:1608",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1608u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
                                                    bb, data) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1609
1610            for statement in &data.statements {
1611                self.codegen_statement(bx, statement);
1612            }
1613            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1614
1615            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1616            if let MergingSucc::False = merging_succ {
1617                break;
1618            }
1619
1620            // We are merging the successor into the produced backend basic
1621            // block. Record that the successor should be skipped when it is
1622            // reached.
1623            //
1624            // Note: we must not have already generated code for the successor.
1625            // This is implicitly ensured by the reverse postorder traversal,
1626            // and the assertion explicitly guarantees that.
1627            let mut successors = data.terminator().successors();
1628            let succ = successors.next().unwrap();
1629            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));
1630            self.cached_llbbs[succ] = CachedLlbb::Skip;
1631            bb = succ;
1632        }
1633    }
1634
1635    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1636        let llbb = match self.try_llbb(bb) {
1637            Some(llbb) => llbb,
1638            None => return,
1639        };
1640        let bx = &mut Bx::build(self.cx, llbb);
1641        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:1641",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1641u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
                                                    bb) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1642        bx.unreachable();
1643    }
1644
1645    fn codegen_terminator(
1646        &mut self,
1647        bx: &mut Bx,
1648        bb: mir::BasicBlock,
1649        terminator: &'tcx mir::Terminator<'tcx>,
1650    ) -> MergingSucc {
1651        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs:1651",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1651u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
                                                    terminator) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1652
1653        let helper = TerminatorCodegenHelper { bb, terminator };
1654
1655        let mergeable_succ = || {
1656            // Note: any call to `switch_to_block` will invalidate a `true` value
1657            // of `mergeable_succ`.
1658            let mut successors = terminator.successors();
1659            if let Some(succ) = successors.next()
1660                && successors.next().is_none()
1661                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1662            {
1663                // bb has a single successor, and bb is its only predecessor. This
1664                // makes it a candidate for merging.
1665                {
    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);
1666                true
1667            } else {
1668                false
1669            }
1670        };
1671
1672        self.set_debug_loc(bx, terminator.source_info);
1673        match terminator.kind {
1674            mir::TerminatorKind::UnwindResume => {
1675                self.codegen_resume_terminator(helper, bx);
1676                MergingSucc::False
1677            }
1678
1679            mir::TerminatorKind::UnwindTerminate(reason) => {
1680                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1681                MergingSucc::False
1682            }
1683
1684            mir::TerminatorKind::Goto { target, ref loop_hint_attrs } => {
1685                helper.funclet_br(self, bx, target, mergeable_succ(), loop_hint_attrs)
1686            }
1687
1688            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1689                self.codegen_switchint_terminator(helper, bx, discr, targets);
1690                MergingSucc::False
1691            }
1692
1693            mir::TerminatorKind::Return => {
1694                self.codegen_return_terminator(bx);
1695                MergingSucc::False
1696            }
1697
1698            mir::TerminatorKind::Unreachable => {
1699                bx.unreachable();
1700                MergingSucc::False
1701            }
1702
1703            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1704                if !drop.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1705                    drop.is_none(),
1706                    "Async Drop must be expanded or reset to sync before codegen"
1707                );
1708                self.codegen_drop_terminator(
1709                    helper,
1710                    bx,
1711                    &terminator.source_info,
1712                    place,
1713                    target,
1714                    unwind,
1715                    mergeable_succ(),
1716                )
1717            }
1718
1719            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1720                .codegen_assert_terminator(
1721                    helper,
1722                    bx,
1723                    terminator,
1724                    cond,
1725                    expected,
1726                    msg,
1727                    target,
1728                    unwind,
1729                    mergeable_succ(),
1730                ),
1731
1732            mir::TerminatorKind::Call {
1733                ref func,
1734                ref args,
1735                destination,
1736                target,
1737                unwind,
1738                call_source: _,
1739                fn_span,
1740            } => self.codegen_call_terminator(
1741                helper,
1742                bx,
1743                terminator,
1744                func,
1745                args,
1746                destination,
1747                target,
1748                unwind,
1749                fn_span,
1750                CallKind::Normal,
1751                mergeable_succ(),
1752            ),
1753            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1754                .codegen_call_terminator(
1755                    helper,
1756                    bx,
1757                    terminator,
1758                    func,
1759                    args,
1760                    mir::Place::from(mir::RETURN_PLACE),
1761                    None,
1762                    mir::UnwindAction::Unreachable,
1763                    fn_span,
1764                    CallKind::Tail,
1765                    mergeable_succ(),
1766                ),
1767            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1768                ::rustc_span::macros::bug_impl(None, format_args!("coroutine ops in codegen"),
    Location::caller())bug!("coroutine ops in codegen")
1769            }
1770            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1771                ::rustc_span::macros::bug_impl(None,
    format_args!("borrowck false edges in codegen"), Location::caller())bug!("borrowck false edges in codegen")
1772            }
1773
1774            mir::TerminatorKind::InlineAsm {
1775                asm_macro,
1776                template,
1777                ref operands,
1778                options,
1779                line_spans,
1780                ref targets,
1781                unwind,
1782            } => self.codegen_asm_terminator(
1783                helper,
1784                bx,
1785                asm_macro,
1786                terminator,
1787                template,
1788                operands,
1789                options,
1790                line_spans,
1791                targets,
1792                unwind,
1793                self.instance,
1794                mergeable_succ(),
1795            ),
1796        }
1797    }
1798
1799    /// When using CMSE, values that cross the secure boundary from secure to non-secure mode can
1800    /// contain stale secure data in their padding bytes. This function clears that data. This is
1801    /// required when a value is:
1802    ///
1803    /// - passed to an `extern "cmse-nonsecure-call"` function
1804    /// - returned from an `extern "cmse-nonsecure-entry"` function
1805    ///
1806    /// This function clears both:
1807    ///
1808    /// - variant-independent padding, bytes that are padding for all valid values of the type
1809    /// - variant-dependent padding, bytes that are padding for some but not all values of the type
1810    ///
1811    /// Clearing variant-dependent padding requires looking at the data at runtime to determine what
1812    /// bytes to clear.
1813    fn clear_padding_cmse(
1814        &mut self,
1815        bx: &mut Bx,
1816        base_ptr: Bx::Value,
1817        limit: Size,
1818        layout: TyAndLayout<'tcx>,
1819    ) {
1820        // First clear variant-independent padding, a series of memsets.
1821        let variant_independent = layout.variant_independent_padding_ranges(self.cx);
1822        self.zero_byte_ranges(bx, base_ptr, Size::ZERO, limit, &variant_independent);
1823
1824        // Then clear the extra padding of the active variant of any (nested) enum.
1825        self.clear_variant_dependent_padding(bx, base_ptr, Size::ZERO, limit, layout);
1826    }
1827
1828    fn clear_variant_dependent_padding(
1829        &mut self,
1830        bx: &mut Bx,
1831        base_ptr: Bx::Value,
1832        base_offset: Size,
1833        limit: Size,
1834        layout: TyAndLayout<'tcx>,
1835    ) {
1836        let cx = self.cx;
1837
1838        if !layout.has_variant_dependent_padding(cx) {
1839            return;
1840        }
1841
1842        // Recurse into aggregate fields/elements to reach any nested enums.
1843        match layout.fields {
1844            FieldsShape::Array { stride, count } => {
1845                let elem = layout.field(cx, 0);
1846                if elem.has_variant_dependent_padding(cx) {
1847                    for idx in 0..count {
1848                        let off = base_offset + idx * stride;
1849                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, elem);
1850                    }
1851                }
1852            }
1853            FieldsShape::Arbitrary { .. } => {
1854                for i in 0..layout.fields.count() {
1855                    let field = layout.field(cx, i);
1856                    if field.has_variant_dependent_padding(cx) {
1857                        let off = base_offset + layout.fields.offset(i);
1858                        self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1859                    }
1860                }
1861            }
1862            FieldsShape::Primitive | FieldsShape::Union(_) => { /* nothing to visit */ }
1863        }
1864
1865        // If this is not a multi-variant enum, we're done.
1866        let Variants::Multiple { ref variants, .. } = layout.variants else {
1867            return;
1868        };
1869
1870        // Collect variants that will need padding cleared.
1871        let mut work = Vec::with_capacity(variants.len());
1872        for i in 0..variants.len() {
1873            let idx = VariantIdx::from_usize(i);
1874            let variant = layout.for_variant(cx, idx);
1875
1876            // Don't consider uninhabited variants.
1877            if variant.is_uninhabited() {
1878                continue;
1879            }
1880
1881            let variant_dependent = layout.variant_dependent_padding_ranges(cx, idx);
1882            let has_nested_variant_dependent = (0..variant.fields.count())
1883                .any(|i| variant.field(cx, i).has_variant_dependent_padding(cx));
1884
1885            if !variant_dependent.is_empty() || has_nested_variant_dependent {
1886                work.push((idx, variant, variant_dependent));
1887            }
1888        }
1889
1890        if work.is_empty() {
1891            return;
1892        }
1893
1894        // Build the switch and clear the appropriate padding for each variant.
1895        let root_block = bx.llbb();
1896        let join_block = bx.append_sibling_block("cmse_pad_join");
1897        let mut cases = Vec::with_capacity(work.len());
1898
1899        for (idx, variant, variant_dependent) in work.into_iter() {
1900            let Some(discr) = layout.ty.discriminant_for_variant(bx.tcx(), idx) else {
1901                ::rustc_span::macros::bug_impl(None,
    format_args!("multi-variant layout on a type without discriminants"),
    Location::caller());bug!("multi-variant layout on a type without discriminants");
1902            };
1903
1904            let variant_block = bx.append_sibling_block("cmse_pad_variant");
1905            bx.switch_to_block(variant_block);
1906
1907            // Clear the padding of this variant.
1908            self.zero_byte_ranges(bx, base_ptr, base_offset, limit, &variant_dependent);
1909
1910            // Recurse into the fields.
1911            for i in 0..variant.fields.count() {
1912                let field = variant.field(cx, i);
1913                let off = base_offset + variant.fields.offset(i);
1914                self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1915            }
1916
1917            bx.br(join_block);
1918            cases.push((discr.val, variant_block));
1919        }
1920
1921        // Construct the dispatch.
1922        bx.switch_to_block(root_block);
1923
1924        let discr_ty = layout.ty.discriminant_ty(bx.tcx());
1925        let enum_ptr = bx.inbounds_ptradd(base_ptr, bx.const_usize(base_offset.bytes()));
1926        let operand = OperandRef {
1927            val: OperandValue::Ref(PlaceValue::new_sized(enum_ptr, layout.align.abi)),
1928            layout,
1929            move_annotation: None,
1930        };
1931        let discr = operand.codegen_get_discr(self, bx, discr_ty);
1932
1933        // Default to the join block (for variants without variant-dependent padding).
1934        bx.switch(discr, join_block, cases.into_iter());
1935
1936        bx.switch_to_block(join_block);
1937    }
1938
1939    fn zero_byte_ranges(
1940        &mut self,
1941        bx: &mut Bx,
1942        ptr: Bx::Value,
1943        offset: Size,
1944        limit: Size,
1945        ranges: &[Range<Size>],
1946    ) {
1947        let zero = bx.const_u8(0);
1948
1949        for range in ranges {
1950            let start = range.start + offset;
1951            let end = range.end + offset;
1952
1953            let end = cmp::min(end, limit);
1954            if range.start >= end {
1955                continue;
1956            }
1957            let offset = bx.const_usize(start.bytes());
1958            let len = bx.const_usize((end - start).bytes());
1959            let ptr = bx.inbounds_ptradd(ptr, offset);
1960            bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1961        }
1962    }
1963
1964    fn codegen_argument(
1965        &mut self,
1966        bx: &mut Bx,
1967        conv: CanonAbi,
1968        op: OperandRef<'tcx, Bx::Value>,
1969        by_move: bool,
1970        llargs: &mut Vec<Bx::Value>,
1971        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1972        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1973    ) {
1974        match arg.mode {
1975            PassMode::Ignore => return,
1976            PassMode::Cast { pad_i32_count, .. } => {
1977                // Fill padding with undef value, where applicable.
1978                let undef = bx.const_undef(bx.reg_backend_type(&Reg::i32()));
1979                llargs.extend(std::iter::repeat_n(undef, usize::from(pad_i32_count)));
1980            }
1981            PassMode::Pair(..) => match op.val {
1982                Pair(a, b) => {
1983                    llargs.push(a);
1984                    llargs.push(b);
1985                    return;
1986                }
1987                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("codegen_argument: {0:?} invalid for pair argument", op),
    Location::caller())bug!("codegen_argument: {:?} invalid for pair argument", op),
1988            },
1989            PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => match op.val {
1990                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1991                    llargs.push(a);
1992                    llargs.push(b);
1993                    return;
1994                }
1995                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
        op), Location::caller())bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1996            },
1997            _ => {}
1998        }
1999
2000        // Force by-ref if we have to load through a cast pointer.
2001        let (mut llval, align, by_ref) = match op.val {
2002            Immediate(_) | Pair(..) => match arg.mode {
2003                PassMode::Indirect { attrs, .. } => {
2004                    // Indirect argument may have higher alignment requirements than the type's
2005                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
2006                    // on the stack on x86.
2007                    let required_align = match attrs.pointee_align {
2008                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
2009                        None => arg.layout.align.abi,
2010                    };
2011                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2012                    bx.lifetime_start(scratch.llval, arg.layout.size);
2013                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
2014                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2015                    (scratch.llval, scratch.align, true)
2016                }
2017                PassMode::Cast { .. } => {
2018                    let scratch = PlaceRef::alloca(bx, arg.layout);
2019                    op.store_with_annotation(bx, scratch);
2020                    (scratch.val.llval, scratch.val.align, true)
2021                }
2022                PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
2023                PassMode::Ignore | PassMode::Pair(..) | PassMode::IndirectUnsized { .. } => {
2024                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above")
2025                }
2026            },
2027            Ref(op_place_val) => match arg.mode {
2028                PassMode::Indirect { attrs, mode, .. } => {
2029                    if mode == IndirectMode::AmdgpuKernelArg {
2030                        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
        arg), Location::caller());bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}");
2031                    }
2032                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
2033                    // alignment requirements may be higher than the type's alignment, so copy
2034                    // to a higher-aligned alloca.
2035                    let required_align = match attrs.pointee_align {
2036                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
2037                        None => arg.layout.align.abi,
2038                    };
2039                    // Copy to an alloca when the argument is neither by-val nor by-move.
2040                    if op_place_val.align < required_align
2041                        || (mode == IndirectMode::Pointer && !by_move)
2042                    {
2043                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2044                        bx.lifetime_start(scratch.llval, arg.layout.size);
2045                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
2046                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2047                        (scratch.llval, scratch.align, true)
2048                    } else {
2049                        (op_place_val.llval, op_place_val.align, true)
2050                    }
2051                }
2052                PassMode::IndirectUnsized { .. } => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above"),
2053                _ => (op_place_val.llval, op_place_val.align, true),
2054            },
2055            ZeroSized => match arg.mode {
2056                PassMode::Indirect { mode, .. } => {
2057                    if mode == IndirectMode::AmdgpuKernelArg {
2058                        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
        arg), Location::caller());bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}");
2059                    }
2060                    if mode == IndirectMode::OnStack {
2061                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
2062                        // is here to replace a would-be untested codepath.
2063                        ::rustc_span::macros::bug_impl(None,
    format_args!("ZST {0:?} passed on stack with abi {1:?}", op, arg),
    Location::caller());bug!("ZST {op:?} passed on stack with abi {arg:?}");
2064                    }
2065                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
2066                    // a pointer for `repr(C)` structs even when empty, so get
2067                    // one from an `alloca` (which can be left uninitialized).
2068                    let scratch = PlaceRef::alloca(bx, arg.layout);
2069                    (scratch.val.llval, scratch.val.align, true)
2070                }
2071                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
        op, arg), Location::caller())bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
2072            },
2073        };
2074
2075        if by_ref && !arg.is_indirect() {
2076            // Have to load the argument, maybe while casting it.
2077            if let PassMode::Cast { cast, pad_i32_count: _ } = &arg.mode {
2078                // The ABI mandates that the value is passed as a different struct representation.
2079                // Spill and reload it from the stack to convert from the Rust representation to
2080                // the ABI representation.
2081                let scratch_size = cast.size(bx);
2082                let scratch_align = cast.align(bx);
2083                // Note that the ABI type may be either larger or smaller than the Rust type,
2084                // due to the presence or absence of trailing padding. For example:
2085                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
2086                //   when passed by value, making it smaller.
2087                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
2088                //   when passed by value, making it larger.
2089                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
2090                // Allocate some scratch space...
2091                let llscratch = bx.alloca(scratch_size, scratch_align);
2092                bx.lifetime_start(llscratch, scratch_size);
2093                // ...memcpy the value...
2094                bx.memcpy(
2095                    llscratch,
2096                    scratch_align,
2097                    llval,
2098                    align,
2099                    bx.const_usize(copy_bytes),
2100                    MemFlags::empty(),
2101                    None,
2102                );
2103
2104                // The arguments of an `extern "cmse-nonsecure-call"` function cross the secure
2105                // boundary. Clear any padding bytes so information does not leak.
2106                if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
2107                    self.clear_padding_cmse(
2108                        bx,
2109                        llscratch,
2110                        Size::from_bytes(copy_bytes),
2111                        arg.layout,
2112                    );
2113                }
2114
2115                // ...and then load it with the ABI type.
2116                llval = load_cast(bx, cast, llscratch, scratch_align);
2117                bx.lifetime_end(llscratch, scratch_size);
2118            } else {
2119                // We can't use `PlaceRef::load` here because the argument
2120                // may have a type we don't treat as immediate, but the ABI
2121                // used for this call is passing it by-value. In that case,
2122                // the load would just produce `OperandValue::Ref` instead
2123                // of the `OperandValue::Immediate` we need for the call.
2124                llval = bx.load(bx.backend_type(arg.layout), llval, align);
2125                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
2126                    if scalar.is_bool() {
2127                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
2128                    }
2129                    // We store bools as `i8` so we need to truncate to `i1`.
2130                    llval = bx.to_immediate_scalar(llval, scalar);
2131                }
2132            }
2133        }
2134
2135        llargs.push(llval);
2136    }
2137
2138    fn codegen_arguments_untupled(
2139        &mut self,
2140        bx: &mut Bx,
2141        conv: CanonAbi,
2142        operand: &mir::Operand<'tcx>,
2143        llargs: &mut Vec<Bx::Value>,
2144        args: &[ArgAbi<'tcx, Ty<'tcx>>],
2145        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
2146    ) -> usize {
2147        let tuple = self.codegen_operand(bx, operand);
2148        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
2149
2150        // Handle both by-ref and immediate tuples.
2151        if let Ref(place_val) = tuple.val {
2152            if place_val.llextra.is_some() {
2153                ::rustc_span::macros::bug_impl(None,
    format_args!("closure arguments must be sized"), Location::caller());bug!("closure arguments must be sized");
2154            }
2155            let tuple_ptr = place_val.with_type(tuple.layout);
2156            for i in 0..tuple.layout.fields.count() {
2157                let field_ptr = tuple_ptr.project_field(bx, i);
2158                let field = bx.load_operand(field_ptr);
2159                self.codegen_argument(
2160                    bx,
2161                    conv,
2162                    field,
2163                    by_move,
2164                    llargs,
2165                    &args[i],
2166                    lifetime_ends_after_call,
2167                );
2168            }
2169        } else {
2170            // If the tuple is immediate, the elements are as well.
2171            for i in 0..tuple.layout.fields.count() {
2172                let op = tuple.extract_field(self, bx, i);
2173                self.codegen_argument(
2174                    bx,
2175                    conv,
2176                    op,
2177                    by_move,
2178                    llargs,
2179                    &args[i],
2180                    lifetime_ends_after_call,
2181                );
2182            }
2183        }
2184        tuple.layout.fields.count()
2185    }
2186
2187    pub(super) fn get_caller_location(
2188        &mut self,
2189        bx: &mut Bx,
2190        source_info: mir::SourceInfo,
2191    ) -> OperandRef<'tcx, Bx::Value> {
2192        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
2193            let const_loc = bx.tcx().span_as_caller_location(span);
2194            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
2195        })
2196    }
2197
2198    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
2199        let cx = bx.cx();
2200        if let Some(slot) = self.personality_slot {
2201            slot
2202        } else {
2203            let layout = cx.layout_of(Ty::new_tup(
2204                cx.tcx(),
2205                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
2206            ));
2207            let slot = PlaceRef::alloca(bx, layout);
2208            self.personality_slot = Some(slot);
2209            slot
2210        }
2211    }
2212
2213    /// Returns the landing/cleanup pad wrapper around the given basic block.
2214    // FIXME(eddyb) rename this to `eh_pad_for`.
2215    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2216        if let Some(landing_pad) = self.landing_pads[bb] {
2217            return landing_pad;
2218        }
2219
2220        let landing_pad = self.landing_pad_for_uncached(bb);
2221        self.landing_pads[bb] = Some(landing_pad);
2222        landing_pad
2223    }
2224
2225    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
2226    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2227        let llbb = self.llbb(bb);
2228        if base::wants_new_eh_instructions(&self.cx.sess().target) {
2229            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:?}"));
2230            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2231            let funclet = cleanup_bx.cleanup_pad(None, &[]);
2232            cleanup_bx.br(llbb);
2233            self.funclets[bb] = Some(funclet);
2234            cleanup_bb
2235        } else {
2236            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2237            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2238
2239            let llpersonality = self.cx.eh_personality();
2240            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2241
2242            let slot = self.get_personality_slot(&mut cleanup_bx);
2243            slot.storage_live(&mut cleanup_bx);
2244            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2245
2246            cleanup_bx.br(llbb);
2247            cleanup_llbb
2248        }
2249    }
2250
2251    fn unreachable_block(&mut self) -> Bx::BasicBlock {
2252        self.unreachable_block.unwrap_or_else(|| {
2253            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2254            let mut bx = Bx::build(self.cx, llbb);
2255            bx.unreachable();
2256            self.unreachable_block = Some(llbb);
2257            llbb
2258        })
2259    }
2260
2261    fn terminate_block(
2262        &mut self,
2263        reason: UnwindTerminateReason,
2264        outer_catchpad_bb: Option<mir::BasicBlock>,
2265    ) -> Bx::BasicBlock {
2266        // mb_funclet_bb should be present if and only if the target is wasm and
2267        // we're terminating because of an unwind in a cleanup block. In that
2268        // case we have nested funclets and the inner catch_switch needs to know
2269        // what outer catch_pad it is contained in.
2270        if true {
    if !(outer_catchpad_bb.is_some() ==
                (base::wants_wasm_eh(&self.cx.tcx().sess.target) &&
                        reason == UnwindTerminateReason::InCleanup)) {
        ::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n    (base::wants_wasm_eh(&self.cx.tcx().sess.target) &&\n            reason == UnwindTerminateReason::InCleanup)")
    };
};debug_assert!(
2271            outer_catchpad_bb.is_some()
2272                == (base::wants_wasm_eh(&self.cx.tcx().sess.target)
2273                    && reason == UnwindTerminateReason::InCleanup)
2274        );
2275
2276        // When we aren't in a wasm InCleanup block, there's only one terminate
2277        // block needed so we cache at START_BLOCK index.
2278        let mut cache_bb = mir::START_BLOCK;
2279        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
2280        // key.
2281        if let Some(outer_bb) = outer_catchpad_bb {
2282            let cleanup_kinds =
2283                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2284            cache_bb = cleanup_kinds[outer_bb]
2285                .funclet_bb(outer_bb)
2286                .expect("funclet_bb should be in a funclet");
2287
2288            // Ensure the outer funclet is created first
2289            if self.funclets[cache_bb].is_none() {
2290                self.landing_pad_for(cache_bb);
2291            }
2292        }
2293        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2294            && reason == cached_reason
2295        {
2296            return cached_bb;
2297        }
2298
2299        let funclet;
2300        let llbb;
2301        let mut bx;
2302        if base::wants_new_eh_instructions(&self.cx.sess().target) {
2303            // This is a basic block that we're aborting the program for,
2304            // notably in an `extern` function. These basic blocks are inserted
2305            // so that we assert that `extern` functions do indeed not panic,
2306            // and if they do we abort the process.
2307            //
2308            // On MSVC these are tricky though (where we're doing funclets). If
2309            // we were to do a cleanuppad (like below) the normal functions like
2310            // `longjmp` would trigger the abort logic, terminating the
2311            // program. Instead we insert the equivalent of `catch(...)` for C++
2312            // which magically doesn't trigger when `longjmp` files over this
2313            // frame.
2314            //
2315            // Lots more discussion can be found on #48251 but this codegen is
2316            // modeled after clang's for:
2317            //
2318            //      try {
2319            //          foo();
2320            //      } catch (...) {
2321            //          bar();
2322            //      }
2323            //
2324            // which creates an IR snippet like
2325            //
2326            //      cs_terminate:
2327            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
2328            //      cp_terminate:
2329            //         %cp = catchpad within %cs [null, i32 64, null]
2330            //         ...
2331            //
2332            // By contrast, on WebAssembly targets, we specifically _do_ want to
2333            // catch foreign exceptions. The situation with MSVC is a
2334            // regrettable hack which we don't want to extend to other targets
2335            // unless necessary. For WebAssembly, to generate catch(...) and
2336            // catch only C++ exception instead of generating a catch_all, we
2337            // need to call the intrinsics @llvm.wasm.get.exception and
2338            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
2339            // this, we generate a catch_all. We originally got this behavior
2340            // by accident but it luckily matches our intention.
2341
2342            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2343
2344            let mut cs_bx = Bx::build(self.cx, llbb);
2345
2346            // For wasm InCleanup blocks, our catch_switch is nested within the
2347            // outer catchpad, so we need to provide it as the parent value to
2348            // catch_switch.
2349            let mut outer_cleanuppad = None;
2350            if outer_catchpad_bb.is_some() {
2351                // Get the outer funclet's catchpad
2352                let outer_funclet = self.funclets[cache_bb]
2353                    .as_ref()
2354                    .expect("landing_pad_for didn't create funclet");
2355                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2356            }
2357            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2358            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2359            drop(cs_bx);
2360
2361            bx = Bx::build(self.cx, cp_llbb);
2362            let null =
2363                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2364
2365            // The `null` in first argument here is actually a RTTI type
2366            // descriptor for the C++ personality function, but `catch (...)`
2367            // has no type so it's null.
2368            let args = if base::wants_msvc_seh(&self.cx.sess().target) {
2369                // This bitmask is a single `HT_IsStdDotDot` flag, which
2370                // represents that this is a C++-style `catch (...)` block that
2371                // only captures programmatic exceptions, not all SEH
2372                // exceptions. The second `null` points to a non-existent
2373                // `alloca` instruction, which an LLVM pass would inline into
2374                // the initial SEH frame allocation.
2375                let adjectives = bx.const_i32(0x40);
2376                &[null, adjectives, null] as &[_]
2377            } else {
2378                // Specifying more arguments than necessary usually doesn't
2379                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2380                // anything other than a single `null` as a `catch_all` block,
2381                // leading to problems down the line during instruction
2382                // selection.
2383                &[null] as &[_]
2384            };
2385
2386            funclet = Some(bx.catch_pad(cs, args));
2387            // On wasm, if we wanted to generate a catch(...) and only catch C++
2388            // exceptions, we'd call @llvm.wasm.get.exception and
2389            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2390            // we leave them out. This is intentionally diverging from the MSVC
2391            // behavior.
2392        } else {
2393            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2394            bx = Bx::build(self.cx, llbb);
2395
2396            let llpersonality = self.cx.eh_personality();
2397            bx.filter_landing_pad(llpersonality);
2398
2399            funclet = None;
2400        }
2401
2402        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2403
2404        let (fn_abi, fn_ptr, instance) =
2405            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2406        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2407            bx.abort_immediate();
2408        } else {
2409            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2410
2411            let llret = bx.call(
2412                fn_ty,
2413                None,
2414                Some(fn_abi),
2415                fn_ptr,
2416                ReturnSlot::Direct,
2417                &[],
2418                funclet.as_ref(),
2419                None,
2420            );
2421            bx.apply_attrs_to_cleanup_callsite(llret);
2422        }
2423
2424        bx.unreachable();
2425
2426        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2427        llbb
2428    }
2429
2430    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2431    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2432    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2433    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2434    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2435        self.try_llbb(bb).unwrap()
2436    }
2437
2438    /// Like `llbb`, but may fail if the basic block should be skipped.
2439    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2440        match self.cached_llbbs[bb] {
2441            CachedLlbb::None => {
2442                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2443                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2444                Some(llbb)
2445            }
2446            CachedLlbb::Some(llbb) => Some(llbb),
2447            CachedLlbb::Skip => None,
2448        }
2449    }
2450
2451    fn make_return_dest(
2452        &mut self,
2453        bx: &mut Bx,
2454        dest: mir::Place<'tcx>,
2455        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2456    ) -> (ReturnDest<'tcx, Bx::Value>, ReturnSlot<Bx::Value>) {
2457        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2458        if fn_ret.is_ignore() {
2459            return (ReturnDest::Nothing, ReturnSlot::Direct);
2460        }
2461        let dest = if let Some(index) = dest.as_local() {
2462            match self.locals[index] {
2463                LocalRef::Place(dest) => dest,
2464                LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
2465                LocalRef::PendingOperand => {
2466                    // Handle temporary places, specifically `Operand` ones, as
2467                    // they don't have `alloca`s.
2468                    return if fn_ret.is_indirect() {
2469                        // Odd, but possible, case, we have an operand temporary,
2470                        // but the calling convention has an indirect return.
2471                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2472                        tmp.storage_live(bx);
2473                        (
2474                            ReturnDest::IndirectOperand(tmp, index),
2475                            ReturnSlot::Indirect(tmp.val.llval),
2476                        )
2477                    } else {
2478                        (ReturnDest::DirectOperand(index), ReturnSlot::Direct)
2479                    };
2480                }
2481                LocalRef::Operand(_) => {
2482                    ::rustc_span::macros::bug_impl(None,
    format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
2483                }
2484            }
2485        } else {
2486            self.codegen_place(bx, dest.as_ref())
2487        };
2488        if fn_ret.is_indirect() {
2489            if dest.val.align < dest.layout.align.abi {
2490                // Currently, MIR code generation does not create calls
2491                // that store directly to fields of packed structs (in
2492                // fact, the calls it creates write only to temps).
2493                //
2494                // If someone changes that, please update this code path
2495                // to create a temporary.
2496                ::rustc_span::macros::bug_impl(Some(self.mir.span),
    format_args!("can\'t directly store to unaligned value"),
    Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
2497            }
2498            (ReturnDest::Nothing, ReturnSlot::Indirect(dest.val.llval))
2499        } else {
2500            (ReturnDest::Store(dest), ReturnSlot::Direct)
2501        }
2502    }
2503
2504    // Stores the return value of a function call into it's final location.
2505    fn store_return(
2506        &mut self,
2507        bx: &mut Bx,
2508        dest: ReturnDest<'tcx, Bx::Value>,
2509        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2510        llval: Bx::Value,
2511    ) {
2512        use self::ReturnDest::*;
2513        let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2514        match dest {
2515            Nothing => (),
2516            Store(dst) => {
2517                bx.store_arg(ret_abi, llval, dst);
2518                if retags_enabled {
2519                    self.codegen_retag_place(bx, dst, false);
2520                }
2521            }
2522            IndirectOperand(tmp, index) => {
2523                let mut op = bx.load_operand(tmp);
2524                tmp.storage_dead(bx);
2525                if retags_enabled {
2526                    op = self.codegen_retag_operand(bx, op, false);
2527                }
2528                self.overwrite_local(index, LocalRef::Operand(op));
2529                self.debug_introduce_local(bx, index);
2530            }
2531            DirectOperand(index) => {
2532                // If there is a cast, we have to store and reload.
2533                let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2534                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2535                    tmp.storage_live(bx);
2536                    bx.store_arg(ret_abi, llval, tmp);
2537                    let op = bx.load_operand(tmp);
2538                    tmp.storage_dead(bx);
2539                    op
2540                } else {
2541                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2542                };
2543                if retags_enabled {
2544                    op = self.codegen_retag_operand(bx, op, false);
2545                }
2546                self.overwrite_local(index, LocalRef::Operand(op));
2547                self.debug_introduce_local(bx, index);
2548            }
2549        }
2550    }
2551}
2552
2553enum ReturnDest<'tcx, V> {
2554    /// Do nothing; the return value is indirect or ignored.
2555    Nothing,
2556    /// Store the return value to the pointer.
2557    Store(PlaceRef<'tcx, V>),
2558    /// Store an indirect return value to an operand local place.
2559    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2560    /// Store a direct return value to an operand local place.
2561    DirectOperand(mir::Local),
2562}
2563
2564fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2565    bx: &mut Bx,
2566    cast: &CastTarget,
2567    ptr: Bx::Value,
2568    align: Align,
2569) -> Bx::Value {
2570    let cast_ty = bx.cast_backend_type(cast);
2571    if let Some(offset_from_start) = cast.rest_offset {
2572        {
    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);
2573        {
    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);
2574        let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2575        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2576        let first = bx.load(first_ty, ptr, align);
2577        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2578        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2579        let res = bx.cx().const_poison(cast_ty);
2580        let res = bx.insert_value(res, first, 0);
2581        bx.insert_value(res, second, 1)
2582    } else {
2583        bx.load(cast_ty, ptr, align)
2584    }
2585}
2586
2587pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2588    bx: &mut Bx,
2589    cast: &CastTarget,
2590    value: Bx::Value,
2591    ptr: Bx::Value,
2592    align: Align,
2593) {
2594    if let Some(offset_from_start) = cast.rest_offset {
2595        {
    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);
2596        {
    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);
2597        let first = bx.extract_value(value, 0);
2598        let second = bx.extract_value(value, 1);
2599        bx.store(first, ptr, align);
2600        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2601        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2602    } else {
2603        bx.store(value, ptr, align);
2604    };
2605}