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_errors::{
10 Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
11};
12use rustc_hir as hir;
13use rustc_hir::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
16use rustc_session::config::OptLevel;
17use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
18use rustc_target::callconv::FnAbi;
19use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
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
28impl 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 = " signed discriminant range and `#[repr]` attribute."]
#[doc =
" N.B.: `u128` values above `i128::MAX` will be treated as signed, but"]
#[doc = " that shouldn\'t affect anything, other than maybe debuginfo."]
#[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: i128, max: i128) -> (abi::Integer, bool) {
let unsigned_fit =
abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
let signed_fit =
cmp::max(abi::Integer::fit_signed(min),
abi::Integer::fit_signed(max));
if let Some(ity) = repr.int {
let discr = abi::Integer::from_attr(&tcx, ity);
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
crate::util::bug::bug_fmt(format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
ty))
}
return (discr, ity.is_signed());
}
let at_least =
if repr.c() {
tcx.data_layout().c_enum_min_size
} else { abi::Integer::I8 };
if unsigned_fit <= signed_fit {
(cmp::max(unsigned_fit, at_least), false)
} else { (cmp::max(signed_fit, at_least), true) }
}
}#[extension(pub trait IntegerExt)]
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 fn discr_range_of_repr<'tcx>(
78 tcx: TyCtxt<'tcx>,
79 ty: Ty<'tcx>,
80 repr: &ReprOptions,
81 min: i128,
82 max: i128,
83 ) -> (abi::Integer, bool) {
84 let unsigned_fit = abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
89 let signed_fit = cmp::max(abi::Integer::fit_signed(min), abi::Integer::fit_signed(max));
90
91 if let Some(ity) = repr.int {
92 let discr = abi::Integer::from_attr(&tcx, ity);
93 let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
94 if discr < fit {
95 bug!(
96 "Integer::repr_discr: `#[repr]` hint too small for \
97 discriminant range of enum `{}`",
98 ty
99 )
100 }
101 return (discr, ity.is_signed());
102 }
103
104 let at_least = if repr.c() {
105 tcx.data_layout().c_enum_min_size
108 } else {
109 abi::Integer::I8
111 };
112
113 if unsigned_fit <= signed_fit {
116 (cmp::max(unsigned_fit, at_least), false)
117 } else {
118 (cmp::max(signed_fit, at_least), true)
119 }
120 }
121}
122
123impl FloatExt for abi::Float {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
use abi::Float::*;
match *self {
F16 => tcx.types.f16,
F32 => tcx.types.f32,
F64 => tcx.types.f64,
F128 => tcx.types.f128,
}
}
fn from_float_ty(fty: ty::FloatTy) -> Self {
use abi::Float::*;
match fty {
ty::FloatTy::F16 => F16,
ty::FloatTy::F32 => F32,
ty::FloatTy::F64 => F64,
ty::FloatTy::F128 => F128,
}
}
}#[extension(pub trait FloatExt)]
124impl abi::Float {
125 #[inline]
126 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
127 use abi::Float::*;
128 match *self {
129 F16 => tcx.types.f16,
130 F32 => tcx.types.f32,
131 F64 => tcx.types.f64,
132 F128 => tcx.types.f128,
133 }
134 }
135
136 fn from_float_ty(fty: ty::FloatTy) -> Self {
137 use abi::Float::*;
138 match fty {
139 ty::FloatTy::F16 => F16,
140 ty::FloatTy::F32 => F32,
141 ty::FloatTy::F64 => F64,
142 ty::FloatTy::F128 => F128,
143 }
144 }
145}
146
147impl PrimitiveExt for Primitive {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
Primitive::Int(i, signed) => i.to_ty(tcx, signed),
Primitive::Float(f) => f.to_ty(tcx),
Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
}
}
#[doc = " Return an *integer* type matching this primitive."]
#[doc = " Useful in particular when dealing with enum discriminants."]
#[inline]
fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
Primitive::Int(i, signed) => i.to_ty(tcx, signed),
Primitive::Pointer(_) => {
let signed = false;
tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
}
Primitive::Float(_) =>
crate::util::bug::bug_fmt(format_args!("floats do not have an int type")),
}
}
}#[extension(pub trait PrimitiveExt)]
148impl Primitive {
149 #[inline]
150 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
151 match *self {
152 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
153 Primitive::Float(f) => f.to_ty(tcx),
154 Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
156 }
157 }
158
159 #[inline]
162 fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
163 match *self {
164 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
165 Primitive::Pointer(_) => {
167 let signed = false;
168 tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
169 }
170 Primitive::Float(_) => bug!("floats do not have an int type"),
171 }
172 }
173}
174
175pub const WIDE_PTR_ADDR: usize = 0;
180
181pub const WIDE_PTR_EXTRA: usize = 1;
186
187pub const MAX_SIMD_LANES: u64 = rustc_abi::MAX_SIMD_LANES;
188
189#[derive(#[automatically_derived]
impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ValidityRequirement {
#[inline]
fn clone(&self) -> ValidityRequirement { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ValidityRequirement {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ValidityRequirement::Inhabited => "Inhabited",
ValidityRequirement::Zero => "Zero",
ValidityRequirement::UninitMitigated0x01Fill =>
"UninitMitigated0x01Fill",
ValidityRequirement::Uninit => "Uninit",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ValidityRequirement {
#[inline]
fn eq(&self, other: &ValidityRequirement) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ValidityRequirement {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ValidityRequirement {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
ValidityRequirement {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ValidityRequirement::Inhabited => {}
ValidityRequirement::Zero => {}
ValidityRequirement::UninitMitigated0x01Fill => {}
ValidityRequirement::Uninit => {}
}
}
}
};StableHash)]
192pub enum ValidityRequirement {
193 Inhabited,
194 Zero,
195 UninitMitigated0x01Fill,
198 Uninit,
200}
201
202impl ValidityRequirement {
203 pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
204 match intrinsic {
205 sym::assert_inhabited => Some(Self::Inhabited),
206 sym::assert_zero_valid => Some(Self::Zero),
207 sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
208 _ => None,
209 }
210 }
211}
212
213impl fmt::Display for ValidityRequirement {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 match self {
216 Self::Inhabited => f.write_str("is inhabited"),
217 Self::Zero => f.write_str("allows being left zeroed"),
218 Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
219 Self::Uninit => f.write_str("allows being left uninitialized"),
220 }
221 }
222}
223
224#[derive(#[automatically_derived]
impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SimdLayoutError {
#[inline]
fn clone(&self) -> SimdLayoutError {
let _: ::core::clone::AssertParamIsClone<u64>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SimdLayoutError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SimdLayoutError::ZeroLength =>
::core::fmt::Formatter::write_str(f, "ZeroLength"),
SimdLayoutError::TooManyLanes(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooManyLanes", &__self_0),
}
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
SimdLayoutError {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for SimdLayoutError {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
SimdLayoutError::ZeroLength => { 0usize }
SimdLayoutError::TooManyLanes(ref __binding_0) => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for SimdLayoutError {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { SimdLayoutError::ZeroLength }
1usize => {
SimdLayoutError::TooManyLanes(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SimdLayoutError`, expected 0..2, actual {0}",
n));
}
}
}
}
};TyDecodable)]
225pub enum SimdLayoutError {
226 ZeroLength,
228 TooManyLanes(u64),
231}
232
233#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutError<'tcx> {
#[inline]
fn clone(&self) -> LayoutError<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<SimdLayoutError>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<NormalizationError<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LayoutError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LayoutError::Unknown(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Unknown", &__self_0),
LayoutError::SizeOverflow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SizeOverflow", &__self_0),
LayoutError::InvalidSimd { ty: __self_0, kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InvalidSimd", "ty", __self_0, "kind", &__self_1),
LayoutError::TooGeneric(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooGeneric", &__self_0),
LayoutError::NormalizationFailure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NormalizationFailure", __self_0, &__self_1),
LayoutError::ReferencesError(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ReferencesError", &__self_0),
}
}
}Debug, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
LayoutError<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
LayoutError::Unknown(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::SizeOverflow(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
LayoutError::TooGeneric(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
LayoutError::ReferencesError(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for LayoutError<'tcx> {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
LayoutError::Unknown(ref __binding_0) => { 0usize }
LayoutError::SizeOverflow(ref __binding_0) => { 1usize }
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
2usize
}
LayoutError::TooGeneric(ref __binding_0) => { 3usize }
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
4usize
}
LayoutError::ReferencesError(ref __binding_0) => { 5usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
LayoutError::Unknown(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::SizeOverflow(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
LayoutError::TooGeneric(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
LayoutError::ReferencesError(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for LayoutError<'tcx> {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
LayoutError::Unknown(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
LayoutError::SizeOverflow(::rustc_serialize::Decodable::decode(__decoder))
}
2usize => {
LayoutError::InvalidSimd {
ty: ::rustc_serialize::Decodable::decode(__decoder),
kind: ::rustc_serialize::Decodable::decode(__decoder),
}
}
3usize => {
LayoutError::TooGeneric(::rustc_serialize::Decodable::decode(__decoder))
}
4usize => {
LayoutError::NormalizationFailure(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
5usize => {
LayoutError::ReferencesError(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `LayoutError`, expected 0..6, actual {0}",
n));
}
}
}
}
};TyDecodable)]
234pub enum LayoutError<'tcx> {
235 Unknown(Ty<'tcx>),
243 SizeOverflow(Ty<'tcx>),
245 InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
247 TooGeneric(Ty<'tcx>),
252 NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
260 ReferencesError(ErrorGuaranteed),
262}
263
264impl<'tcx> fmt::Display for LayoutError<'tcx> {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 match *self {
267 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"),
268 LayoutError::TooGeneric(ty) => {
269 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")
270 }
271 LayoutError::SizeOverflow(ty) => {
272 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")
273 }
274 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
275 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}")
276 }
277 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
278 f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
279 }
280 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!(
281 f,
282 "unable to determine layout for `{}` because `{}` cannot be normalized",
283 t,
284 e.get_type_for_failure()
285 ),
286 LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
287 }
288 }
289}
290
291impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
292 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
293 self.to_string().into_diag_arg(&mut None)
294 }
295}
296
297#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
#[inline]
fn clone(&self) -> LayoutCx<'tcx> {
let _:
::core::clone::AssertParamIsClone<abi::LayoutCalculator<TyCtxt<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<ty::TypingEnv<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutCx<'tcx> { }Copy)]
298pub struct LayoutCx<'tcx> {
299 pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
300 pub typing_env: ty::TypingEnv<'tcx>,
301}
302
303impl<'tcx> LayoutCx<'tcx> {
304 pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
305 Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
306 }
307}
308
309#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for SizeSkeleton<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx> {
#[inline]
fn clone(&self) -> SizeSkeleton<'tcx> {
let _: ::core::clone::AssertParamIsClone<Size>;
let _: ::core::clone::AssertParamIsClone<Option<Align>>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SizeSkeleton<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SizeSkeleton::Known(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Known",
__self_0, &__self_1),
SizeSkeleton::Pointer { non_zero: __self_0, tail: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Pointer", "non_zero", __self_0, "tail", &__self_1),
}
}
}Debug)]
314pub enum SizeSkeleton<'tcx> {
315 Known(Size, Option<Align>),
318
319 Pointer {
321 non_zero: bool,
323 tail: Ty<'tcx>,
327 },
328}
329
330impl<'tcx> SizeSkeleton<'tcx> {
331 pub fn compute(
332 ty: Ty<'tcx>,
333 tcx: TyCtxt<'tcx>,
334 typing_env: ty::TypingEnv<'tcx>,
335 span: Span,
336 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
337 Self::compute_inner(ty, tcx, typing_env, span, 0)
338 }
339
340 fn compute_inner(
341 ty: Ty<'tcx>,
342 tcx: TyCtxt<'tcx>,
343 typing_env: ty::TypingEnv<'tcx>,
344 span: Span,
345 depth: usize,
346 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
347 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());
348
349 let recursion_limit = tcx.recursion_limit();
354 if depth >= recursion_limit.0 {
355 let suggested_limit = match recursion_limit {
356 hir::limit::Limit(0) => hir::limit::Limit(2),
357 limit => limit * 2,
358 };
359 let reported = tcx.dcx().emit_err(crate::error::RecursionLimitReachedSizeSkeleton {
360 span,
361 ty,
362 suggested_limit,
363 });
364 return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
365 }
366
367 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
369 Ok(layout) => {
370 if layout.is_sized() {
371 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
372 } else {
373 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
375 }
376 }
377 Err(err @ LayoutError::TooGeneric(_)) => err,
378 Err(
380 e @ LayoutError::Unknown(_)
381 | e @ LayoutError::SizeOverflow(_)
382 | e @ LayoutError::InvalidSimd { .. }
383 | e @ LayoutError::NormalizationFailure(..)
384 | e @ LayoutError::ReferencesError(_),
385 ) => return Err(e),
386 };
387
388 match *ty.kind() {
389 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
390 let non_zero = !ty.is_raw_ptr();
391
392 tcx.assert_fully_normalized(typing_env, pointee);
393 let tail = tcx.struct_tail_raw(
394 pointee,
395 &ObligationCause::dummy(),
396 |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
397 Ok(ty) => ty,
398 Err(e) => Ty::new_error_with_message(
399 tcx,
400 DUMMY_SP,
401 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
402 "normalization failed for {} but no errors reported",
403 e.get_type_for_failure()
404 ),
405 ),
406 },
407 || {},
408 );
409
410 match tail.kind() {
411 ty::Param(_)
414 | ty::Alias(
415 _,
416 ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
417 ) => {
418 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());
419 Ok(SizeSkeleton::Pointer {
420 non_zero,
421 tail: tcx.erase_and_anonymize_regions(tail),
422 })
423 }
424 ty::Error(guar) => {
425 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
427 }
428 _ => crate::util::bug::bug_fmt(format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
ty, err, tail))bug!(
429 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
430 tail `{tail}` is not a type parameter or a projection",
431 ),
432 }
433 }
434 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
435 let len_eval = len.try_to_target_usize(tcx);
436 if len_eval == Some(0) {
437 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
438 }
439
440 match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
441 SizeSkeleton::Known(s, a) => {
444 if let Some(c) = len_eval {
445 let size = s
446 .bytes()
447 .checked_mul(c)
448 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
449 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
451 }
452 Err(err)
453 }
454 SizeSkeleton::Pointer { .. } => Err(err),
455 }
456 }
457
458 ty::Adt(def, args) => {
459 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
461 return Err(err);
462 }
463 {
465 let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
470 def.repr();
471 let mut ignored_flags = ReprFlags::IS_TRANSPARENT
472 | ReprFlags::IS_LINEAR
473 | ReprFlags::RANDOMIZE_LAYOUT;
474 if def.is_struct() {
475 ignored_flags |= ReprFlags::IS_C;
480 }
481 if int.is_some()
482 || align.is_some()
483 || pack.is_some()
484 || flags.difference(ignored_flags) != ReprFlags::default()
485 || scalable.is_some()
486 {
487 return Err(err);
488 }
489 }
490
491 let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
495 let i = VariantIdx::from_usize(i);
496 let fields = def.variant(i).fields.iter().map(|field| {
497 SizeSkeleton::compute_inner(
498 field.ty(tcx, args).skip_norm_wip(),
499 tcx,
500 typing_env,
501 span,
502 depth + 1,
503 )
504 });
505 let mut ptr = None;
506 for field in fields {
507 let field = field?;
508 match field {
509 SizeSkeleton::Known(size, align) => {
510 let is_1zst = size.bytes() == 0
511 && align.is_some_and(|align| align.bytes() == 1);
512 if !is_1zst {
513 return Err(err);
514 }
515 }
516 SizeSkeleton::Pointer { .. } => {
517 if ptr.is_some() {
518 return Err(err);
519 }
520 ptr = Some(field);
521 }
522 }
523 }
524 Ok(ptr)
525 };
526
527 let v0 = zero_or_ptr_variant(0)?;
528 if def.variants().len() == 1 {
531 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
532 return Ok(SizeSkeleton::Pointer { non_zero, tail });
533 } else {
534 return Err(err);
535 }
536 }
537
538 let v1 = zero_or_ptr_variant(1)?;
539 match (v0, v1) {
543 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
544 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
545 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
546 }
547 _ => Err(err),
548 }
549 }
550
551 ty::Alias(..) => {
552 let normalized =
553 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
554 if ty == normalized {
555 Err(err)
556 } else {
557 SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
558 }
559 }
560
561 ty::Pat(base, pat) => {
562 let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
564 match *pat {
565 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
566 ty::PatternKind::NotNull => match base? {
569 SizeSkeleton::Known(..) => base,
570 SizeSkeleton::Pointer { non_zero: _, tail } => {
571 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
572 }
573 },
574 }
575 }
576
577 _ => Err(err),
578 }
579 }
580
581 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
582 match (self, other) {
583 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
584 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
585 a == b
586 }
587 _ => false,
588 }
589 }
590}
591
592pub trait HasTyCtxt<'tcx>: HasDataLayout {
593 fn tcx(&self) -> TyCtxt<'tcx>;
594}
595
596pub trait HasTypingEnv<'tcx> {
597 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
598}
599
600impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
601 #[inline]
602 fn data_layout(&self) -> &TargetDataLayout {
603 &self.data_layout
604 }
605}
606
607impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
608 fn target_spec(&self) -> &Target {
609 &self.sess.target
610 }
611}
612
613impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
614 fn x86_abi_opt(&self) -> X86Abi {
615 X86Abi {
616 regparm: self.sess.opts.unstable_opts.regparm,
617 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
618 }
619 }
620}
621
622impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
623 #[inline]
624 fn tcx(&self) -> TyCtxt<'tcx> {
625 *self
626 }
627}
628
629impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
630 #[inline]
631 fn data_layout(&self) -> &TargetDataLayout {
632 &self.data_layout
633 }
634}
635
636impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
637 fn target_spec(&self) -> &Target {
638 &self.sess.target
639 }
640}
641
642impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
643 #[inline]
644 fn tcx(&self) -> TyCtxt<'tcx> {
645 **self
646 }
647}
648
649impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
650 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
651 self.typing_env
652 }
653}
654
655impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
656 fn data_layout(&self) -> &TargetDataLayout {
657 self.calc.cx.data_layout()
658 }
659}
660
661impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
662 fn target_spec(&self) -> &Target {
663 self.calc.cx.target_spec()
664 }
665}
666
667impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
668 fn x86_abi_opt(&self) -> X86Abi {
669 self.calc.cx.x86_abi_opt()
670 }
671}
672
673impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
674 fn tcx(&self) -> TyCtxt<'tcx> {
675 self.calc.cx
676 }
677}
678
679pub trait MaybeResult<T> {
680 type Error;
681
682 fn from(x: Result<T, Self::Error>) -> Self;
683 fn to_result(self) -> Result<T, Self::Error>;
684}
685
686impl<T> MaybeResult<T> for T {
687 type Error = !;
688
689 fn from(Ok(x): Result<T, Self::Error>) -> Self {
690 x
691 }
692 fn to_result(self) -> Result<T, Self::Error> {
693 Ok(self)
694 }
695}
696
697impl<T, E> MaybeResult<T> for Result<T, E> {
698 type Error = E;
699
700 fn from(x: Result<T, Self::Error>) -> Self {
701 x
702 }
703 fn to_result(self) -> Result<T, Self::Error> {
704 self
705 }
706}
707
708pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
709
710pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
713 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
716
717 #[inline]
720 fn layout_tcx_at_span(&self) -> Span {
721 DUMMY_SP
722 }
723
724 fn handle_layout_err(
732 &self,
733 err: LayoutError<'tcx>,
734 span: Span,
735 ty: Ty<'tcx>,
736 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
737}
738
739pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
741 #[inline]
744 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
745 self.spanned_layout_of(ty, DUMMY_SP)
746 }
747
748 #[inline]
753 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
754 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
755 let tcx = self.tcx().at(span);
756
757 MaybeResult::from(
758 tcx.layout_of(self.typing_env().as_query_input(ty))
759 .map_err(|err| self.handle_layout_err(*err, span, ty)),
760 )
761 }
762}
763
764impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
765
766impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
767 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
768
769 #[inline]
770 fn handle_layout_err(
771 &self,
772 err: LayoutError<'tcx>,
773 _: Span,
774 _: Ty<'tcx>,
775 ) -> &'tcx LayoutError<'tcx> {
776 self.tcx().arena.alloc(err)
777 }
778}
779
780impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
781where
782 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
783{
784 fn ty_and_layout_for_variant(
785 this: TyAndLayout<'tcx>,
786 cx: &C,
787 variant_index: VariantIdx,
788 ) -> TyAndLayout<'tcx> {
789 let layout = match this.variants {
790 Variants::Single { index } if index == variant_index => {
792 return this;
793 }
794
795 Variants::Single { .. } | Variants::Empty => {
796 let tcx = cx.tcx();
801 let typing_env = cx.typing_env();
802
803 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
805 {
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);
806 }
807
808 let fields = match this.ty.kind() {
809 ty::Adt(def, _) if def.variants().is_empty() => {
810 crate::util::bug::bug_fmt(format_args!("for_variant called on zero-variant enum {0}",
this.ty))bug!("for_variant called on zero-variant enum {}", this.ty)
811 }
812 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
813 _ => crate::util::bug::bug_fmt(format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
this.ty))bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
814 };
815 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
816 }
817
818 Variants::Multiple { .. } => {
819 cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
820 }
821 };
822
823 {
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 });
824
825 TyAndLayout { ty: this.ty, layout }
826 }
827
828 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
829 enum TyMaybeWithLayout<'tcx> {
830 Ty(Ty<'tcx>),
831 TyAndLayout(TyAndLayout<'tcx>),
832 }
833
834 fn field_ty_or_layout<'tcx>(
835 this: TyAndLayout<'tcx>,
836 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
837 i: usize,
838 ) -> TyMaybeWithLayout<'tcx> {
839 let tcx = cx.tcx();
840 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
841 TyAndLayout {
842 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
843 ty: tag.primitive().to_ty(tcx),
844 }
845 };
846
847 match *this.ty.kind() {
848 ty::Bool
849 | ty::Char
850 | ty::Int(_)
851 | ty::Uint(_)
852 | ty::Float(_)
853 | ty::FnPtr(..)
854 | ty::Never
855 | ty::FnDef(..)
856 | ty::CoroutineWitness(..)
857 | ty::Foreign(..)
858 | ty::Dynamic(_, _) => {
859 crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this)
860 }
861
862 ty::Pat(base, _) => {
863 {
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);
864 TyMaybeWithLayout::Ty(base)
865 }
866
867 ty::UnsafeBinder(bound_ty) => {
868 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
869 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
870 }
871
872 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
874 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
875
876 if i == 0 {
881 let nil = tcx.types.unit;
882 let unit_ptr_ty = if this.ty.is_raw_ptr() {
883 Ty::new_mut_ptr(tcx, nil)
884 } else {
885 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
886 };
887
888 let typing_env = ty::TypingEnv::fully_monomorphized();
892 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
893 ty: this.ty,
894 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
895 });
896 }
897
898 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
899 let min_count = ty::vtable_min_entries(
900 tcx,
901 principal.map(|principal| {
902 tcx.instantiate_bound_regions_with_erased(principal)
903 }),
904 );
905 Ty::new_imm_ref(
906 tcx,
907 tcx.lifetimes.re_static,
908 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
910 )
911 };
912
913 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
914 && !pointee.references_error()
917 {
918 let metadata = tcx.normalize_erasing_regions(
919 cx.typing_env(),
920 Unnormalized::new(Ty::new_projection(
921 tcx,
922 ty::IsRigid::No,
923 metadata_def_id,
924 [pointee],
925 )),
926 );
927
928 if let ty::Adt(def, args) = metadata.kind()
933 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
934 && let ty::Dynamic(data, _) = args.type_at(0).kind()
935 {
936 mk_dyn_vtable(data.principal())
937 } else {
938 metadata
939 }
940 } else {
941 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
942 ty::Slice(_) | ty::Str => tcx.types.usize,
943 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
944 _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this),
945 }
946 };
947
948 TyMaybeWithLayout::Ty(metadata)
949 }
950
951 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
953 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
954
955 ty::Closure(_, args) => field_ty_or_layout(
957 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
958 cx,
959 i,
960 ),
961
962 ty::CoroutineClosure(_, args) => field_ty_or_layout(
963 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
964 cx,
965 i,
966 ),
967
968 ty::Coroutine(def_id, args) => match this.variants {
969 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
970 Variants::Single { index } => TyMaybeWithLayout::Ty(
971 args.as_coroutine()
972 .state_tys(def_id, tcx)
973 .nth(index.as_usize())
974 .unwrap()
975 .nth(i)
976 .unwrap(),
977 ),
978 Variants::Multiple { tag, tag_field, .. } => {
979 if FieldIdx::from_usize(i) == tag_field {
980 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
981 }
982 TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i])
983 }
984 },
985
986 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
987
988 ty::Adt(def, args) => {
990 match this.variants {
991 Variants::Single { index } => {
992 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
993 TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
994 }
995 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"),
996
997 Variants::Multiple { tag, .. } => {
999 {
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);
1000 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1001 }
1002 }
1003 }
1004
1005 ty::Alias(..)
1006 | ty::Bound(..)
1007 | ty::Placeholder(..)
1008 | ty::Param(_)
1009 | ty::Infer(_)
1010 | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1011 }
1012 }
1013
1014 match field_ty_or_layout(this, cx, i) {
1015 TyMaybeWithLayout::Ty(field_ty) => {
1016 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1017 crate::util::bug::bug_fmt(format_args!("failed to get layout for `{0}`: {1:?},\ndespite it being a field (#{2}) of an existing layout: {3:#?}",
field_ty, e, i, this))bug!(
1018 "failed to get layout for `{field_ty}`: {e:?},\n\
1019 despite it being a field (#{i}) of an existing layout: {this:#?}",
1020 )
1021 })
1022 }
1023 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1024 }
1025 }
1026
1027 fn ty_and_layout_pointee_info_at(
1030 this: TyAndLayout<'tcx>,
1031 cx: &C,
1032 offset: Size,
1033 ) -> Option<PointeeInfo> {
1034 let tcx = cx.tcx();
1035 let typing_env = cx.typing_env();
1036
1037 let optimize = tcx.sess.opts.optimize != OptLevel::No;
1041
1042 let pointee_info = match *this.ty.kind() {
1043 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1044 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1045 }
1046 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1047 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1048 let kind = match mt {
1049 hir::Mutability::Not => {
1050 let frozen = optimize && ty.is_freeze(tcx, typing_env);
1051 PointerKind::SharedRef { frozen }
1052 }
1053 hir::Mutability::Mut => {
1054 let unpin = optimize
1055 && ty.is_unpin(tcx, typing_env)
1056 && ty.is_unsafe_unpin(tcx, typing_env);
1057 PointerKind::MutableRef { unpin }
1058 }
1059 };
1060 PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1061 })
1062 }
1063
1064 ty::Adt(..)
1065 if offset.bytes() == 0
1066 && let Some(pointee) = this.ty.boxed_ty() =>
1067 {
1068 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1069 safe: Some(PointerKind::Box {
1070 unpin: optimize
1072 && pointee.is_unpin(tcx, typing_env)
1073 && pointee.is_unsafe_unpin(tcx, typing_env),
1074 global: this.ty.is_box_global(tcx),
1075 }),
1076 size: layout.size,
1077 align: layout.align.abi,
1078 })
1079 }
1080
1081 ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1082 Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1083 PointeeInfo {
1084 safe: None,
1087 size: Size::ZERO,
1089 align: info.align,
1091 }
1092 })
1093 }
1094
1095 _ => {
1096 let mut data_variant = match &this.variants {
1097 Variants::Multiple {
1107 tag_encoding:
1108 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1109 tag_field,
1110 variants,
1111 ..
1112 } if variants.len() == 2
1113 && this.fields.offset(tag_field.as_usize()) == offset =>
1114 {
1115 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1116 VariantIdx::from_u32(1)
1117 } else {
1118 VariantIdx::from_u32(0)
1119 };
1120 {
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);
1121 if *niche_start == 0 {
1122 Some(this.for_variant(cx, *untagged_variant))
1128 } else {
1129 None
1130 }
1131 }
1132 Variants::Multiple { .. } => None,
1133 Variants::Empty | Variants::Single { .. } => Some(this),
1134 };
1135
1136 if let Some(variant) = data_variant
1137 && let FieldsShape::Union(_) = variant.fields
1139 {
1140 data_variant = None;
1141 }
1142
1143 let mut result = None;
1144
1145 if let Some(variant) = data_variant {
1146 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1149 for i in 0..variant.fields.count() {
1150 let field_start = variant.fields.offset(i);
1151 if field_start <= offset {
1152 let field = variant.field(cx, i);
1153 result = field.to_result().ok().and_then(|field| {
1154 if ptr_end <= field_start + field.size {
1155 let field_info =
1157 field.pointee_info_at(cx, offset - field_start);
1158 field_info
1159 } else {
1160 None
1161 }
1162 });
1163 if result.is_some() {
1164 break;
1165 }
1166 }
1167 }
1168 }
1169
1170 result
1171 }
1172 };
1173
1174 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/layout.rs:1174",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1174u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
offset, this.ty.kind(), pointee_info) as &dyn Value))])
});
} else { ; }
};debug!(
1175 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1176 offset,
1177 this.ty.kind(),
1178 pointee_info
1179 );
1180
1181 pointee_info
1182 }
1183
1184 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1185 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1186 }
1187
1188 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1189 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1190 }
1191
1192 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1193 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1194 }
1195
1196 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1197 #[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)
1198 }
1199
1200 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1201 #[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())
1202 }
1203
1204 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1205 this.ty.is_scalable_vector()
1206 }
1207
1208 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1210 #[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))
1211 }
1212}
1213
1214#[inline]
1255#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_can_unwind",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1255u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["fn_def_id", "abi"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(did) = fn_def_id {
if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
{
return false;
}
if !tcx.sess.panic_strategy().unwinds() &&
!tcx.is_foreign_item(did) {
return false;
}
if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
tcx.is_lang_item(did, LangItem::DropGlue) {
return false;
}
}
use ExternAbi::*;
match abi {
C { unwind } | System { unwind } | Cdecl { unwind } |
Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
unwind } | SysV64 { unwind } => unwind,
PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
CmseNonSecureCall | CmseNonSecureEntry | Custom |
RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
Unadjusted => false,
Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
tcx.sess.panic_strategy().unwinds()
}
}
}
}
}#[tracing::instrument(level = "debug", skip(tcx))]
1256pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1257 if let Some(did) = fn_def_id {
1258 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1260 return false;
1261 }
1262
1263 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1268 return false;
1269 }
1270
1271 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1276 && tcx.is_lang_item(did, LangItem::DropGlue)
1277 {
1278 return false;
1279 }
1280 }
1281
1282 use ExternAbi::*;
1289 match abi {
1290 C { unwind }
1291 | System { unwind }
1292 | Cdecl { unwind }
1293 | Stdcall { unwind }
1294 | Fastcall { unwind }
1295 | Vectorcall { unwind }
1296 | Thiscall { unwind }
1297 | Aapcs { unwind }
1298 | Win64 { unwind }
1299 | SysV64 { unwind } => unwind,
1300 PtxKernel
1301 | Msp430Interrupt
1302 | X86Interrupt
1303 | GpuKernel
1304 | EfiApi
1305 | AvrInterrupt
1306 | AvrNonBlockingInterrupt
1307 | CmseNonSecureCall
1308 | CmseNonSecureEntry
1309 | Custom
1310 | RiscvInterruptM
1311 | RiscvInterruptS
1312 | RustInvalid
1313 | Swift
1314 | Unadjusted => false,
1315 Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1316 tcx.sess.panic_strategy().unwinds()
1317 }
1318 }
1319}
1320
1321#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
#[inline]
fn clone(&self) -> FnAbiError<'tcx> {
let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnAbiError::Layout(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
&__self_0),
}
}
}Debug, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
FnAbiError<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
FnAbiError::Layout(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1323pub enum FnAbiError<'tcx> {
1324 Layout(LayoutError<'tcx>),
1326}
1327
1328impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1329 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1330 match self {
1331 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1332 }
1333 }
1334}
1335
1336#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiRequest<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnAbiRequest::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OfFnPtr", "sig", __self_0, "extra_args", &__self_1),
FnAbiRequest::OfInstance {
instance: __self_0, extra_args: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OfInstance", "instance", __self_0, "extra_args",
&__self_1),
}
}
}Debug)]
1339pub enum FnAbiRequest<'tcx> {
1340 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1341 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1342}
1343
1344pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1347 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1350
1351 fn handle_fn_abi_err(
1359 &self,
1360 err: FnAbiError<'tcx>,
1361 span: Span,
1362 fn_abi_request: FnAbiRequest<'tcx>,
1363 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1364}
1365
1366pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1368 #[inline]
1373 fn fn_abi_of_fn_ptr(
1374 &self,
1375 sig: ty::PolyFnSig<'tcx>,
1376 extra_args: &'tcx ty::List<Ty<'tcx>>,
1377 ) -> Self::FnAbiOfResult {
1378 let span = self.layout_tcx_at_span();
1380 let tcx = self.tcx().at(span);
1381
1382 MaybeResult::from(
1383 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1384 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1385 ),
1386 )
1387 }
1388
1389 #[inline]
1401 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_abi_of_instance_no_deduced_attrs",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1401u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["instance",
"extra_args"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: 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))]
1402 fn fn_abi_of_instance_no_deduced_attrs(
1403 &self,
1404 instance: ty::Instance<'tcx>,
1405 extra_args: &'tcx ty::List<Ty<'tcx>>,
1406 ) -> Self::FnAbiOfResult {
1407 let span = self.layout_tcx_at_span();
1409 let tcx = self.tcx().at(span);
1410
1411 MaybeResult::from(
1412 tcx.fn_abi_of_instance_no_deduced_attrs(
1413 self.typing_env().as_query_input((instance, extra_args)),
1414 )
1415 .map_err(|err| {
1416 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1421 self.handle_fn_abi_err(
1422 *err,
1423 span,
1424 FnAbiRequest::OfInstance { instance, extra_args },
1425 )
1426 }),
1427 )
1428 }
1429
1430 #[inline]
1440 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_abi_of_instance",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1440u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["instance",
"extra_args"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: 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))]
1441 fn fn_abi_of_instance(
1442 &self,
1443 instance: ty::Instance<'tcx>,
1444 extra_args: &'tcx ty::List<Ty<'tcx>>,
1445 ) -> Self::FnAbiOfResult {
1446 let span = self.layout_tcx_at_span();
1448 let tcx = self.tcx().at(span);
1449
1450 MaybeResult::from(
1451 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1452 .map_err(|err| {
1453 let span =
1458 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1459 self.handle_fn_abi_err(
1460 *err,
1461 span,
1462 FnAbiRequest::OfInstance { instance, extra_args },
1463 )
1464 }),
1465 )
1466 }
1467}
1468
1469impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}