Skip to main content

rustc_middle/ty/
instance.rs

1use std::{assert_matches, fmt};
2
3use rustc_data_structures::fx::FxHashMap;
4use rustc_errors::ErrorGuaranteed;
5use rustc_hir as hir;
6use rustc_hir::def::{CtorKind, DefKind, Namespace};
7use rustc_hir::def_id::{CrateNum, DefId};
8use rustc_hir::lang_items::LangItem;
9use rustc_macros::{Lift, StableHash, TyDecodable, TyEncodable};
10use rustc_span::def_id::LOCAL_CRATE;
11use rustc_span::{DUMMY_SP, Span};
12use tracing::{debug, instrument};
13
14use crate::error;
15use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
16use crate::ty::normalize_erasing_regions::NormalizationError;
17use crate::ty::print::{FmtPrinter, Print};
18use crate::ty::{
19    self, AssocContainer, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
20    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
21};
22
23/// An `InstanceKind` along with the args that are needed to substitute the instance.
24///
25/// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type
26/// simply couples a potentially generic `InstanceKind` with some args, and codegen and const eval
27/// will do all required instantiations as they run.
28///
29/// Note: the `Lift` impl is currently not used by rustc, but is used by
30/// rustc_codegen_cranelift when the `jit` feature is enabled.
31#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Instance<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Instance<'tcx> {
    #[inline]
    fn clone(&self) -> Instance<'tcx> {
        let _: ::core::clone::AssertParamIsClone<InstanceKind<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for Instance<'tcx> {
    #[inline]
    fn eq(&self, other: &Instance<'tcx>) -> bool {
        self.def == other.def && self.args == other.args
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for Instance<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<InstanceKind<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<GenericArgsRef<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for Instance<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.def, state);
        ::core::hash::Hash::hash(&self.args, state)
    }
}Hash, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Instance<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Instance",
            "def", &self.def, "args", &&self.args)
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Instance<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Instance { def: ref __binding_0, args: ref __binding_1 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Instance<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                Instance {
                    def: ::rustc_serialize::Decodable::decode(__decoder),
                    args: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
32#[derive(const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Instance<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Instance { def: ref __binding_0, args: ref __binding_1 } =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, '__lifted>
            ::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>
            for Instance<'tcx> {
            type Lifted = Instance<'__lifted>;
            fn lift_to_interner(self,
                __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
                -> Instance<'__lifted> {
                match self {
                    Instance { def: __binding_0, args: __binding_1 } => {
                        Instance {
                            def: __tcx.lift(__binding_0),
                            args: __tcx.lift(__binding_1),
                        }
                    }
                }
            }
        }
    };Lift, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Instance<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        Instance { def: __binding_0, args: __binding_1 } => {
                            Instance {
                                def: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                args: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Instance { def: __binding_0, args: __binding_1 } => {
                        Instance {
                            def: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            args: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Instance<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    Instance { def: ref __binding_0, args: ref __binding_1 } =>
                        {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
33pub struct Instance<'tcx> {
34    pub def: InstanceKind<'tcx>,
35    pub args: GenericArgsRef<'tcx>,
36}
37
38/// Describes why a `ReifyShim` was created. This is needed to distinguish a ReifyShim created to
39/// adjust for things like `#[track_caller]` in a vtable from a `ReifyShim` created to produce a
40/// function pointer from a vtable entry.
41/// Currently, this is only used when KCFI is enabled, as only KCFI needs to treat those two
42/// `ReifyShim`s differently.
43#[derive(#[automatically_derived]
impl ::core::marker::Copy for ReifyReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReifyReason {
    #[inline]
    fn clone(&self) -> ReifyReason { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReifyReason {
    #[inline]
    fn eq(&self, other: &ReifyReason) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReifyReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ReifyReason {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for ReifyReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ReifyReason::FnPtr => "FnPtr",
                ReifyReason::Vtable => "Vtable",
            })
    }
}Debug)]
44#[derive(const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ReifyReason {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        ReifyReason::FnPtr => { 0usize }
                        ReifyReason::Vtable => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    ReifyReason::FnPtr => {}
                    ReifyReason::Vtable => {}
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ReifyReason {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { ReifyReason::FnPtr }
                    1usize => { ReifyReason::Vtable }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ReifyReason`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ReifyReason
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    ReifyReason::FnPtr => {}
                    ReifyReason::Vtable => {}
                }
            }
        }
    };StableHash)]
45pub enum ReifyReason {
46    /// The `ReifyShim` was created to produce a function pointer. This happens when:
47    /// * A vtable entry is directly converted to a function call (e.g. creating a fn ptr from a
48    ///   method on a `dyn` object).
49    /// * A function with `#[track_caller]` is converted to a function pointer
50    /// * If KCFI is enabled, creating a function pointer from a method on a dyn-compatible trait.
51    /// This includes the case of converting `::call`-like methods on closure-likes to function
52    /// pointers.
53    FnPtr,
54    /// This `ReifyShim` was created to populate a vtable. Currently, this happens when a
55    /// `#[track_caller]` mismatch occurs between the implementation of a method and the method.
56    /// This includes the case of `::call`-like methods in closure-likes' vtables.
57    Vtable,
58}
59
60#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for InstanceKind<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for InstanceKind<'tcx> {
    #[inline]
    fn clone(&self) -> InstanceKind<'tcx> {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<Option<ReifyReason>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<Ty<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for InstanceKind<'tcx> {
    #[inline]
    fn eq(&self, other: &InstanceKind<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (InstanceKind::Item(__self_0), InstanceKind::Item(__arg1_0))
                    => __self_0 == __arg1_0,
                (InstanceKind::Intrinsic(__self_0),
                    InstanceKind::Intrinsic(__arg1_0)) => __self_0 == __arg1_0,
                (InstanceKind::VTableShim(__self_0),
                    InstanceKind::VTableShim(__arg1_0)) => __self_0 == __arg1_0,
                (InstanceKind::ReifyShim(__self_0, __self_1),
                    InstanceKind::ReifyShim(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::FnPtrShim(__self_0, __self_1),
                    InstanceKind::FnPtrShim(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::Virtual(__self_0, __self_1),
                    InstanceKind::Virtual(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::ClosureOnceShim {
                    call_once: __self_0, track_caller: __self_1 },
                    InstanceKind::ClosureOnceShim {
                    call_once: __arg1_0, track_caller: __arg1_1 }) =>
                    __self_1 == __arg1_1 && __self_0 == __arg1_0,
                (InstanceKind::ConstructCoroutineInClosureShim {
                    coroutine_closure_def_id: __self_0,
                    receiver_by_ref: __self_1 },
                    InstanceKind::ConstructCoroutineInClosureShim {
                    coroutine_closure_def_id: __arg1_0,
                    receiver_by_ref: __arg1_1 }) =>
                    __self_1 == __arg1_1 && __self_0 == __arg1_0,
                (InstanceKind::ThreadLocalShim(__self_0),
                    InstanceKind::ThreadLocalShim(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (InstanceKind::FutureDropPollShim(__self_0, __self_1,
                    __self_2),
                    InstanceKind::FutureDropPollShim(__arg1_0, __arg1_1,
                    __arg1_2)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                (InstanceKind::DropGlue(__self_0, __self_1),
                    InstanceKind::DropGlue(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::CloneShim(__self_0, __self_1),
                    InstanceKind::CloneShim(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::FnPtrAddrShim(__self_0, __self_1),
                    InstanceKind::FnPtrAddrShim(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::AsyncDropGlueCtorShim(__self_0, __self_1),
                    InstanceKind::AsyncDropGlueCtorShim(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (InstanceKind::AsyncDropGlue(__self_0, __self_1),
                    InstanceKind::AsyncDropGlue(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for InstanceKind<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<Option<ReifyReason>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Option<Ty<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for InstanceKind<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            InstanceKind::Item(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            InstanceKind::Intrinsic(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            InstanceKind::VTableShim(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            InstanceKind::ReifyShim(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::FnPtrShim(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::Virtual(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::ClosureOnceShim {
                call_once: __self_0, track_caller: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::ConstructCoroutineInClosureShim {
                coroutine_closure_def_id: __self_0, receiver_by_ref: __self_1
                } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::ThreadLocalShim(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            InstanceKind::FutureDropPollShim(__self_0, __self_1, __self_2) =>
                {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
            InstanceKind::DropGlue(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::CloneShim(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::FnPtrAddrShim(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::AsyncDropGlueCtorShim(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            InstanceKind::AsyncDropGlue(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
        }
    }
}Hash, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstanceKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            InstanceKind::Item(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
                    &__self_0),
            InstanceKind::Intrinsic(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Intrinsic", &__self_0),
            InstanceKind::VTableShim(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "VTableShim", &__self_0),
            InstanceKind::ReifyShim(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ReifyShim", __self_0, &__self_1),
            InstanceKind::FnPtrShim(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "FnPtrShim", __self_0, &__self_1),
            InstanceKind::Virtual(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Virtual", __self_0, &__self_1),
            InstanceKind::ClosureOnceShim {
                call_once: __self_0, track_caller: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ClosureOnceShim", "call_once", __self_0, "track_caller",
                    &__self_1),
            InstanceKind::ConstructCoroutineInClosureShim {
                coroutine_closure_def_id: __self_0, receiver_by_ref: __self_1
                } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ConstructCoroutineInClosureShim",
                    "coroutine_closure_def_id", __self_0, "receiver_by_ref",
                    &__self_1),
            InstanceKind::ThreadLocalShim(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ThreadLocalShim", &__self_0),
            InstanceKind::FutureDropPollShim(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "FutureDropPollShim", __self_0, __self_1, &__self_2),
            InstanceKind::DropGlue(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "DropGlue", __self_0, &__self_1),
            InstanceKind::CloneShim(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "CloneShim", __self_0, &__self_1),
            InstanceKind::FnPtrAddrShim(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "FnPtrAddrShim", __self_0, &__self_1),
            InstanceKind::AsyncDropGlueCtorShim(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AsyncDropGlueCtorShim", __self_0, &__self_1),
            InstanceKind::AsyncDropGlue(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AsyncDropGlue", __self_0, &__self_1),
        }
    }
}Debug)]
61#[derive(const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for InstanceKind<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        InstanceKind::Item(ref __binding_0) => { 0usize }
                        InstanceKind::Intrinsic(ref __binding_0) => { 1usize }
                        InstanceKind::VTableShim(ref __binding_0) => { 2usize }
                        InstanceKind::ReifyShim(ref __binding_0, ref __binding_1) =>
                            {
                            3usize
                        }
                        InstanceKind::FnPtrShim(ref __binding_0, ref __binding_1) =>
                            {
                            4usize
                        }
                        InstanceKind::Virtual(ref __binding_0, ref __binding_1) => {
                            5usize
                        }
                        InstanceKind::ClosureOnceShim {
                            call_once: ref __binding_0, track_caller: ref __binding_1 }
                            => {
                            6usize
                        }
                        InstanceKind::ConstructCoroutineInClosureShim {
                            coroutine_closure_def_id: ref __binding_0,
                            receiver_by_ref: ref __binding_1 } => {
                            7usize
                        }
                        InstanceKind::ThreadLocalShim(ref __binding_0) => { 8usize }
                        InstanceKind::FutureDropPollShim(ref __binding_0,
                            ref __binding_1, ref __binding_2) => {
                            9usize
                        }
                        InstanceKind::DropGlue(ref __binding_0, ref __binding_1) =>
                            {
                            10usize
                        }
                        InstanceKind::CloneShim(ref __binding_0, ref __binding_1) =>
                            {
                            11usize
                        }
                        InstanceKind::FnPtrAddrShim(ref __binding_0,
                            ref __binding_1) => {
                            12usize
                        }
                        InstanceKind::AsyncDropGlueCtorShim(ref __binding_0,
                            ref __binding_1) => {
                            13usize
                        }
                        InstanceKind::AsyncDropGlue(ref __binding_0,
                            ref __binding_1) => {
                            14usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    InstanceKind::Item(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    InstanceKind::Intrinsic(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    InstanceKind::VTableShim(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    InstanceKind::ReifyShim(ref __binding_0, ref __binding_1) =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::FnPtrShim(ref __binding_0, ref __binding_1) =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::Virtual(ref __binding_0, ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::ClosureOnceShim {
                        call_once: ref __binding_0, track_caller: ref __binding_1 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::ConstructCoroutineInClosureShim {
                        coroutine_closure_def_id: ref __binding_0,
                        receiver_by_ref: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::ThreadLocalShim(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    InstanceKind::FutureDropPollShim(ref __binding_0,
                        ref __binding_1, ref __binding_2) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                    }
                    InstanceKind::DropGlue(ref __binding_0, ref __binding_1) =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::CloneShim(ref __binding_0, ref __binding_1) =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::FnPtrAddrShim(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::AsyncDropGlueCtorShim(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    InstanceKind::AsyncDropGlue(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for InstanceKind<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        InstanceKind::Item(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        InstanceKind::Intrinsic(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        InstanceKind::VTableShim(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    3usize => {
                        InstanceKind::ReifyShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    4usize => {
                        InstanceKind::FnPtrShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    5usize => {
                        InstanceKind::Virtual(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    6usize => {
                        InstanceKind::ClosureOnceShim {
                            call_once: ::rustc_serialize::Decodable::decode(__decoder),
                            track_caller: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    7usize => {
                        InstanceKind::ConstructCoroutineInClosureShim {
                            coroutine_closure_def_id: ::rustc_serialize::Decodable::decode(__decoder),
                            receiver_by_ref: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    8usize => {
                        InstanceKind::ThreadLocalShim(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    9usize => {
                        InstanceKind::FutureDropPollShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    10usize => {
                        InstanceKind::DropGlue(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    11usize => {
                        InstanceKind::CloneShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    12usize => {
                        InstanceKind::FnPtrAddrShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    13usize => {
                        InstanceKind::AsyncDropGlueCtorShim(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    14usize => {
                        InstanceKind::AsyncDropGlue(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `InstanceKind`, expected 0..15, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            InstanceKind<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    InstanceKind::Item(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::Intrinsic(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::VTableShim(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::ReifyShim(ref __binding_0, ref __binding_1) =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::FnPtrShim(ref __binding_0, ref __binding_1) =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::Virtual(ref __binding_0, ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::ClosureOnceShim {
                        call_once: ref __binding_0, track_caller: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::ConstructCoroutineInClosureShim {
                        coroutine_closure_def_id: ref __binding_0,
                        receiver_by_ref: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::ThreadLocalShim(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::FutureDropPollShim(ref __binding_0,
                        ref __binding_1, ref __binding_2) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::DropGlue(ref __binding_0, ref __binding_1) =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::CloneShim(ref __binding_0, ref __binding_1) =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::FnPtrAddrShim(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::AsyncDropGlueCtorShim(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    InstanceKind::AsyncDropGlue(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InstanceKind<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        InstanceKind::Item(__binding_0) => {
                            InstanceKind::Item(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        InstanceKind::Intrinsic(__binding_0) => {
                            InstanceKind::Intrinsic(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        InstanceKind::VTableShim(__binding_0) => {
                            InstanceKind::VTableShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        InstanceKind::ReifyShim(__binding_0, __binding_1) => {
                            InstanceKind::ReifyShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::FnPtrShim(__binding_0, __binding_1) => {
                            InstanceKind::FnPtrShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::Virtual(__binding_0, __binding_1) => {
                            InstanceKind::Virtual(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::ClosureOnceShim {
                            call_once: __binding_0, track_caller: __binding_1 } => {
                            InstanceKind::ClosureOnceShim {
                                call_once: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                track_caller: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                        InstanceKind::ConstructCoroutineInClosureShim {
                            coroutine_closure_def_id: __binding_0,
                            receiver_by_ref: __binding_1 } => {
                            InstanceKind::ConstructCoroutineInClosureShim {
                                coroutine_closure_def_id: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                receiver_by_ref: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                        InstanceKind::ThreadLocalShim(__binding_0) => {
                            InstanceKind::ThreadLocalShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        InstanceKind::FutureDropPollShim(__binding_0, __binding_1,
                            __binding_2) => {
                            InstanceKind::FutureDropPollShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?)
                        }
                        InstanceKind::DropGlue(__binding_0, __binding_1) => {
                            InstanceKind::DropGlue(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::CloneShim(__binding_0, __binding_1) => {
                            InstanceKind::CloneShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::FnPtrAddrShim(__binding_0, __binding_1) => {
                            InstanceKind::FnPtrAddrShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::AsyncDropGlueCtorShim(__binding_0,
                            __binding_1) => {
                            InstanceKind::AsyncDropGlueCtorShim(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        InstanceKind::AsyncDropGlue(__binding_0, __binding_1) => {
                            InstanceKind::AsyncDropGlue(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    InstanceKind::Item(__binding_0) => {
                        InstanceKind::Item(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    InstanceKind::Intrinsic(__binding_0) => {
                        InstanceKind::Intrinsic(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    InstanceKind::VTableShim(__binding_0) => {
                        InstanceKind::VTableShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    InstanceKind::ReifyShim(__binding_0, __binding_1) => {
                        InstanceKind::ReifyShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::FnPtrShim(__binding_0, __binding_1) => {
                        InstanceKind::FnPtrShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::Virtual(__binding_0, __binding_1) => {
                        InstanceKind::Virtual(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::ClosureOnceShim {
                        call_once: __binding_0, track_caller: __binding_1 } => {
                        InstanceKind::ClosureOnceShim {
                            call_once: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            track_caller: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                    InstanceKind::ConstructCoroutineInClosureShim {
                        coroutine_closure_def_id: __binding_0,
                        receiver_by_ref: __binding_1 } => {
                        InstanceKind::ConstructCoroutineInClosureShim {
                            coroutine_closure_def_id: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            receiver_by_ref: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                    InstanceKind::ThreadLocalShim(__binding_0) => {
                        InstanceKind::ThreadLocalShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    InstanceKind::FutureDropPollShim(__binding_0, __binding_1,
                        __binding_2) => {
                        InstanceKind::FutureDropPollShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder))
                    }
                    InstanceKind::DropGlue(__binding_0, __binding_1) => {
                        InstanceKind::DropGlue(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::CloneShim(__binding_0, __binding_1) => {
                        InstanceKind::CloneShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::FnPtrAddrShim(__binding_0, __binding_1) => {
                        InstanceKind::FnPtrAddrShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::AsyncDropGlueCtorShim(__binding_0,
                        __binding_1) => {
                        InstanceKind::AsyncDropGlueCtorShim(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    InstanceKind::AsyncDropGlue(__binding_0, __binding_1) => {
                        InstanceKind::AsyncDropGlue(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InstanceKind<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    InstanceKind::Item(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::Intrinsic(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::VTableShim(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::ReifyShim(ref __binding_0, ref __binding_1) =>
                        {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::FnPtrShim(ref __binding_0, ref __binding_1) =>
                        {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::Virtual(ref __binding_0, ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::ClosureOnceShim {
                        call_once: ref __binding_0, track_caller: ref __binding_1 }
                        => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::ConstructCoroutineInClosureShim {
                        coroutine_closure_def_id: ref __binding_0,
                        receiver_by_ref: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::ThreadLocalShim(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::FutureDropPollShim(ref __binding_0,
                        ref __binding_1, ref __binding_2) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::DropGlue(ref __binding_0, ref __binding_1) =>
                        {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::CloneShim(ref __binding_0, ref __binding_1) =>
                        {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::FnPtrAddrShim(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::AsyncDropGlueCtorShim(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    InstanceKind::AsyncDropGlue(ref __binding_0,
                        ref __binding_1) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx, '__lifted>
            ::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>
            for InstanceKind<'tcx> {
            type Lifted = InstanceKind<'__lifted>;
            fn lift_to_interner(self,
                __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>)
                -> InstanceKind<'__lifted> {
                match self {
                    InstanceKind::Item(__binding_0) => {
                        InstanceKind::Item(__tcx.lift(__binding_0))
                    }
                    InstanceKind::Intrinsic(__binding_0) => {
                        InstanceKind::Intrinsic(__tcx.lift(__binding_0))
                    }
                    InstanceKind::VTableShim(__binding_0) => {
                        InstanceKind::VTableShim(__tcx.lift(__binding_0))
                    }
                    InstanceKind::ReifyShim(__binding_0, __binding_1) => {
                        InstanceKind::ReifyShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::FnPtrShim(__binding_0, __binding_1) => {
                        InstanceKind::FnPtrShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::Virtual(__binding_0, __binding_1) => {
                        InstanceKind::Virtual(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::ClosureOnceShim {
                        call_once: __binding_0, track_caller: __binding_1 } => {
                        InstanceKind::ClosureOnceShim {
                            call_once: __tcx.lift(__binding_0),
                            track_caller: __tcx.lift(__binding_1),
                        }
                    }
                    InstanceKind::ConstructCoroutineInClosureShim {
                        coroutine_closure_def_id: __binding_0,
                        receiver_by_ref: __binding_1 } => {
                        InstanceKind::ConstructCoroutineInClosureShim {
                            coroutine_closure_def_id: __tcx.lift(__binding_0),
                            receiver_by_ref: __tcx.lift(__binding_1),
                        }
                    }
                    InstanceKind::ThreadLocalShim(__binding_0) => {
                        InstanceKind::ThreadLocalShim(__tcx.lift(__binding_0))
                    }
                    InstanceKind::FutureDropPollShim(__binding_0, __binding_1,
                        __binding_2) => {
                        InstanceKind::FutureDropPollShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1), __tcx.lift(__binding_2))
                    }
                    InstanceKind::DropGlue(__binding_0, __binding_1) => {
                        InstanceKind::DropGlue(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::CloneShim(__binding_0, __binding_1) => {
                        InstanceKind::CloneShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::FnPtrAddrShim(__binding_0, __binding_1) => {
                        InstanceKind::FnPtrAddrShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::AsyncDropGlueCtorShim(__binding_0,
                        __binding_1) => {
                        InstanceKind::AsyncDropGlueCtorShim(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                    InstanceKind::AsyncDropGlue(__binding_0, __binding_1) => {
                        InstanceKind::AsyncDropGlue(__tcx.lift(__binding_0),
                            __tcx.lift(__binding_1))
                    }
                }
            }
        }
    };Lift)]
62pub enum InstanceKind<'tcx> {
63    /// A user-defined callable item.
64    ///
65    /// This includes:
66    /// - `fn` items
67    /// - closures
68    /// - coroutines
69    Item(DefId),
70
71    /// An intrinsic `fn` item (with`#[rustc_intrinsic]`).
72    ///
73    /// Alongside `Virtual`, this is the only `InstanceKind` that does not have its own callable MIR.
74    /// Instead, codegen and const eval "magically" evaluate calls to intrinsics purely in the
75    /// caller.
76    Intrinsic(DefId),
77
78    /// `<T as Trait>::method` where `method` receives unsizeable `self: Self` (part of the
79    /// `unsized_fn_params` feature).
80    ///
81    /// The generated shim will take `Self` via `*mut Self` - conceptually this is `&owned Self` -
82    /// and dereference the argument to call the original function.
83    VTableShim(DefId),
84
85    /// `fn()` pointer where the function itself cannot be turned into a pointer.
86    ///
87    /// One example is `<dyn Trait as Trait>::fn`, where the shim contains
88    /// a virtual call, which codegen supports only via a direct call to the
89    /// `<dyn Trait as Trait>::fn` instance (an `InstanceKind::Virtual`).
90    ///
91    /// Another example is functions annotated with `#[track_caller]`, which
92    /// must have their implicit caller location argument populated for a call.
93    /// Because this is a required part of the function's ABI but can't be tracked
94    /// as a property of the function pointer, we use a single "caller location"
95    /// (the definition of the function itself).
96    ///
97    /// The second field encodes *why* this shim was created. This allows distinguishing between
98    /// a `ReifyShim` that appears in a vtable vs one that appears as a function pointer.
99    ///
100    /// This field will only be populated if we are compiling in a mode that needs these shims
101    /// to be separable, currently only when KCFI is enabled.
102    ReifyShim(DefId, Option<ReifyReason>),
103
104    /// `<fn() as FnTrait>::call_*` (generated `FnTrait` implementation for `fn()` pointers).
105    ///
106    /// `DefId` is `FnTrait::call_*`.
107    FnPtrShim(DefId, Ty<'tcx>),
108
109    /// Dynamic dispatch to `<dyn Trait as Trait>::fn`.
110    ///
111    /// This `InstanceKind` may have a callable MIR as the default implementation.
112    /// Calls to `Virtual` instances must be codegen'd as virtual calls through the vtable.
113    /// *This means we might not know exactly what is being called.*
114    ///
115    /// If this is reified to a `fn` pointer, a `ReifyShim` is used (see `ReifyShim` above for more
116    /// details on that).
117    Virtual(DefId, usize),
118
119    /// `<[FnMut/Fn closure] as FnOnce>::call_once`.
120    ///
121    /// The `DefId` is the ID of the `call_once` method in `FnOnce`.
122    ///
123    /// This generates a body that will just borrow the (owned) self type,
124    /// and dispatch to the `FnMut::call_mut` instance for the closure.
125    ClosureOnceShim { call_once: DefId, track_caller: bool },
126
127    /// `<[FnMut/Fn coroutine-closure] as FnOnce>::call_once`
128    ///
129    /// The body generated here differs significantly from the `ClosureOnceShim`,
130    /// since we need to generate a distinct coroutine type that will move the
131    /// closure's upvars *out* of the closure.
132    ConstructCoroutineInClosureShim {
133        coroutine_closure_def_id: DefId,
134        // Whether the generated MIR body takes the coroutine by-ref. This is
135        // because the signature of `<{async fn} as FnMut>::call_mut` is:
136        // `fn(&mut self, args: A) -> <Self as FnOnce>::Output`, that is to say
137        // that it returns the `FnOnce`-flavored coroutine but takes the closure
138        // by mut ref (and similarly for `Fn::call`).
139        receiver_by_ref: bool,
140    },
141
142    /// Compiler-generated accessor for thread locals which returns a reference to the thread local
143    /// the `DefId` defines. This is used to export thread locals from dylibs on platforms lacking
144    /// native support.
145    ThreadLocalShim(DefId),
146
147    /// Proxy shim for async drop of future (def_id, proxy_cor_ty, impl_cor_ty)
148    FutureDropPollShim(DefId, Ty<'tcx>, Ty<'tcx>),
149
150    /// `core::ptr::drop_glue::<T>`.
151    ///
152    /// The `DefId` is for `core::ptr::drop_glue`.
153    /// The `Option<Ty<'tcx>>` is either `Some(T)`, or `None` for empty drop glue.
154    DropGlue(DefId, Option<Ty<'tcx>>),
155
156    /// Compiler-generated `<T as Clone>::clone` implementation.
157    ///
158    /// For all types that automatically implement `Copy`, a trivial `Clone` impl is provided too.
159    /// Additionally, arrays, tuples, and closures get a `Clone` shim even if they aren't `Copy`.
160    ///
161    /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl.
162    CloneShim(DefId, Ty<'tcx>),
163
164    /// Compiler-generated `<T as FnPtr>::addr` implementation.
165    ///
166    /// Automatically generated for all potentially higher-ranked `fn(I) -> R` types.
167    ///
168    /// The `DefId` is for `FnPtr::addr`, the `Ty` is the type `T`.
169    FnPtrAddrShim(DefId, Ty<'tcx>),
170
171    /// `core::future::async_drop::async_drop_in_place::<'_, T>`.
172    ///
173    /// The `DefId` is for `core::future::async_drop::async_drop_in_place`, the `Ty`
174    /// is the type `T`.
175    AsyncDropGlueCtorShim(DefId, Ty<'tcx>),
176
177    /// `core::future::async_drop::async_drop_in_place::<'_, T>::{closure}`.
178    ///
179    /// async_drop_in_place poll function implementation (for generated coroutine).
180    /// `Ty` here is `async_drop_in_place<T>::{closure}` coroutine type, not just `T`
181    AsyncDropGlue(DefId, Ty<'tcx>),
182}
183
184impl<'tcx> Instance<'tcx> {
185    /// Returns the `Ty` corresponding to this `Instance`, with generic instantiations applied and
186    /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization.
187    pub fn ty(&self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
188        let ty = tcx.type_of(self.def.def_id());
189        tcx.instantiate_and_normalize_erasing_regions(self.args, typing_env, ty)
190    }
191
192    /// Finds a crate that contains a monomorphization of this instance that
193    /// can be linked to from the local crate. A return value of `None` means
194    /// no upstream crate provides such an exported monomorphization.
195    ///
196    /// This method already takes into account the global `-Zshare-generics`
197    /// setting, always returning `None` if `share-generics` is off.
198    pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
199        // If this is an item that is defined in the local crate, no upstream
200        // crate can know about it/provide a monomorphization.
201        if self.def_id().is_local() {
202            return None;
203        }
204
205        // If we are not in share generics mode, we don't link to upstream
206        // monomorphizations but always instantiate our own internal versions
207        // instead.
208        if !tcx.sess.opts.share_generics()
209            // However, if the def_id is marked inline(never), then it's fine to just reuse the
210            // upstream monomorphization.
211            && tcx.codegen_fn_attrs(self.def_id()).inline != rustc_hir::attrs::InlineAttr::Never
212        {
213            return None;
214        }
215
216        // If this a non-generic instance, it cannot be a shared monomorphization.
217        self.args.non_erasable_generics().next()?;
218
219        // compiler_builtins cannot use upstream monomorphizations.
220        if tcx.is_compiler_builtins(LOCAL_CRATE) {
221            return None;
222        }
223
224        match self.def {
225            InstanceKind::Item(def) => tcx
226                .upstream_monomorphizations_for(def)
227                .and_then(|monos| monos.get(&self.args).cloned()),
228            InstanceKind::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.args),
229            InstanceKind::AsyncDropGlue(_, _) => None,
230            InstanceKind::FutureDropPollShim(_, _, _) => None,
231            InstanceKind::AsyncDropGlueCtorShim(_, _) => {
232                tcx.upstream_async_drop_glue_for(self.args)
233            }
234            _ => None,
235        }
236    }
237}
238
239impl<'tcx> InstanceKind<'tcx> {
240    #[inline]
241    pub fn def_id(self) -> DefId {
242        match self {
243            InstanceKind::Item(def_id)
244            | InstanceKind::VTableShim(def_id)
245            | InstanceKind::ReifyShim(def_id, _)
246            | InstanceKind::FnPtrShim(def_id, _)
247            | InstanceKind::Virtual(def_id, _)
248            | InstanceKind::Intrinsic(def_id)
249            | InstanceKind::ThreadLocalShim(def_id)
250            | InstanceKind::ClosureOnceShim { call_once: def_id, track_caller: _ }
251            | ty::InstanceKind::ConstructCoroutineInClosureShim {
252                coroutine_closure_def_id: def_id,
253                receiver_by_ref: _,
254            }
255            | InstanceKind::DropGlue(def_id, _)
256            | InstanceKind::CloneShim(def_id, _)
257            | InstanceKind::FnPtrAddrShim(def_id, _)
258            | InstanceKind::FutureDropPollShim(def_id, _, _)
259            | InstanceKind::AsyncDropGlue(def_id, _)
260            | InstanceKind::AsyncDropGlueCtorShim(def_id, _) => def_id,
261        }
262    }
263
264    /// Returns the `DefId` of instances which might not require codegen locally.
265    pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
266        match self {
267            ty::InstanceKind::Item(def) => Some(def),
268            ty::InstanceKind::DropGlue(def_id, Some(_))
269            | InstanceKind::AsyncDropGlueCtorShim(def_id, _)
270            | InstanceKind::AsyncDropGlue(def_id, _)
271            | InstanceKind::FutureDropPollShim(def_id, ..)
272            | InstanceKind::ThreadLocalShim(def_id) => Some(def_id),
273            InstanceKind::VTableShim(..)
274            | InstanceKind::ReifyShim(..)
275            | InstanceKind::FnPtrShim(..)
276            | InstanceKind::Virtual(..)
277            | InstanceKind::Intrinsic(..)
278            | InstanceKind::ClosureOnceShim { .. }
279            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
280            | InstanceKind::DropGlue(..)
281            | InstanceKind::CloneShim(..)
282            | InstanceKind::FnPtrAddrShim(..) => None,
283        }
284    }
285
286    /// Returns `true` if the LLVM version of this instance is unconditionally
287    /// marked with `inline`. This implies that a copy of this instance is
288    /// generated in every codegen unit.
289    /// Note that this is only a hint. See the documentation for
290    /// `generates_cgu_internal_copy` for more information.
291    pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
292        use rustc_hir::definitions::DefPathData;
293        let def_id = match *self {
294            ty::InstanceKind::Item(def) => def,
295            ty::InstanceKind::DropGlue(_, Some(ty)) => return ty.is_array(),
296            ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => return ty.is_coroutine(),
297            ty::InstanceKind::FutureDropPollShim(_, _, _) => return false,
298            ty::InstanceKind::AsyncDropGlue(_, _) => return false,
299            ty::InstanceKind::ThreadLocalShim(_) => return false,
300            _ => return true,
301        };
302        #[allow(non_exhaustive_omitted_patterns)] match tcx.def_key(def_id).disambiguated_data.data
    {
    DefPathData::Ctor | DefPathData::Closure => true,
    _ => false,
}matches!(
303            tcx.def_key(def_id).disambiguated_data.data,
304            DefPathData::Ctor | DefPathData::Closure
305        )
306    }
307
308    pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool {
309        match *self {
310            InstanceKind::Item(def_id) | InstanceKind::Virtual(def_id, _) => {
311                tcx.body_codegen_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
312            }
313            InstanceKind::ClosureOnceShim { call_once: _, track_caller } => track_caller,
314            _ => false,
315        }
316    }
317
318    /// Returns `true` when the MIR body associated with this instance should be monomorphized
319    /// by its users (e.g. codegen or miri) by instantiating the `args` from `Instance` (see
320    /// `Instance::args_for_mir_body`).
321    ///
322    /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR
323    /// body should perform necessary instantiations.
324    pub fn has_polymorphic_mir_body(&self) -> bool {
325        match *self {
326            InstanceKind::CloneShim(..)
327            | InstanceKind::ThreadLocalShim(..)
328            | InstanceKind::FnPtrAddrShim(..)
329            | InstanceKind::FnPtrShim(..)
330            | InstanceKind::DropGlue(_, Some(_))
331            | InstanceKind::FutureDropPollShim(..)
332            | InstanceKind::AsyncDropGlue(_, _) => false,
333            InstanceKind::AsyncDropGlueCtorShim(_, _) => false,
334            InstanceKind::ClosureOnceShim { .. }
335            | InstanceKind::ConstructCoroutineInClosureShim { .. }
336            | InstanceKind::DropGlue(..)
337            | InstanceKind::Item(_)
338            | InstanceKind::Intrinsic(..)
339            | InstanceKind::ReifyShim(..)
340            | InstanceKind::Virtual(..)
341            | InstanceKind::VTableShim(..) => true,
342        }
343    }
344}
345
346fn type_length<'tcx>(item: impl TypeVisitable<TyCtxt<'tcx>>) -> usize {
347    struct Visitor<'tcx> {
348        type_length: usize,
349        cache: FxHashMap<Ty<'tcx>, usize>,
350    }
351    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Visitor<'tcx> {
352        fn visit_ty(&mut self, t: Ty<'tcx>) {
353            if let Some(&value) = self.cache.get(&t) {
354                self.type_length += value;
355                return;
356            }
357
358            let prev = self.type_length;
359            self.type_length += 1;
360            t.super_visit_with(self);
361
362            // We don't try to use the cache if the type is fairly small.
363            if self.type_length > 16 {
364                self.cache.insert(t, self.type_length - prev);
365            }
366        }
367
368        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
369            self.type_length += 1;
370            ct.super_visit_with(self);
371        }
372    }
373    let mut visitor = Visitor { type_length: 0, cache: Default::default() };
374    item.visit_with(&mut visitor);
375
376    visitor.type_length
377}
378
379impl<'tcx> fmt::Display for Instance<'tcx> {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        ty::tls::with(|tcx| {
382            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
383            tcx.lift(*self).print(&mut p)?;
384            let s = p.into_buffer();
385            f.write_str(&s)
386        })
387    }
388}
389
390// async_drop_in_place<T>::coroutine.poll, when T is a standard coroutine,
391// should be resolved to this coroutine's future_drop_poll (through FutureDropPollShim proxy).
392// async_drop_in_place<async_drop_in_place<T>::coroutine>::coroutine.poll,
393// when T is a standard coroutine, should be resolved to this coroutine's future_drop_poll.
394// async_drop_in_place<async_drop_in_place<T>::coroutine>::coroutine.poll,
395// when T is not a coroutine, should be resolved to the innermost
396// async_drop_in_place<T>::coroutine's poll function (through FutureDropPollShim proxy)
397fn resolve_async_drop_poll<'tcx>(mut cor_ty: Ty<'tcx>) -> Instance<'tcx> {
398    let first_cor = cor_ty;
399    let ty::Coroutine(poll_def_id, proxy_args) = first_cor.kind() else {
400        crate::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
401    };
402    let poll_def_id = *poll_def_id;
403    let mut child_ty = cor_ty;
404    loop {
405        if let ty::Coroutine(child_def, child_args) = child_ty.kind() {
406            cor_ty = child_ty;
407            if *child_def == poll_def_id {
408                child_ty = child_args.first().unwrap().expect_ty();
409                continue;
410            } else {
411                return Instance {
412                    def: ty::InstanceKind::FutureDropPollShim(poll_def_id, first_cor, cor_ty),
413                    args: proxy_args,
414                };
415            }
416        } else {
417            let ty::Coroutine(_, child_args) = cor_ty.kind() else {
418                crate::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
419            };
420            if first_cor != cor_ty {
421                return Instance {
422                    def: ty::InstanceKind::FutureDropPollShim(poll_def_id, first_cor, cor_ty),
423                    args: proxy_args,
424                };
425            } else {
426                return Instance {
427                    def: ty::InstanceKind::AsyncDropGlue(poll_def_id, cor_ty),
428                    args: child_args,
429                };
430            }
431        }
432    }
433}
434
435impl<'tcx> Instance<'tcx> {
436    /// Creates a new [`InstanceKind::Item`] from the `def_id` and `args`.
437    ///
438    /// Note that this item corresponds to the body of `def_id` directly, which
439    /// likely does not make sense for trait items which need to be resolved to an
440    /// implementation, and which may not even have a body themselves. Usages of
441    /// this function should probably use [`Instance::expect_resolve`], or if run
442    /// in a polymorphic environment or within a lint (that may encounter ambiguity)
443    /// [`Instance::try_resolve`] instead.
444    pub fn new_raw(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> {
445        if !!args.has_escaping_bound_vars() {
    {
        ::core::panicking::panic_fmt(format_args!("args of instance {0:?} has escaping bound vars: {1:?}",
                def_id, args));
    }
};assert!(
446            !args.has_escaping_bound_vars(),
447            "args of instance {def_id:?} has escaping bound vars: {args:?}"
448        );
449        Instance { def: InstanceKind::Item(def_id), args }
450    }
451
452    pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
453        let args = GenericArgs::for_item(tcx, def_id, |param, _| match param.kind {
454            ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
455            ty::GenericParamDefKind::Type { .. } => {
456                crate::util::bug::bug_fmt(format_args!("Instance::mono: {0:?} has type parameters",
        def_id))bug!("Instance::mono: {:?} has type parameters", def_id)
457            }
458            ty::GenericParamDefKind::Const { .. } => {
459                crate::util::bug::bug_fmt(format_args!("Instance::mono: {0:?} has const parameters",
        def_id))bug!("Instance::mono: {:?} has const parameters", def_id)
460            }
461        });
462
463        Instance::new_raw(def_id, args)
464    }
465
466    #[inline]
467    pub fn def_id(&self) -> DefId {
468        self.def.def_id()
469    }
470
471    /// Resolves a `(def_id, args)` pair to an (optional) instance -- most commonly,
472    /// this is used to find the precise code that will run for a trait method invocation,
473    /// if known. This should only be used for functions and consts. If you want to
474    /// resolve an associated type, use [`TyCtxt::try_normalize_erasing_regions`].
475    ///
476    /// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
477    /// For example, in a context like this,
478    ///
479    /// ```ignore (illustrative)
480    /// fn foo<T: Debug>(t: T) { ... }
481    /// ```
482    ///
483    /// trying to resolve `Debug::fmt` applied to `T` will yield `Ok(None)`, because we do not
484    /// know what code ought to run. This setting is also affected by the current `TypingMode`
485    /// of the environment.
486    ///
487    /// Presuming that coherence and type-check have succeeded, if this method is invoked
488    /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
489    /// `Ok(Some(instance))`, **except** for when the instance's inputs hit the type size limit,
490    /// in which case it may bail out and return `Ok(None)`.
491    ///
492    /// Returns `Err(ErrorGuaranteed)` when the `Instance` resolution process
493    /// couldn't complete due to errors elsewhere - this is distinct
494    /// from `Ok(None)` to avoid misleading diagnostics when an error
495    /// has already been/will be emitted, for the original cause
496    x;#[instrument(level = "debug", skip(tcx), ret)]
497    pub fn try_resolve(
498        tcx: TyCtxt<'tcx>,
499        typing_env: ty::TypingEnv<'tcx>,
500        def_id: DefId,
501        args: GenericArgsRef<'tcx>,
502    ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
503        assert_matches!(
504            tcx.def_kind(def_id),
505            DefKind::Fn
506                | DefKind::AssocFn
507                | DefKind::Const { .. }
508                | DefKind::AssocConst { .. }
509                | DefKind::AnonConst
510                | DefKind::InlineConst
511                | DefKind::Static { .. }
512                | DefKind::Ctor(_, CtorKind::Fn)
513                | DefKind::Closure
514                | DefKind::SyntheticCoroutineBody,
515            "`Instance::try_resolve` should only be used to resolve instances of \
516            functions, statics, and consts; to resolve associated types, use \
517            `try_normalize_erasing_regions`."
518        );
519
520        // Rust code can easily create exponentially-long types using only a
521        // polynomial recursion depth. Even with the default recursion
522        // depth, you can easily get cases that take >2^60 steps to run,
523        // which means that rustc basically hangs.
524        //
525        // Bail out in these cases to avoid that bad user experience.
526        if tcx.sess.opts.unstable_opts.enforce_type_length_limit
527            && !tcx.type_length_limit().value_within_limit(type_length(args))
528        {
529            return Ok(None);
530        }
531
532        // All regions in the result of this query are erased, so it's
533        // fine to erase all of the input regions.
534        tcx.resolve_instance_raw(
535            tcx.erase_and_anonymize_regions(typing_env.as_query_input((def_id, args))),
536        )
537    }
538
539    pub fn expect_resolve(
540        tcx: TyCtxt<'tcx>,
541        typing_env: ty::TypingEnv<'tcx>,
542        def_id: DefId,
543        args: GenericArgsRef<'tcx>,
544        span: Span,
545    ) -> Instance<'tcx> {
546        // We compute the span lazily, to avoid unnecessary query calls.
547        // If `span` is a DUMMY_SP, and the def id is local, then use the
548        // def span of the def id.
549        let span_or_local_def_span =
550            || if span.is_dummy() && def_id.is_local() { tcx.def_span(def_id) } else { span };
551
552        match ty::Instance::try_resolve(tcx, typing_env, def_id, args) {
553            Ok(Some(instance)) => instance,
554            Ok(None) => {
555                let type_length = type_length(args);
556                if !tcx.type_length_limit().value_within_limit(type_length) {
557                    tcx.dcx().emit_fatal(error::TypeLengthLimit {
558                        // We don't use `def_span(def_id)` so that diagnostics point
559                        // to the crate root during mono instead of to foreign items.
560                        // This is arguably better.
561                        span: span_or_local_def_span(),
562                        instance: Instance::new_raw(def_id, args),
563                        type_length,
564                    });
565                } else {
566                    crate::util::bug::span_bug_fmt(span_or_local_def_span(),
    format_args!("failed to resolve instance for {0}",
        tcx.def_path_str_with_args(def_id, args)))span_bug!(
567                        span_or_local_def_span(),
568                        "failed to resolve instance for {}",
569                        tcx.def_path_str_with_args(def_id, args)
570                    )
571                }
572            }
573            instance => crate::util::bug::span_bug_fmt(span_or_local_def_span(),
    format_args!("failed to resolve instance for {0}: {1:#?}",
        tcx.def_path_str_with_args(def_id, args), instance))span_bug!(
574                span_or_local_def_span(),
575                "failed to resolve instance for {}: {instance:#?}",
576                tcx.def_path_str_with_args(def_id, args)
577            ),
578        }
579    }
580
581    pub fn resolve_for_fn_ptr(
582        tcx: TyCtxt<'tcx>,
583        typing_env: ty::TypingEnv<'tcx>,
584        def_id: DefId,
585        args: GenericArgsRef<'tcx>,
586    ) -> Option<Instance<'tcx>> {
587        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:587",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(587u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve(def_id={0:?}, args={1:?})",
                                                    def_id, args) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve(def_id={:?}, args={:?})", def_id, args);
588        // Use either `resolve_closure` or `resolve_for_vtable`
589        if !!tcx.is_closure_like(def_id) {
    {
        ::core::panicking::panic_fmt(format_args!("Called `resolve_for_fn_ptr` on closure: {0:?}",
                def_id));
    }
};assert!(!tcx.is_closure_like(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}");
590        let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::FnPtr);
591        Instance::try_resolve(tcx, typing_env, def_id, args).ok().flatten().map(|mut resolved| {
592            match resolved.def {
593                InstanceKind::Item(def) if resolved.def.requires_caller_location(tcx) => {
594                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:594",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(594u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => fn pointer created for function with #[track_caller]")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(" => fn pointer created for function with #[track_caller]");
595                    resolved.def = InstanceKind::ReifyShim(def, reason);
596                }
597                InstanceKind::Virtual(def_id, _) => {
598                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:598",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(598u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => fn pointer created for virtual call")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(" => fn pointer created for virtual call");
599                    resolved.def = InstanceKind::ReifyShim(def_id, reason);
600                }
601                _ if tcx.sess.is_sanitizer_kcfi_enabled() => {
602                    // Reify `::call`-like method implementations
603                    if tcx.is_closure_like(resolved.def_id()) {
604                        // Reroute through a reify via the *unresolved* instance. The resolved one can't
605                        // be directly reified because it's closure-like. The reify can handle the
606                        // unresolved instance.
607                        resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args }
608                    // Reify `Trait::method` implementations if the trait is dyn-compatible.
609                    } else if let Some(assoc) = tcx.opt_associated_item(def_id)
610                        && let AssocContainer::Trait | AssocContainer::TraitImpl(Ok(_)) =
611                            assoc.container
612                        && tcx.is_dyn_compatible(assoc.container_id(tcx))
613                    {
614                        // If this function could also go in a vtable, we need to `ReifyShim` it with
615                        // KCFI because it can only attach one type per function.
616                        resolved.def = InstanceKind::ReifyShim(resolved.def_id(), reason)
617                    }
618                }
619                _ => {}
620            }
621
622            resolved
623        })
624    }
625
626    pub fn expect_resolve_for_vtable(
627        tcx: TyCtxt<'tcx>,
628        typing_env: ty::TypingEnv<'tcx>,
629        def_id: DefId,
630        args: GenericArgsRef<'tcx>,
631        span: Span,
632    ) -> Instance<'tcx> {
633        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:633",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(633u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_for_vtable(def_id={0:?}, args={1:?})",
                                                    def_id, args) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_for_vtable(def_id={:?}, args={:?})", def_id, args);
634        let fn_sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
635        let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty()
636            && fn_sig.input(0).skip_binder().is_param(0)
637            && tcx.generics_of(def_id).has_self;
638
639        if is_vtable_shim {
640            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:640",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(640u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => associated item with unsizeable self: Self")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(" => associated item with unsizeable self: Self");
641            return Instance { def: InstanceKind::VTableShim(def_id), args };
642        }
643
644        let mut resolved = Instance::expect_resolve(tcx, typing_env, def_id, args, span);
645
646        let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::Vtable);
647        match resolved.def {
648            InstanceKind::Item(def) => {
649                // We need to generate a shim when we cannot guarantee that
650                // the caller of a trait object method will be aware of
651                // `#[track_caller]` - this ensures that the caller
652                // and callee ABI will always match.
653                //
654                // The shim is generated when all of these conditions are met:
655                //
656                // 1) The underlying method expects a caller location parameter
657                // in the ABI
658                let needs_track_caller_shim = resolved.def.requires_caller_location(tcx)
659                    // 2) The caller location parameter comes from having `#[track_caller]`
660                    // on the implementation, and *not* on the trait method.
661                    && !tcx.should_inherit_track_caller(def)
662                    // If the method implementation comes from the trait definition itself
663                    // (e.g. `trait Foo { #[track_caller] my_fn() { /* impl */ } }`),
664                    // then we don't need to generate a shim. This check is needed because
665                    // `should_inherit_track_caller` returns `false` if our method
666                    // implementation comes from the trait block, and not an impl block
667                    && !#[allow(non_exhaustive_omitted_patterns)] match tcx.opt_associated_item(def) {
    Some(ty::AssocItem { container: ty::AssocContainer::Trait, .. }) => true,
    _ => false,
}matches!(
668                        tcx.opt_associated_item(def),
669                        Some(ty::AssocItem {
670                            container: ty::AssocContainer::Trait,
671                            ..
672                        })
673                    );
674                if needs_track_caller_shim {
675                    if tcx.is_closure_like(def) {
676                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:676",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(676u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => vtable fn pointer created for closure with #[track_caller]: {0:?} for method {1:?} {2:?}",
                                                    def, def_id, args) as &dyn Value))])
            });
    } else { ; }
};debug!(
677                            " => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
678                            def, def_id, args
679                        );
680
681                        // Create a shim for the `FnOnce/FnMut/Fn` method we are calling
682                        // - unlike functions, invoking a closure always goes through a
683                        // trait.
684                        resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args };
685                    } else {
686                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:686",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(686u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => vtable fn pointer created for function with #[track_caller]: {0:?}",
                                                    def) as &dyn Value))])
            });
    } else { ; }
};debug!(
687                            " => vtable fn pointer created for function with #[track_caller]: {:?}",
688                            def
689                        );
690                        resolved.def = InstanceKind::ReifyShim(def, reason);
691                    }
692                }
693            }
694            InstanceKind::Virtual(def_id, _) => {
695                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/instance.rs:695",
                        "rustc_middle::ty::instance", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/instance.rs"),
                        ::tracing_core::__macro_support::Option::Some(695u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::instance"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => vtable fn pointer created for virtual call")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(" => vtable fn pointer created for virtual call");
696                resolved.def = InstanceKind::ReifyShim(def_id, reason)
697            }
698            _ => {}
699        }
700
701        resolved
702    }
703
704    pub fn resolve_closure(
705        tcx: TyCtxt<'tcx>,
706        def_id: DefId,
707        args: ty::GenericArgsRef<'tcx>,
708        requested_kind: ty::ClosureKind,
709    ) -> Instance<'tcx> {
710        let actual_kind = args.as_closure().kind();
711
712        match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
713            Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, args),
714            _ => Instance::new_raw(def_id, args),
715        }
716    }
717
718    pub fn resolve_drop_glue(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
719        let def_id = tcx.require_lang_item(LangItem::DropGlue, DUMMY_SP);
720        let args = tcx.mk_args(&[ty.into()]);
721        Instance::expect_resolve(
722            tcx,
723            ty::TypingEnv::fully_monomorphized(),
724            def_id,
725            args,
726            ty.ty_adt_def().and_then(|adt| tcx.hir_span_if_local(adt.did())).unwrap_or(DUMMY_SP),
727        )
728    }
729
730    pub fn resolve_async_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
731        let def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, DUMMY_SP);
732        let args = tcx.mk_args(&[ty.into()]);
733        Instance::expect_resolve(
734            tcx,
735            ty::TypingEnv::fully_monomorphized(),
736            def_id,
737            args,
738            ty.ty_adt_def().and_then(|adt| tcx.hir_span_if_local(adt.did())).unwrap_or(DUMMY_SP),
739        )
740    }
741
742    pub fn resolve_async_drop_in_place_poll(
743        tcx: TyCtxt<'tcx>,
744        def_id: DefId,
745        ty: Ty<'tcx>,
746    ) -> ty::Instance<'tcx> {
747        let args = tcx.mk_args(&[ty.into()]);
748        Instance::expect_resolve(tcx, ty::TypingEnv::fully_monomorphized(), def_id, args, DUMMY_SP)
749    }
750
751    x;#[instrument(level = "debug", skip(tcx), ret)]
752    pub fn fn_once_adapter_instance(
753        tcx: TyCtxt<'tcx>,
754        closure_did: DefId,
755        args: ty::GenericArgsRef<'tcx>,
756    ) -> Instance<'tcx> {
757        let fn_once = tcx.require_lang_item(LangItem::FnOnce, DUMMY_SP);
758        let call_once = tcx
759            .associated_items(fn_once)
760            .in_definition_order()
761            .find(|it| it.is_fn())
762            .unwrap()
763            .def_id;
764        let track_caller =
765            tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
766        let def = ty::InstanceKind::ClosureOnceShim { call_once, track_caller };
767
768        let self_ty = Ty::new_closure(tcx, closure_did, args);
769
770        let tupled_inputs_ty = args.as_closure().sig().map_bound(|sig| sig.inputs()[0]);
771        let tupled_inputs_ty = tcx.instantiate_bound_regions_with_erased(tupled_inputs_ty);
772        let args = tcx.mk_args_trait(self_ty, [tupled_inputs_ty.into()]);
773
774        debug!(?self_ty, args=?tupled_inputs_ty.tuple_fields());
775        Instance { def, args }
776    }
777
778    pub fn try_resolve_item_for_coroutine(
779        tcx: TyCtxt<'tcx>,
780        trait_item_id: DefId,
781        trait_id: DefId,
782        rcvr_args: ty::GenericArgsRef<'tcx>,
783    ) -> Option<Instance<'tcx>> {
784        let ty::Coroutine(coroutine_def_id, args) = *rcvr_args.type_at(0).kind() else {
785            return None;
786        };
787        let coroutine_kind = tcx.coroutine_kind(coroutine_def_id).unwrap();
788
789        let coroutine_callable_item = if tcx.is_lang_item(trait_id, LangItem::Future) {
790            {
    match coroutine_kind {
        hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) =>
            {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
791                coroutine_kind,
792                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
793            );
794            hir::LangItem::FuturePoll
795        } else if tcx.is_lang_item(trait_id, LangItem::Iterator) {
796            {
    match coroutine_kind {
        hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
797                coroutine_kind,
798                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
799            );
800            hir::LangItem::IteratorNext
801        } else if tcx.is_lang_item(trait_id, LangItem::AsyncIterator) {
802            {
    match coroutine_kind {
        hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
            => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
803                coroutine_kind,
804                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
805            );
806            hir::LangItem::AsyncIteratorPollNext
807        } else if tcx.is_lang_item(trait_id, LangItem::Coroutine) {
808            {
    match coroutine_kind {
        hir::CoroutineKind::Coroutine(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "hir::CoroutineKind::Coroutine(_)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
809            hir::LangItem::CoroutineResume
810        } else {
811            return None;
812        };
813
814        if tcx.is_lang_item(trait_item_id, coroutine_callable_item) {
815            if tcx.is_async_drop_in_place_coroutine(coroutine_def_id) {
816                return Some(resolve_async_drop_poll(rcvr_args.type_at(0)));
817            }
818            let ty::Coroutine(_, id_args) = *tcx.type_of(coroutine_def_id).skip_binder().kind()
819            else {
820                crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
821            };
822
823            // If the closure's kind ty disagrees with the identity closure's kind ty,
824            // then this must be a coroutine generated by one of the `ConstructCoroutineInClosureShim`s.
825            if args.as_coroutine().kind_ty() == id_args.as_coroutine().kind_ty() {
826                Some(Instance { def: ty::InstanceKind::Item(coroutine_def_id), args })
827            } else {
828                Some(Instance {
829                    def: ty::InstanceKind::Item(
830                        tcx.coroutine_by_move_body_def_id(coroutine_def_id),
831                    ),
832                    args,
833                })
834            }
835        } else {
836            // All other methods should be defaulted methods of the built-in trait.
837            // This is important for `Iterator`'s combinators, but also useful for
838            // adding future default methods to `Future`, for instance.
839            if true {
    if !tcx.defaultness(trait_item_id).has_value() {
        ::core::panicking::panic("assertion failed: tcx.defaultness(trait_item_id).has_value()")
    };
};debug_assert!(tcx.defaultness(trait_item_id).has_value());
840            Some(Instance::new_raw(trait_item_id, rcvr_args))
841        }
842    }
843
844    /// Depending on the kind of `InstanceKind`, the MIR body associated with an
845    /// instance is expressed in terms of the generic parameters of `self.def_id()`, and in other
846    /// cases the MIR body is expressed in terms of the types found in the generic parameter array.
847    /// In the former case, we want to instantiate those generic types and replace them with the
848    /// values from the args when monomorphizing the function body. But in the latter case, we
849    /// don't want to do that instantiation, since it has already been done effectively.
850    ///
851    /// This function returns `Some(args)` in the former case and `None` otherwise -- i.e., if
852    /// this function returns `None`, then the MIR body does not require instantiation during
853    /// codegen.
854    fn args_for_mir_body(&self) -> Option<GenericArgsRef<'tcx>> {
855        self.def.has_polymorphic_mir_body().then_some(self.args)
856    }
857
858    pub fn instantiate_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<'tcx, &T>) -> T
859    where
860        T: TypeFoldable<TyCtxt<'tcx>> + Copy,
861    {
862        let v = v.map_bound(|v| *v);
863        if let Some(args) = self.args_for_mir_body() {
864            v.instantiate(tcx, args).skip_norm_wip()
865        } else {
866            v.instantiate_identity().skip_norm_wip()
867        }
868    }
869
870    #[inline(always)]
871    // Keep me in sync with try_instantiate_mir_and_normalize_erasing_regions
872    pub fn instantiate_mir_and_normalize_erasing_regions<T>(
873        &self,
874        tcx: TyCtxt<'tcx>,
875        typing_env: ty::TypingEnv<'tcx>,
876        v: EarlyBinder<'tcx, T>,
877    ) -> T
878    where
879        T: TypeFoldable<TyCtxt<'tcx>>,
880    {
881        if let Some(args) = self.args_for_mir_body() {
882            tcx.instantiate_and_normalize_erasing_regions(args, typing_env, v)
883        } else {
884            tcx.normalize_erasing_regions(typing_env, v.instantiate_identity())
885        }
886    }
887
888    #[inline(always)]
889    // Keep me in sync with instantiate_mir_and_normalize_erasing_regions
890    pub fn try_instantiate_mir_and_normalize_erasing_regions<T>(
891        &self,
892        tcx: TyCtxt<'tcx>,
893        typing_env: ty::TypingEnv<'tcx>,
894        v: EarlyBinder<'tcx, T>,
895    ) -> Result<T, NormalizationError<'tcx>>
896    where
897        T: TypeFoldable<TyCtxt<'tcx>>,
898    {
899        if let Some(args) = self.args_for_mir_body() {
900            tcx.try_instantiate_and_normalize_erasing_regions(args, typing_env, v)
901        } else {
902            // We're using `instantiate_identity` as e.g.
903            // `FnPtrShim` is separately generated for every
904            // instantiation of the `FnDef`, so the MIR body
905            // is already instantiated. Any generic parameters it
906            // contains are generic parameters from the caller.
907            tcx.try_normalize_erasing_regions(typing_env, v.instantiate_identity())
908        }
909    }
910}
911
912fn needs_fn_once_adapter_shim(
913    actual_closure_kind: ty::ClosureKind,
914    trait_closure_kind: ty::ClosureKind,
915) -> Result<bool, ()> {
916    match (actual_closure_kind, trait_closure_kind) {
917        (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
918        | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
919        | (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
920            // No adapter needed.
921            Ok(false)
922        }
923        (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
924            // The closure fn is a `fn(&self, ...)`, but we want a `fn(&mut self, ...)`.
925            // At codegen time, these are basically the same, so we can just return the closure.
926            Ok(false)
927        }
928        (ty::ClosureKind::Fn | ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
929            // The closure fn is a `fn(&self, ...)` or `fn(&mut self, ...)`, but
930            // we want a `fn(self, ...)`. We can produce this by doing something like:
931            //
932            //     fn call_once(self, ...) { Fn::call(&self, ...) }
933            //     fn call_once(mut self, ...) { FnMut::call_mut(&mut self, ...) }
934            //
935            // These are both the same at codegen time.
936            Ok(true)
937        }
938        (ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce, _) => Err(()),
939    }
940}