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_attr_ir::lang_items::LangItem;
10use rustc_errors::{Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, IntoDiagArg, Level};
11use rustc_hir as hir;
12use rustc_hir::def_id::DefId;
13use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
14use rustc_session::config::OptLevel;
15use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Spanned, Symbol, bug, span_bug, sym};
16use rustc_structures::Limit;
17use rustc_target::callconv::FnAbi;
18use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
19use rustc_type_ir::Const;
20use tracing::debug;
21
22use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
23use crate::query::TyCtxtAt;
24use crate::traits::ObligationCause;
25use crate::ty::normalize_erasing_regions::NormalizationError;
26use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
27
28pub trait IntegerExt {
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool)
    -> Ty<'tcx>;
    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy)
    -> abi::Integer;
    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
    -> abi::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);
}
impl 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 {
                ::rustc_span::macros::bug_impl(None,
                    format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
                        ty), Location::caller())
            }
            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)]
29impl abi::Integer {
30    #[inline]
31    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
32        use abi::Integer::{I8, I16, I32, I64, I128};
33        match (*self, signed) {
34            (I8, false) => tcx.types.u8,
35            (I16, false) => tcx.types.u16,
36            (I32, false) => tcx.types.u32,
37            (I64, false) => tcx.types.u64,
38            (I128, false) => tcx.types.u128,
39            (I8, true) => tcx.types.i8,
40            (I16, true) => tcx.types.i16,
41            (I32, true) => tcx.types.i32,
42            (I64, true) => tcx.types.i64,
43            (I128, true) => tcx.types.i128,
44        }
45    }
46
47    fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
48        use abi::Integer::{I8, I16, I32, I64, I128};
49        match ity {
50            ty::IntTy::I8 => I8,
51            ty::IntTy::I16 => I16,
52            ty::IntTy::I32 => I32,
53            ty::IntTy::I64 => I64,
54            ty::IntTy::I128 => I128,
55            ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
56        }
57    }
58    fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
59        use abi::Integer::{I8, I16, I32, I64, I128};
60        match ity {
61            ty::UintTy::U8 => I8,
62            ty::UintTy::U16 => I16,
63            ty::UintTy::U32 => I32,
64            ty::UintTy::U64 => I64,
65            ty::UintTy::U128 => I128,
66            ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
67        }
68    }
69
70    /// Finds the appropriate Integer type and signedness for the given
71    /// discriminant range and `#[repr]` attribute.
72    ///
73    /// To represent the way the values were written in the rust source, min and max
74    /// are in different types. It's thus possible to pass in an unrepresentable range,
75    /// and the method will panic in those cases.
76    ///
77    /// This is the basis for computing the type of the *tag* of an enum (which can be smaller than
78    /// the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`]).
79    fn discr_range_of_repr<'tcx>(
80        tcx: TyCtxt<'tcx>,
81        ty: Ty<'tcx>,
82        repr: &ReprOptions,
83        min_negative: i128,
84        max_positive: u128,
85    ) -> (abi::Integer, bool) {
86        assert!(
87            min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned(),
88            "No type can represent the full range of {min_negative}..={max_positive}",
89        );
90
91        // Theoretically, negative values could be larger in unsigned representation
92        // than the unsigned representation of the signed minimum. However, if there
93        // are any negative values, the only valid unsigned representation is u128
94        // which can fit all i128 values, so the result remains unaffected.
95        let unsigned_fit =
96            abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(), max_positive));
97        let signed_fit = cmp::max(
98            abi::Integer::fit_signed(min_negative),
99            abi::Integer::fit_signed(max_positive.cast_signed()),
100        );
101
102        if let Some(ity) = repr.int {
103            let discr = abi::Integer::from_attr(&tcx, ity);
104            let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
105            if discr < fit {
106                bug!(
107                    "Integer::repr_discr: `#[repr]` hint too small for \
108                      discriminant range of enum `{}`",
109                    ty
110                )
111            }
112            return (discr, ity.is_signed());
113        }
114
115        let at_least = if repr.c() {
116            // This is usually I32, however it can be different on some platforms,
117            // notably hexagon and arm-none/thumb-none
118            tcx.data_layout().c_enum_min_size
119        } else {
120            // repr(Rust) enums try to be as small as possible
121            abi::Integer::I8
122        };
123
124        // Pick the smallest fit. Prefer unsigned; that matches clang in cases where this makes a
125        // difference (https://godbolt.org/z/h4xEasW1d) so it is crucial for repr(C).
126        if unsigned_fit <= signed_fit {
127            (cmp::max(unsigned_fit, at_least), false)
128        } else {
129            (cmp::max(signed_fit, at_least), true)
130        }
131    }
132}
133
134pub trait FloatExt {
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
    -> Ty<'tcx>;
    fn from_float_ty(fty: ty::FloatTy)
    -> Self;
}
impl FloatExt for abi::Float {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        use abi::Float::*;
        match *self {
            F16 => tcx.types.f16,
            F16B =>
                Ty::new_adt(tcx,
                    tcx.adt_def(tcx.require_lang_item(LangItem::F16B,
                            DUMMY_SP)), ty::GenericArgs::empty()),
            F32 => tcx.types.f32,
            F64 => tcx.types.f64,
            X87F80 =>
                Ty::new_adt(tcx,
                    tcx.adt_def(tcx.require_lang_item(LangItem::X87F80Raw,
                            DUMMY_SP)), ty::GenericArgs::empty()),
            F128 => tcx.types.f128,
            PpcF128 =>
                Ty::new_adt(tcx,
                    tcx.adt_def(tcx.require_lang_item(LangItem::PpcF128,
                            DUMMY_SP)), ty::GenericArgs::empty()),
        }
    }
    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)]
