Skip to main content

rustc_const_eval/interpret/
call.rs

1//! Manages calling a concrete function (with known MIR body) with argument passing,
2//! and returning the return value to the caller.
3
4use std::borrow::Cow;
5
6use either::{Left, Right};
7use rustc_abi::{self as abi, ExternAbi, FieldIdx, Integer, VariantIdx};
8use rustc_data_structures::assert_matches;
9use rustc_errors::msg;
10use rustc_hir::def_id::DefId;
11use rustc_hir::find_attr;
12use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
13use rustc_middle::ty::{self, AdtDef, Instance, Ty, VariantDef};
14use rustc_middle::{bug, mir, span_bug};
15use rustc_target::callconv::{ArgAbi, FnAbi, PassMode};
16use tracing::field::Empty;
17use tracing::{info, instrument, trace};
18
19use super::{
20    CtfeProvenance, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy,
21    Projectable, Provenance, ReturnAction, ReturnContinuation, Scalar, interp_ok, throw_ub,
22    throw_ub_custom,
23};
24use crate::enter_trace_span;
25use crate::interpret::EnteredTraceSpan;
26
27/// An argument passed to a function.
28#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
    FnArg<'tcx, Prov> {
    #[inline]
    fn clone(&self) -> FnArg<'tcx, Prov> {
        match self {
            FnArg::Copy(__self_0) =>
                FnArg::Copy(::core::clone::Clone::clone(__self_0)),
            FnArg::InPlace(__self_0) =>
                FnArg::InPlace(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx, Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
    FnArg<'tcx, Prov> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnArg::Copy(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Copy",
                    &__self_0),
            FnArg::InPlace(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "InPlace", &__self_0),
        }
    }
}Debug)]
29pub enum FnArg<'tcx, Prov: Provenance = CtfeProvenance> {
30    /// Pass a copy of the given operand.
31    Copy(OpTy<'tcx, Prov>),
32    /// Allow for the argument to be passed in-place: destroy the value originally stored at that
33    /// place and make the place inaccessible for the duration of the function call. This *must* be
34    /// an in-memory place so that we can do the proper alias checks.
35    InPlace(MPlaceTy<'tcx, Prov>),
36}
37
38impl<'tcx, Prov: Provenance> FnArg<'tcx, Prov> {
39    pub fn layout(&self) -> &TyAndLayout<'tcx> {
40        match self {
41            FnArg::Copy(op) => &op.layout,
42            FnArg::InPlace(mplace) => &mplace.layout,
43        }
44    }
45
46    /// Make a copy of the given fn_arg. Any `InPlace` are degenerated to copies, no protection of the
47    /// original memory occurs.
48    pub fn copy_fn_arg(&self) -> OpTy<'tcx, Prov> {
49        match self {
50            FnArg::Copy(op) => op.clone(),
51            FnArg::InPlace(mplace) => mplace.clone().into(),
52        }
53    }
54}
55
56impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
57    /// Make a copy of the given fn_args. Any `InPlace` are degenerated to copies, no protection of the
58    /// original memory occurs.
59    pub fn copy_fn_args(args: &[FnArg<'tcx, M::Provenance>]) -> Vec<OpTy<'tcx, M::Provenance>> {
60        args.iter().map(|fn_arg| fn_arg.copy_fn_arg()).collect()
61    }
62
63    /// Helper function for argument untupling.
64    pub(super) fn fn_arg_field(
65        &self,
66        arg: &FnArg<'tcx, M::Provenance>,
67        field: FieldIdx,
68    ) -> InterpResult<'tcx, FnArg<'tcx, M::Provenance>> {
69        interp_ok(match arg {
70            FnArg::Copy(op) => FnArg::Copy(self.project_field(op, field)?),
71            FnArg::InPlace(mplace) => FnArg::InPlace(self.project_field(mplace, field)?),
72        })
73    }
74
75    /// Find the wrapped inner type of a transparent wrapper.
76    /// Must not be called on 1-ZST (as they don't have a uniquely defined "wrapped field").
77    ///
78    /// We work with `TyAndLayout` here since that makes it much easier to iterate over all fields.
79    fn unfold_transparent(
80        &self,
81        layout: TyAndLayout<'tcx>,
82        may_unfold: impl Fn(AdtDef<'tcx>) -> bool,
83    ) -> TyAndLayout<'tcx> {
84        match layout.ty.kind() {
85            ty::Adt(adt_def, _) if adt_def.repr().transparent() && may_unfold(*adt_def) => {
86                if !!adt_def.is_enum() {
    ::core::panicking::panic("assertion failed: !adt_def.is_enum()")
};assert!(!adt_def.is_enum());
87                // Find the non-1-ZST field, and recurse.
88                let (_, field) = layout.non_1zst_field(self).unwrap();
89                self.unfold_transparent(field, may_unfold)
90            }
91            ty::Pat(base, _) => self.layout_of(*base).expect(
92                "if the layout of a pattern type could be computed, so can the layout of its base",
93            ),
94            // Not a transparent type, no further unfolding.
95            _ => layout,
96        }
97    }
98
99    /// Unwrap types that are guaranteed a null-pointer-optimization
100    fn unfold_npo(&self, layout: TyAndLayout<'tcx>) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
101        // Check if this is an option-like type wrapping some type.
102        let ty::Adt(def, args) = layout.ty.kind() else {
103            // Not an ADT, so definitely no NPO.
104            return interp_ok(layout);
105        };
106        if def.variants().len() != 2 {
107            // Not a 2-variant enum, so no NPO.
108            return interp_ok(layout);
109        }
110        if !def.is_enum() {
    ::core::panicking::panic("assertion failed: def.is_enum()")
};assert!(def.is_enum());
111
112        let all_fields_1zst = |variant: &VariantDef| -> InterpResult<'tcx, _> {
113            for field in &variant.fields {
114                let ty = field.ty(*self.tcx, args);
115                let layout = self.layout_of(ty)?;
116                if !layout.is_1zst() {
117                    return interp_ok(false);
118                }
119            }
120            interp_ok(true)
121        };
122
123        // If one variant consists entirely of 1-ZST, then the other variant
124        // is the only "relevant" one for this check.
125        let var0 = VariantIdx::from_u32(0);
126        let var1 = VariantIdx::from_u32(1);
127        let relevant_variant = if all_fields_1zst(def.variant(var0))? {
128            def.variant(var1)
129        } else if all_fields_1zst(def.variant(var1))? {
130            def.variant(var0)
131        } else {
132            // No variant is all-1-ZST, so no NPO.
133            return interp_ok(layout);
134        };
135        // The "relevant" variant must have exactly one field, and its type is the "inner" type.
136        if relevant_variant.fields.len() != 1 {
137            return interp_ok(layout);
138        }
139        let inner = relevant_variant.fields[FieldIdx::from_u32(0)].ty(*self.tcx, args);
140        let inner = self.layout_of(inner)?;
141
142        // Check if the inner type is one of the NPO-guaranteed ones.
143        // For that we first unpeel transparent *structs* (but not unions).
144        let is_npo =
145            |def: AdtDef<'tcx>| {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(def.did()) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcNonnullOptimizationGuaranteed)
                                => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.tcx, def.did(), RustcNonnullOptimizationGuaranteed);
146        let inner = self.unfold_transparent(inner, /* may_unfold */ |def| {
147            // Stop at NPO types so that we don't miss that attribute in the check below!
148            def.is_struct() && !is_npo(def)
149        });
150        interp_ok(match inner.ty.kind() {
151            ty::Ref(..) | ty::FnPtr(..) => {
152                // Option<&T> behaves like &T, and same for fn()
153                inner
154            }
155            ty::Adt(def, _) if is_npo(*def) => {
156                // Once we found a `nonnull_optimization_guaranteed` type, further strip off
157                // newtype structs from it to find the underlying ABI type.
158                self.unfold_transparent(inner, /* may_unfold */ |def| def.is_struct())
159            }
160            _ => {
161                // Everything else we do not unfold.
162                layout
163            }
164        })
165    }
166
167    /// Check if these two layouts look like they are fn-ABI-compatible.
168    /// (We also compare the `PassMode`, so this doesn't have to check everything. But it turns out
169    /// that only checking the `PassMode` is insufficient.)
170    fn layout_compat(
171        &self,
172        caller: TyAndLayout<'tcx>,
173        callee: TyAndLayout<'tcx>,
174    ) -> InterpResult<'tcx, bool> {
175        // Fast path: equal types are definitely compatible.
176        if caller.ty == callee.ty {
177            return interp_ok(true);
178        }
179        // 1-ZST are compatible with all 1-ZST (and with nothing else).
180        if caller.is_1zst() || callee.is_1zst() {
181            return interp_ok(caller.is_1zst() && callee.is_1zst());
182        }
183        // Unfold newtypes and NPO optimizations.
184        let unfold = |layout: TyAndLayout<'tcx>| {
185            self.unfold_npo(self.unfold_transparent(layout, /* may_unfold */ |_def| true))
186        };
187        let caller = unfold(caller)?;
188        let callee = unfold(callee)?;
189        // Now see if these inner types are compatible.
190
191        // Compatible pointer types. For thin pointers, we have to accept even non-`repr(transparent)`
192        // things as compatible due to `DispatchFromDyn`. For instance, `Rc<i32>` and `*mut i32`
193        // must be compatible. So we just accept everything with Pointer ABI as compatible,
194        // even if this will accept some code that is not stably guaranteed to work.
195        // This also handles function pointers.
196        let thin_pointer = |layout: TyAndLayout<'tcx>| match layout.backend_repr {
197            abi::BackendRepr::Scalar(s) => match s.primitive() {
198                abi::Primitive::Pointer(addr_space) => Some(addr_space),
199                _ => None,
200            },
201            _ => None,
202        };
203        if let (Some(caller), Some(callee)) = (thin_pointer(caller), thin_pointer(callee)) {
204            return interp_ok(caller == callee);
205        }
206        // For wide pointers we have to get the pointee type.
207        let pointee_ty = |ty: Ty<'tcx>| -> InterpResult<'tcx, Option<Ty<'tcx>>> {
208            // We cannot use `builtin_deref` here since we need to reject `Box<T, MyAlloc>`.
209            interp_ok(Some(match ty.kind() {
210                ty::Ref(_, ty, _) => *ty,
211                ty::RawPtr(ty, _) => *ty,
212                // We only accept `Box` with the default allocator.
213                _ if ty.is_box_global(*self.tcx) => ty.expect_boxed_ty(),
214                _ => return interp_ok(None),
215            }))
216        };
217        if let (Some(caller), Some(callee)) = (pointee_ty(caller.ty)?, pointee_ty(callee.ty)?) {
218            // This is okay if they have the same metadata type.
219            let meta_ty = |ty: Ty<'tcx>| {
220                // Even if `ty` is normalized, the search for the unsized tail will project
221                // to fields, which can yield non-normalized types. So we need to provide a
222                // normalization function.
223                let normalize = |ty| self.tcx.normalize_erasing_regions(self.typing_env, ty);
224                ty.ptr_metadata_ty(*self.tcx, normalize)
225            };
226            return interp_ok(meta_ty(caller) == meta_ty(callee));
227        }
228
229        // Compatible integer types (in particular, usize vs ptr-sized-u32/u64).
230        // `char` counts as `u32.`
231        let int_ty = |ty: Ty<'tcx>| {
232            Some(match ty.kind() {
233                ty::Int(ity) => (Integer::from_int_ty(&self.tcx, *ity), /* signed */ true),
234                ty::Uint(uty) => (Integer::from_uint_ty(&self.tcx, *uty), /* signed */ false),
235                ty::Char => (Integer::I32, /* signed */ false),
236                _ => return None,
237            })
238        };
239        if let (Some(caller), Some(callee)) = (int_ty(caller.ty), int_ty(callee.ty)) {
240            // This is okay if they are the same integer type.
241            return interp_ok(caller == callee);
242        }
243
244        // Fall back to exact equality.
245        interp_ok(caller == callee)
246    }
247
248    /// Returns a `bool` saying whether the two arguments are ABI-compatible.
249    pub fn check_argument_compat(
250        &self,
251        caller_abi: &ArgAbi<'tcx, Ty<'tcx>>,
252        callee_abi: &ArgAbi<'tcx, Ty<'tcx>>,
253    ) -> InterpResult<'tcx, bool> {
254        // We do not want to accept things as ABI-compatible that just "happen to be" compatible on the current target,
255        // so we implement a type-based check that reflects the guaranteed rules for ABI compatibility.
256        if self.layout_compat(caller_abi.layout, callee_abi.layout)? {
257            // Ensure that our checks imply actual ABI compatibility for this concrete call.
258            // (This can fail e.g. if `#[rustc_nonnull_optimization_guaranteed]` is used incorrectly.)
259            if !caller_abi.eq_abi(callee_abi) {
    ::core::panicking::panic("assertion failed: caller_abi.eq_abi(callee_abi)")
};assert!(caller_abi.eq_abi(callee_abi));
260            interp_ok(true)
261        } else {
262            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:262",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(262u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_argument_compat: incompatible ABIs:\ncaller: {0:?}\ncallee: {1:?}",
                                                    caller_abi, callee_abi) as &dyn Value))])
            });
    } else { ; }
};trace!(
263                "check_argument_compat: incompatible ABIs:\ncaller: {:?}\ncallee: {:?}",
264                caller_abi, callee_abi
265            );
266            interp_ok(false)
267        }
268    }
269
270    /// Initialize a single callee argument, checking the types for compatibility.
271    fn pass_argument<'x, 'y>(
272        &mut self,
273        caller_args: &mut impl Iterator<
274            Item = (&'x FnArg<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>),
275        >,
276        callee_abi: &ArgAbi<'tcx, Ty<'tcx>>,
277        callee_arg_idx: usize,
278        callee_arg: &mir::Place<'tcx>,
279        callee_ty: Ty<'tcx>,
280        already_live: bool,
281    ) -> InterpResult<'tcx>
282    where
283        'tcx: 'x,
284        'tcx: 'y,
285    {
286        match (&callee_ty, &callee_abi.layout.ty) {
    (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!(callee_ty, callee_abi.layout.ty);
287        if callee_abi.mode == PassMode::Ignore {
288            // This one is skipped. Still must be made live though!
289            if !already_live {
290                self.storage_live(callee_arg.as_local().unwrap())?;
291            }
292            return interp_ok(());
293        }
294        // Find next caller arg.
295        let Some((caller_arg, caller_abi)) = caller_args.next() else {
296            do yeet {
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("calling a function with fewer arguments than it requires")),
                    add_args: Box::new(move |mut set_arg| {}),
                }))
    };throw_ub_custom!(msg!("calling a function with fewer arguments than it requires"));
297        };
298        match (&caller_arg.layout().layout, &caller_abi.layout.layout) {
    (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!(caller_arg.layout().layout, caller_abi.layout.layout);
299        // Sadly we cannot assert that `caller_arg.layout().ty` and `caller_abi.layout.ty` are
300        // equal; in closures the types sometimes differ. We just hope that `caller_abi` is the
301        // right type to print to the user.
302
303        // Check compatibility
304        if !self.check_argument_compat(caller_abi, callee_abi)? {
305            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AbiMismatchArgument {
            arg_idx: callee_arg_idx,
            caller_ty: caller_abi.layout.ty,
            callee_ty: callee_abi.layout.ty,
        });throw_ub!(AbiMismatchArgument {
306                arg_idx: callee_arg_idx,
307                caller_ty: caller_abi.layout.ty,
308                callee_ty: callee_abi.layout.ty
309            });
310        }
311        // We work with a copy of the argument for now; if this is in-place argument passing, we
312        // will later protect the source it comes from. This means the callee cannot observe if we
313        // did in-place of by-copy argument passing, except for pointer equality tests.
314        let caller_arg_copy = caller_arg.copy_fn_arg();
315        if !already_live {
316            let local = callee_arg.as_local().unwrap();
317            let meta = caller_arg_copy.meta();
318            // `check_argument_compat` ensures that if metadata is needed, both have the same type,
319            // so we know they will use the metadata the same way.
320            if !(!meta.has_meta() || caller_arg_copy.layout.ty == callee_ty) {
    ::core::panicking::panic("assertion failed: !meta.has_meta() || caller_arg_copy.layout.ty == callee_ty")
};assert!(!meta.has_meta() || caller_arg_copy.layout.ty == callee_ty);
321
322            self.storage_live_dyn(local, meta)?;
323        }
324        // Now we can finally actually evaluate the callee place.
325        let callee_arg = self.eval_place(*callee_arg)?;
326        // We allow some transmutes here.
327        // FIXME: Depending on the PassMode, this should reset some padding to uninitialized. (This
328        // is true for all `copy_op`, but there are a lot of special cases for argument passing
329        // specifically.)
330        self.copy_op_allow_transmute(&caller_arg_copy, &callee_arg)?;
331        // If this was an in-place pass, protect the place it comes from for the duration of the call.
332        if let FnArg::InPlace(mplace) = caller_arg {
333            M::protect_in_place_function_argument(self, mplace)?;
334        }
335        interp_ok(())
336    }
337
338    /// The main entry point for creating a new stack frame: performs ABI checks and initializes
339    /// arguments.
340    #[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("init_stack_frame",
                                    "rustc_const_eval::interpret::call",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                    ::tracing_core::__macro_support::Option::Some(340u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                    ::tracing_core::field::FieldSet::new(&["instance", "body",
                                                    "caller_fn_abi", "args", "with_caller_location",
                                                    "destination", "cont"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&caller_fn_abi)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&with_caller_location
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&destination)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cont)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let _trace =
                <M as
                        crate::interpret::Machine>::enter_trace_span(||
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("step",
                                                "rustc_const_eval::interpret::call", ::tracing::Level::INFO,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                                ::tracing_core::__macro_support::Option::Some(351u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                                ::tracing_core::field::FieldSet::new(&["step", "instance",
                                                                "tracing_separate_thread"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::SPAN)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let mut interest = ::tracing::subscriber::Interest::never();
                            if ::tracing::Level::INFO <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::INFO <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        { interest = __CALLSITE.interest(); !interest.is_never() }
                                    &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest) {
                                let meta = __CALLSITE.metadata();
                                ::tracing::Span::new(meta,
                                    &{
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            let mut iter = meta.fields().iter();
                                            meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&display(&"init_stack_frame")
                                                                        as &dyn Value)),
                                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&display(&instance)
                                                                        as &dyn Value)),
                                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&Empty as
                                                                        &dyn Value))])
                                        })
                            } else {
                                let span =
                                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                                {};
                                span
                            }
                        });
            let extra_tys =
                if caller_fn_abi.c_variadic {
                    let fixed_count =
                        usize::try_from(caller_fn_abi.fixed_count).unwrap();
                    let extra_tys =
                        args[fixed_count..].iter().map(|arg| arg.layout().ty);
                    self.tcx.mk_type_list_from_iter(extra_tys)
                } else { ty::List::empty() };
            let callee_fn_abi = self.fn_abi_of_instance(instance, extra_tys)?;
            if caller_fn_abi.conv != callee_fn_abi.conv {
                do yeet {
                        let (callee_conv, caller_conv) =
                            (::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}",
                                                callee_fn_abi.conv))
                                    }),
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}",
                                                caller_fn_abi.conv))
                                    }));
                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                                    msg: ||
                                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("calling a function with calling convention \"{$callee_conv}\" using calling convention \"{$caller_conv}\"")),
                                    add_args: Box::new(move |mut set_arg|
                                            {
                                                set_arg("callee_conv".into(),
                                                    rustc_errors::IntoDiagArg::into_diag_arg(callee_conv,
                                                        &mut None));
                                                set_arg("caller_conv".into(),
                                                    rustc_errors::IntoDiagArg::into_diag_arg(caller_conv,
                                                        &mut None));
                                            }),
                                }))
                    }
            }
            if caller_fn_abi.c_variadic != callee_fn_abi.c_variadic {
                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::CVariadicMismatch {
                            caller_is_c_variadic: caller_fn_abi.c_variadic,
                            callee_is_c_variadic: callee_fn_abi.c_variadic,
                        });
            }
            if caller_fn_abi.c_variadic &&
                    caller_fn_abi.fixed_count != callee_fn_abi.fixed_count {
                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::CVariadicFixedCountMismatch {
                            caller: caller_fn_abi.fixed_count,
                            callee: callee_fn_abi.fixed_count,
                        });
            }
            M::check_fn_target_features(self, instance)?;
            if !callee_fn_abi.can_unwind {
                match &mut cont {
                    ReturnContinuation::Stop { .. } => {}
                    ReturnContinuation::Goto { unwind, .. } => {
                        *unwind = mir::UnwindAction::Unreachable;
                    }
                }
            }
            let destination_mplace =
                self.place_to_op(destination)?.as_mplace_or_imm().left();
            self.push_stack_frame_raw(instance, body, destination, cont)?;
            let res: InterpResult<'tcx> =
                try {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:414",
                                            "rustc_const_eval::interpret::call",
                                            ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                            ::tracing_core::__macro_support::Option::Some(414u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("caller ABI: {0:#?}, args: {1:#?}",
                                                                        caller_fn_abi,
                                                                        args.iter().map(|arg|
                                                                                    (arg.layout().ty,
                                                                                        match arg {
                                                                                            FnArg::Copy(op) =>
                                                                                                ::alloc::__export::must_use({
                                                                                                        ::alloc::fmt::format(format_args!("copy({0:?})", op))
                                                                                                    }),
                                                                                            FnArg::InPlace(mplace) =>
                                                                                                ::alloc::__export::must_use({
                                                                                                        ::alloc::fmt::format(format_args!("in-place({0:?})",
                                                                                                                mplace))
                                                                                                    }),
                                                                                        })).collect::<Vec<_>>()) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:427",
                                            "rustc_const_eval::interpret::call",
                                            ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                            ::tracing_core::__macro_support::Option::Some(427u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("spread_arg: {0:?}, locals: {1:#?}",
                                                                        body.spread_arg,
                                                                        body.args_iter().map(|local|
                                                                                    (local,
                                                                                        self.layout_of_local(self.frame(), local,
                                                                                                    None).unwrap().ty)).collect::<Vec<_>>()) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    match (&(args.len() +
                                    if with_caller_location { 1 } else { 0 }),
                            &caller_fn_abi.args.len()) {
                        (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!("mismatch between caller ABI and caller arguments")));
                            }
                        }
                    };
                    let mut caller_args =
                        args.iter().zip(caller_fn_abi.args.iter()).filter(|arg_and_abi|
                                !#[allow(non_exhaustive_omitted_patterns)] match arg_and_abi.1.mode
                                        {
                                        PassMode::Ignore => true,
                                        _ => false,
                                    });
                    let mut callee_args_abis =
                        callee_fn_abi.args.iter().enumerate();
                    let va_list_arg =
                        callee_fn_abi.c_variadic.then(||
                                mir::Local::from_usize(body.arg_count));
                    for local in body.args_iter() {
                        let dest = mir::Place::from(local);
                        let ty =
                            self.layout_of_local(self.frame(), local, None)?.ty;
                        if Some(local) == va_list_arg {
                            self.storage_live(local)?;
                            let place = self.eval_place(dest)?;
                            let mplace = self.force_allocation(&place)?;
                            let varargs =
                                self.allocate_varargs(&mut caller_args,
                                        &mut callee_args_abis)?;
                            self.frame_mut().va_list = varargs.clone();
                            let key = self.va_list_ptr(varargs.into());
                            self.write_bytes_ptr(mplace.ptr(),
                                    (0..mplace.layout.size.bytes()).map(|_| 0u8))?;
                            let key_mplace = self.va_list_key_field(&mplace)?;
                            self.write_pointer(key, &key_mplace)?;
                        } else if Some(local) == body.spread_arg {
                            self.storage_live(local)?;
                            let ty::Tuple(fields) =
                                ty.kind() else {
                                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
                                        format_args!("non-tuple type for `spread_arg`: {0}", ty))
                                };
                            for (i, field_ty) in fields.iter().enumerate() {
                                let dest =
                                    dest.project_deeper(&[mir::ProjectionElem::Field(FieldIdx::from_usize(i),
                                                        field_ty)], *self.tcx);
                                let (idx, callee_abi) = callee_args_abis.next().unwrap();
                                self.pass_argument(&mut caller_args, callee_abi, idx, &dest,
                                        field_ty, true)?;
                            }
                        } else {
                            let (idx, callee_abi) = callee_args_abis.next().unwrap();
                            self.pass_argument(&mut caller_args, callee_abi, idx, &dest,
                                    ty, false)?;
                        }
                    }
                    if instance.def.requires_caller_location(*self.tcx) {
                        callee_args_abis.next().unwrap();
                    }
                    if !callee_args_abis.next().is_none() {
                        {
                            ::core::panicking::panic_fmt(format_args!("mismatch between callee ABI and callee body arguments"));
                        }
                    };
                    if caller_args.next().is_some() {
                        do yeet {
                                ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                                            msg: ||
                                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("calling a function with more arguments than it expected")),
                                            add_args: Box::new(move |mut set_arg| {}),
                                        }))
                            };
                    }
                    if !self.check_argument_compat(&caller_fn_abi.ret,
                                    &callee_fn_abi.ret)? {
                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AbiMismatchReturn {
                                    caller_ty: caller_fn_abi.ret.layout.ty,
                                    callee_ty: callee_fn_abi.ret.layout.ty,
                                });
                    }
                    if let Some(mplace) = destination_mplace {
                        M::protect_in_place_function_argument(self, &mplace)?;
                    }
                    self.storage_live_for_always_live_locals()?;
                };
            res.inspect_err_kind(|_| { self.stack_mut().pop(); })
        }
    }
}#[instrument(skip(self), level = "trace")]
341    pub fn init_stack_frame(
342        &mut self,
343        instance: Instance<'tcx>,
344        body: &'tcx mir::Body<'tcx>,
345        caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
346        args: &[FnArg<'tcx, M::Provenance>],
347        with_caller_location: bool,
348        destination: &PlaceTy<'tcx, M::Provenance>,
349        mut cont: ReturnContinuation,
350    ) -> InterpResult<'tcx> {
351        let _trace = enter_trace_span!(M, step::init_stack_frame, %instance, tracing_separate_thread = Empty);
352
353        // The first order of business is to figure out the callee signature.
354        // However, that requires the list of variadic arguments.
355        // We use the *caller* information to determine where to split the list of arguments,
356        // and then later check that the callee indeed has the same number of fixed arguments.
357        let extra_tys = if caller_fn_abi.c_variadic {
358            let fixed_count = usize::try_from(caller_fn_abi.fixed_count).unwrap();
359            let extra_tys = args[fixed_count..].iter().map(|arg| arg.layout().ty);
360            self.tcx.mk_type_list_from_iter(extra_tys)
361        } else {
362            ty::List::empty()
363        };
364        let callee_fn_abi = self.fn_abi_of_instance(instance, extra_tys)?;
365
366        if caller_fn_abi.conv != callee_fn_abi.conv {
367            throw_ub_custom!(
368                rustc_errors::msg!(
369                    "calling a function with calling convention \"{$callee_conv}\" using calling convention \"{$caller_conv}\""
370                ),
371                callee_conv = format!("{}", callee_fn_abi.conv),
372                caller_conv = format!("{}", caller_fn_abi.conv),
373            )
374        }
375
376        if caller_fn_abi.c_variadic != callee_fn_abi.c_variadic {
377            throw_ub!(CVariadicMismatch {
378                caller_is_c_variadic: caller_fn_abi.c_variadic,
379                callee_is_c_variadic: callee_fn_abi.c_variadic,
380            });
381        }
382        if caller_fn_abi.c_variadic && caller_fn_abi.fixed_count != callee_fn_abi.fixed_count {
383            throw_ub!(CVariadicFixedCountMismatch {
384                caller: caller_fn_abi.fixed_count,
385                callee: callee_fn_abi.fixed_count,
386            });
387        }
388
389        // Check that all target features required by the callee (i.e., from
390        // the attribute `#[target_feature(enable = ...)]`) are enabled at
391        // compile time.
392        M::check_fn_target_features(self, instance)?;
393
394        if !callee_fn_abi.can_unwind {
395            // The callee cannot unwind, so force the `Unreachable` unwind handling.
396            match &mut cont {
397                ReturnContinuation::Stop { .. } => {}
398                ReturnContinuation::Goto { unwind, .. } => {
399                    *unwind = mir::UnwindAction::Unreachable;
400                }
401            }
402        }
403
404        // *Before* pushing the new frame, determine whether the return destination is in memory.
405        // Need to use `place_to_op` to be *sure* we get the mplace if there is one.
406        let destination_mplace = self.place_to_op(destination)?.as_mplace_or_imm().left();
407
408        // Push the "raw" frame -- this leaves locals uninitialized.
409        self.push_stack_frame_raw(instance, body, destination, cont)?;
410
411        // If an error is raised here, pop the frame again to get an accurate backtrace.
412        // To this end, we wrap it all in a `try` block.
413        let res: InterpResult<'tcx> = try {
414            trace!(
415                "caller ABI: {:#?}, args: {:#?}",
416                caller_fn_abi,
417                args.iter()
418                    .map(|arg| (
419                        arg.layout().ty,
420                        match arg {
421                            FnArg::Copy(op) => format!("copy({op:?})"),
422                            FnArg::InPlace(mplace) => format!("in-place({mplace:?})"),
423                        }
424                    ))
425                    .collect::<Vec<_>>()
426            );
427            trace!(
428                "spread_arg: {:?}, locals: {:#?}",
429                body.spread_arg,
430                body.args_iter()
431                    .map(|local| (
432                        local,
433                        self.layout_of_local(self.frame(), local, None).unwrap().ty,
434                    ))
435                    .collect::<Vec<_>>()
436            );
437
438            // In principle, we have two iterators: Where the arguments come from, and where
439            // they go to.
440
441            // The "where they come from" part is easy, we expect the caller to do any special handling
442            // that might be required here (e.g. for untupling).
443            // If `with_caller_location` is set we pretend there is an extra argument (that
444            // we will not pass; our `caller_location` intrinsic implementation walks the stack instead).
445            assert_eq!(
446                args.len() + if with_caller_location { 1 } else { 0 },
447                caller_fn_abi.args.len(),
448                "mismatch between caller ABI and caller arguments",
449            );
450            let mut caller_args = args
451                .iter()
452                .zip(caller_fn_abi.args.iter())
453                .filter(|arg_and_abi| !matches!(arg_and_abi.1.mode, PassMode::Ignore));
454
455            // Now we have to spread them out across the callee's locals,
456            // taking into account the `spread_arg`. If we could write
457            // this is a single iterator (that handles `spread_arg`), then
458            // `pass_argument` would be the loop body. It takes care to
459            // not advance `caller_iter` for ignored arguments.
460            let mut callee_args_abis = callee_fn_abi.args.iter().enumerate();
461            // Determine whether there is a special VaList argument. This is always the
462            // last argument, and since arguments start at index 1 that's `arg_count`.
463            let va_list_arg =
464                callee_fn_abi.c_variadic.then(|| mir::Local::from_usize(body.arg_count));
465            for local in body.args_iter() {
466                // Construct the destination place for this argument. At this point all
467                // locals are still dead, so we cannot construct a `PlaceTy`.
468                let dest = mir::Place::from(local);
469                // `layout_of_local` does more than just the instantiation we need to get the
470                // type, but the result gets cached so this avoids calling the instantiation
471                // query *again* the next time this local is accessed.
472                let ty = self.layout_of_local(self.frame(), local, None)?.ty;
473                if Some(local) == va_list_arg {
474                    // This is the last callee-side argument of a variadic function.
475                    // This argument is a VaList holding the remaining caller-side arguments.
476                    self.storage_live(local)?;
477
478                    let place = self.eval_place(dest)?;
479                    let mplace = self.force_allocation(&place)?;
480
481                    // Consume the remaining arguments by putting them into the variable argument
482                    // list.
483                    let varargs = self.allocate_varargs(&mut caller_args, &mut callee_args_abis)?;
484                    // When the frame is dropped, these variable arguments are deallocated.
485                    self.frame_mut().va_list = varargs.clone();
486                    let key = self.va_list_ptr(varargs.into());
487
488                    // Zero the VaList, so it is fully initialized.
489                    self.write_bytes_ptr(
490                        mplace.ptr(),
491                        (0..mplace.layout.size.bytes()).map(|_| 0u8),
492                    )?;
493
494                    // Store the "key" pointer in the right field.
495                    let key_mplace = self.va_list_key_field(&mplace)?;
496                    self.write_pointer(key, &key_mplace)?;
497                } else if Some(local) == body.spread_arg {
498                    // Make the local live once, then fill in the value field by field.
499                    self.storage_live(local)?;
500                    // Must be a tuple
501                    let ty::Tuple(fields) = ty.kind() else {
502                        span_bug!(self.cur_span(), "non-tuple type for `spread_arg`: {ty}")
503                    };
504                    for (i, field_ty) in fields.iter().enumerate() {
505                        let dest = dest.project_deeper(
506                            &[mir::ProjectionElem::Field(FieldIdx::from_usize(i), field_ty)],
507                            *self.tcx,
508                        );
509                        let (idx, callee_abi) = callee_args_abis.next().unwrap();
510                        self.pass_argument(
511                            &mut caller_args,
512                            callee_abi,
513                            idx,
514                            &dest,
515                            field_ty,
516                            /* already_live */ true,
517                        )?;
518                    }
519                } else {
520                    // Normal argument. Cannot mark it as live yet, it might be unsized!
521                    let (idx, callee_abi) = callee_args_abis.next().unwrap();
522                    self.pass_argument(
523                        &mut caller_args,
524                        callee_abi,
525                        idx,
526                        &dest,
527                        ty,
528                        /* already_live */ false,
529                    )?;
530                }
531            }
532            // If the callee needs a caller location, pretend we consume one more argument from the ABI.
533            if instance.def.requires_caller_location(*self.tcx) {
534                callee_args_abis.next().unwrap();
535            }
536            // Now we should have no more caller args or callee arg ABIs.
537            assert!(
538                callee_args_abis.next().is_none(),
539                "mismatch between callee ABI and callee body arguments"
540            );
541            if caller_args.next().is_some() {
542                throw_ub_custom!(msg!("calling a function with more arguments than it expected"));
543            }
544            // Don't forget to check the return type!
545            if !self.check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret)? {
546                throw_ub!(AbiMismatchReturn {
547                    caller_ty: caller_fn_abi.ret.layout.ty,
548                    callee_ty: callee_fn_abi.ret.layout.ty
549                });
550            }
551
552            // Protect return place for in-place return value passing.
553            // We only need to protect anything if this is actually an in-memory place.
554            if let Some(mplace) = destination_mplace {
555                M::protect_in_place_function_argument(self, &mplace)?;
556            }
557
558            // Don't forget to mark "initially live" locals as live.
559            self.storage_live_for_always_live_locals()?;
560        };
561        res.inspect_err_kind(|_| {
562            // Don't show the incomplete stack frame in the error stacktrace.
563            self.stack_mut().pop();
564        })
565    }
566
567    /// Initiate a call to this function -- pushing the stack frame and initializing the arguments.
568    ///
569    /// `caller_fn_abi` is used to determine if all the arguments are passed the proper way.
570    /// However, we also need `caller_abi` to determine if we need to do untupling of arguments.
571    ///
572    /// `with_caller_location` indicates whether the caller passed a caller location. Miri
573    /// implements caller locations without argument passing, but to match `FnAbi` we need to know
574    /// when those arguments are present.
575    pub(super) fn init_fn_call(
576        &mut self,
577        fn_val: FnVal<'tcx, M::ExtraFnVal>,
578        (caller_abi, caller_fn_abi): (ExternAbi, &FnAbi<'tcx, Ty<'tcx>>),
579        args: &[FnArg<'tcx, M::Provenance>],
580        with_caller_location: bool,
581        destination: &PlaceTy<'tcx, M::Provenance>,
582        target: Option<mir::BasicBlock>,
583        unwind: mir::UnwindAction,
584    ) -> InterpResult<'tcx> {
585        let _trace =
586            <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("step",
                                "rustc_const_eval::interpret::call", ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                ::tracing_core::__macro_support::Option::Some(586u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                ::tracing_core::field::FieldSet::new(&["step",
                                                "tracing_separate_thread", "fn_val"],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = meta.fields().iter();
                            meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&display(&"init_fn_call")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&Empty as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&fn_val) as
                                                        &dyn Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, step::init_fn_call, tracing_separate_thread = Empty, ?fn_val)
587                .or_if_tracing_disabled(|| {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:587",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(587u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("init_fn_call: {0:#?}",
                                                    fn_val) as &dyn Value))])
            });
    } else { ; }
}trace!("init_fn_call: {:#?}", fn_val));
588
589        let instance = match fn_val {
590            FnVal::Instance(instance) => instance,
591            FnVal::Other(extra) => {
592                return M::call_extra_fn(
593                    self,
594                    extra,
595                    caller_fn_abi,
596                    args,
597                    destination,
598                    target,
599                    unwind,
600                );
601            }
602        };
603
604        match instance.def {
605            ty::InstanceKind::Intrinsic(def_id) => {
606                if !self.tcx.intrinsic(def_id).is_some() {
    ::core::panicking::panic("assertion failed: self.tcx.intrinsic(def_id).is_some()")
};assert!(self.tcx.intrinsic(def_id).is_some());
607                // FIXME: Should `InPlace` arguments be reset to uninit?
608                if let Some(fallback) = M::call_intrinsic(
609                    self,
610                    instance,
611                    &Self::copy_fn_args(args),
612                    destination,
613                    target,
614                    unwind,
615                )? {
616                    if !!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden {
    ::core::panicking::panic("assertion failed: !self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden")
};assert!(!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden);
617                    match fallback.def {
    ty::InstanceKind::Item(_) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "ty::InstanceKind::Item(_)", ::core::option::Option::None);
    }
};assert_matches!(fallback.def, ty::InstanceKind::Item(_));
618                    return self.init_fn_call(
619                        FnVal::Instance(fallback),
620                        (caller_abi, caller_fn_abi),
621                        args,
622                        with_caller_location,
623                        destination,
624                        target,
625                        unwind,
626                    );
627                } else {
628                    interp_ok(())
629                }
630            }
631            ty::InstanceKind::VTableShim(..)
632            | ty::InstanceKind::ReifyShim(..)
633            | ty::InstanceKind::ClosureOnceShim { .. }
634            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
635            | ty::InstanceKind::FnPtrShim(..)
636            | ty::InstanceKind::DropGlue(..)
637            | ty::InstanceKind::CloneShim(..)
638            | ty::InstanceKind::FnPtrAddrShim(..)
639            | ty::InstanceKind::ThreadLocalShim(..)
640            | ty::InstanceKind::AsyncDropGlueCtorShim(..)
641            | ty::InstanceKind::AsyncDropGlue(..)
642            | ty::InstanceKind::FutureDropPollShim(..)
643            | ty::InstanceKind::Item(_) => {
644                // We need MIR for this fn.
645                // Note that this can be an intrinsic, if we are executing its fallback body.
646                let Some((body, instance)) = M::find_mir_or_eval_fn(
647                    self,
648                    instance,
649                    caller_fn_abi,
650                    args,
651                    destination,
652                    target,
653                    unwind,
654                )?
655                else {
656                    return interp_ok(());
657                };
658
659                // Special handling for the closure ABI: untuple the last argument.
660                let args: Cow<'_, [FnArg<'tcx, M::Provenance>]> =
661                    if caller_abi == ExternAbi::RustCall && !args.is_empty() {
662                        // Untuple
663                        let (untuple_arg, args) = args.split_last().unwrap();
664                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:664",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(664u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("init_fn_call: Will pass last argument by untupling")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("init_fn_call: Will pass last argument by untupling");
665                        Cow::from(
666                            args.iter()
667                                .map(|a| interp_ok(a.clone()))
668                                .chain((0..untuple_arg.layout().fields.count()).map(|i| {
669                                    self.fn_arg_field(untuple_arg, FieldIdx::from_usize(i))
670                                }))
671                                .collect::<InterpResult<'_, Vec<_>>>()?,
672                        )
673                    } else {
674                        // Plain arg passing
675                        Cow::from(args)
676                    };
677
678                self.init_stack_frame(
679                    instance,
680                    body,
681                    caller_fn_abi,
682                    &args,
683                    with_caller_location,
684                    destination,
685                    ReturnContinuation::Goto { ret: target, unwind },
686                )
687            }
688            // `InstanceKind::Virtual` does not have callable MIR. Calls to `Virtual` instances must be
689            // codegen'd / interpreted as virtual calls through the vtable.
690            ty::InstanceKind::Virtual(def_id, idx) => {
691                let mut args = args.to_vec();
692                // We have to implement all "dyn-compatible receivers". So we have to go search for a
693                // pointer or `dyn Trait` type, but it could be wrapped in newtypes. So recursively
694                // unwrap those newtypes until we are there.
695                // An `InPlace` does nothing here, we keep the original receiver intact. We can't
696                // really pass the argument in-place anyway, and we are constructing a new
697                // `Immediate` receiver.
698                let mut receiver = args[0].copy_fn_arg();
699                let receiver_place = loop {
700                    match receiver.layout.ty.kind() {
701                        ty::Ref(..) | ty::RawPtr(..) => {
702                            // We do *not* use `deref_pointer` here: we don't want to conceptually
703                            // create a place that must be dereferenceable, since the receiver might
704                            // be a raw pointer and (for `*const dyn Trait`) we don't need to
705                            // actually access memory to resolve this method.
706                            // Also see <https://github.com/rust-lang/miri/issues/2786>.
707                            let val = self.read_immediate(&receiver)?;
708                            break self.ref_to_mplace(&val)?;
709                        }
710                        ty::Dynamic(..) => break receiver.assert_mem_place(), // no immediate unsized values
711                        _ => {
712                            // Not there yet, search for the only non-ZST field.
713                            // (The rules for `DispatchFromDyn` ensure there's exactly one such field.)
714                            let (idx, _) = receiver.layout.non_1zst_field(self).expect(
715                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
716                            );
717                            receiver = self.project_field(&receiver, idx)?;
718                        }
719                    }
720                };
721
722                // Obtain the underlying trait we are working on, and the adjusted receiver argument.
723                // Doesn't have to be a `dyn Trait`, but the unsized tail must be `dyn Trait`.
724                // (For that reason we also cannot use `unpack_dyn_trait`.)
725                let receiver_tail =
726                    self.tcx.struct_tail_for_codegen(receiver_place.layout.ty, self.typing_env);
727                let ty::Dynamic(receiver_trait, _) = receiver_tail.kind() else {
728                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("dynamic call on non-`dyn` type {0}", receiver_tail))span_bug!(self.cur_span(), "dynamic call on non-`dyn` type {}", receiver_tail)
729                };
730                if !receiver_place.layout.is_unsized() {
    ::core::panicking::panic("assertion failed: receiver_place.layout.is_unsized()")
};assert!(receiver_place.layout.is_unsized());
731
732                // Get the required information from the vtable.
733                let vptr = receiver_place.meta().unwrap_meta().to_pointer(self)?;
734                let dyn_ty = self.get_ptr_vtable_ty(vptr, Some(receiver_trait))?;
735                let adjusted_recv = receiver_place.ptr();
736
737                // Now determine the actual method to call. Usually we use the easy way of just
738                // looking up the method at index `idx`.
739                let vtable_entries = self.vtable_entries(receiver_trait.principal(), dyn_ty);
740                let Some(ty::VtblEntry::Method(fn_inst)) = vtable_entries.get(idx).copied() else {
741                    // FIXME(fee1-dead) these could be variants of the UB info enum instead of this
742                    do yeet {
        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                    msg: ||
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`dyn` call trying to call something that is not a method")),
                    add_args: Box::new(move |mut set_arg| {}),
                }))
    };throw_ub_custom!(msg!(
743                        "`dyn` call trying to call something that is not a method"
744                    ));
745                };
746                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:746",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(746u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Virtual call dispatches to {0:#?}",
                                                    fn_inst) as &dyn Value))])
            });
    } else { ; }
};trace!("Virtual call dispatches to {fn_inst:#?}");
747                // We can also do the lookup based on `def_id` and `dyn_ty`, and check that that
748                // produces the same result.
749                self.assert_virtual_instance_matches_concrete(dyn_ty, def_id, instance, fn_inst);
750
751                // Adjust receiver argument. Layout can be any (thin) ptr.
752                let receiver_ty = Ty::new_mut_ptr(self.tcx.tcx, dyn_ty);
753                args[0] = FnArg::Copy(
754                    ImmTy::from_immediate(
755                        Scalar::from_maybe_pointer(adjusted_recv, self).into(),
756                        self.layout_of(receiver_ty)?,
757                    )
758                    .into(),
759                );
760                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:760",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(760u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Patched receiver operand to {0:#?}",
                                                    args[0]) as &dyn Value))])
            });
    } else { ; }
};trace!("Patched receiver operand to {:#?}", args[0]);
761                // Need to also adjust the type in the ABI. Strangely, the layout there is actually
762                // already fine! Just the type is bogus. This is due to what `force_thin_self_ptr`
763                // does in `fn_abi_new_uncached`; supposedly, codegen relies on having the bogus
764                // type, so we just patch this up locally.
765                let mut caller_fn_abi = caller_fn_abi.clone();
766                caller_fn_abi.args[0].layout.ty = receiver_ty;
767
768                // recurse with concrete function
769                self.init_fn_call(
770                    FnVal::Instance(fn_inst),
771                    (caller_abi, &caller_fn_abi),
772                    &args,
773                    with_caller_location,
774                    destination,
775                    target,
776                    unwind,
777                )
778            }
779        }
780    }
781
782    fn assert_virtual_instance_matches_concrete(
783        &self,
784        dyn_ty: Ty<'tcx>,
785        def_id: DefId,
786        virtual_instance: ty::Instance<'tcx>,
787        concrete_instance: ty::Instance<'tcx>,
788    ) {
789        let tcx = *self.tcx;
790
791        let trait_def_id = tcx.parent(def_id);
792        let virtual_trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, virtual_instance.args);
793        let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref);
794        let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty);
795
796        let concrete_method = {
797            let _trace = <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("resolve",
                                "rustc_const_eval::interpret::call", ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                ::tracing_core::__macro_support::Option::Some(797u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                ::tracing_core::field::FieldSet::new(&["resolve", "def_id"],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = meta.fields().iter();
                            meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&display(&"expect_resolve_for_vtable")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&def_id) as
                                                        &dyn Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, resolve::expect_resolve_for_vtable, ?def_id);
798            Instance::expect_resolve_for_vtable(
799                tcx,
800                self.typing_env,
801                def_id,
802                virtual_instance.args.rebase_onto(tcx, trait_def_id, concrete_trait_ref.args),
803                self.cur_span(),
804            )
805        };
806        match (&concrete_instance, &concrete_method) {
    (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!(concrete_instance, concrete_method);
807    }
808
809    /// Initiate a tail call to this function -- popping the current stack frame, pushing the new
810    /// stack frame and initializing the arguments.
811    pub(super) fn init_fn_tail_call(
812        &mut self,
813        fn_val: FnVal<'tcx, M::ExtraFnVal>,
814        (caller_abi, caller_fn_abi): (ExternAbi, &FnAbi<'tcx, Ty<'tcx>>),
815        args: &[FnArg<'tcx, M::Provenance>],
816        with_caller_location: bool,
817    ) -> InterpResult<'tcx> {
818        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:818",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(818u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("init_fn_tail_call: {0:#?}",
                                                    fn_val) as &dyn Value))])
            });
    } else { ; }
};trace!("init_fn_tail_call: {:#?}", fn_val);
819        // This is the "canonical" implementation of tails calls,
820        // a pop of the current stack frame, followed by a normal call
821        // which pushes a new stack frame, with the return address from
822        // the popped stack frame.
823        //
824        // Note that we cannot use `return_from_current_stack_frame`,
825        // as that "executes" the goto to the return block, but we don't want to,
826        // only the tail called function should return to the current return block.
827
828        // The arguments need to all be copied since the current stack frame will be removed
829        // before the callee even starts executing.
830        // FIXME(explicit_tail_calls,#144855): does this match what codegen does?
831        let args = args.iter().map(|fn_arg| FnArg::Copy(fn_arg.copy_fn_arg())).collect::<Vec<_>>();
832        // Remove the frame from the stack.
833        let frame = self.pop_stack_frame_raw()?;
834        // Remember where this frame would have returned to.
835        let ReturnContinuation::Goto { ret, unwind } = frame.return_cont() else {
836            ::rustc_middle::util::bug::bug_fmt(format_args!("can\'t tailcall as root of the stack"));bug!("can't tailcall as root of the stack");
837        };
838        // There's no return value to deal with! Instead, we forward the old return place
839        // to the new function.
840        // FIXME(explicit_tail_calls):
841        //   we should check if both caller&callee can/n't unwind,
842        //   see <https://github.com/rust-lang/rust/pull/113128#issuecomment-1614979803>
843
844        // Now push the new stack frame.
845        self.init_fn_call(
846            fn_val,
847            (caller_abi, caller_fn_abi),
848            &*args,
849            with_caller_location,
850            frame.return_place(),
851            ret,
852            unwind,
853        )?;
854
855        // Finally, clear the local variables. Has to be done after pushing to support
856        // non-scalar arguments.
857        // FIXME(explicit_tail_calls,#144855): revisit this once codegen supports indirect
858        // arguments, to ensure the semantics are compatible.
859        let return_action = self.cleanup_stack_frame(/* unwinding */ false, frame)?;
860        match (&return_action, &ReturnAction::Normal) {
    (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!(return_action, ReturnAction::Normal);
861
862        interp_ok(())
863    }
864
865    pub(super) fn init_drop_in_place_call(
866        &mut self,
867        place: &PlaceTy<'tcx, M::Provenance>,
868        instance: ty::Instance<'tcx>,
869        target: mir::BasicBlock,
870        unwind: mir::UnwindAction,
871    ) -> InterpResult<'tcx> {
872        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:872",
                        "rustc_const_eval::interpret::call",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                        ::tracing_core::__macro_support::Option::Some(872u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("init_drop_in_place_call: {0:?},\n  instance={1:?}",
                                                    place, instance) as &dyn Value))])
            });
    } else { ; }
};trace!("init_drop_in_place_call: {:?},\n  instance={:?}", place, instance);
873        // We take the address of the object. This may well be unaligned, which is fine
874        // for us here. However, unaligned accesses will probably make the actual drop
875        // implementation fail -- a problem shared by rustc.
876        let place = self.force_allocation(place)?;
877
878        // We behave a bit different from codegen here.
879        // Codegen creates an `InstanceKind::Virtual` with index 0 (the slot of the drop method) and
880        // then dispatches that to the normal call machinery. However, our call machinery currently
881        // only supports calling `VtblEntry::Method`; it would choke on a `MetadataDropInPlace`. So
882        // instead we do the virtual call stuff ourselves. It's easier here than in `eval_fn_call`
883        // since we can just get a place of the underlying type and use `mplace_to_ref`.
884        let place = match place.layout.ty.kind() {
885            ty::Dynamic(data, _) => {
886                // Dropping a trait object. Need to find actual drop fn.
887                self.unpack_dyn_trait(&place, data)?
888            }
889            _ => {
890                if true {
    match (&instance,
            &ty::Instance::resolve_drop_in_place(*self.tcx, place.layout.ty))
        {
        (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);
            }
        }
    };
};debug_assert_eq!(
891                    instance,
892                    ty::Instance::resolve_drop_in_place(*self.tcx, place.layout.ty)
893                );
894                place
895            }
896        };
897        let instance = {
898            let _trace =
899                <M as
        crate::interpret::Machine>::enter_trace_span(||
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("resolve",
                                "rustc_const_eval::interpret::call", ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                ::tracing_core::__macro_support::Option::Some(899u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                ::tracing_core::field::FieldSet::new(&["resolve", "ty"],
                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = meta.fields().iter();
                            meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&display(&"resolve_drop_in_place")
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&place.layout.ty)
                                                        as &dyn Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        })enter_trace_span!(M, resolve::resolve_drop_in_place, ty = ?place.layout.ty);
900            ty::Instance::resolve_drop_in_place(*self.tcx, place.layout.ty)
901        };
902        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty())?;
903
904        let arg = self.mplace_to_ref(&place)?;
905        let ret = MPlaceTy::fake_alloc_zst(self.layout_of(self.tcx.types.unit)?);
906
907        self.init_fn_call(
908            FnVal::Instance(instance),
909            (ExternAbi::Rust, fn_abi),
910            &[FnArg::Copy(arg.into())],
911            false,
912            &ret.into(),
913            Some(target),
914            unwind,
915        )
916    }
917
918    /// Pops the current frame from the stack, copies the return value to the caller, deallocates
919    /// the memory for allocated locals, and jumps to an appropriate place.
920    ///
921    /// If `unwinding` is `false`, then we are performing a normal return
922    /// from a function. In this case, we jump back into the frame of the caller,
923    /// and continue execution as normal.
924    ///
925    /// If `unwinding` is `true`, then we are in the middle of a panic,
926    /// and need to unwind this frame. In this case, we jump to the
927    /// `cleanup` block for the function, which is responsible for running
928    /// `Drop` impls for any locals that have been initialized at this point.
929    /// The cleanup block ends with a special `Resume` terminator, which will
930    /// cause us to continue unwinding.
931    #[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("return_from_current_stack_frame",
                                    "rustc_const_eval::interpret::call",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                    ::tracing_core::__macro_support::Option::Some(931u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                    ::tracing_core::field::FieldSet::new(&["unwinding"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&unwinding as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:936",
                                    "rustc_const_eval::interpret::call", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                    ::tracing_core::__macro_support::Option::Some(936u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("popping stack frame ({0})",
                                                                if unwinding {
                                                                    "during unwinding"
                                                                } else { "returning from function" }) as &dyn Value))])
                        });
                } else { ; }
            };
            match (&unwinding,
                    &match self.frame().loc {
                            Left(loc) => self.body().basic_blocks[loc.block].is_cleanup,
                            Right(_) => true,
                        }) {
                (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);
                    }
                }
            };
            if unwinding && self.frame_idx() == 0 {
                do yeet {
                        ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
                                    msg: ||
                                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unwinding past the topmost frame of the stack")),
                                    add_args: Box::new(move |mut set_arg| {}),
                                }))
                    };
            }
            let return_op =
                self.local_to_op(mir::RETURN_PLACE,
                        None).expect("return place should always be live");
            let frame = self.pop_stack_frame_raw()?;
            if !unwinding {
                self.copy_op_allow_transmute(&return_op,
                        frame.return_place())?;
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/call.rs:962",
                                        "rustc_const_eval::interpret::call",
                                        ::tracing::Level::TRACE,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/call.rs"),
                                        ::tracing_core::__macro_support::Option::Some(962u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("return value: {0:?}",
                                                                    self.dump_place(frame.return_place())) as &dyn Value))])
                            });
                    } else { ; }
                };
            }
            let return_cont = frame.return_cont();
            let return_action = self.cleanup_stack_frame(unwinding, frame)?;
            match return_action {
                ReturnAction::Normal => {}
                ReturnAction::NoJump => { return interp_ok(()); }
                ReturnAction::NoCleanup => {
                    if !self.stack().is_empty() {
                        {
                            ::core::panicking::panic_fmt(format_args!("only the topmost frame should ever be leaked"));
                        }
                    };
                    if !!unwinding {
                        {
                            ::core::panicking::panic_fmt(format_args!("tried to skip cleanup during unwinding"));
                        }
                    };
                    return interp_ok(());
                }
            }
            if unwinding {
                match return_cont {
                    ReturnContinuation::Goto { unwind, .. } => {
                        self.unwind_to_block(unwind)
                    }
                    ReturnContinuation::Stop { .. } => {
                        {
                            ::core::panicking::panic_fmt(format_args!("encountered ReturnContinuation::Stop when unwinding!"));
                        }
                    }
                }
            } else {
                match return_cont {
                    ReturnContinuation::Goto { ret, .. } =>
                        self.return_to_block(ret),
                    ReturnContinuation::Stop { .. } => {
                        if !self.stack().is_empty() {
                            {
                                ::core::panicking::panic_fmt(format_args!("only the bottommost frame can have ReturnContinuation::Stop"));
                            }
                        };
                        interp_ok(())
                    }
                }
            }
        }
    }
}#[instrument(skip(self), level = "trace")]
932    pub(super) fn return_from_current_stack_frame(
933        &mut self,
934        unwinding: bool,
935    ) -> InterpResult<'tcx> {
936        info!(
937            "popping stack frame ({})",
938            if unwinding { "during unwinding" } else { "returning from function" }
939        );
940
941        // Check `unwinding`.
942        assert_eq!(
943            unwinding,
944            match self.frame().loc {
945                Left(loc) => self.body().basic_blocks[loc.block].is_cleanup,
946                Right(_) => true,
947            }
948        );
949        if unwinding && self.frame_idx() == 0 {
950            throw_ub_custom!(msg!("unwinding past the topmost frame of the stack"));
951        }
952
953        // Get out the return value. Must happen *before* the frame is popped as we have to get the
954        // local's value out.
955        let return_op =
956            self.local_to_op(mir::RETURN_PLACE, None).expect("return place should always be live");
957        // Remove the frame from the stack.
958        let frame = self.pop_stack_frame_raw()?;
959        // Copy the return value and remember the return continuation.
960        if !unwinding {
961            self.copy_op_allow_transmute(&return_op, frame.return_place())?;
962            trace!("return value: {:?}", self.dump_place(frame.return_place()));
963        }
964        let return_cont = frame.return_cont();
965        // Finish popping the stack frame.
966        let return_action = self.cleanup_stack_frame(unwinding, frame)?;
967        // Jump to the next block.
968        match return_action {
969            ReturnAction::Normal => {}
970            ReturnAction::NoJump => {
971                // The hook already did everything.
972                return interp_ok(());
973            }
974            ReturnAction::NoCleanup => {
975                // If we are not doing cleanup, also skip everything else.
976                assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
977                assert!(!unwinding, "tried to skip cleanup during unwinding");
978                // Don't jump anywhere.
979                return interp_ok(());
980            }
981        }
982
983        // Normal return, figure out where to jump.
984        if unwinding {
985            // Follow the unwind edge.
986            match return_cont {
987                ReturnContinuation::Goto { unwind, .. } => {
988                    // This must be the very last thing that happens, since it can in fact push a new stack frame.
989                    self.unwind_to_block(unwind)
990                }
991                ReturnContinuation::Stop { .. } => {
992                    panic!("encountered ReturnContinuation::Stop when unwinding!")
993                }
994            }
995        } else {
996            // Follow the normal return edge.
997            match return_cont {
998                ReturnContinuation::Goto { ret, .. } => self.return_to_block(ret),
999                ReturnContinuation::Stop { .. } => {
1000                    assert!(
1001                        self.stack().is_empty(),
1002                        "only the bottommost frame can have ReturnContinuation::Stop"
1003                    );
1004                    interp_ok(())
1005                }
1006            }
1007        }
1008    }
1009}