Skip to main content

rustc_middle/ty/
layout.rs

1use std::{cmp, fmt};
2
3use rustc_abi as abi;
4use rustc_abi::{
5    AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
6    PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
7    TyAbiInterface, VariantIdx, Variants,
8};
9use rustc_data_structures::Limit;
10use rustc_errors::{
11    Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
12};
13use rustc_hir as hir;
14use rustc_hir::attrs::lang_items::LangItem;
15use rustc_hir::def_id::DefId;
16use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
17use rustc_session::config::OptLevel;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
19use rustc_target::callconv::FnAbi;
20use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
21use tracing::debug;
22
23use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
24use crate::query::TyCtxtAt;
25use crate::traits::ObligationCause;
26use crate::ty::normalize_erasing_regions::NormalizationError;
27use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
28
29impl IntegerExt for abi::Integer {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match (*self, signed) {
            (I8, false) => tcx.types.u8,
            (I16, false) => tcx.types.u16,
            (I32, false) => tcx.types.u32,
            (I64, false) => tcx.types.u64,
            (I128, false) => tcx.types.u128,
            (I8, true) => tcx.types.i8,
            (I16, true) => tcx.types.i16,
            (I32, true) => tcx.types.i32,
            (I64, true) => tcx.types.i64,
            (I128, true) => tcx.types.i128,
        }
    }
    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match ity {
            ty::IntTy::I8 => I8,
            ty::IntTy::I16 => I16,
            ty::IntTy::I32 => I32,
            ty::IntTy::I64 => I64,
            ty::IntTy::I128 => I128,
            ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
        }
    }
    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
        -> abi::Integer {
        use abi::Integer::{I8, I16, I32, I64, I128};
        match ity {
            ty::UintTy::U8 => I8,
            ty::UintTy::U16 => I16,
            ty::UintTy::U32 => I32,
            ty::UintTy::U64 => I64,
            ty::UintTy::U128 => I128,
            ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
        }
    }
    #[doc =
    " Finds the appropriate Integer type and signedness for the given"]
    #[doc = " discriminant range and `#[repr]` attribute."]
    #[doc = ""]
    #[doc =
    " To represent the way the values were written in the rust source, min and max"]
    #[doc =
    " are in different types. It\'s thus possible to pass in an unrepresentable range,"]
    #[doc = " and the method will panic in those cases."]
    #[doc = ""]
    #[doc =
    " This is the basis for computing the type of the *tag* of an enum (which can be smaller than"]
    #[doc =
    " the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`])."]
    fn discr_range_of_repr<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>,
        repr: &ReprOptions, min_negative: i128, max_positive: u128)
        -> (abi::Integer, bool) {
        if !(min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned()) {
            {
                ::core::panicking::panic_fmt(format_args!("No type can represent the full range of {0}..={1}",
                        min_negative, max_positive));
            }
        };
        let unsigned_fit =
            abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(),
                    max_positive));
        let signed_fit =
            cmp::max(abi::Integer::fit_signed(min_negative),
                abi::Integer::fit_signed(max_positive.cast_signed()));
        if let Some(ity) = repr.int {
            let discr = abi::Integer::from_attr(&tcx, ity);
            let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
            if discr < fit {
                crate::util::bug::bug_fmt(format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
                        ty))
            }
            return (discr, ity.is_signed());
        }
        let at_least =
            if repr.c() {
                tcx.data_layout().c_enum_min_size
            } else { abi::Integer::I8 };
        if unsigned_fit <= signed_fit {
            (cmp::max(unsigned_fit, at_least), false)
        } else { (cmp::max(signed_fit, at_least), true) }
    }
}#[extension(pub trait IntegerExt)]
30impl abi::Integer {
31    #[inline]
32    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
33        use abi::Integer::{I8, I16, I32, I64, I128};
34        match (*self, signed) {
35            (I8, false) => tcx.types.u8,
36            (I16, false) => tcx.types.u16,
37            (I32, false) => tcx.types.u32,
38            (I64, false) => tcx.types.u64,
39            (I128, false) => tcx.types.u128,
40            (I8, true) => tcx.types.i8,
41            (I16, true) => tcx.types.i16,
42            (I32, true) => tcx.types.i32,
43            (I64, true) => tcx.types.i64,
44            (I128, true) => tcx.types.i128,
45        }
46    }
47
48    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
49        use abi::Integer::{I8, I16, I32, I64, I128};
50        match ity {
51            ty::IntTy::I8 => I8,
52            ty::IntTy::I16 => I16,
53            ty::IntTy::I32 => I32,
54            ty::IntTy::I64 => I64,
55            ty::IntTy::I128 => I128,
56            ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
57        }
58    }
59    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
60        use abi::Integer::{I8, I16, I32, I64, I128};
61        match ity {
62            ty::UintTy::U8 => I8,
63            ty::UintTy::U16 => I16,
64            ty::UintTy::U32 => I32,
65            ty::UintTy::U64 => I64,
66            ty::UintTy::U128 => I128,
67            ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
68        }
69    }
70
71    /// Finds the appropriate Integer type and signedness for the given
72    /// discriminant range and `#[repr]` attribute.
73    ///
74    /// To represent the way the values were written in the rust source, min and max
75    /// are in different types. It's thus possible to pass in an unrepresentable range,
76    /// and the method will panic in those cases.
77    ///
78    /// This is the basis for computing the type of the *tag* of an enum (which can be smaller than
79    /// the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`]).
80    fn discr_range_of_repr<'tcx>(
81        tcx: TyCtxt<'tcx>,
82        ty: Ty<'tcx>,
83        repr: &ReprOptions,
84        min_negative: i128,
85        max_positive: u128,
86    ) -> (abi::Integer, bool) {
87        assert!(
88            min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned(),
89            "No type can represent the full range of {min_negative}..={max_positive}",
90        );
91
92        // Theoretically, negative values could be larger in unsigned representation
93        // than the unsigned representation of the signed minimum. However, if there
94        // are any negative values, the only valid unsigned representation is u128
95        // which can fit all i128 values, so the result remains unaffected.
96        let unsigned_fit =
97            abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(), max_positive));
98        let signed_fit = cmp::max(
99            abi::Integer::fit_signed(min_negative),
100            abi::Integer::fit_signed(max_positive.cast_signed()),
101        );
102
103        if let Some(ity) = repr.int {
104            let discr = abi::Integer::from_attr(&tcx, ity);
105            let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
106            if discr < fit {
107                bug!(
108                    "Integer::repr_discr: `#[repr]` hint too small for \
109                      discriminant range of enum `{}`",
110                    ty
111                )
112            }
113            return (discr, ity.is_signed());
114        }
115
116        let at_least = if repr.c() {
117            // This is usually I32, however it can be different on some platforms,
118            // notably hexagon and arm-none/thumb-none
119            tcx.data_layout().c_enum_min_size
120        } else {
121            // repr(Rust) enums try to be as small as possible
122            abi::Integer::I8
123        };
124
125        // Pick the smallest fit. Prefer unsigned; that matches clang in cases where this makes a
126        // difference (https://godbolt.org/z/h4xEasW1d) so it is crucial for repr(C).
127        if unsigned_fit <= signed_fit {
128            (cmp::max(unsigned_fit, at_least), false)
129        } else {
130            (cmp::max(signed_fit, at_least), true)
131        }
132    }
133}
134
135impl FloatExt for abi::Float {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        use abi::Float::*;
        match *self {
            F16 => tcx.types.f16,
            F32 => tcx.types.f32,
            F64 => tcx.types.f64,
            F128 => tcx.types.f128,
        }
    }
    fn from_float_ty(fty: ty::FloatTy) -> Self {
        use abi::Float::*;
        match fty {
            ty::FloatTy::F16 => F16,
            ty::FloatTy::F32 => F32,
            ty::FloatTy::F64 => F64,
            ty::FloatTy::F128 => F128,
        }
    }
}#[extension(pub trait FloatExt)]
136impl abi::Float {
137    #[inline]
138    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
139        use abi::Float::*;
140        match *self {
141            F16 => tcx.types.f16,
142            F32 => tcx.types.f32,
143            F64 => tcx.types.f64,
144            F128 => tcx.types.f128,
145        }
146    }
147
148    fn from_float_ty(fty: ty::FloatTy) -> Self {
149        use abi::Float::*;
150        match fty {
151            ty::FloatTy::F16 => F16,
152            ty::FloatTy::F32 => F32,
153            ty::FloatTy::F64 => F64,
154            ty::FloatTy::F128 => F128,
155        }
156    }
157}
158
159impl PrimitiveExt for Primitive {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match *self {
            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
            Primitive::Float(f) => f.to_ty(tcx),
            Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
        }
    }
    #[doc = " Return an *integer* type matching this primitive."]
    #[doc = " Useful in particular when dealing with enum discriminants."]
    #[inline]
    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match *self {
            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
            Primitive::Pointer(_) => {
                let signed = false;
                tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
            }
            Primitive::Float(_) =>
                crate::util::bug::bug_fmt(format_args!("floats do not have an int type")),
        }
    }
}#[extension(pub trait PrimitiveExt)]
160impl Primitive {
161    #[inline]
162    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
163        match *self {
164            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
165            Primitive::Float(f) => f.to_ty(tcx),
166            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
167            Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
168        }
169    }
170
171    /// Return an *integer* type matching this primitive.
172    /// Useful in particular when dealing with enum discriminants.
173    #[inline]
174    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
175        match *self {
176            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
177            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
178            Primitive::Pointer(_) => {
179                let signed = false;
180                tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
181            }
182            Primitive::Float(_) => bug!("floats do not have an int type"),
183        }
184    }
185}
186
187/// The first half of a wide pointer.
188///
189/// - For a trait object, this is the address of the box.
190/// - For a slice, this is the base address.
191pub const WIDE_PTR_ADDR: usize = 0;
192
193/// The second half of a wide pointer.
194///
195/// - For a trait object, this is the address of the vtable.
196/// - For a slice, this is the length.
197pub const WIDE_PTR_EXTRA: usize = 1;
198
199/// Used in `check_validity_requirement` to indicate the kind of initialization
200/// that is checked to be valid
201#[derive(#[automatically_derived]
impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ValidityRequirement {
    #[inline]
    fn clone(&self) -> ValidityRequirement { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ValidityRequirement {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ValidityRequirement::Inhabited => "Inhabited",
                ValidityRequirement::Zero => "Zero",
                ValidityRequirement::UninitMitigated0x01Fill =>
                    "UninitMitigated0x01Fill",
                ValidityRequirement::Uninit => "Uninit",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ValidityRequirement {
    #[inline]
    fn eq(&self, other: &ValidityRequirement) -> 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 ValidityRequirement {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ValidityRequirement {
    #[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, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            ValidityRequirement {
            #[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 {
                    ValidityRequirement::Inhabited => {}
                    ValidityRequirement::Zero => {}
                    ValidityRequirement::UninitMitigated0x01Fill => {}
                    ValidityRequirement::Uninit => {}
                }
            }
        }
    };StableHash)]