135impl abi::Float {
136    #[inline]
137    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
138        use abi::Float::*;
139        match *self {
140            F16 => tcx.types.f16,
141            F16B => Ty::new_adt(
142                tcx,
143                tcx.adt_def(tcx.require_lang_item(LangItem::F16B, DUMMY_SP)),
144                ty::GenericArgs::empty(),
145            ),
146            F32 => tcx.types.f32,
147            F64 => tcx.types.f64,
148            X87F80 => Ty::new_adt(
149                tcx,
150                tcx.adt_def(tcx.require_lang_item(LangItem::X87F80Raw, DUMMY_SP)),
151                ty::GenericArgs::empty(),
152            ),
153            F128 => tcx.types.f128,
154            PpcF128 => Ty::new_adt(
155                tcx,
156                tcx.adt_def(tcx.require_lang_item(LangItem::PpcF128, DUMMY_SP)),
157                ty::GenericArgs::empty(),
158            ),
159        }
160    }
161
162    fn from_float_ty(fty: ty::FloatTy) -> Self {
163        use abi::Float::*;
164        match fty {
165            ty::FloatTy::F16 => F16,
166            ty::FloatTy::F32 => F32,
167            ty::FloatTy::F64 => F64,
168            ty::FloatTy::F128 => F128,
169        }
170    }
171}
172
173pub trait PrimitiveExt {
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
    -> Ty<'tcx>;
    #[doc = " Return an *integer* type matching this primitive."]
    #[doc = " Useful in particular when dealing with enum discriminants."]
    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
    -> Ty<'tcx>;
}
impl PrimitiveExt for Primitive {
    #[inline]
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match *self {
            Primitive::Bool => tcx.types.u8,
            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::Bool => tcx.types.u8,
            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(_) =>
                ::rustc_span::macros::bug_impl(None,
                    format_args!("floats do not have an int type"),
                    Location::caller()),
        }
    }
}#[extension(pub trait PrimitiveExt)]
174impl Primitive {
175    #[inline]
176    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
177        match *self {
178            Primitive::Bool => tcx.types.u8,
179            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
180            Primitive::Float(f) => f.to_ty(tcx),
181            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
182            Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
183        }
184    }
185
186    /// Return an *integer* type matching this primitive.
187    /// Useful in particular when dealing with enum discriminants.
188    #[inline]
189    fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
190        match *self {
191            Primitive::Bool => tcx.types.u8,
192            Primitive::Int(i, signed) => i.to_ty(tcx, signed),
193            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
194            Primitive::Pointer(_) => {
195                let signed = false;
196                tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
197            }
198            Primitive::Float(_) => bug!("floats do not have an int type"),
199        }
200    }
201}
202
203/// The first half of a wide pointer.
204///
205/// - For a trait object, this is the address of the box.
206/// - For a slice, this is the base address.
207pub const WIDE_PTR_ADDR: usize = 0;
208
209/// The second half of a wide pointer.
210///
211/// - For a trait object, this is the address of the vtable.
212/// - For a slice, this is the length.
213pub const WIDE_PTR_EXTRA: usize = 1;
214
215/// Used in `check_validity_requirement` to indicate the kind of initialization
216/// that is checked to be valid
217#[derive(#[automatically_derived]impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ValidityRequirement {
}
#[automatically_derived]impl ::core::clone::Clone for ValidityRequirement {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ValidityRequirement {
    #[inline]
    #[rustc_trivial_field_reads]
    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::marker::StructuralPartialEq for
    ValidityRequirement {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ValidityRequirement {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ValidityRequirement { }Eq, #[automatically_derived]impl ::core::hash::Hash for ValidityRequirement {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            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) {
                match *self {
                    ValidityRequirement::Inhabited =>
                        0u8.stable_hash(__hcx, __hasher),
                    ValidityRequirement::Zero =>
                        1u8.stable_hash(__hcx, __hasher),
                    ValidityRequirement::UninitMitigated0x01Fill =>
                        2u8.stable_hash(__hcx, __hasher),
                    ValidityRequirement::Uninit =>
                        3u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    ValidityRequirement::Inhabited => {}
                    ValidityRequirement::Zero => {}
                    ValidityRequirement::UninitMitigated0x01Fill => {}
                    ValidityRequirement::Uninit => {}
                }
            }
        }
    };StableHash)]
218pub enum ValidityRequirement {
219    Inhabited,
220    Zero,
221    /// The return value of mem::uninitialized, 0x01
222    /// (unless -Zstrict-init-checks is on, in which case it's the same as Uninit).
223    UninitMitigated0x01Fill,
224    /// True uninitialized memory.
225    Uninit,
226}
227
228impl ValidityRequirement {
229    pub fn from_rustc_intrinsic(intrinsic: Symbol) -> Option<Self> {
230        match intrinsic {
231            sym::assert_inhabited => Some(Self::Inhabited),
232            sym::assert_zero_valid => Some(Self::Zero),
233            sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
234            _ => None,
235        }
236    }
237}
238
239impl fmt::Display for ValidityRequirement {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        match self {
242            Self::Inhabited => f.write_str("is inhabited"),
243            Self::Zero => f.write_str("allows being left zeroed"),
244            Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
245            Self::Uninit => f.write_str("allows being left uninitialized"),
246        }
247    }
248}
249
250#[derive(#[automatically_derived]impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SimdLayoutError {
}
#[automatically_derived]impl ::core::clone::Clone for SimdLayoutError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Limit>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SimdLayoutError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ZeroLength =>
                ::core::fmt::Formatter::write_str(f, "ZeroLength"),
            Self::TooManyLanes(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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) {
                match *self {
                    SimdLayoutError::ZeroLength =>
                        0u8.stable_hash(__hcx, __hasher),
                    SimdLayoutError::TooManyLanes(ref __binding_0) =>
                        1u8.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)]
