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