202pub enum ValidityRequirement {
203    Inhabited,
204    Zero,
205    /// The return value of mem::uninitialized, 0x01
206    /// (unless -Zstrict-init-checks is on, in which case it's the same as Uninit).
207    UninitMitigated0x01Fill,
208    /// True uninitialized memory.
209    Uninit,
210}
211
212impl ValidityRequirement {
213    pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
214        match intrinsic {
215            sym::assert_inhabited => Some(Self::Inhabited),
216            sym::assert_zero_valid => Some(Self::Zero),
217            sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
218            _ => None,
219        }
220    }
221}
222
223impl fmt::Display for ValidityRequirement {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        match self {
226            Self::Inhabited => f.write_str("is inhabited"),
227            Self::Zero => f.write_str("allows being left zeroed"),
228            Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
229            Self::Uninit => f.write_str("allows being left uninitialized"),
230        }
231    }
232}
233
234#[derive(#[automatically_derived]
impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SimdLayoutError {
    #[inline]
    fn clone(&self) -> SimdLayoutError {
        let _: ::core::clone::AssertParamIsClone<Limit>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SimdLayoutError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SimdLayoutError::ZeroLength =>
                ::core::fmt::Formatter::write_str(f, "ZeroLength"),
            SimdLayoutError::TooManyLanes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TooManyLanes", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            SimdLayoutError {
            #[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 {
                    SimdLayoutError::ZeroLength => {}
                    SimdLayoutError::TooManyLanes(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for SimdLayoutError {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        SimdLayoutError::ZeroLength => { 0usize }
                        SimdLayoutError::TooManyLanes(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    SimdLayoutError::ZeroLength => {}
                    SimdLayoutError::TooManyLanes(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for SimdLayoutError {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { SimdLayoutError::ZeroLength }
                    1usize => {
                        SimdLayoutError::TooManyLanes(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SimdLayoutError`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable)]
235pub enum SimdLayoutError {
236    /// The vector has 0 lanes.
237    ZeroLength,
238    /// The vector has more lanes than supported or permitted by
239    /// #\[rustc_simd_monomorphize_lane_limit\].
240    TooManyLanes(Limit),
241}
242
243#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutError<'tcx> {
    #[inline]
    fn clone(&self) -> LayoutError<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<SimdLayoutError>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<NormalizationError<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LayoutError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LayoutError::Unknown(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Unknown", &__self_0),
            LayoutError::SizeOverflow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SizeOverflow", &__self_0),
            LayoutError::InvalidSimd { ty: __self_0, kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "InvalidSimd", "ty", __self_0, "kind", &__self_1),
            LayoutError::TooGeneric(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "TooGeneric", &__self_0),
            LayoutError::NormalizationFailure(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "NormalizationFailure", __self_0, &__self_1),
            LayoutError::ReferencesError(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ReferencesError", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            LayoutError<'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 {
                    LayoutError::Unknown(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::SizeOverflow(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::InvalidSimd {
                        ty: ref __binding_0, kind: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::TooGeneric(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::NormalizationFailure(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    LayoutError::ReferencesError(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for LayoutError<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        LayoutError::Unknown(ref __binding_0) => { 0usize }
                        LayoutError::SizeOverflow(ref __binding_0) => { 1usize }
                        LayoutError::InvalidSimd {
                            ty: ref __binding_0, kind: ref __binding_1 } => {
                            2usize
                        }
                        LayoutError::TooGeneric(ref __binding_0) => { 3usize }
                        LayoutError::NormalizationFailure(ref __binding_0,
                            ref __binding_1) => {
                            4usize
                        }
                        LayoutError::ReferencesError(ref __binding_0) => { 5usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    LayoutError::Unknown(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::SizeOverflow(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::InvalidSimd {
                        ty: ref __binding_0, kind: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    LayoutError::TooGeneric(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    LayoutError::NormalizationFailure(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    LayoutError::ReferencesError(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for LayoutError<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        LayoutError::Unknown(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        LayoutError::SizeOverflow(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        LayoutError::InvalidSimd {
                            ty: ::rustc_serialize::Decodable::decode(__decoder),
                            kind: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    3usize => {
                        LayoutError::TooGeneric(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    4usize => {
                        LayoutError::NormalizationFailure(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    5usize => {
                        LayoutError::ReferencesError(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `LayoutError`, expected 0..6, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable)]
244pub enum LayoutError<'tcx> {
245    /// A type doesn't have a sensible layout.
246    ///
247    /// This variant is used for layout errors that don't necessarily cause
248    /// compile errors.
249    ///
250    /// For example, this can happen if a struct contains an unsized type in a
251    /// non-tail field, but has an unsatisfiable bound like `str: Sized`.
252    Unknown(Ty<'tcx>),
253    /// The size of a type exceeds [`TargetDataLayout::obj_size_bound`].
254    SizeOverflow(Ty<'tcx>),
255    /// A SIMD vector has invalid layout, such as zero-length or too many lanes.
256    InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
257    /// The layout can vary due to a generic parameter.
258    ///
259    /// Unlike `Unknown`, this variant is a "soft" error and indicates that the layout
260    /// may become computable after further instantiating the generic parameter(s).
261    TooGeneric(Ty<'tcx>),
262    /// An alias failed to normalize.
263    ///
264    /// This variant is necessary, because, due to trait solver incompleteness, it is
265    /// possible than an alias that was rigid during analysis fails to normalize after
266    /// revealing opaque types.
267    ///
268    /// See `tests/ui/layout/normalization-failure.rs` for an example.
269    NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
270    /// A non-layout error is reported elsewhere.
271    ReferencesError(ErrorGuaranteed),
272}
273
274impl<'tcx> fmt::Display for LayoutError<'tcx> {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        match *self {
277            LayoutError::Unknown(ty) => f.write_fmt(format_args!("the type `{0}` has an unknown layout", ty))write!(f, "the type `{ty}` has an unknown layout"),
278            LayoutError::TooGeneric(ty) => {
279                f.write_fmt(format_args!("the type `{0}` does not have a fixed layout", ty))write!(f, "the type `{ty}` does not have a fixed layout")
280            }
281            LayoutError::SizeOverflow(ty) => {
282                f.write_fmt(format_args!("values of the type `{0}` are too big for the target architecture",
        ty))write!(f, "values of the type `{ty}` are too big for the target architecture")
283            }
284            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
285                f.write_fmt(format_args!("the SIMD type `{0}` has more elements than the limit {1}",
        ty, max_lanes))write!(f, "the SIMD type `{ty}` has more elements than the limit {max_lanes}")
286            }
287            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
288                f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
289            }
290            LayoutError::NormalizationFailure(t, e) => f.write_fmt(format_args!("unable to determine layout for `{0}` because `{1}` cannot be normalized",
        t, e.get_type_for_failure()))write!(
291                f,
292                "unable to determine layout for `{}` because `{}` cannot be normalized",
293                t,
294                e.get_type_for_failure()
295            ),
296            LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
297        }
298    }
299}
300
301impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
302    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
303        self.to_string().into_diag_arg(&mut None)
304    }
305}
306
307#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
    #[inline]
    fn clone(&self) -> LayoutCx<'tcx> {
        let _:
                ::core::clone::AssertParamIsClone<abi::LayoutCalculator<TyCtxt<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<ty::TypingEnv<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutCx<'tcx> { }Copy)]
308pub struct LayoutCx<'tcx> {
309    pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
310    pub typing_env: ty::TypingEnv<'tcx>,
311}
312
313impl<'tcx> LayoutCx<'tcx> {
314    pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
315        Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
316    }
317}
318
319/// Type size "skeleton", i.e., the only information determining a type's size.
320/// While this is conservative, (aside from constant sizes, only pointers,
321/// newtypes thereof and null pointer optimized enums are allowed), it is
322/// enough to statically check common use cases of transmute.
323#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for SizeSkeleton<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx> {
    #[inline]
    fn clone(&self) -> SizeSkeleton<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Size>;
        let _: ::core::clone::AssertParamIsClone<Option<Align>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SizeSkeleton<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SizeSkeleton::Known(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Known",
                    __self_0, &__self_1),
            SizeSkeleton::Pointer { non_zero: __self_0, tail: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Pointer", "non_zero", __self_0, "tail", &__self_1),
        }
    }
}Debug)]
324pub enum SizeSkeleton<'tcx> {
325    /// Any statically computable Layout.
326    /// Alignment can be `None` if unknown.
327    Known(Size, Option<Align>),
328
329    /// A potentially-wide pointer.
330    Pointer {
331        /// If true, this pointer is never null.
332        non_zero: bool,
333        /// The type which determines the unsized metadata, if any,
334        /// of this pointer. Either a type parameter or a projection
335        /// depending on one, with regions erased.
336        tail: Ty<'tcx>,
337    },
338}
339
340impl<'tcx> SizeSkeleton<'tcx> {
341    pub fn compute(
342        ty: Ty<'tcx>,
343        tcx: TyCtxt<'tcx>,
344        typing_env: ty::TypingEnv<'tcx>,
345        span: Span,
346    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
347        Self::compute_inner(ty, tcx, typing_env, span, 0)
348    }
349
350    fn compute_inner(
351        ty: Ty<'tcx>,
352        tcx: TyCtxt<'tcx>,
353        typing_env: ty::TypingEnv<'tcx>,
354        span: Span,
355        depth: usize,
356    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
357        if true {
    if !!ty.has_non_region_infer() {
        ::core::panicking::panic("assertion failed: !ty.has_non_region_infer()")
    };
};debug_assert!(!ty.has_non_region_infer());
358
359        // Bail out if we've recursed too deeply (issue #156137); a cyclic type
360        // alias can otherwise blow the stack here. Using `>=` rather than `>`
361        // means we fire exactly at the limit, which lets us report the
362        // cycle-root type (`Thing<T>`) instead of an innocent field type.
363        let recursion_limit = tcx.recursion_limit();
364        if depth >= recursion_limit.0 {
365            let suggested_limit = match recursion_limit {
366                Limit(0) => Limit(2),
367                limit => limit * 2,
368            };
369            let reported =
370                tcx.dcx().emit_err(crate::diagnostics::RecursionLimitReachedSizeSkeleton {
371                    span,
372                    ty,
373                    suggested_limit,
374                });
375            return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
376        }
377
378        // First try computing a static layout.
379        let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
380            Ok(layout) => {
381                if layout.is_sized() {
382                    return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
383                } else {
384                    // Just to be safe, don't claim a known layout for unsized types.
385                    return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
386                }
387            }
388            Err(err @ LayoutError::TooGeneric(_)) => err,
389            // We can't extract SizeSkeleton info from other layout errors
390            Err(
391                e @ LayoutError::Unknown(_)
392                | e @ LayoutError::SizeOverflow(_)
393                | e @ LayoutError::InvalidSimd { .. }
394                | e @ LayoutError::NormalizationFailure(..)
395                | e @ LayoutError::ReferencesError(_),
396            ) => return Err(e),
397        };
398
399        match *ty.kind() {
400            ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
401                let non_zero = !ty.is_raw_ptr();
402
403                tcx.assert_fully_normalized(typing_env, pointee);
404                let tail = tcx.struct_tail_raw(
405                    pointee,
406                    &ObligationCause::dummy(),
407                    |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
408                        Ok(ty) => ty,
409                        Err(e) => Ty::new_error_with_message(
410                            tcx,
411                            DUMMY_SP,
412                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
                e.get_type_for_failure()))
    })format!(
413                                "normalization failed for {} but no errors reported",
414                                e.get_type_for_failure()
415                            ),
416                        ),
417                    },
418                    || {},
419                );
420
421                match tail.kind() {
422                    // FIXME(#155345): This should only handle rigid aliases if we're using
423                    // the new solver.
424                    ty::Param(_)
425                    | ty::Alias(
426                        _,
427                        ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
428                    ) => {
429                        if true {
    if !tail.has_non_region_param() {
        ::core::panicking::panic("assertion failed: tail.has_non_region_param()")
    };
};debug_assert!(tail.has_non_region_param());
430                        Ok(SizeSkeleton::Pointer {
431                            non_zero,
432                            tail: tcx.erase_and_anonymize_regions(tail),
433                        })
434                    }
435                    ty::Error(guar) => {
436                        // Fixes ICE #124031
437                        return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
438                    }
439                    _ => crate::util::bug::bug_fmt(format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
        ty, err, tail))bug!(
440                        "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
441                              tail `{tail}` is not a type parameter or a projection",
442                    ),
443                }
444            }
445            ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
446                let len_eval = len.try_to_target_usize(tcx);
447                if len_eval == Some(0) {
448                    return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
449                }
450
451                match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
452                    // This may succeed because the multiplication of two types may overflow
453                    // but a single size of a nested array will not.
454                    SizeSkeleton::Known(s, a) => {
455                        if let Some(c) = len_eval {
456                            let size = s
457                                .bytes()
458                                .checked_mul(c)
459                                .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
460                            // Alignment is unchanged by arrays.
461                            return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
462                        }
463                        Err(err)
464                    }
465                    SizeSkeleton::Pointer { .. } => Err(err),
466                }
467            }
468
469            ty::Adt(def, args) => {
470                // Only newtypes and enums w/ nullable pointer optimization (NPO).
471                if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
472                    return Err(err);
473                }
474                // Only default repr types.
475                {
476                    // We can ignore the seed and some particular flags that can never affect the
477                    // layout of newtypes / NPO types, but we have to check everything else.
478                    // If you are adding a new field to `ReprOptions`, make sure to extend the check
479                    // below so that we bail out if it is not at its default value!
480                    let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
481                        def.repr();
482                    let mut ignored_flags = ReprFlags::IS_TRANSPARENT
483                        | ReprFlags::IS_LINEAR
484                        | ReprFlags::RANDOMIZE_LAYOUT;
485                    if def.is_struct() {
486                        // `repr(C)` is only okay for structs, not for enums.
487                        // Below, the *only* thing we do for structs is propagating
488                        // `SizeSkeleton::Pointer`. We do *not* assume that `repr(C)` preserved
489                        // ZST-ness (which might stop being true eventually).
490                        ignored_flags |= ReprFlags::IS_C;
491                    }
492                    if int.is_some()
493                        || align.is_some()
494                        || pack.is_some()
495                        || flags.difference(ignored_flags) != ReprFlags::default()
496                        || scalable.is_some()
497                    {
498                        return Err(err);
499                    }
500                }
501
502                // Get a zero-sized variant or a pointer newtype.
503                // Returns `Ok(None)` for 1-ZST types, `Ok(Some)` if (ignoring all 1-ZST fields)
504                // there's just a single pointer, and `Err` otherwise.
505                let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
506                    let i = VariantIdx::from_usize(i);
507                    let fields = def.variant(i).fields.iter().map(|field| {
508                        SizeSkeleton::compute_inner(
509                            field.ty(tcx, args).skip_norm_wip(),
510                            tcx,
511                            typing_env,
512                            span,
513                            depth + 1,
514                        )
515                    });
516                    let mut ptr = None;
517                    for field in fields {
518                        let field = field?;
519                        match field {
520                            SizeSkeleton::Known(size, align) => {
521                                let is_1zst = size.bytes() == 0
522                                    && align.is_some_and(|align| align.bytes() == 1);
523                                if !is_1zst {
524                                    return Err(err);
525                                }
526                            }
527                            SizeSkeleton::Pointer { .. } => {
528                                if ptr.is_some() {
529                                    return Err(err);
530                                }
531                                ptr = Some(field);
532                            }
533                        }
534                    }
535                    Ok(ptr)
536                };
537
538                let v0 = zero_or_ptr_variant(0)?;
539                // Single-variant case: Check if this is a newtype around a pointer.
540                // Such types are themselves pointer-sized.
541                if def.variants().len() == 1 {
542                    if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
543                        return Ok(SizeSkeleton::Pointer { non_zero, tail });
544                    } else {
545                        return Err(err);
546                    }
547                }
548
549                let v1 = zero_or_ptr_variant(1)?;
550                // 2-variant case: Check if one variant is a *non-zero* pointer and the other a
551                // 1-ZST. Such types are eligible to for the nullable pointer enum optimization, so
552                // they are themselves pointer-sized.
553                match (v0, v1) {
554                    (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
555                    | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
556                        Ok(SizeSkeleton::Pointer { non_zero: false, tail })
557                    }
558                    _ => Err(err),
559                }
560            }
561
562            ty::Alias(..) => {
563                let normalized =
564                    tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
565                if ty == normalized {
566                    Err(err)
567                } else {
568                    SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
569                }
570            }
571
572            ty::Pat(base, pat) => {
573                // Pattern types are always the same size as their base.
574                let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
575                match *pat {
576                    ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
577                    // But in the case of `!null` patterns we need to note that in the
578                    // raw pointer.
579                    ty::PatternKind::NotNull => match base? {
580                        SizeSkeleton::Known(..) => base,
581                        SizeSkeleton::Pointer { non_zero: _, tail } => {
582                            Ok(SizeSkeleton::Pointer { non_zero: true, tail })
583                        }
584                    },
585                }
586            }
587
588            _ => Err(err),
589        }
590    }
591
592    pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
593        match (self, other) {
594            (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
595            (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
596                a == b
597            }
598            _ => false,
599        }
600    }
601}
602
603pub trait HasTyCtxt<'tcx>: HasDataLayout {
604    fn tcx(&self) -> TyCtxt<'tcx>;
605}
606
607pub trait HasTypingEnv<'tcx> {
608    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
609}
610
611impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
612    #[inline]
613    fn data_layout(&self) -> &TargetDataLayout {
614        &self.data_layout
615    }
616}
617
618impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
619    fn target_spec(&self) -> &Target {
620        &self.sess.target
621    }
622}
623
624impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
625    fn x86_abi_opt(&self) -> X86Abi {
626        X86Abi {
627            regparm: self.sess.opts.unstable_opts.regparm,
628            reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
629        }
630    }
631}
632
633impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
634    #[inline]
635    fn tcx(&self) -> TyCtxt<'tcx> {
636        *self
637    }
638}
639
640impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
641    #[inline]
642    fn data_layout(&self) -> &TargetDataLayout {
643        &self.data_layout
644    }
645}
646
647impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
648    fn target_spec(&self) -> &Target {
649        &self.sess.target
650    }
651}
652
653impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
654    #[inline]
655    fn tcx(&self) -> TyCtxt<'tcx> {
656        **self
657    }
658}
659
660impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
661    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
662        self.typing_env
663    }
664}
665
666impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
667    fn data_layout(&self) -> &TargetDataLayout {
668        self.calc.cx.data_layout()
669    }
670}
671
672impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
673    fn target_spec(&self) -> &Target {
674        self.calc.cx.target_spec()
675    }
676}
677
678impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
679    fn x86_abi_opt(&self) -> X86Abi {
680        self.calc.cx.x86_abi_opt()
681    }
682}
683
684impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
685    fn tcx(&self) -> TyCtxt<'tcx> {
686        self.calc.cx
687    }
688}
689
690pub trait MaybeResult<T> {
691    type Error;
692
693    fn from(x: Result<T, Self::Error>) -> Self;
694    fn to_result(self) -> Result<T, Self::Error>;
695}
696
697impl<T> MaybeResult<T> for T {
698    type Error = !;
699
700    fn from(Ok(x): Result<T, Self::Error>) -> Self {
701        x
702    }
703    fn to_result(self) -> Result<T, Self::Error> {
704        Ok(self)
705    }
706}
707
708impl<T, E> MaybeResult<T> for Result<T, E> {
709    type Error = E;
710
711    fn from(x: Result<T, Self::Error>) -> Self {
712        x
713    }
714    fn to_result(self) -> Result<T, Self::Error> {
715        self
716    }
717}
718
719pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
720
721/// Trait for contexts that want to be able to compute layouts of types.
722/// This automatically gives access to `LayoutOf`, through a blanket `impl`.
723pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
724    /// The `TyAndLayout`-wrapping type (or `TyAndLayout` itself), which will be
725    /// returned from `layout_of` (see also `handle_layout_err`).
726    type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
727
728    /// `Span` to use for `tcx.at(span)`, from `layout_of`.
729    // FIXME(eddyb) perhaps make this mandatory to get contexts to track it better?
730    #[inline]
731    fn layout_tcx_at_span(&self) -> Span {
732        DUMMY_SP
733    }
734
735    /// Helper used for `layout_of`, to adapt `tcx.layout_of(...)` into a
736    /// `Self::LayoutOfResult` (which does not need to be a `Result<...>`).
737    ///
738    /// Most `impl`s, which propagate `LayoutError`s, should simply return `err`,
739    /// but this hook allows e.g. codegen to return only `TyAndLayout` from its
740    /// `cx.layout_of(...)`, without any `Result<...>` around it to deal with
741    /// (and any `LayoutError`s are turned into fatal errors or ICEs).
742    fn handle_layout_err(
743        &self,
744        err: LayoutError<'tcx>,
745        span: Span,
746        ty: Ty<'tcx>,
747    ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
748}
749
750/// Blanket extension trait for contexts that can compute layouts of types.
751pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
752    /// Computes the layout of a type. Note that this implicitly
753    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
754    #[inline]
755    fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
756        self.spanned_layout_of(ty, DUMMY_SP)
757    }
758
759    /// Computes the layout of a type, at `span`. Note that this implicitly
760    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
761    // FIXME(eddyb) avoid passing information like this, and instead add more
762    // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`.
763    #[inline]
764    fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
765        let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
766        let tcx = self.tcx().at(span);
767
768        MaybeResult::from(
769            tcx.layout_of(self.typing_env().as_query_input(ty))
770                .map_err(|err| self.handle_layout_err(*err, span, ty)),
771        )
772    }
773}
774
775impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
776
777impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
778    type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
779
780    #[inline]
781    fn handle_layout_err(
782        &self,
783        err: LayoutError<'tcx>,
784        _: Span,
785        _: Ty<'tcx>,
786    ) -> &'tcx LayoutError<'tcx> {
787        self.tcx().arena.alloc(err)
788    }
789}
790
791impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
792where
793    C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
794{
795    fn ty_and_layout_for_variant(
796        this: TyAndLayout<'tcx>,
797        cx: &C,
798        variant_index: VariantIdx,
799    ) -> TyAndLayout<'tcx> {
800        let layout = match this.variants {
801            // If all variants but one are uninhabited, the variant layout is the enum layout.
802            Variants::Single { index } if index == variant_index => {
803                return this;
804            }
805
806            Variants::Single { .. } | Variants::Empty => {
807                // Single-variant and no-variant enums *can* have other variants, but those are
808                // uninhabited. Produce a layout that has the right fields for that variant, so that
809                // the rest of the compiler can project fields etc as usual.
810
811                let tcx = cx.tcx();
812                let typing_env = cx.typing_env();
813
814                // Deny calling for_variant more than once for non-Single enums.
815                if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
816                    {
    match (&original_layout.variants, &this.variants) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(original_layout.variants, this.variants);
817                }
818
819                let fields = match this.ty.kind() {
820                    ty::Adt(def, _) if def.variants().is_empty() => {
821                        crate::util::bug::bug_fmt(format_args!("for_variant called on zero-variant enum {0}",
        this.ty))bug!("for_variant called on zero-variant enum {}", this.ty)
822                    }
823                    ty::Adt(def, _) => def.variant(variant_index).fields.len(),
824                    _ => crate::util::bug::bug_fmt(format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
        this.ty))bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
825                };
826                tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
827            }
828
829            Variants::Multiple { .. } => {
830                cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
831            }
832        };
833
834        {
    match (&*layout.variants(), &Variants::Single { index: variant_index }) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(*layout.variants(), Variants::Single { index: variant_index });
835
836        TyAndLayout { ty: this.ty, layout }
837    }
838
839    fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
840        enum TyMaybeWithLayout<'tcx> {
841            Ty(Ty<'tcx>),
842            TyAndLayout(TyAndLayout<'tcx>),
843        }
844
845        fn field_ty_or_layout<'tcx>(
846            this: TyAndLayout<'tcx>,
847            cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
848            i: usize,
849        ) -> TyMaybeWithLayout<'tcx> {
850            let tcx = cx.tcx();
851            let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
852                TyAndLayout {
853                    layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
854                    ty: tag.primitive().to_ty(tcx),
855                }
856            };
857
858            match *this.ty.kind() {
859                ty::Bool
860                | ty::Char
861                | ty::Int(_)
862                | ty::Uint(_)
863                | ty::Float(_)
864                | ty::FnPtr(..)
865                | ty::Never
866                | ty::FnDef(..)
867                | ty::CoroutineWitness(..)
868                | ty::Foreign(..)
869                | ty::Dynamic(_, _) => {
870                    crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
        this))bug!("TyAndLayout::field({:?}): not applicable", this)
871                }
872
873                ty::Pat(base, _) => {
874                    {
    match (&i, &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(i, 0);
875                    TyMaybeWithLayout::Ty(base)
876                }
877
878                ty::UnsafeBinder(bound_ty) => {
879                    let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
880                    field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
881                }
882
883                // Potentially-wide pointers.
884                ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
885                    if !(i < this.fields.count()) {
    ::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
886
887                    // Reuse the wide `*T` type as its own thin pointer data field.
888                    // This provides information about, e.g., DST struct pointees
889                    // (which may have no non-DST form), and will work as long
890                    // as the `Abi` or `FieldsShape` is checked by users.
891                    if i == 0 {
892                        let nil = tcx.types.unit;
893                        let unit_ptr_ty = if this.ty.is_raw_ptr() {
894                            Ty::new_mut_ptr(tcx, nil)
895                        } else {
896                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
897                        };
898
899                        // NOTE: using an fully monomorphized typing env and `unwrap`-ing
900                        // the `Result` should always work because the type is always either
901                        // `*mut ()` or `&'static mut ()`.
902                        let typing_env = ty::TypingEnv::fully_monomorphized();
903                        return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
904                            ty: this.ty,
905                            ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
906                        });
907                    }
908
909                    let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
910                        let min_count = ty::vtable_min_entries(
911                            tcx,
912                            principal.map(|principal| {
913                                tcx.instantiate_bound_regions_with_erased(principal)
914                            }),
915                        );
916                        Ty::new_imm_ref(
917                            tcx,
918                            tcx.lifetimes.re_static,
919                            // FIXME: properly type (e.g. usize and fn pointers) the fields.
920                            Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
921                        )
922                    };
923
924                    let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
925                        // Projection eagerly bails out when the pointee references errors,
926                        // fall back to structurally deducing metadata.
927                        && !pointee.references_error()
928                    {
929                        let metadata = tcx.normalize_erasing_regions(
930                            cx.typing_env(),
931                            Unnormalized::new(Ty::new_projection(
932                                tcx,
933                                ty::IsRigid::No,
934                                metadata_def_id,
935                                [pointee],
936                            )),
937                        );
938
939                        // Map `Metadata = DynMetadata<dyn Trait>` back to a vtable, since it
940                        // offers better information than `std::ptr::metadata::VTable`,
941                        // and we rely on this layout information to trigger a panic in
942                        // `std::mem::uninitialized::<&dyn Trait>()`, for example.
943                        if let ty::Adt(def, args) = metadata.kind()
944                            && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
945                            && let ty::Dynamic(data, _) = args.type_at(0).kind()
946                        {
947                            mk_dyn_vtable(data.principal())
948                        } else {
949                            metadata
950                        }
951                    } else {
952                        match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
953                            ty::Slice(_) | ty::Str => tcx.types.usize,
954                            ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
955                            _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
        this))bug!("TyAndLayout::field({:?}): not applicable", this),
956                        }
957                    };
958
959                    TyMaybeWithLayout::Ty(metadata)
960                }
961
962                // Arrays and slices.
963                ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
964                ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
965
966                // Tuples, coroutines and closures.
967                ty::Closure(_, args) => field_ty_or_layout(
968                    TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
969                    cx,
970                    i,
971                ),
972
973                ty::CoroutineClosure(_, args) => field_ty_or_layout(
974                    TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
975                    cx,
976                    i,
977                ),
978
979                ty::Coroutine(def_id, args) => match this.variants {
980                    Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
981                    Variants::Single { index } => TyMaybeWithLayout::Ty(
982                        args.as_coroutine()
983                            .state_tys(def_id, tcx)
984                            .nth(index.as_usize())
985                            .unwrap()
986                            .nth(i)
987                            .unwrap(),
988                    ),
989                    Variants::Multiple { tag, tag_field, .. } => {
990                        if FieldIdx::from_usize(i) == tag_field {
991                            TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
992                        } else {
993                            TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
994                        }
995                    }
996                },
997
998                ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
999
1000                // ADTs.
1001                ty::Adt(def, args) => {
1002                    match this.variants {
1003                        Variants::Single { index } => {
1004                            let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
1005                            TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
1006                        }
1007                        Variants::Empty => {
    ::core::panicking::panic_fmt(format_args!("there is no field in Variants::Empty types"));
}panic!("there is no field in Variants::Empty types"),
1008
1009                        // Discriminant field for enums (where applicable).
1010                        Variants::Multiple { tag, .. } => {
1011                            {
    match (&i, &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(i, 0);
1012                            return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1013                        }
1014                    }
1015                }
1016
1017                ty::Alias(..)
1018                | ty::Bound(..)
1019                | ty::Placeholder(..)
1020                | ty::Param(_)
1021                | ty::Infer(_)
1022                | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
        this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1023            }
1024        }
1025
1026        match field_ty_or_layout(this, cx, i) {
1027            TyMaybeWithLayout::Ty(field_ty) => {
1028                cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1029                    crate::util::bug::bug_fmt(format_args!("failed to get layout for `{0}`: {1:?},\ndespite it being a field (#{2}) of an existing layout: {3:#?}",
        field_ty, e, i, this))bug!(
1030                        "failed to get layout for `{field_ty}`: {e:?},\n\
1031                         despite it being a field (#{i}) of an existing layout: {this:#?}",
1032                    )
1033                })
1034            }
1035            TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1036        }
1037    }
1038
1039    /// Compute the information for the pointer stored at the given offset inside this type.
1040    /// This will recurse into fields of ADTs to find the inner pointer.
1041    fn ty_and_layout_pointee_info_at(
1042        this: TyAndLayout<'tcx>,
1043        cx: &C,
1044        offset: Size,
1045    ) -> Option<PointeeInfo> {
1046        let tcx = cx.tcx();
1047        let typing_env = cx.typing_env();
1048
1049        // Use conservative pointer kind if not optimizing. This saves us the
1050        // Freeze/Unpin queries, and can save time in the codegen backend (noalias
1051        // attributes in LLVM have compile-time cost even in unoptimized builds).
1052        let optimize = tcx.sess.opts.optimize != OptLevel::No;
1053
1054        let pointee_info = match *this.ty.kind() {
1055            ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1056                Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1057            }
1058            ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1059                tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1060                    let kind = match mt {
1061                        hir::Mutability::Not => {
1062                            let frozen = optimize && ty.is_freeze(tcx, typing_env);
1063                            PointerKind::SharedRef { frozen }
1064                        }
1065                        hir::Mutability::Mut => {
1066                            let unpin = optimize
1067                                && ty.is_unpin(tcx, typing_env)
1068                                && ty.is_unsafe_unpin(tcx, typing_env);
1069                            PointerKind::MutableRef { unpin }
1070                        }
1071                    };
1072                    PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1073                })
1074            }
1075
1076            ty::Adt(..)
1077                if offset.bytes() == 0
1078                    && let Some(pointee) = this.ty.boxed_ty() =>
1079            {
1080                tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1081                    safe: Some(PointerKind::Box {
1082                        // Same logic as for mutable references above.
1083                        unpin: optimize
1084                            && pointee.is_unpin(tcx, typing_env)
1085                            && pointee.is_unsafe_unpin(tcx, typing_env),
1086                        global: this.ty.is_box_global(tcx),
1087                    }),
1088                    size: layout.size,
1089                    align: layout.align.abi,
1090                })
1091            }
1092
1093            ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1094                Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1095                    PointeeInfo {
1096                        // Mark the pointer as raw
1097                        // (thus removing noalias/readonly/etc in case of the llvm backend)
1098                        safe: None,
1099                        // Make sure we don't assert dereferenceability of the pointer.
1100                        size: Size::ZERO,
1101                        // Preserve the alignment assertion! That is required even inside `MaybeDangling`.
1102                        align: info.align,
1103                    }
1104                })
1105            }
1106
1107            _ => {
1108                let mut data_variant = match &this.variants {
1109                    // Within the discriminant field, only the niche itself is
1110                    // always initialized, so we only check for a pointer at its
1111                    // offset.
1112                    //
1113                    // Our goal here is to check whether this represents a
1114                    // "dereferenceable or null" pointer, so we need to ensure
1115                    // that there is only one other variant, and it must be null.
1116                    // Below, we will then check whether the pointer is indeed
1117                    // dereferenceable.
1118                    Variants::Multiple {
1119                        tag_encoding:
1120                            TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1121                        tag_field,
1122                        variants,
1123                        ..
1124                    } if variants.len() == 2
1125                        && this.fields.offset(tag_field.as_usize()) == offset =>
1126                    {
1127                        let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1128                            VariantIdx::from_u32(1)
1129                        } else {
1130                            VariantIdx::from_u32(0)
1131                        };
1132                        {
    match (&tagged_variant, &niche_variants.start) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(tagged_variant, niche_variants.start);
1133                        if *niche_start == 0 {
1134                            // The other variant is encoded as "null", so we can recurse searching for
1135                            // a pointer here. This relies on the fact that the codegen backend
1136                            // only adds "dereferenceable" if there's also a "nonnull" proof,
1137                            // and that null is aligned for all alignments so it's okay to forward
1138                            // the pointer's alignment.
1139                            Some(this.for_variant(cx, *untagged_variant))
1140                        } else {
1141                            None
1142                        }
1143                    }
1144                    Variants::Multiple { .. } => None,
1145                    Variants::Empty | Variants::Single { .. } => Some(this),
1146                };
1147
1148                if let Some(variant) = data_variant
1149                    // We're not interested in any unions.
1150                    && let FieldsShape::Union(_) = variant.fields
1151                {
1152                    data_variant = None;
1153                }
1154
1155                let mut result = None;
1156
1157                if let Some(variant) = data_variant {
1158                    // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1159                    // (requires passing in the expected address space from the caller)
1160                    let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1161                    for i in 0..variant.fields.count() {
1162                        let field_start = variant.fields.offset(i);
1163                        if field_start <= offset {
1164                            let field = variant.field(cx, i);
1165                            result = field.to_result().ok().and_then(|field| {
1166                                if ptr_end <= field_start + field.size {
1167                                    // We found the right field, look inside it.
1168                                    let field_info =
1169                                        field.pointee_info_at(cx, offset - field_start);
1170                                    field_info
1171                                } else {
1172                                    None
1173                                }
1174                            });
1175                            if result.is_some() {
1176                                break;
1177                            }
1178                        }
1179                    }
1180                }
1181
1182                result
1183            }
1184        };
1185
1186        {
    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/layout.rs:1186",
                        "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1186u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
                                                    offset, this.ty.kind(), pointee_info) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1187            "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1188            offset,