251pub enum SimdLayoutError {
252    /// The vector has 0 lanes.
253    ZeroLength,
254    /// The vector has more lanes than supported or permitted by
255    /// #\[rustc_simd_monomorphize_lane_limit\].
256    TooManyLanes(Limit),
257}
258
259#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for LayoutError<'tcx>
    {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for LayoutError<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for LayoutError<'tcx>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        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]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Unknown(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Unknown", &__self_0),
            Self::SizeOverflow(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "SizeOverflow", &__self_0),
            Self::InvalidSimd { ty: __self_0, kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "InvalidSimd ty kind", __self_0, &__self_1),
            Self::TooGeneric(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TooGeneric", &__self_0),
            Self::NormalizationFailure(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "NormalizationFailure", __self_0, &__self_1),
            Self::ReferencesError(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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) {
                match *self {
                    LayoutError::Unknown(ref __binding_0) =>
                        0u8.stable_hash(__hcx, __hasher),
                    LayoutError::SizeOverflow(ref __binding_0) =>
                        1u8.stable_hash(__hcx, __hasher),
                    LayoutError::InvalidSimd {
                        ty: ref __binding_0, kind: ref __binding_1 } =>
                        2u8.stable_hash(__hcx, __hasher),
                    LayoutError::TooGeneric(ref __binding_0) =>
                        3u8.stable_hash(__hcx, __hasher),
                    LayoutError::NormalizationFailure(ref __binding_0,
                        ref __binding_1) => 4u8.stable_hash(__hcx, __hasher),
                    LayoutError::ReferencesError(ref __binding_0) =>
                        5u8.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)]
260pub enum LayoutError<'tcx> {
261    /// A type doesn't have a sensible layout.
262    ///
263    /// This variant is used for layout errors that don't necessarily cause
264    /// compile errors.
265    ///
266    /// For example, this can happen if a struct contains an unsized type in a
267    /// non-tail field, but has an unsatisfiable bound like `str: Sized`.
268    Unknown(Ty<'tcx>),
269    /// The size of a type exceeds [`TargetDataLayout::obj_size_bound`].
270    SizeOverflow(Ty<'tcx>),
271    /// A SIMD vector has invalid layout, such as zero-length or too many lanes.
272    InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
273    /// The layout can vary due to a generic parameter.
274    ///
275    /// Unlike `Unknown`, this variant is a "soft" error and indicates that the layout
276    /// may become computable after further instantiating the generic parameter(s).
277    TooGeneric(Ty<'tcx>),
278    /// An alias failed to normalize.
279    ///
280    /// This variant is necessary, because, due to trait solver incompleteness, it is
281    /// possible than an alias that was rigid during analysis fails to normalize after
282    /// revealing opaque types.
283    ///
284    /// See `tests/ui/layout/normalization-failure.rs` for an example.
285    NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
286    /// A non-layout error is reported elsewhere.
287    ReferencesError(ErrorGuaranteed),
288}
289
290impl<'tcx> fmt::Display for LayoutError<'tcx> {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        match *self {
293            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"),
294            LayoutError::TooGeneric(ty) => {
295                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")
296            }
297            LayoutError::SizeOverflow(ty) => {
298                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")
299            }
300            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
301                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}")
302            }
303            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
304                f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
305            }
306            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!(
307                f,
308                "unable to determine layout for `{}` because `{}` cannot be normalized",
309                t,
310                e.get_type_for_failure()
311            ),
312            LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
313        }
314    }
315}
316
317impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
318    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
319        self.to_string().into_diag_arg(&mut None)
320    }
321}
322
323#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for LayoutCx<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        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)]
324pub struct LayoutCx<'tcx> {
325    pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
326    pub typing_env: ty::TypingEnv<'tcx>,
327}
328
329impl<'tcx> LayoutCx<'tcx> {
330    pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
331        Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
332    }
333}
334
335/// Type size "skeleton", i.e., the only information determining a type's size.
336/// While this is conservative, (aside from constant sizes, only pointers,
337/// newtypes thereof and null pointer optimized enums are allowed), it is
338/// enough to statically check common use cases of transmute.
339#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Known(__self_0, __self_1) =>
                SizeSkeleton::Known(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::Array {
                base: __self_0, align: __self_1, const_lens: __self_2 } =>
                SizeSkeleton::Array {
                    base: ::core::clone::Clone::clone(__self_0),
                    align: ::core::clone::Clone::clone(__self_1),
                    const_lens: ::core::clone::Clone::clone(__self_2),
                },
            Self::Pointer { non_zero: __self_0, tail: __self_1 } =>
                SizeSkeleton::Pointer {
                    non_zero: ::core::clone::Clone::clone(__self_0),
                    tail: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for SizeSkeleton<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Known(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Known",
                    __self_0, &__self_1),
            Self::Array {
                base: __self_0, align: __self_1, const_lens: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Array base align const_lens", __self_0, __self_1,
                    &__self_2),
            Self::Pointer { non_zero: __self_0, tail: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Pointer non_zero tail", __self_0, &__self_1),
        }
    }
}Debug)]
340pub enum SizeSkeleton<'tcx> {
341    /// Any statically computable Layout.
342    /// Alignment can be `None` if unknown.
343    Known(Size, Option<Align>),
344
345    /// An array with unevaluated const lengths.
346    Array {
347        /// The base size, including the element size and all known array
348        /// lengths accumulated.
349        base: Size,
350        align: Option<Align>,
351        const_lens: Vec<Const<TyCtxt<'tcx>>>,
352    },
353
354    /// A potentially-wide pointer.
355    Pointer {
356        /// If true, this pointer is never null.
357        non_zero: bool,
358        /// The type which determines the unsized metadata, if any,
359        /// of this pointer. Either a type parameter or a projection
360        /// depending on one, with regions erased.
361        tail: Ty<'tcx>,
362    },
363}
364
365impl<'tcx> SizeSkeleton<'tcx> {
366    pub fn compute(
367        ty: Ty<'tcx>,
368        tcx: TyCtxt<'tcx>,
369        typing_env: ty::TypingEnv<'tcx>,
370        span: Span,
371    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
372        Self::compute_inner(ty, tcx, typing_env, span, 0)
373    }
374
375    fn compute_inner(
376        ty: Ty<'tcx>,
377        tcx: TyCtxt<'tcx>,
378        typing_env: ty::TypingEnv<'tcx>,
379        span: Span,
380        depth: usize,
381    ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
382        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());
383
384        // Bail out if we've recursed too deeply (issue #156137); a cyclic type
385        // alias can otherwise blow the stack here. Using `>=` rather than `>`
386        // means we fire exactly at the limit, which lets us report the
387        // cycle-root type (`Thing<T>`) instead of an innocent field type.
388        let recursion_limit = tcx.recursion_limit();
389        if depth >= recursion_limit.0 {
390            let suggested_limit = match recursion_limit {
391                Limit(0) => Limit(2),
392                limit => limit * 2,
393            };
394            let reported =
395                tcx.dcx().emit_err(crate::diagnostics::RecursionLimitReachedSizeSkeleton {
396                    span,
397                    ty,
398                    suggested_limit,
399                });
400            return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
401        }
402
403        // First try computing a static layout.
404        let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
405            Ok(layout) => {
406                if layout.is_sized() {
407                    return Ok(SizeSkeleton::Known(layout.size, Some(layout.align)));
408                } else {
409                    // Just to be safe, don't claim a known layout for unsized types.
410                    return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
411                }
412            }
413            Err(err @ LayoutError::TooGeneric(_)) => err,
414            // We can't extract SizeSkeleton info from other layout errors
415            Err(
416                e @ LayoutError::Unknown(_)
417                | e @ LayoutError::SizeOverflow(_)
418                | e @ LayoutError::InvalidSimd { .. }
419                | e @ LayoutError::NormalizationFailure(..)
420                | e @ LayoutError::ReferencesError(_),
421            ) => return Err(e),
422        };
423
424        match *ty.kind() {
425            ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
426                let non_zero = !ty.is_raw_ptr();
427
428                tcx.assert_fully_normalized(typing_env, pointee);
429                let tail = tcx.struct_tail_raw(
430                    pointee,
431                    &ObligationCause::dummy(),
432                    |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
433                        Ok(ty) => ty,
434                        Err(e) => Ty::new_error_with_message(
435                            tcx,
436                            DUMMY_SP,
437                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
                e.get_type_for_failure()))
    })format!(
438                                "normalization failed for {} but no errors reported",
439                                e.get_type_for_failure()
440                            ),
441                        ),
442                    },
443                    || {},
444                );
445
446                match tail.kind() {
447                    // FIXME(#155345): This should only handle rigid aliases if we're using
448                    // the new solver.
449                    ty::Param(_)
450                    | ty::Alias(
451                        _,
452                        ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
453                    ) => {
454                        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());
455                        Ok(SizeSkeleton::Pointer {
456                            non_zero,
457                            tail: tcx.erase_and_anonymize_regions(tail),
458                        })
459                    }
460                    ty::Error(guar) => {
461                        // Fixes ICE #124031
462                        return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
463                    }
464                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
        ty, err, tail), Location::caller())bug!(
465                        "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
466                              tail `{tail}` is not a type parameter or a projection",
467                    ),
468                }
469            }
470            ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
471                let len_eval = len.try_to_target_usize(tcx);
472                if len_eval == Some(0) {
473                    return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
474                }
475
476                match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
477                    // This may succeed because the multiplication of two types may overflow
478                    // but a single size of a nested array will not.
479                    SizeSkeleton::Known(s, a) => {
480                        if let Some(c) = len_eval {
481                            let size = s
482                                .bytes()
483                                .checked_mul(c)
484                                .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
485                            // Alignment is unchanged by arrays.
486                            Ok(SizeSkeleton::Known(Size::from_bytes(size), a))
487                        } else if s.bytes() == 0 {
488                            Ok(SizeSkeleton::Known(s, a))
489                        } else {
490                            Ok(SizeSkeleton::Array { base: s, align: a, const_lens: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [len]))vec![len] })
491                        }
492                    }
493                    SizeSkeleton::Array { mut base, align, mut const_lens } => {
494                        match len_eval {
495                            Some(c) => {
496                                base = Size::from_bytes(base.bytes().checked_mul(c).ok_or_else(
497                                    || &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)),
498                                )?);
499                            }
500                            None => {
501                                const_lens.push(len);
502                            }
503                        }
504                        Ok(SizeSkeleton::Array { base, align, const_lens })
505                    }
506                    SizeSkeleton::Pointer { .. } => Err(err),
507                }
508            }
509
510            ty::Adt(def, args) => {
511                // Only newtypes and enums w/ nullable pointer optimization (NPO).
512                if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
513                    return Err(err);
514                }
515                // Only default repr types.
516                {
517                    // We can ignore the seed and some particular flags that can never affect the
518                    // layout of newtypes / NPO types, but we have to check everything else.
519                    // If you are adding a new field to `ReprOptions`, make sure to extend the check
520                    // below so that we bail out if it is not at its default value!
521                    let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
522                        def.repr();
523                    let mut ignored_flags = ReprFlags::IS_TRANSPARENT
524                        | ReprFlags::IS_LINEAR
525                        | ReprFlags::RANDOMIZE_LAYOUT;
526                    if def.is_struct() {
527                        // `repr(C)` is only okay for structs, not for enums.
528                        // Below, the *only* thing we do for structs is propagating
529                        // `SizeSkeleton::Pointer`. We do *not* assume that `repr(C)` preserved
530                        // ZST-ness (which might stop being true eventually).
531                        ignored_flags |= ReprFlags::IS_C;
532                    }
533                    if int.is_some()
534                        || align.is_some()
535                        || pack.is_some()
536                        || flags.difference(ignored_flags) != ReprFlags::default()
537                        || scalable.is_some()
538                    {
539                        return Err(err);
540                    }
541                }
542
543                // Get a zero-sized variant or a pointer newtype.
544                // Returns `Ok(None)` for 1-ZST types, `Ok(Some)` if (ignoring all 1-ZST fields)
545                // there's just a single pointer, and `Err` otherwise.
546                let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
547                    let i = VariantIdx::from_usize(i);
548                    let fields = def.variant(i).fields.iter().map(|field| {
549                        SizeSkeleton::compute_inner(
550                            field.ty(tcx, args).skip_norm_wip(),
551                            tcx,
552                            typing_env,
553                            span,
554                            depth + 1,
555                        )
556                    });
557                    let mut ptr = None;
558                    for field in fields {
559                        let field = field?;
560                        match field {
561                            SizeSkeleton::Known(size, align) => {
562                                let is_1zst = size.bytes() == 0
563                                    && align.is_some_and(|align| align.bytes() == 1);
564                                if !is_1zst {
565                                    return Err(err);
566                                }
567                            }
568                            SizeSkeleton::Array { .. } => {
569                                return Err(err);
570                            }
571                            SizeSkeleton::Pointer { .. } => {
572                                if ptr.is_some() {
573                                    return Err(err);
574                                }
575                                ptr = Some(field);
576                            }
577                        }
578                    }
579                    Ok(ptr)
580                };
581
582                let v0 = zero_or_ptr_variant(0)?;
583                // Single-variant case: Check if this is a newtype around a pointer.
584                // Such types are themselves pointer-sized.
585                if def.variants().len() == 1 {
586                    if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
587                        return Ok(SizeSkeleton::Pointer { non_zero, tail });
588                    } else {
589                        return Err(err);
590                    }
591                }
592
593                let v1 = zero_or_ptr_variant(1)?;
594                // 2-variant case: Check if one variant is a *non-zero* pointer and the other a
595                // 1-ZST. Such types are eligible to for the nullable pointer enum optimization, so
596                // they are themselves pointer-sized.
597                match (v0, v1) {
598                    (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
599                    | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
600                        Ok(SizeSkeleton::Pointer { non_zero: false, tail })
601                    }
602                    _ => Err(err),
603                }
604            }
605
606            ty::Alias(..) => {
607                let normalized =
608                    tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
609                if ty == normalized {
610                    Err(err)
611                } else {
612                    SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
613                }
614            }
615
616            ty::Pat(base, pat) => {
617                // Pattern types are always the same size as their base.
618                let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
619                match *pat {
620                    ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
621                    // But in the case of `!null` patterns we need to note that in the
622                    // raw pointer.
623                    ty::PatternKind::NotNull => match base? {
624                        known @ SizeSkeleton::Known(..) => Ok(known),
625                        array @ SizeSkeleton::Array { .. } => Ok(array),
626                        SizeSkeleton::Pointer { non_zero: _, tail } => {
627                            Ok(SizeSkeleton::Pointer { non_zero: true, tail })
628                        }
629                    },
630                }
631            }
632
633            _ => Err(err),
634        }
635    }
636
637    pub fn same_size(&self, other: &SizeSkeleton<'tcx>) -> bool {
638        match (self, other) {
639            (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
640            (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
641                a == b
642            }
643            (
644                SizeSkeleton::Array { base: a, const_lens: al, .. },
645                SizeSkeleton::Array { base: b, const_lens: bl, .. },
646            ) => a == b && al == bl,
647            _ => false,
648        }
649    }
650}
651
652pub trait HasTyCtxt<'tcx>: HasDataLayout {
653    fn tcx(&self) -> TyCtxt<'tcx>;
654}
655
656pub trait HasTypingEnv<'tcx> {
657    fn typing_env(&self) -> ty::TypingEnv<'tcx>;
658}
659
660impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
661    #[inline]
662    fn data_layout(&self) -> &TargetDataLayout {
663        &self.data_layout
664    }
665}
666
667impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
668    fn target_spec(&self) -> &Target {
669        &self.sess.target
670    }
671}
672
673impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
674    fn x86_abi_opt(&self) -> X86Abi {
675        X86Abi {
676            regparm: self.sess.opts.unstable_opts.regparm,
677            reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
678        }
679    }
680}
681
682impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
683    #[inline]
684    fn tcx(&self) -> TyCtxt<'tcx> {
685        *self
686    }
687}
688
689impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
690    #[inline]
691    fn data_layout(&self) -> &TargetDataLayout {
692        &self.data_layout
693    }
694}
695
696impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
697    fn target_spec(&self) -> &Target {
698        &self.sess.target
699    }
700}
701
702impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
703    #[inline]
704    fn tcx(&self) -> TyCtxt<'tcx> {
705        **self
706    }
707}
708
709impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
710    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
711        self.typing_env
712    }
713}
714
715impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
716    fn data_layout(&self) -> &TargetDataLayout {
717        self.calc.cx.data_layout()
718    }
719}
720
721impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
722    fn target_spec(&self) -> &Target {
723        self.calc.cx.target_spec()
724    }
725}
726
727impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
728    fn x86_abi_opt(&self) -> X86Abi {
729        self.calc.cx.x86_abi_opt()
730    }
731}
732
733impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
734    fn tcx(&self) -> TyCtxt<'tcx> {
735        self.calc.cx
736    }
737}
738
739pub trait MaybeResult<T> {
740    type Error;
741
742    fn from(x: Result<T, Self::Error>) -> Self;
743    fn to_result(self) -> Result<T, Self::Error>;
744}
745
746impl<T> MaybeResult<T> for T {
747    type Error = !;
748
749    fn from(Ok(x): Result<T, Self::Error>) -> Self {
750        x
751    }
752    fn to_result(self) -> Result<T, Self::Error> {
753        Ok(self)
754    }
755}
756
757impl<T, E> MaybeResult<T> for Result<T, E> {
758    type Error = E;
759
760    fn from(x: Result<T, Self::Error>) -> Self {
761        x
762    }
763    fn to_result(self) -> Result<T, Self::Error> {
764        self
765    }
766}
767
768pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
769
770/// Trait for contexts that want to be able to compute layouts of types.
771/// This automatically gives access to `LayoutOf`, through a blanket `impl`.
772pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
773    /// The `TyAndLayout`-wrapping type (or `TyAndLayout` itself), which will be
774    /// returned from `layout_of` (see also `handle_layout_err`).
775    type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
776
777    /// `Span` to use for `tcx.at(span)`, from `layout_of`.
778    // FIXME(eddyb) perhaps make this mandatory to get contexts to track it better?
779    #[inline]
780    fn layout_tcx_at_span(&self) -> Span {
781        DUMMY_SP
782    }
783
784    /// Helper used for `layout_of`, to adapt `tcx.layout_of(...)` into a
785    /// `Self::LayoutOfResult` (which does not need to be a `Result<...>`).
786    ///
787    /// Most `impl`s, which propagate `LayoutError`s, should simply return `err`,
788    /// but this hook allows e.g. codegen to return only `TyAndLayout` from its
789    /// `cx.layout_of(...)`, without any `Result<...>` around it to deal with
790    /// (and any `LayoutError`s are turned into fatal errors or ICEs).
791    fn handle_layout_err(
792        &self,
793        err: LayoutError<'tcx>,
794        span: Span,
795        ty: Ty<'tcx>,
796    ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
797}
798
799/// Blanket extension trait for contexts that can compute layouts of types.
800pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
801    /// Computes the layout of a type. Note that this implicitly
802    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
803    #[inline]
804    fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
805        self.spanned_layout_of(ty, DUMMY_SP)
806    }
807
808    /// Computes the layout of a type, at `span`. Note that this implicitly
809    /// executes in `TypingMode::PostAnalysis`, and will normalize the input type.
810    // FIXME(eddyb) avoid passing information like this, and instead add more
811    // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`.
812    #[inline]
813    fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
814        let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
815        let tcx = self.tcx().at(span);
816
817        MaybeResult::from(
818            tcx.layout_of(self.typing_env().as_query_input(ty))
819                .map_err(|err| self.handle_layout_err(*err, span, ty)),
820        )
821    }
822}
823
824impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
825
826impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
827    type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
828
829    #[inline]
830    fn handle_layout_err(
831        &self,
832        err: LayoutError<'tcx>,
833        _: Span,
834        _: Ty<'tcx>,
835    ) -> &'tcx LayoutError<'tcx> {
836        self.tcx().arena.alloc(err)
837    }
838}
839
840impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
841where
842    C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
843{
844    fn ty_and_layout_for_variant(
845        this: TyAndLayout<'tcx>,
846        cx: &C,
847        variant_index: VariantIdx,
848    ) -> TyAndLayout<'tcx> {
849        let layout = match this.variants {
850            // If all variants but one are uninhabited, the variant layout is the enum layout.
851            Variants::Single { index } if index == variant_index => {
852                return this;
853            }
854
855            Variants::Single { .. } | Variants::Empty => {
856                // Single-variant and no-variant enums *can* have other variants, but those are
857                // uninhabited. Produce a layout that has the right fields for that variant, so that
858                // the rest of the compiler can project fields etc as usual.
859
860                let tcx = cx.tcx();
861                let typing_env = cx.typing_env();
862
863                // Deny calling for_variant more than once for non-Single enums.
864                if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
865                    {
    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);
866                }
867
868                let fields = match this.ty.kind() {
869                    ty::Adt(def, _) if def.variants().is_empty() => {
870                        ::rustc_span::macros::bug_impl(None,
    format_args!("for_variant called on zero-variant enum {0}", this.ty),
    Location::caller())bug!("for_variant called on zero-variant enum {}", this.ty)
871                    }
872                    ty::Adt(def, _) => def.variant(variant_index).fields.len(),
873                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
        this.ty), Location::caller())bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
874                };
875                tcx.mk_layout(LayoutData::uninhabited_variant(variant_index, fields))
876            }
877
878            Variants::Multiple { .. } => {
879                cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
880            }
881        };
882
883        {
    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 });
