1use std::ops::Bound;
2use std::{cmp, fmt};
3
4use rustc_abi as abi;
5use rustc_abi::{
6 AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
7 PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
8 TyAbiInterface, VariantIdx, Variants,
9};
10use rustc_errors::{
11 Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
12};
13use rustc_hir as hir;
14use rustc_hir::LangItem;
15use rustc_hir::def_id::DefId;
16use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension};
17use rustc_session::config::OptLevel;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
19use rustc_target::callconv::FnAbi;
20use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
21use tracing::debug;
22
23use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
24use crate::query::TyCtxtAt;
25use crate::traits::ObligationCause;
26use crate::ty::normalize_erasing_regions::NormalizationError;
27use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt};
28
29impl IntegerExt for abi::Integer {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
use abi::Integer::{I8, I16, I32, I64, I128};
match (*self, signed) {
(I8, false) => tcx.types.u8,
(I16, false) => tcx.types.u16,
(I32, false) => tcx.types.u32,
(I64, false) => tcx.types.u64,
(I128, false) => tcx.types.u128,
(I8, true) => tcx.types.i8,
(I16, true) => tcx.types.i16,
(I32, true) => tcx.types.i32,
(I64, true) => tcx.types.i64,
(I128, true) => tcx.types.i128,
}
}
fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::IntTy::I8 => I8,
ty::IntTy::I16 => I16,
ty::IntTy::I32 => I32,
ty::IntTy::I64 => I64,
ty::IntTy::I128 => I128,
ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
}
}
fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
-> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::UintTy::U8 => I8,
ty::UintTy::U16 => I16,
ty::UintTy::U32 => I32,
ty::UintTy::U64 => I64,
ty::UintTy::U128 => I128,
ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
}
}
#[doc =
" Finds the appropriate Integer type and signedness for the given"]
#[doc = " 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)]
30impl abi::Integer {
31 #[inline]
32 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
33 use abi::Integer::{I8, I16, I32, I64, I128};
34 match (*self, signed) {
35 (I8, false) => tcx.types.u8,
36 (I16, false) => tcx.types.u16,
37 (I32, false) => tcx.types.u32,
38 (I64, false) => tcx.types.u64,
39 (I128, false) => tcx.types.u128,
40 (I8, true) => tcx.types.i8,
41 (I16, true) => tcx.types.i16,
42 (I32, true) => tcx.types.i32,
43 (I64, true) => tcx.types.i64,
44 (I128, true) => tcx.types.i128,
45 }
46 }
47
48 fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
49 use abi::Integer::{I8, I16, I32, I64, I128};
50 match ity {
51 ty::IntTy::I8 => I8,
52 ty::IntTy::I16 => I16,
53 ty::IntTy::I32 => I32,
54 ty::IntTy::I64 => I64,
55 ty::IntTy::I128 => I128,
56 ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
57 }
58 }
59 fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
60 use abi::Integer::{I8, I16, I32, I64, I128};
61 match ity {
62 ty::UintTy::U8 => I8,
63 ty::UintTy::U16 => I16,
64 ty::UintTy::U32 => I32,
65 ty::UintTy::U64 => I64,
66 ty::UintTy::U128 => I128,
67 ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
68 }
69 }
70
71 fn discr_range_of_repr<'tcx>(
79 tcx: TyCtxt<'tcx>,
80 ty: Ty<'tcx>,
81 repr: &ReprOptions,
82 min: i128,
83 max: i128,
84 ) -> (abi::Integer, bool) {
85 let unsigned_fit = abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
90 let signed_fit = cmp::max(abi::Integer::fit_signed(min), abi::Integer::fit_signed(max));
91
92 if let Some(ity) = repr.int {
93 let discr = abi::Integer::from_attr(&tcx, ity);
94 let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
95 if discr < fit {
96 bug!(
97 "Integer::repr_discr: `#[repr]` hint too small for \
98 discriminant range of enum `{}`",
99 ty
100 )
101 }
102 return (discr, ity.is_signed());
103 }
104
105 let at_least = if repr.c() {
106 tcx.data_layout().c_enum_min_size
109 } else {
110 abi::Integer::I8
112 };
113
114 if unsigned_fit <= signed_fit {
117 (cmp::max(unsigned_fit, at_least), false)
118 } else {
119 (cmp::max(signed_fit, at_least), true)
120 }
121 }
122}
123
124impl 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)]
125impl abi::Float {
126 #[inline]
127 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
128 use abi::Float::*;
129 match *self {
130 F16 => tcx.types.f16,
131 F32 => tcx.types.f32,
132 F64 => tcx.types.f64,
133 F128 => tcx.types.f128,
134 }
135 }
136
137 fn from_float_ty(fty: ty::FloatTy) -> Self {
138 use abi::Float::*;
139 match fty {
140 ty::FloatTy::F16 => F16,
141 ty::FloatTy::F32 => F32,
142 ty::FloatTy::F64 => F64,
143 ty::FloatTy::F128 => F128,
144 }
145 }
146}
147
148impl 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)]
149impl Primitive {
150 #[inline]
151 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
152 match *self {
153 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
154 Primitive::Float(f) => f.to_ty(tcx),
155 Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
157 }
158 }
159
160 #[inline]
163 fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
164 match *self {
165 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
166 Primitive::Pointer(_) => {
168 let signed = false;
169 tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
170 }
171 Primitive::Float(_) => bug!("floats do not have an int type"),
172 }
173 }
174}
175
176pub const WIDE_PTR_ADDR: usize = 0;
181
182pub const WIDE_PTR_EXTRA: usize = 1;
187
188pub const MAX_SIMD_LANES: u64 = rustc_abi::MAX_SIMD_LANES;
189
190#[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<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for ValidityRequirement {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
ValidityRequirement::Inhabited => {}
ValidityRequirement::Zero => {}
ValidityRequirement::UninitMitigated0x01Fill => {}
ValidityRequirement::Uninit => {}
}
}
}
};HashStable)]
193pub enum ValidityRequirement {
194 Inhabited,
195 Zero,
196 UninitMitigated0x01Fill,
199 Uninit,
201}
202
203impl ValidityRequirement {
204 pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
205 match intrinsic {
206 sym::assert_inhabited => Some(Self::Inhabited),
207 sym::assert_zero_valid => Some(Self::Zero),
208 sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
209 _ => None,
210 }
211 }
212}
213
214impl fmt::Display for ValidityRequirement {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match self {
217 Self::Inhabited => f.write_str("is inhabited"),
218 Self::Zero => f.write_str("allows being left zeroed"),
219 Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
220 Self::Uninit => f.write_str("allows being left uninitialized"),
221 }
222 }
223}
224
225#[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<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for SimdLayoutError {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable, 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)]
226pub enum SimdLayoutError {
227 ZeroLength,
229 TooManyLanes(u64),
232}
233
234#[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, '__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for LayoutError<'tcx> {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
LayoutError::Unknown(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::SizeOverflow(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
}
LayoutError::TooGeneric(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
}
LayoutError::ReferencesError(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable, 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)]
235pub enum LayoutError<'tcx> {
236 Unknown(Ty<'tcx>),
244 SizeOverflow(Ty<'tcx>),
246 InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
248 TooGeneric(Ty<'tcx>),
253 NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
261 ReferencesError(ErrorGuaranteed),
263}
264
265impl<'tcx> fmt::Display for LayoutError<'tcx> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 match *self {
268 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"),
269 LayoutError::TooGeneric(ty) => {
270 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")
271 }
272 LayoutError::SizeOverflow(ty) => {
273 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")
274 }
275 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
276 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}")
277 }
278 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
279 f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
280 }
281 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!(
282 f,
283 "unable to determine layout for `{}` because `{}` cannot be normalized",
284 t,
285 e.get_type_for_failure()
286 ),
287 LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
288 }
289 }
290}
291
292impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
293 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
294 self.to_string().into_diag_arg(&mut None)
295 }
296}
297
298#[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)]
299pub struct LayoutCx<'tcx> {
300 pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
301 pub typing_env: ty::TypingEnv<'tcx>,
302}
303
304impl<'tcx> LayoutCx<'tcx> {
305 pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
306 Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
307 }
308}
309
310#[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)]
315pub enum SizeSkeleton<'tcx> {
316 Known(Size, Option<Align>),
319
320 Pointer {
322 non_zero: bool,
324 tail: Ty<'tcx>,
328 },
329}
330
331impl<'tcx> SizeSkeleton<'tcx> {
332 pub fn compute(
333 ty: Ty<'tcx>,
334 tcx: TyCtxt<'tcx>,
335 typing_env: ty::TypingEnv<'tcx>,
336 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
337 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());
338
339 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
341 Ok(layout) => {
342 if layout.is_sized() {
343 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
344 } else {
345 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
347 }
348 }
349 Err(err @ LayoutError::TooGeneric(_)) => err,
350 Err(
352 e @ LayoutError::Unknown(_)
353 | e @ LayoutError::SizeOverflow(_)
354 | e @ LayoutError::InvalidSimd { .. }
355 | e @ LayoutError::NormalizationFailure(..)
356 | e @ LayoutError::ReferencesError(_),
357 ) => return Err(e),
358 };
359
360 match *ty.kind() {
361 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
362 let non_zero = !ty.is_raw_ptr();
363
364 let tail = tcx.struct_tail_raw(
365 pointee,
366 &ObligationCause::dummy(),
367 |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
368 Ok(ty) => ty,
369 Err(e) => Ty::new_error_with_message(
370 tcx,
371 DUMMY_SP,
372 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
373 "normalization failed for {} but no errors reported",
374 e.get_type_for_failure()
375 ),
376 ),
377 },
378 || {},
379 );
380
381 match tail.kind() {
382 ty::Param(_)
383 | ty::Alias(ty::AliasTy {
384 kind: ty::Projection { .. } | ty::Inherent { .. },
385 ..
386 }) => {
387 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());
388 Ok(SizeSkeleton::Pointer {
389 non_zero,
390 tail: tcx.erase_and_anonymize_regions(tail),
391 })
392 }
393 ty::Error(guar) => {
394 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
396 }
397 _ => 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!(
398 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
399 tail `{tail}` is not a type parameter or a projection",
400 ),
401 }
402 }
403 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
404 let len_eval = len.try_to_target_usize(tcx);
405 if len_eval == Some(0) {
406 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
407 }
408
409 match SizeSkeleton::compute(inner, tcx, typing_env)? {
410 SizeSkeleton::Known(s, a) => {
413 if let Some(c) = len_eval {
414 let size = s
415 .bytes()
416 .checked_mul(c)
417 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
418 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
420 }
421 Err(err)
422 }
423 SizeSkeleton::Pointer { .. } => Err(err),
424 }
425 }
426
427 ty::Adt(def, args) => {
428 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
430 return Err(err);
431 }
432
433 let zero_or_ptr_variant = |i| {
435 let i = VariantIdx::from_usize(i);
436 let fields =
437 def.variant(i).fields.iter().map(|field| {
438 SizeSkeleton::compute(field.ty(tcx, args), tcx, typing_env)
439 });
440 let mut ptr = None;
441 for field in fields {
442 let field = field?;
443 match field {
444 SizeSkeleton::Known(size, align) => {
445 let is_1zst = size.bytes() == 0
446 && align.is_some_and(|align| align.bytes() == 1);
447 if !is_1zst {
448 return Err(err);
449 }
450 }
451 SizeSkeleton::Pointer { .. } => {
452 if ptr.is_some() {
453 return Err(err);
454 }
455 ptr = Some(field);
456 }
457 }
458 }
459 Ok(ptr)
460 };
461
462 let v0 = zero_or_ptr_variant(0)?;
463 if def.variants().len() == 1 {
465 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
466 return Ok(SizeSkeleton::Pointer {
467 non_zero: non_zero
468 || match tcx.layout_scalar_valid_range(def.did()) {
469 (Bound::Included(start), Bound::Unbounded) => start > 0,
470 (Bound::Included(start), Bound::Included(end)) => {
471 0 < start && start < end
472 }
473 _ => false,
474 },
475 tail,
476 });
477 } else {
478 return Err(err);
479 }
480 }
481
482 let v1 = zero_or_ptr_variant(1)?;
483 match (v0, v1) {
485 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
486 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
487 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
488 }
489 _ => Err(err),
490 }
491 }
492
493 ty::Alias(..) => {
494 let normalized = tcx.normalize_erasing_regions(typing_env, ty);
495 if ty == normalized {
496 Err(err)
497 } else {
498 SizeSkeleton::compute(normalized, tcx, typing_env)
499 }
500 }
501
502 ty::Pat(base, pat) => {
503 let base = SizeSkeleton::compute(base, tcx, typing_env);
505 match *pat {
506 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
507 ty::PatternKind::NotNull => match base? {
510 SizeSkeleton::Known(..) => base,
511 SizeSkeleton::Pointer { non_zero: _, tail } => {
512 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
513 }
514 },
515 }
516 }
517
518 _ => Err(err),
519 }
520 }
521
522 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
523 match (self, other) {
524 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
525 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
526 a == b
527 }
528 _ => false,
529 }
530 }
531}
532
533pub trait HasTyCtxt<'tcx>: HasDataLayout {
534 fn tcx(&self) -> TyCtxt<'tcx>;
535}
536
537pub trait HasTypingEnv<'tcx> {
538 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
539
540 fn param_env(&self) -> ty::ParamEnv<'tcx> {
543 self.typing_env().param_env
544 }
545}
546
547impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
548 #[inline]
549 fn data_layout(&self) -> &TargetDataLayout {
550 &self.data_layout
551 }
552}
553
554impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
555 fn target_spec(&self) -> &Target {
556 &self.sess.target
557 }
558}
559
560impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
561 fn x86_abi_opt(&self) -> X86Abi {
562 X86Abi {
563 regparm: self.sess.opts.unstable_opts.regparm,
564 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
565 }
566 }
567}
568
569impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
570 #[inline]
571 fn tcx(&self) -> TyCtxt<'tcx> {
572 *self
573 }
574}
575
576impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
577 #[inline]
578 fn data_layout(&self) -> &TargetDataLayout {
579 &self.data_layout
580 }
581}
582
583impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
584 fn target_spec(&self) -> &Target {
585 &self.sess.target
586 }
587}
588
589impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
590 #[inline]
591 fn tcx(&self) -> TyCtxt<'tcx> {
592 **self
593 }
594}
595
596impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
597 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
598 self.typing_env
599 }
600}
601
602impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
603 fn data_layout(&self) -> &TargetDataLayout {
604 self.calc.cx.data_layout()
605 }
606}
607
608impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
609 fn target_spec(&self) -> &Target {
610 self.calc.cx.target_spec()
611 }
612}
613
614impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
615 fn x86_abi_opt(&self) -> X86Abi {
616 self.calc.cx.x86_abi_opt()
617 }
618}
619
620impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
621 fn tcx(&self) -> TyCtxt<'tcx> {
622 self.calc.cx
623 }
624}
625
626pub trait MaybeResult<T> {
627 type Error;
628
629 fn from(x: Result<T, Self::Error>) -> Self;
630 fn to_result(self) -> Result<T, Self::Error>;
631}
632
633impl<T> MaybeResult<T> for T {
634 type Error = !;
635
636 fn from(Ok(x): Result<T, Self::Error>) -> Self {
637 x
638 }
639 fn to_result(self) -> Result<T, Self::Error> {
640 Ok(self)
641 }
642}
643
644impl<T, E> MaybeResult<T> for Result<T, E> {
645 type Error = E;
646
647 fn from(x: Result<T, Self::Error>) -> Self {
648 x
649 }
650 fn to_result(self) -> Result<T, Self::Error> {
651 self
652 }
653}
654
655pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
656
657pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
660 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
663
664 #[inline]
667 fn layout_tcx_at_span(&self) -> Span {
668 DUMMY_SP
669 }
670
671 fn handle_layout_err(
679 &self,
680 err: LayoutError<'tcx>,
681 span: Span,
682 ty: Ty<'tcx>,
683 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
684}
685
686pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
688 #[inline]
691 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
692 self.spanned_layout_of(ty, DUMMY_SP)
693 }
694
695 #[inline]
700 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
701 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
702 let tcx = self.tcx().at(span);
703
704 MaybeResult::from(
705 tcx.layout_of(self.typing_env().as_query_input(ty))
706 .map_err(|err| self.handle_layout_err(*err, span, ty)),
707 )
708 }
709}
710
711impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
712
713impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
714 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
715
716 #[inline]
717 fn handle_layout_err(
718 &self,
719 err: LayoutError<'tcx>,
720 _: Span,
721 _: Ty<'tcx>,
722 ) -> &'tcx LayoutError<'tcx> {
723 self.tcx().arena.alloc(err)
724 }
725}
726
727impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
728where
729 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
730{
731 fn ty_and_layout_for_variant(
732 this: TyAndLayout<'tcx>,
733 cx: &C,
734 variant_index: VariantIdx,
735 ) -> TyAndLayout<'tcx> {
736 let layout = match this.variants {
737 Variants::Single { index } if index == variant_index => {
739 return this;
740 }
741
742 Variants::Single { .. } | Variants::Empty => {
743 let tcx = cx.tcx();
748 let typing_env = cx.typing_env();
749
750 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
752 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);
753 }
754
755 let fields = match this.ty.kind() {
756 ty::Adt(def, _) if def.variants().is_empty() => {
757 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)
758 }
759 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
760 _ => 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),
761 };
762 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
763 }
764
765 Variants::Multiple { ref variants, .. } => {
766 cx.tcx().mk_layout(variants[variant_index].clone())
767 }
768 };
769
770 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 });
771
772 TyAndLayout { ty: this.ty, layout }
773 }
774
775 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
776 enum TyMaybeWithLayout<'tcx> {
777 Ty(Ty<'tcx>),
778 TyAndLayout(TyAndLayout<'tcx>),
779 }
780
781 fn field_ty_or_layout<'tcx>(
782 this: TyAndLayout<'tcx>,
783 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
784 i: usize,
785 ) -> TyMaybeWithLayout<'tcx> {
786 let tcx = cx.tcx();
787 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
788 TyAndLayout {
789 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
790 ty: tag.primitive().to_ty(tcx),
791 }
792 };
793
794 match *this.ty.kind() {
795 ty::Bool
796 | ty::Char
797 | ty::Int(_)
798 | ty::Uint(_)
799 | ty::Float(_)
800 | ty::FnPtr(..)
801 | ty::Never
802 | ty::FnDef(..)
803 | ty::CoroutineWitness(..)
804 | ty::Foreign(..)
805 | ty::Dynamic(_, _) => {
806 crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this)
807 }
808
809 ty::Pat(base, _) => {
810 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);
811 TyMaybeWithLayout::Ty(base)
812 }
813
814 ty::UnsafeBinder(bound_ty) => {
815 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
816 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
817 }
818
819 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
821 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
822
823 if i == 0 {
828 let nil = tcx.types.unit;
829 let unit_ptr_ty = if this.ty.is_raw_ptr() {
830 Ty::new_mut_ptr(tcx, nil)
831 } else {
832 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
833 };
834
835 let typing_env = ty::TypingEnv::fully_monomorphized();
839 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
840 ty: this.ty,
841 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
842 });
843 }
844
845 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
846 let min_count = ty::vtable_min_entries(
847 tcx,
848 principal.map(|principal| {
849 tcx.instantiate_bound_regions_with_erased(principal)
850 }),
851 );
852 Ty::new_imm_ref(
853 tcx,
854 tcx.lifetimes.re_static,
855 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
857 )
858 };
859
860 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
861 && !pointee.references_error()
864 {
865 let metadata = tcx.normalize_erasing_regions(
866 cx.typing_env(),
867 Ty::new_projection(tcx, metadata_def_id, [pointee]),
868 );
869
870 if let ty::Adt(def, args) = metadata.kind()
875 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
876 && let ty::Dynamic(data, _) = args.type_at(0).kind()
877 {
878 mk_dyn_vtable(data.principal())
879 } else {
880 metadata
881 }
882 } else {
883 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
884 ty::Slice(_) | ty::Str => tcx.types.usize,
885 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
886 _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this),
887 }
888 };
889
890 TyMaybeWithLayout::Ty(metadata)
891 }
892
893 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
895 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
896
897 ty::Closure(_, args) => field_ty_or_layout(
899 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
900 cx,
901 i,
902 ),
903
904 ty::CoroutineClosure(_, args) => field_ty_or_layout(
905 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
906 cx,
907 i,
908 ),
909
910 ty::Coroutine(def_id, args) => match this.variants {
911 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
912 Variants::Single { index } => TyMaybeWithLayout::Ty(
913 args.as_coroutine()
914 .state_tys(def_id, tcx)
915 .nth(index.as_usize())
916 .unwrap()
917 .nth(i)
918 .unwrap(),
919 ),
920 Variants::Multiple { tag, tag_field, .. } => {
921 if FieldIdx::from_usize(i) == tag_field {
922 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
923 }
924 TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i])
925 }
926 },
927
928 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
929
930 ty::Adt(def, args) => {
932 match this.variants {
933 Variants::Single { index } => {
934 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
935 TyMaybeWithLayout::Ty(field.ty(tcx, args))
936 }
937 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"),
938
939 Variants::Multiple { tag, .. } => {
941 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);
942 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
943 }
944 }
945 }
946
947 ty::Alias(..)
948 | ty::Bound(..)
949 | ty::Placeholder(..)
950 | ty::Param(_)
951 | ty::Infer(_)
952 | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
953 }
954 }
955
956 match field_ty_or_layout(this, cx, i) {
957 TyMaybeWithLayout::Ty(field_ty) => {
958 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
959 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!(
960 "failed to get layout for `{field_ty}`: {e:?},\n\
961 despite it being a field (#{i}) of an existing layout: {this:#?}",
962 )
963 })
964 }
965 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
966 }
967 }
968
969 fn ty_and_layout_pointee_info_at(
972 this: TyAndLayout<'tcx>,
973 cx: &C,
974 offset: Size,
975 ) -> Option<PointeeInfo> {
976 let tcx = cx.tcx();
977 let typing_env = cx.typing_env();
978
979 let optimize = tcx.sess.opts.optimize != OptLevel::No;
983
984 let pointee_info = match *this.ty.kind() {
985 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
986 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
987 }
988 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
989 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
990 let (size, kind);
991 match mt {
992 hir::Mutability::Not => {
993 let frozen = optimize && ty.is_freeze(tcx, typing_env);
994
995 size = if frozen { layout.size } else { Size::ZERO };
999
1000 kind = PointerKind::SharedRef { frozen };
1001 }
1002 hir::Mutability::Mut => {
1003 let unpin = optimize
1004 && ty.is_unpin(tcx, typing_env)
1005 && ty.is_unsafe_unpin(tcx, typing_env);
1006
1007 size = if unpin { layout.size } else { Size::ZERO };
1012
1013 kind = PointerKind::MutableRef { unpin };
1014 }
1015 };
1016 PointeeInfo { safe: Some(kind), size, align: layout.align.abi }
1017 })
1018 }
1019
1020 ty::Adt(..)
1021 if offset.bytes() == 0
1022 && let Some(pointee) = this.ty.boxed_ty() =>
1023 {
1024 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1025 safe: Some(PointerKind::Box {
1026 unpin: optimize
1028 && pointee.is_unpin(tcx, typing_env)
1029 && pointee.is_unsafe_unpin(tcx, typing_env),
1030 global: this.ty.is_box_global(tcx),
1031 }),
1032
1033 size: Size::ZERO,
1037
1038 align: layout.align.abi,
1039 })
1040 }
1041
1042 ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1043 Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1044 PointeeInfo {
1045 safe: None,
1048 size: Size::ZERO,
1050 align: info.align,
1052 }
1053 })
1054 }
1055
1056 _ => {
1057 let mut data_variant = match &this.variants {
1058 Variants::Multiple {
1068 tag_encoding:
1069 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1070 tag_field,
1071 variants,
1072 ..
1073 } if variants.len() == 2
1074 && this.fields.offset(tag_field.as_usize()) == offset =>
1075 {
1076 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1077 VariantIdx::from_u32(1)
1078 } else {
1079 VariantIdx::from_u32(0)
1080 };
1081 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());
1082 if *niche_start == 0 {
1083 Some(this.for_variant(cx, *untagged_variant))
1089 } else {
1090 None
1091 }
1092 }
1093 Variants::Multiple { .. } => None,
1094 Variants::Empty | Variants::Single { .. } => Some(this),
1095 };
1096
1097 if let Some(variant) = data_variant
1098 && let FieldsShape::Union(_) = variant.fields
1100 {
1101 data_variant = None;
1102 }
1103
1104 let mut result = None;
1105
1106 if let Some(variant) = data_variant {
1107 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1110 for i in 0..variant.fields.count() {
1111 let field_start = variant.fields.offset(i);
1112 if field_start <= offset {
1113 let field = variant.field(cx, i);
1114 result = field.to_result().ok().and_then(|field| {
1115 if ptr_end <= field_start + field.size {
1116 let field_info =
1118 field.pointee_info_at(cx, offset - field_start);
1119 field_info
1120 } else {
1121 None
1122 }
1123 });
1124 if result.is_some() {
1125 break;
1126 }
1127 }
1128 }
1129 }
1130
1131 result
1132 }
1133 };
1134
1135 {
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:1135",
"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(1135u32),
::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!(
1136 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1137 offset,
1138 this.ty.kind(),
1139 pointee_info
1140 );
1141
1142 pointee_info
1143 }
1144
1145 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1146 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1147 }
1148
1149 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1150 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1151 }
1152
1153 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1154 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1155 }
1156
1157 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1158 #[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)
1159 }
1160
1161 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1162 #[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())
1163 }
1164
1165 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1166 this.ty.is_scalable_vector()
1167 }
1168
1169 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1171 #[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))
1172 }
1173}
1174
1175#[inline]
1216#[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(1216u32),
::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::DropInPlace) {
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 | Unadjusted
=> false,
Rust | RustCall | RustCold | RustPreserveNone =>
tcx.sess.panic_strategy().unwinds(),
}
}
}
}#[tracing::instrument(level = "debug", skip(tcx))]
1217pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1218 if let Some(did) = fn_def_id {
1219 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1221 return false;
1222 }
1223
1224 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1229 return false;
1230 }
1231
1232 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1237 && tcx.is_lang_item(did, LangItem::DropInPlace)
1238 {
1239 return false;
1240 }
1241 }
1242
1243 use ExternAbi::*;
1250 match abi {
1251 C { unwind }
1252 | System { unwind }
1253 | Cdecl { unwind }
1254 | Stdcall { unwind }
1255 | Fastcall { unwind }
1256 | Vectorcall { unwind }
1257 | Thiscall { unwind }
1258 | Aapcs { unwind }
1259 | Win64 { unwind }
1260 | SysV64 { unwind } => unwind,
1261 PtxKernel
1262 | Msp430Interrupt
1263 | X86Interrupt
1264 | GpuKernel
1265 | EfiApi
1266 | AvrInterrupt
1267 | AvrNonBlockingInterrupt
1268 | CmseNonSecureCall
1269 | CmseNonSecureEntry
1270 | Custom
1271 | RiscvInterruptM
1272 | RiscvInterruptS
1273 | RustInvalid
1274 | Unadjusted => false,
1275 Rust | RustCall | RustCold | RustPreserveNone => tcx.sess.panic_strategy().unwinds(),
1276 }
1277}
1278
1279#[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, '__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for FnAbiError<'tcx> {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
FnAbiError::Layout(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable)]
1281pub enum FnAbiError<'tcx> {
1282 Layout(LayoutError<'tcx>),
1284}
1285
1286impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1287 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1288 match self {
1289 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1290 }
1291 }
1292}
1293
1294#[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)]
1297pub enum FnAbiRequest<'tcx> {
1298 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1299 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1300}
1301
1302pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1305 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1308
1309 fn handle_fn_abi_err(
1317 &self,
1318 err: FnAbiError<'tcx>,
1319 span: Span,
1320 fn_abi_request: FnAbiRequest<'tcx>,
1321 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1322}
1323
1324pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1326 #[inline]
1331 fn fn_abi_of_fn_ptr(
1332 &self,
1333 sig: ty::PolyFnSig<'tcx>,
1334 extra_args: &'tcx ty::List<Ty<'tcx>>,
1335 ) -> Self::FnAbiOfResult {
1336 let span = self.layout_tcx_at_span();
1338 let tcx = self.tcx().at(span);
1339
1340 MaybeResult::from(
1341 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1342 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1343 ),
1344 )
1345 }
1346
1347 #[inline]
1359 #[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(1359u32),
::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))]
1360 fn fn_abi_of_instance_no_deduced_attrs(
1361 &self,
1362 instance: ty::Instance<'tcx>,
1363 extra_args: &'tcx ty::List<Ty<'tcx>>,
1364 ) -> Self::FnAbiOfResult {
1365 let span = self.layout_tcx_at_span();
1367 let tcx = self.tcx().at(span);
1368
1369 MaybeResult::from(
1370 tcx.fn_abi_of_instance_no_deduced_attrs(
1371 self.typing_env().as_query_input((instance, extra_args)),
1372 )
1373 .map_err(|err| {
1374 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1379 self.handle_fn_abi_err(
1380 *err,
1381 span,
1382 FnAbiRequest::OfInstance { instance, extra_args },
1383 )
1384 }),
1385 )
1386 }
1387
1388 #[inline]
1398 #[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(1398u32),
::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))]
1399 fn fn_abi_of_instance(
1400 &self,
1401 instance: ty::Instance<'tcx>,
1402 extra_args: &'tcx ty::List<Ty<'tcx>>,
1403 ) -> Self::FnAbiOfResult {
1404 let span = self.layout_tcx_at_span();
1406 let tcx = self.tcx().at(span);
1407
1408 MaybeResult::from(
1409 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1410 .map_err(|err| {
1411 let span =
1416 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1417 self.handle_fn_abi_err(
1418 *err,
1419 span,
1420 FnAbiRequest::OfInstance { instance, extra_args },
1421 )
1422 }),
1423 )
1424 }
1425}
1426
1427impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}