1189            this.ty.kind(),
1190            pointee_info
1191        );
1192
1193        pointee_info
1194    }
1195
1196    fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1197        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1198    }
1199
1200    fn is_never(this: TyAndLayout<'tcx>) -> bool {
1201        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(this.ty.kind(), ty::Never)
1202    }
1203
1204    fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1205        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1206    }
1207
1208    fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1209        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Tuple(list) if list.len() == 0 => true,
    _ => false,
}matches!(this.ty.kind(), ty::Tuple(list) if list.len() == 0)
1210    }
1211
1212    fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1213        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(def, _) if def.repr().transparent() => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().transparent())
1214    }
1215
1216    /// Is this type `core::num::Complex<T>`?
1217    fn is_complex_number_lang_item(this: TyAndLayout<'tcx>, cx: &C) -> bool {
1218        let Some(def) = this.ty.ty_adt_def() else { return false };
1219        cx.tcx().is_lang_item(def.did(), LangItem::Complex)
1220    }
1221
1222    fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1223        this.ty.is_scalable_vector()
1224    }
1225
1226    /// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
1227    fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1228        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(def, _) if
        def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS)
        => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS))
1229    }
1230}
1231
1232/// Calculates whether a function's ABI can unwind or not.
1233///
1234/// This takes two primary parameters:
1235///
1236/// * `fn_def_id` - the `DefId` of the function. If this is provided then we can
1237///   determine more precisely if the function can unwind. If this is not provided
1238///   then we will only infer whether the function can unwind or not based on the
1239///   ABI of the function. For example, a function marked with `#[rustc_nounwind]`
1240///   is known to not unwind even if it's using Rust ABI.
1241///
1242/// * `abi` - this is the ABI that the function is defined with. This is the
1243///   primary factor for determining whether a function can unwind or not.
1244///
1245/// Note that in this case unwinding is not necessarily panicking in Rust. Rust
1246/// panics are implemented with unwinds on most platform (when
1247/// `-Cpanic=unwind`), but this also accounts for `-Cpanic=abort` build modes.
1248/// Notably unwinding is disallowed for more non-Rust ABIs unless it's
1249/// specifically in the name (e.g. `"C-unwind"`). Unwinding within each ABI is
1250/// defined for each ABI individually, but it always corresponds to some form of
1251/// stack-based unwinding (the exact mechanism of which varies
1252/// platform-by-platform).
1253///
1254/// Rust functions are classified whether or not they can unwind based on the
1255/// active "panic strategy". In other words Rust functions are considered to
1256/// unwind in `-Cpanic=unwind` mode and cannot unwind in `-Cpanic=abort` mode.
1257/// Note that Rust supports intermingling panic=abort and panic=unwind code, but
1258/// only if the final panic mode is panic=abort. In this scenario any code
1259/// previously compiled assuming that a function can unwind is still correct, it
1260/// just never happens to actually unwind at runtime.
1261///
1262/// This function's answer to whether or not a function can unwind is quite
1263/// impactful throughout the compiler. This affects things like:
1264///
1265/// * Calling a function which can't unwind means codegen simply ignores any
1266///   associated unwinding cleanup.
1267/// * Calling a function which can unwind from a function which can't unwind
1268///   causes the `abort_unwinding_calls` MIR pass to insert a landing pad that
1269///   aborts the process.
1270/// * This affects whether functions have the LLVM `nounwind` attribute, which
1271///   affects various optimizations and codegen.
1272#[inline]
1273#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_can_unwind",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1273u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("abi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("abi");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(did) = fn_def_id {
                if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
                    {
                    return false;
                }
                if !tcx.sess.panic_strategy().unwinds() &&
                        !tcx.is_foreign_item(did) {
                    return false;
                }
                if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
                        tcx.is_lang_item(did, LangItem::DropGlue) {
                    return false;
                }
            }
            use ExternAbi::*;
            match abi {
                C { unwind } | System { unwind } | Cdecl { unwind } |
                    Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
                    unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
                    unwind } | SysV64 { unwind } => unwind,
                PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
                    EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
                    CmseNonSecureCall | CmseNonSecureEntry | Custom |
                    RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
                    Unadjusted => false,
                Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
                    tcx.sess.panic_strategy().unwinds()
                }
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(tcx))]
1274pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1275    if let Some(did) = fn_def_id {
1276        // Special attribute for functions which can't unwind.
1277        if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1278            return false;
1279        }
1280
1281        // With `-C panic=abort`, all non-FFI functions are required to not unwind.
1282        //
1283        // Note that this is true regardless ABI specified on the function -- a `extern "C-unwind"`
1284        // function defined in Rust is also required to abort.
1285        if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1286            return false;
1287        }
1288
1289        // With -Z panic-in-drop=abort, `drop_glue` never unwinds.
1290        //
1291        // This is not part of `codegen_fn_attrs` as it can differ between crates
1292        // and therefore cannot be computed in core.
1293        if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1294            && tcx.is_lang_item(did, LangItem::DropGlue)
1295        {
1296            return false;
1297        }
1298    }
1299
1300    // Otherwise if this isn't special then unwinding is generally determined by
1301    // the ABI of the itself. ABIs like `C` have variants which also
1302    // specifically allow unwinding (`C-unwind`), but not all platform-specific
1303    // ABIs have such an option. Otherwise the only other thing here is Rust
1304    // itself, and those ABIs are determined by the panic strategy configured
1305    // for this compilation.
1306    use ExternAbi::*;
1307    match abi {
1308        C { unwind }
1309        | System { unwind }
1310        | Cdecl { unwind }
1311        | Stdcall { unwind }
1312        | Fastcall { unwind }
1313        | Vectorcall { unwind }
1314        | Thiscall { unwind }
1315        | Aapcs { unwind }
1316        | Win64 { unwind }
1317        | SysV64 { unwind } => unwind,
1318        PtxKernel
1319        | Msp430Interrupt
1320        | X86Interrupt
1321        | GpuKernel
1322        | EfiApi
1323        | AvrInterrupt
1324        | AvrNonBlockingInterrupt
1325        | CmseNonSecureCall
1326        | CmseNonSecureEntry
1327        | Custom
1328        | RiscvInterruptM
1329        | RiscvInterruptS
1330        | RustInvalid
1331        | Swift
1332        | Unadjusted => false,
1333        Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1334            tcx.sess.panic_strategy().unwinds()
1335        }
1336    }
1337}
1338
1339/// Error produced by attempting to compute or adjust a `FnAbi`.
1340#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
    #[inline]
    fn clone(&self) -> FnAbiError<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnAbiError::Layout(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
                    &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            FnAbiError<'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 {
                    FnAbiError::Layout(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1341pub enum FnAbiError<'tcx> {
1342    /// Error produced by a `layout_of` call, while computing `FnAbi` initially.
1343    Layout(LayoutError<'tcx>),
1344}
1345
1346impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1347    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1348        match self {
1349            Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1350        }
1351    }
1352}
1353
1354// FIXME(eddyb) maybe use something like this for an unified `fn_abi_of`, not
1355// just for error handling.
1356#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiRequest<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FnAbiRequest::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfFnPtr", "sig", __self_0, "extra_args", &__self_1),
            FnAbiRequest::OfInstance {
                instance: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfInstance", "instance", __self_0, "extra_args",
                    &__self_1),
        }
    }
}Debug)]
1357pub enum FnAbiRequest<'tcx> {
1358    OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1359    OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1360}
1361
1362/// Trait for contexts that want to be able to compute `FnAbi`s.
1363/// This automatically gives access to `FnAbiOf`, through a blanket `impl`.
1364pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1365    /// The `&FnAbi`-wrapping type (or `&FnAbi` itself), which will be
1366    /// returned from `fn_abi_of_*` (see also `handle_fn_abi_err`).
1367    type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1368
1369    /// Helper used for `fn_abi_of_*`, to adapt `tcx.fn_abi_of_*(...)` into a
1370    /// `Self::FnAbiOfResult` (which does not need to be a `Result<...>`).
1371    ///
1372    /// Most `impl`s, which propagate `FnAbiError`s, should simply return `err`,
1373    /// but this hook allows e.g. codegen to return only `&FnAbi` from its
1374    /// `cx.fn_abi_of_*(...)`, without any `Result<...>` around it to deal with
1375    /// (and any `FnAbiError`s are turned into fatal errors or ICEs).
1376    fn handle_fn_abi_err(
1377        &self,
1378        err: FnAbiError<'tcx>,
1379        span: Span,
1380        fn_abi_request: FnAbiRequest<'tcx>,
1381    ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1382}
1383
1384/// Blanket extension trait for contexts that can compute `FnAbi`s.
1385pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1386    /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers.
1387    ///
1388    /// NB: this doesn't handle virtual calls - those should use `fn_abi_of_instance`
1389    /// instead, where the instance is an `InstanceKind::Virtual`.
1390    #[inline]
1391    fn fn_abi_of_fn_ptr(
1392        &self,
1393        sig: ty::PolyFnSig<'tcx>,
1394        extra_args: &'tcx ty::List<Ty<'tcx>>,
1395    ) -> Self::FnAbiOfResult {
1396        // FIXME(eddyb) get a better `span` here.
1397        let span = self.layout_tcx_at_span();
1398        let tcx = self.tcx().at(span);
1399
1400        MaybeResult::from(
1401            tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1402                |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1403            ),
1404        )
1405    }
1406
1407    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1408    /// to an `fn`. Indirectly-passed parameters in the returned ABI might not include all possible
1409    /// codegen optimization attributes (such as `ReadOnly` or `CapturesNone`), as deducing these
1410    /// requires inspection of function bodies that can lead to cycles when performed during typeck.
1411    /// Post typeck, you should prefer the optimized ABI returned by `fn_abi_of_instance`.
1412    ///
1413    /// NB: the ABI returned by this query must not differ from that returned by
1414    ///     `fn_abi_of_instance` in any other way.
1415    ///
1416    /// * that includes virtual calls, which are represented by "direct calls" to an
1417    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1418    #[inline]
1419    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_abi_of_instance_no_deduced_attrs",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1419u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("extra_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("extra_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.layout_tcx_at_span();
            let tcx = self.tcx().at(span);
            MaybeResult::from(tcx.fn_abi_of_instance_no_deduced_attrs(self.typing_env().as_query_input((instance,
                                extra_args))).map_err(|err|
                        {
                            let span =
                                if !span.is_dummy() {
                                    span
                                } else { tcx.def_span(instance.def_id()) };
                            self.handle_fn_abi_err(*err, span,
                                FnAbiRequest::OfInstance { instance, extra_args })
                        }))
        }
    }
}#[tracing::instrument(level = "debug", skip(self))]
1420    fn fn_abi_of_instance_no_deduced_attrs(
1421        &self,
1422        instance: ty::Instance<'tcx>,
1423        extra_args: &'tcx ty::List<Ty<'tcx>>,
1424    ) -> Self::FnAbiOfResult {
1425        // FIXME(eddyb) get a better `span` here.
1426        let span = self.layout_tcx_at_span();
1427        let tcx = self.tcx().at(span);
1428
1429        MaybeResult::from(
1430            tcx.fn_abi_of_instance_no_deduced_attrs(
1431                self.typing_env().as_query_input((instance, extra_args)),
1432            )
1433            .map_err(|err| {
1434                // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1435                // we can get some kind of span even if one wasn't provided.
1436                // However, we don't do this early in order to avoid calling
1437                // `def_span` unconditionally (which may have a perf penalty).
1438                let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1439                self.handle_fn_abi_err(
1440                    *err,
1441                    span,
1442                    FnAbiRequest::OfInstance { instance, extra_args },
1443                )
1444            }),
1445        )
1446    }
1447
1448    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1449    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
1450    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
1451    /// which requires inspection of function bodies that can lead to cycles when performed during
1452    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
1453    /// `fn_abi_of_instance_no_deduced_attrs`.
1454    ///
1455    /// * that includes virtual calls, which are represented by "direct calls" to an
1456    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1457    #[inline]
1458    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_abi_of_instance",
                                    "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1458u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("extra_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("extra_args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.layout_tcx_at_span();
            let tcx = self.tcx().at(span);
            MaybeResult::from(tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance,
                                extra_args))).map_err(|err|
                        {
                            let span =
                                if !span.is_dummy() {
                                    span
                                } else { tcx.def_span(instance.def_id()) };
                            self.handle_fn_abi_err(*err, span,
                                FnAbiRequest::OfInstance { instance, extra_args })
                        }))
        }
    }
}#[tracing::instrument(level = "debug", skip(self))]
1459    fn fn_abi_of_instance(
1460        &self,
1461        instance: ty::Instance<'tcx>,
1462        extra_args: &'tcx ty::List<Ty<'tcx>>,
1463    ) -> Self::FnAbiOfResult {
1464        // FIXME(eddyb) get a better `span` here.
1465        let span = self.layout_tcx_at_span();
1466        let tcx = self.tcx().at(span);
1467
1468        MaybeResult::from(
1469            tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1470                .map_err(|err| {
1471                    // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1472                    // we can get some kind of span even if one wasn't provided.
1473                    // However, we don't do this early in order to avoid calling
1474                    // `def_span` unconditionally (which may have a perf penalty).
1475                    let span =
1476                        if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1477                    self.handle_fn_abi_err(
1478                        *err,
1479                        span,
1480                        FnAbiRequest::OfInstance { instance, extra_args },
1481                    )
1482                }),
1483        )
1484    }
1485}
1486
1487impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}