884
885        TyAndLayout { ty: this.ty, layout }
886    }
887
888    fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
889        enum TyMaybeWithLayout<'tcx> {
890            Ty(Ty<'tcx>),
891            TyAndLayout(TyAndLayout<'tcx>),
892        }
893
894        fn field_ty_or_layout<'tcx>(
895            this: TyAndLayout<'tcx>,
896            cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
897            i: usize,
898        ) -> TyMaybeWithLayout<'tcx> {
899            let tcx = cx.tcx();
900            let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
901                TyAndLayout {
902                    layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
903                    ty: tag.primitive().to_ty(tcx),
904                }
905            };
906
907            match *this.ty.kind() {
908                ty::Bool
909                | ty::Char
910                | ty::Int(_)
911                | ty::Uint(_)
912                | ty::Float(_)
913                | ty::FnPtr(..)
914                | ty::Never
915                | ty::FnDef(..)
916                | ty::CoroutineWitness(..)
917                | ty::Foreign(..)
918                | ty::Dynamic(_, _) => {
919                    ::rustc_span::macros::bug_impl(None,
    format_args!("TyAndLayout::field({0:?}): not applicable", this),
    Location::caller())bug!("TyAndLayout::field({:?}): not applicable", this)
920                }
921
922                ty::Pat(base, _) => {
923                    {
    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);
924                    TyMaybeWithLayout::Ty(base)
925                }
926
927                ty::UnsafeBinder(bound_ty) => {
928                    let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
929                    field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
930                }
931
932                // Potentially-wide pointers.
933                ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
934                    if !(i < this.fields.count()) {
    ::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
935
936                    // Reuse the wide `*T` type as its own thin pointer data field.
937                    // This provides information about, e.g., DST struct pointees
938                    // (which may have no non-DST form), and will work as long
939                    // as the `Abi` or `FieldsShape` is checked by users.
940                    if i == 0 {
941                        let nil = tcx.types.unit;
942                        let unit_ptr_ty = if this.ty.is_raw_ptr() {
943                            Ty::new_mut_ptr(tcx, nil)
944                        } else {
945                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
946                        };
947
948                        // NOTE: using an fully monomorphized typing env and `unwrap`-ing
949                        // the `Result` should always work because the type is always either
950                        // `*mut ()` or `&'static mut ()`.
951                        let typing_env = ty::TypingEnv::fully_monomorphized();
952                        return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
953                            ty: this.ty,
954                            ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
955                        });
956                    }
957
958                    let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
959                        let min_count = ty::vtable_min_entries(
960                            tcx,
961                            principal.map(|principal| {
962                                tcx.instantiate_bound_regions_with_erased(principal)
963                            }),
964                        );
965                        Ty::new_imm_ref(
966                            tcx,
967                            tcx.lifetimes.re_static,
968                            // FIXME: properly type (e.g. usize and fn pointers) the fields.
969                            Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
970                        )
971                    };
972
973                    let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
974                        // Projection eagerly bails out when the pointee references errors,
975                        // fall back to structurally deducing metadata.
976                        && !pointee.references_error()
977                    {
978                        let metadata = tcx.normalize_erasing_regions(
979                            cx.typing_env(),
980                            Unnormalized::new(Ty::new_projection(
981                                tcx,
982                                ty::IsRigid::No,
983                                metadata_def_id,
984                                [pointee],
985                            )),
986                        );
987
988                        // Map `Metadata = DynMetadata<dyn Trait>` back to a vtable, since it
989                        // offers better information than `std::ptr::metadata::VTable`,
990                        // and we rely on this layout information to trigger a panic in
991                        // `std::mem::uninitialized::<&dyn Trait>()`, for example.
992                        if let ty::Adt(def, args) = metadata.kind()
993                            && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
994                            && let ty::Dynamic(data, _) = args.type_at(0).kind()
995                        {
996                            mk_dyn_vtable(data.principal())
997                        } else {
998                            metadata
999                        }
1000                    } else {
1001                        match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
1002                            ty::Slice(_) | ty::Str => tcx.types.usize,
1003                            ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
1004                            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("TyAndLayout::field({0:?}): not applicable", this),
    Location::caller())bug!("TyAndLayout::field({:?}): not applicable", this),
1005                        }
1006                    };
1007
1008                    TyMaybeWithLayout::Ty(metadata)
1009                }
1010
1011                // Arrays and slices.
1012                ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
1013                ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
1014
1015                // Tuples, coroutines and closures.
1016                ty::Closure(_, args) => field_ty_or_layout(
1017                    TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
1018                    cx,
1019                    i,
1020                ),
1021
1022                ty::CoroutineClosure(_, args) => field_ty_or_layout(
1023                    TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
1024                    cx,
1025                    i,
1026                ),
1027
1028                ty::Coroutine(def_id, args) => match this.variants {
1029                    Variants::Empty => ::core::panicking::unreachable_default_msg()unreachable!(),
1030                    Variants::Single { index } => TyMaybeWithLayout::Ty(
1031                        args.as_coroutine()
1032                            .state_tys(def_id, tcx)
1033                            .nth(index.as_usize())
1034                            .unwrap()
1035                            .nth(i)
1036                            .unwrap(),
1037                    ),
1038                    Variants::Multiple { tag, tag_field, .. } => {
1039                        if FieldIdx::from_usize(i) == tag_field {
1040                            TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
1041                        } else {
1042                            TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
1043                        }
1044                    }
1045                },
1046
1047                ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
1048
1049                // ADTs.
1050                ty::Adt(def, args) => {
1051                    match this.variants {
1052                        Variants::Single { index } => {
1053                            let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
1054                            // Below we call `layout_of` which performs normalization, so we do not
1055                            // need it here.
1056                            TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
1057                        }
1058                        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"),
1059
1060                        // Discriminant field for enums (where applicable).
1061                        Variants::Multiple { tag, .. } => {
1062                            {
    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);
1063                            return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1064                        }
1065                    }
1066                }
1067
1068                ty::Alias(..)
1069                | ty::Bound(..)
1070                | ty::Placeholder(..)
1071                | ty::Param(_)
1072                | ty::Infer(_)
1073                | ty::Error(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("TyAndLayout::field: unexpected type `{0}`", this.ty),
    Location::caller())bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1074
1075                // FIXME(scrabsha)
1076                ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
1077            }
1078        }
1079
1080        match field_ty_or_layout(this, cx, i) {
1081            TyMaybeWithLayout::Ty(field_ty) => {
1082                cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1083                    ::rustc_span::macros::bug_impl(None,
    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), Location::caller())bug!(
1084                        "failed to get layout for `{field_ty}`: {e:?},\n\
1085                         despite it being a field (#{i}) of an existing layout: {this:#?}",
1086                    )
1087                })
1088            }
1089            TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1090        }
1091    }
1092
1093    /// Compute the information for the pointer stored at the given offset inside this type.
1094    /// This will recurse into fields of ADTs to find the inner pointer.
1095    fn ty_and_layout_pointee_info_at(
1096        this: TyAndLayout<'tcx>,
1097        cx: &C,
1098        offset: Size,
1099    ) -> Option<PointeeInfo> {
1100        let tcx = cx.tcx();
1101        let typing_env = cx.typing_env();
1102
1103        // Use conservative pointer kind if not optimizing. This saves us the
1104        // Freeze/Unpin queries, and can save time in the codegen backend (noalias
1105        // attributes in LLVM have compile-time cost even in unoptimized builds).
1106        let optimize = tcx.sess.opts.optimize != OptLevel::No;
1107
1108        let pointee_info = match *this.ty.kind() {
1109            ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1110                Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1111            }
1112            ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1113                tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1114                    let kind;
1115                    let size;
1116
1117                    match mt {
1118                        hir::Mutability::Not => {
1119                            let frozen = optimize && ty.is_freeze(tcx, typing_env);
1120                            kind = PointerKind::SharedRef { frozen };
1121
1122                            // Set the `size` to zero for non-frozen shared references.
1123                            //
1124                            // `PointeeInfo::size` is defined to allow adding spurious reads.
1125                            // Adding spurious reads is only valid for `&Freeze` and `&mut Unpin`
1126                            // references, as otherwise the spurious read can invalidate aliasing
1127                            // references.
1128                            //
1129                            // See discussions in
1130                            // - https://github.com/rust-lang/unsafe-code-guidelines/issues/381
1131                            // - https://github.com/llvm/llvm-project/pull/218413
1132                            // - https://discourse.llvm.org/t/interaction-of-noalias-and-dereferenceable/66979
1133                            size = layout.size * frozen as _;
1134                        }
1135                        hir::Mutability::Mut => {
1136                            let unpin = optimize
1137                                && ty.is_unpin(tcx, typing_env)
1138                                && ty.is_unsafe_unpin(tcx, typing_env);
1139                            kind = PointerKind::MutableRef { unpin };
1140
1141                            // Set the `size` to zero for non-unpin unique references.
1142                            // See the above comment for reasons to do this.
1143                            size = layout.size * unpin as _;
1144                        }
1145                    };
1146
1147                    PointeeInfo { safe: Some(kind), size, align: layout.align }
1148                })
1149            }
1150
1151            ty::Adt(..)
1152                if offset.bytes() == 0
1153                    && let Some(pointee) = this.ty.boxed_ty() =>
1154            {
1155                tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| {
1156                    // Same logic as for mutable references above.
1157                    let unpin = optimize
1158                        && pointee.is_unpin(tcx, typing_env)
1159                        && pointee.is_unsafe_unpin(tcx, typing_env);
1160                    let size = layout.size * unpin as _;
1161
1162                    PointeeInfo {
1163                        safe: Some(PointerKind::Box { unpin, global: this.ty.is_box_global(tcx) }),
1164                        size,
1165                        align: layout.align,
1166                    }
1167                })
1168            }
1169
1170            _ => {
1171                let mut data_variant = match &this.variants {
1172                    // Within the discriminant field, only the niche itself is
1173                    // always initialized, so we only check for a pointer at its
1174                    // offset.
1175                    //
1176                    // Our goal here is to check whether this represents a
1177                    // "dereferenceable or null" pointer, so we need to ensure
1178                    // that there is only one other variant, and it must be null.
1179                    // Below, we will then check whether the pointer is indeed
1180                    // dereferenceable.
1181                    Variants::Multiple {
1182                        tag_encoding:
1183                            TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1184                        tag_field,
1185                        variants,
1186                        ..
1187                    } if variants.len() == 2
1188                        && this.fields.offset(tag_field.as_usize()) == offset =>
1189                    {
1190                        let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1191                            VariantIdx::from_u32(1)
1192                        } else {
1193                            VariantIdx::from_u32(0)
1194                        };
1195                        {
    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);
1196                        if *niche_start == 0 {
1197                            // The other variant is encoded as "null", so we can recurse searching for
1198                            // a pointer here. This relies on the fact that the codegen backend
1199                            // only adds "dereferenceable" if there's also a "nonnull" proof,
1200                            // and that null is aligned for all alignments so it's okay to forward
1201                            // the pointer's alignment.
1202                            Some(this.for_variant(cx, *untagged_variant))
1203                        } else {
1204                            None
1205                        }
1206                    }
1207                    Variants::Multiple { .. } => None,
1208                    Variants::Empty | Variants::Single { .. } => Some(this),
1209                };
1210
1211                if let Some(variant) = data_variant
1212                    // We're not interested in any unions.
1213                    && let FieldsShape::Union(_) = variant.fields
1214                {
1215                    data_variant = None;
1216                }
1217
1218                let mut result = None;
1219
1220                if let Some(variant) = data_variant {
1221                    // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1222                    // (requires passing in the expected address space from the caller)
1223                    let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1224                    for i in 0..variant.fields.count() {
1225                        let field_start = variant.fields.offset(i);
1226                        if field_start <= offset {
1227                            let field = variant.field(cx, i);
1228                            result = field.to_result().ok().and_then(|field| {
1229                                if ptr_end <= field_start + field.size {
1230                                    // We found the right field, look inside it.
1231                                    let field_info =
1232                                        field.pointee_info_at(cx, offset - field_start);
1233                                    field_info
1234                                } else {
1235                                    None
1236                                }
1237                            });
1238                            if result.is_some() {
1239                                break;
1240                            }
1241                        }
1242                    }
1243                }
1244
1245                // Patch result if we are a MaybeDangling-like type.
1246                if this.ty.is_like_maybe_dangling()
1247                    && let Some(info) = result
1248                {
1249                    result = Some(PointeeInfo {
1250                        // Mark the pointer as raw
1251                        // (thus removing noalias/readonly/etc in case of the llvm backend)
1252                        safe: None,
1253                        // Make sure we don't assert dereferenceability of the pointer.
1254                        size: Size::ZERO,
1255                        // Preserve the alignment assertion! That is required even inside `MaybeDangling`.
1256                        align: info.align,
1257                    });
1258                }
1259
1260                result
1261            }
1262        };
1263
1264        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/2be539647feed020b47ddbf897b8533d2d8d4c46/compiler/rustc_middle/src/ty/layout.rs:1264",
                        "rustc_middle::ty::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/2be539647feed020b47ddbf897b8533d2d8d4c46/compiler/rustc_middle/src/ty/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1264u32),
                        ::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!(
1265            "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1266            offset,
1267            this.ty.kind(),
1268            pointee_info
1269        );
1270
1271        pointee_info
1272    }
1273
1274    fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1275        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1276    }
1277
1278    fn is_enum(this: TyAndLayout<'tcx>) -> bool {
1279        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Adt(def, _) if def.is_enum() => true,
    _ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.is_enum())
1280    }
1281
1282    fn is_never(this: TyAndLayout<'tcx>) -> bool {
1283        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Never => true,
    _ => false,
}matches!(this.ty.kind(), ty::Never)
1284    }
1285
1286    fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1287        #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
    ty::Tuple(..) => true,
    _ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1288    }
1289
1290    fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1291        #[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)
1292    }
1293
1294    fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1295        #[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())
1296    }
1297
1298    /// Is this type `core::num::Complex<T>`?
1299    fn is_complex_number_lang_item(this: TyAndLayout<'tcx>, cx: &C) -> bool {
1300        let Some(def) = this.ty.ty_adt_def() else { return false };
1301        cx.tcx().is_lang_item(def.did(), LangItem::Complex)
1302    }
1303
1304    /// Is this type `core::arch::{x86, x86_64}::x87_f80`?
1305    fn is_x87_f80_lang_item(this: TyAndLayout<'tcx>, cx: &C) -> bool {
1306        let Some(def) = this.ty.ty_adt_def() else { return false };
1307        cx.tcx().is_lang_item(def.did(), LangItem::X87F80)
1308    }
1309
1310    fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1311        this.ty.is_scalable_vector()
1312    }
1313
1314    /// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
1315    fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1316        #[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))
1317    }
1318}
1319
1320/// Calculates whether a function's ABI can unwind or not.
1321///
1322/// This takes two primary parameters:
1323///
1324/// * `fn_def_id` - the `DefId` of the function. If this is provided then we can
1325///   determine more precisely if the function can unwind. If this is not provided
1326///   then we will only infer whether the function can unwind or not based on the
1327///   ABI of the function. For example, a function marked with `#[rustc_nounwind]`
1328///   is known to not unwind even if it's using Rust ABI.
1329///
1330/// * `abi` - this is the ABI that the function is defined with. This is the
1331///   primary factor for determining whether a function can unwind or not.
1332///
1333/// Note that in this case unwinding is not necessarily panicking in Rust. Rust
1334/// panics are implemented with unwinds on most platform (when
1335/// `-Cpanic=unwind`), but this also accounts for `-Cpanic=abort` build modes.
1336/// Notably unwinding is disallowed for more non-Rust ABIs unless it's
1337/// specifically in the name (e.g. `"C-unwind"`). Unwinding within each ABI is
1338/// defined for each ABI individually, but it always corresponds to some form of
1339/// stack-based unwinding (the exact mechanism of which varies
1340/// platform-by-platform).
1341///
1342/// Rust functions are classified whether or not they can unwind based on the
1343/// active "panic strategy". In other words Rust functions are considered to
1344/// unwind in `-Cpanic=unwind` mode and cannot unwind in `-Cpanic=abort` mode.
1345/// Note that Rust supports intermingling panic=abort and panic=unwind code, but
1346/// only if the final panic mode is panic=abort. In this scenario any code
1347/// previously compiled assuming that a function can unwind is still correct, it
1348/// just never happens to actually unwind at runtime.
1349///
1350/// This function's answer to whether or not a function can unwind is quite
1351/// impactful throughout the compiler. This affects things like:
1352///
1353/// * Calling a function which can't unwind means codegen simply ignores any
1354///   associated unwinding cleanup.
1355/// * Calling a function which can unwind from a function which can't unwind
1356///   causes the `abort_unwinding_calls` MIR pass to insert a landing pad that
1357///   aborts the process.
1358/// * This affects whether functions have the LLVM `nounwind` attribute, which
1359///   affects various optimizations and codegen.
1360#[inline]
1361{}
#[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("/rustc-dev/2be539647feed020b47ddbf897b8533d2d8d4c46/compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1361u32),
                                    ::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 |
                    LlvmIntrinsic => false,
                Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
                    tcx.sess.panic_strategy().unwinds()
                }
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(tcx))]
1362pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1363    if let Some(did) = fn_def_id {
1364        // Special attribute for functions which can't unwind.
1365        if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1366            return false;
1367        }
1368
1369        // With `-C panic=abort`, all non-FFI functions are required to not unwind.
1370        //
1371        // Note that this is true regardless ABI specified on the function -- a `extern "C-unwind"`
1372        // function defined in Rust is also required to abort.
1373        if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1374            return false;
1375        }
1376
1377        // With -Z panic-in-drop=abort, `drop_glue` never unwinds.
1378        //
1379        // This is not part of `codegen_fn_attrs` as it can differ between crates
1380        // and therefore cannot be computed in core.
1381        if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1382            && tcx.is_lang_item(did, LangItem::DropGlue)
1383        {
1384            return false;
1385        }
1386    }
1387
1388    // Otherwise if this isn't special then unwinding is generally determined by
1389    // the ABI of the itself. ABIs like `C` have variants which also
1390    // specifically allow unwinding (`C-unwind`), but not all platform-specific
1391    // ABIs have such an option. Otherwise the only other thing here is Rust
1392    // itself, and those ABIs are determined by the panic strategy configured
1393    // for this compilation.
1394    use ExternAbi::*;
1395    match abi {
1396        C { unwind }
1397        | System { unwind }
1398        | Cdecl { unwind }
1399        | Stdcall { unwind }
1400        | Fastcall { unwind }
1401        | Vectorcall { unwind }
1402        | Thiscall { unwind }
1403        | Aapcs { unwind }
1404        | Win64 { unwind }
1405        | SysV64 { unwind } => unwind,
1406        PtxKernel
1407        | Msp430Interrupt
1408        | X86Interrupt
1409        | GpuKernel
1410        | EfiApi
1411        | AvrInterrupt
1412        | AvrNonBlockingInterrupt
1413        | CmseNonSecureCall
1414        | CmseNonSecureEntry
1415        | Custom
1416        | RiscvInterruptM
1417        | RiscvInterruptS
1418        | RustInvalid
1419        | Swift
1420        | LlvmIntrinsic => false,
1421        Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1422            tcx.sess.panic_strategy().unwinds()
1423        }
1424    }
1425}
1426
1427/// Error produced by attempting to compute or adjust a `FnAbi`.
1428#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for FnAbiError<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Layout(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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) {
                match *self {
                    FnAbiError::Layout(ref __binding_0) =>
                        0u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    FnAbiError::Layout(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1429pub enum FnAbiError<'tcx> {
1430    /// Error produced by a `layout_of` call, while computing `FnAbi` initially.
1431    Layout(LayoutError<'tcx>),
1432}
1433
1434impl<'a, 'b> Diagnostic<'a> for FnAbiError<'b> {
1435    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1436        match self {
1437            Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1438        }
1439    }
1440}
1441
1442// FIXME(eddyb) maybe use something like this for an unified `fn_abi_of`, not
1443// just for error handling.
1444#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for FnAbiRequest<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfFnPtr sig extra_args", __self_0, &__self_1),
            Self::OfInstance { instance: __self_0, extra_args: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "OfInstance instance extra_args", __self_0, &__self_1),
        }
    }
}Debug)]
1445pub enum FnAbiRequest<'tcx> {
1446    OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1447    OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1448}
1449
1450/// Trait for contexts that want to be able to compute `FnAbi`s.
1451/// This automatically gives access to `FnAbiOf`, through a blanket `impl`.
1452pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1453    /// The `&FnAbi`-wrapping type (or `&FnAbi` itself), which will be
1454    /// returned from `fn_abi_of_*` (see also `handle_fn_abi_err`).
1455    type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1456
1457    /// Helper used for `fn_abi_of_*`, to adapt `tcx.fn_abi_of_*(...)` into a
1458    /// `Self::FnAbiOfResult` (which does not need to be a `Result<...>`).
1459    ///
1460    /// Most `impl`s, which propagate `FnAbiError`s, should simply return `err`,
1461    /// but this hook allows e.g. codegen to return only `&FnAbi` from its
1462    /// `cx.fn_abi_of_*(...)`, without any `Result<...>` around it to deal with
1463    /// (and any `FnAbiError`s are turned into fatal errors or ICEs).
1464    ///
1465    /// Codegen backends should use [`codegen_handle_fn_abi_err`] as implementation.
1466    fn handle_fn_abi_err(
1467        &self,
1468        err: FnAbiError<'tcx>,
1469        span: Span,
1470        fn_abi_request: FnAbiRequest<'tcx>,
1471    ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1472}
1473
1474/// Implementation of [`FnAbiOfHelpers::handle_fn_abi_err`] for codegen backends.
1475pub fn codegen_handle_fn_abi_err<'tcx>(
1476    tcx: TyCtxt<'tcx>,
1477    err: FnAbiError<'tcx>,
1478    span: Span,
1479    fn_abi_request: FnAbiRequest<'tcx>,
1480) -> ErrorGuaranteed {
1481    match err {
1482        FnAbiError::Layout(LayoutError::ReferencesError(guar)) => guar,
1483        FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::InvalidSimd { .. }) => {
1484            tcx.dcx().emit_err(Spanned { span, node: err })
1485        }
1486        _ => match fn_abi_request {
1487            FnAbiRequest::OfFnPtr { sig, extra_args } => {
1488                ::rustc_span::macros::bug_impl(Some(span),
    format_args!("`fn_abi_of_fn_ptr({0}, {1:?})` failed: {2:?}", sig,
        extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1489            }
1490            FnAbiRequest::OfInstance { instance, extra_args } => {
1491                ::rustc_span::macros::bug_impl(Some(span),
    format_args!("`fn_abi_of_instance({0}, {1:?})` failed: {2:?}", instance,
        extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",);
1492            }
1493        },
1494    }
1495}
1496
1497/// Blanket extension trait for contexts that can compute `FnAbi`s.
1498pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1499    /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers.
1500    ///
1501    /// NB: this doesn't handle virtual calls - those should use `fn_abi_of_instance`
1502    /// instead, where the instance is an `InstanceKind::Virtual`.
1503    #[inline]
1504    fn fn_abi_of_fn_ptr(
1505        &self,
1506        sig: ty::PolyFnSig<'tcx>,
1507        extra_args: &'tcx ty::List<Ty<'tcx>>,
1508    ) -> Self::FnAbiOfResult {
1509        // FIXME(eddyb) get a better `span` here.
1510        let span = self.layout_tcx_at_span();
1511        let tcx = self.tcx().at(span);
1512
1513        MaybeResult::from(
1514            tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1515                |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1516            ),
1517        )
1518    }
1519
1520    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1521    /// to an `fn`. Indirectly-passed parameters in the returned ABI might not include all possible
1522    /// codegen optimization attributes (such as `ReadOnly` or `CapturesNone`), as deducing these
1523    /// requires inspection of function bodies that can lead to cycles when performed during typeck.
1524    /// Post typeck, you should prefer the optimized ABI returned by `fn_abi_of_instance`.
1525    ///
1526    /// NB: the ABI returned by this query must not differ from that returned by
1527    ///     `fn_abi_of_instance` in any other way.
1528    ///
1529    /// * that includes virtual calls, which are represented by "direct calls" to an
1530    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1531    #[inline]
1532    {}
#[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("/rustc-dev/2be539647feed020b47ddbf897b8533d2d8d4c46/compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1532u32),
                                    ::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))]
1533    fn fn_abi_of_instance_no_deduced_attrs(
1534        &self,
1535        instance: ty::Instance<'tcx>,
1536        extra_args: &'tcx ty::List<Ty<'tcx>>,
1537    ) -> Self::FnAbiOfResult {
1538        // FIXME(eddyb) get a better `span` here.
1539        let span = self.layout_tcx_at_span();
1540        let tcx = self.tcx().at(span);
1541
1542        MaybeResult::from(
1543            tcx.fn_abi_of_instance_no_deduced_attrs(
1544                self.typing_env().as_query_input((instance, extra_args)),
1545            )
1546            .map_err(|err| {
1547                // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1548                // we can get some kind of span even if one wasn't provided.
1549                // However, we don't do this early in order to avoid calling
1550                // `def_span` unconditionally (which may have a perf penalty).
1551                let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1552                self.handle_fn_abi_err(
1553                    *err,
1554                    span,
1555                    FnAbiRequest::OfInstance { instance, extra_args },
1556                )
1557            }),
1558        )
1559    }
1560
1561    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
1562    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
1563    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
1564    /// which requires inspection of function bodies that can lead to cycles when performed during
1565    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
1566    /// `fn_abi_of_instance_no_deduced_attrs`.
1567    ///
1568    /// * that includes virtual calls, which are represented by "direct calls" to an
1569    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
1570    #[inline]
1571    {}
#[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("/rustc-dev/2be539647feed020b47ddbf897b8533d2d8d4c46/compiler/rustc_middle/src/ty/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1571u32),
                                    ::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))]
1572    fn fn_abi_of_instance(
1573        &self,
1574        instance: ty::Instance<'tcx>,
1575        extra_args: &'tcx ty::List<Ty<'tcx>>,
1576    ) -> Self::FnAbiOfResult {
1577        // FIXME(eddyb) get a better `span` here.
1578        let span = self.layout_tcx_at_span();
1579        let tcx = self.tcx().at(span);
1580
1581        MaybeResult::from(
1582            tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1583                .map_err(|err| {
1584                    // HACK(eddyb) at least for definitions of/calls to `Instance`s,
1585                    // we can get some kind of span even if one wasn't provided.
1586                    // However, we don't do this early in order to avoid calling
1587                    // `def_span` unconditionally (which may have a perf penalty).
1588                    let span =
1589                        if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1590                    self.handle_fn_abi_err(
1591                        *err,
1592                        span,
1593                        FnAbiRequest::OfInstance { instance, extra_args },
1594                    )
1595                }),
1596        )
1597    }
1598}
1599
1600impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}