1use std::{cmp, fmt};
2
3use rustc_abi as abi;
4use rustc_abi::{
5 AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
6 PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
7 TyAbiInterface, VariantIdx, Variants,
8};
9use rustc_attr_ir::lang_items::LangItem;
10use rustc_errors::{Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, IntoDiagArg, Level};
11use rustc_hir as hir;
12use rustc_hir::def_id::DefId;
13use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
14use rustc_session::config::OptLevel;
15use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Spanned, Symbol, bug, span_bug, sym};
16use rustc_structures::Limit;
17use rustc_target::callconv::FnAbi;
18use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
19use tracing::debug;
20
21use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
22use crate::query::TyCtxtAt;
23use crate::traits::ObligationCause;
24use crate::ty::consts::ConstExt;
25use crate::ty::normalize_erasing_regions::NormalizationError;
26use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
27
28pub trait IntegerExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool)
-> Ty<'tcx>;
fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy)
-> abi::Integer;
fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
-> abi::Integer;
#[doc =
" Finds the appropriate Integer type and signedness for the given"]
#[doc = " discriminant range and `#[repr]` attribute."]
#[doc = ""]
#[doc =
" To represent the way the values were written in the rust source, min and max"]
#[doc =
" are in different types. It\'s thus possible to pass in an unrepresentable range,"]
#[doc = " and the method will panic in those cases."]
#[doc = ""]
#[doc =
" This is the basis for computing the type of the *tag* of an enum (which can be smaller than"]
#[doc =
" the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`])."]
fn discr_range_of_repr<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>,
repr: &ReprOptions, min_negative: i128, max_positive: u128)
-> (abi::Integer, bool);
}
impl IntegerExt for abi::Integer {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
use abi::Integer::{I8, I16, I32, I64, I128};
match (*self, signed) {
(I8, false) => tcx.types.u8,
(I16, false) => tcx.types.u16,
(I32, false) => tcx.types.u32,
(I64, false) => tcx.types.u64,
(I128, false) => tcx.types.u128,
(I8, true) => tcx.types.i8,
(I16, true) => tcx.types.i16,
(I32, true) => tcx.types.i32,
(I64, true) => tcx.types.i64,
(I128, true) => tcx.types.i128,
}
}
fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::IntTy::I8 => I8,
ty::IntTy::I16 => I16,
ty::IntTy::I32 => I32,
ty::IntTy::I64 => I64,
ty::IntTy::I128 => I128,
ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
}
}
fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
-> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::UintTy::U8 => I8,
ty::UintTy::U16 => I16,
ty::UintTy::U32 => I32,
ty::UintTy::U64 => I64,
ty::UintTy::U128 => I128,
ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
}
}
#[doc =
" Finds the appropriate Integer type and signedness for the given"]
#[doc = " discriminant range and `#[repr]` attribute."]
#[doc = ""]
#[doc =
" To represent the way the values were written in the rust source, min and max"]
#[doc =
" are in different types. It\'s thus possible to pass in an unrepresentable range,"]
#[doc = " and the method will panic in those cases."]
#[doc = ""]
#[doc =
" This is the basis for computing the type of the *tag* of an enum (which can be smaller than"]
#[doc =
" the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`])."]
fn discr_range_of_repr<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>,
repr: &ReprOptions, min_negative: i128, max_positive: u128)
-> (abi::Integer, bool) {
if !(min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned()) {
{
::core::panicking::panic_fmt(format_args!("No type can represent the full range of {0}..={1}",
min_negative, max_positive));
}
};
let unsigned_fit =
abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(),
max_positive));
let signed_fit =
cmp::max(abi::Integer::fit_signed(min_negative),
abi::Integer::fit_signed(max_positive.cast_signed()));
if let Some(ity) = repr.int {
let discr = abi::Integer::from_attr(&tcx, ity);
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
::rustc_span::macros::bug_impl(None,
format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
ty), Location::caller())
}
return (discr, ity.is_signed());
}
let at_least =
if repr.c() {
tcx.data_layout().c_enum_min_size
} else { abi::Integer::I8 };
if unsigned_fit <= signed_fit {
(cmp::max(unsigned_fit, at_least), false)
} else { (cmp::max(signed_fit, at_least), true) }
}
}#[extension(pub trait IntegerExt)]
29impl abi::Integer {
30 #[inline]
31 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
32 use abi::Integer::{I8, I16, I32, I64, I128};
33 match (*self, signed) {
34 (I8, false) => tcx.types.u8,
35 (I16, false) => tcx.types.u16,
36 (I32, false) => tcx.types.u32,
37 (I64, false) => tcx.types.u64,
38 (I128, false) => tcx.types.u128,
39 (I8, true) => tcx.types.i8,
40 (I16, true) => tcx.types.i16,
41 (I32, true) => tcx.types.i32,
42 (I64, true) => tcx.types.i64,
43 (I128, true) => tcx.types.i128,
44 }
45 }
46
47 fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
48 use abi::Integer::{I8, I16, I32, I64, I128};
49 match ity {
50 ty::IntTy::I8 => I8,
51 ty::IntTy::I16 => I16,
52 ty::IntTy::I32 => I32,
53 ty::IntTy::I64 => I64,
54 ty::IntTy::I128 => I128,
55 ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
56 }
57 }
58 fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
59 use abi::Integer::{I8, I16, I32, I64, I128};
60 match ity {
61 ty::UintTy::U8 => I8,
62 ty::UintTy::U16 => I16,
63 ty::UintTy::U32 => I32,
64 ty::UintTy::U64 => I64,
65 ty::UintTy::U128 => I128,
66 ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
67 }
68 }
69
70 fn discr_range_of_repr<'tcx>(
80 tcx: TyCtxt<'tcx>,
81 ty: Ty<'tcx>,
82 repr: &ReprOptions,
83 min_negative: i128,
84 max_positive: u128,
85 ) -> (abi::Integer, bool) {
86 assert!(
87 min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned(),
88 "No type can represent the full range of {min_negative}..={max_positive}",
89 );
90
91 let unsigned_fit =
96 abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(), max_positive));
97 let signed_fit = cmp::max(
98 abi::Integer::fit_signed(min_negative),
99 abi::Integer::fit_signed(max_positive.cast_signed()),
100 );
101
102 if let Some(ity) = repr.int {
103 let discr = abi::Integer::from_attr(&tcx, ity);
104 let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
105 if discr < fit {
106 bug!(
107 "Integer::repr_discr: `#[repr]` hint too small for \
108 discriminant range of enum `{}`",
109 ty
110 )
111 }
112 return (discr, ity.is_signed());
113 }
114
115 let at_least = if repr.c() {
116 tcx.data_layout().c_enum_min_size
119 } else {
120 abi::Integer::I8
122 };
123
124 if unsigned_fit <= signed_fit {
127 (cmp::max(unsigned_fit, at_least), false)
128 } else {
129 (cmp::max(signed_fit, at_least), true)
130 }
131 }
132}
133
134pub trait FloatExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
-> Ty<'tcx>;
fn from_float_ty(fty: ty::FloatTy)
-> Self;
}
impl FloatExt for abi::Float {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
use abi::Float::*;
match *self {
F16 => tcx.types.f16,
F16B =>
Ty::new_adt(tcx,
tcx.adt_def(tcx.require_lang_item(LangItem::F16B,
DUMMY_SP)), ty::List::empty()),
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)]
135impl abi::Float {
136 #[inline]
137 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
138 use abi::Float::*;
139 match *self {
140 F16 => tcx.types.f16,
141 F16B => Ty::new_adt(
142 tcx,
143 tcx.adt_def(tcx.require_lang_item(LangItem::F16B, DUMMY_SP)),
144 ty::List::empty(),
145 ),
146 F32 => tcx.types.f32,
147 F64 => tcx.types.f64,
148 F128 => tcx.types.f128,
149 }
150 }
151
152 fn from_float_ty(fty: ty::FloatTy) -> Self {
153 use abi::Float::*;
154 match fty {
155 ty::FloatTy::F16 => F16,
156 ty::FloatTy::F32 => F32,
157 ty::FloatTy::F64 => F64,
158 ty::FloatTy::F128 => F128,
159 }
160 }
161}
162
163pub trait PrimitiveExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
-> Ty<'tcx>;
#[doc = " Return an *integer* type matching this primitive."]
#[doc = " Useful in particular when dealing with enum discriminants."]
fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
-> Ty<'tcx>;
}
impl PrimitiveExt for Primitive {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
Primitive::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(_) =>
::rustc_span::macros::bug_impl(None,
format_args!("floats do not have an int type"),
Location::caller()),
}
}
}#[extension(pub trait PrimitiveExt)]
164impl Primitive {
165 #[inline]
166 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
167 match *self {
168 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
169 Primitive::Float(f) => f.to_ty(tcx),
170 Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
172 }
173 }
174
175 #[inline]
178 fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
179 match *self {
180 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
181 Primitive::Pointer(_) => {
183 let signed = false;
184 tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
185 }
186 Primitive::Float(_) => bug!("floats do not have an int type"),
187 }
188 }
189}
190
191pub const WIDE_PTR_ADDR: usize = 0;
196
197pub const WIDE_PTR_EXTRA: usize = 1;
202
203#[derive(#[automatically_derived]
impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ValidityRequirement { }
#[automatically_derived]
impl ::core::clone::Clone for ValidityRequirement {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for ValidityRequirement { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ValidityRequirement {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ValidityRequirement { }Eq, #[automatically_derived]
impl ::core::hash::Hash for ValidityRequirement {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
ValidityRequirement {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ValidityRequirement::Inhabited => {}
ValidityRequirement::Zero => {}
ValidityRequirement::UninitMitigated0x01Fill => {}
ValidityRequirement::Uninit => {}
}
}
}
};StableHash)]
206pub enum ValidityRequirement {
207 Inhabited,
208 Zero,
209 UninitMitigated0x01Fill,
212 Uninit,
214}
215
216impl ValidityRequirement {
217 pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
218 match intrinsic {
219 sym::assert_inhabited => Some(Self::Inhabited),
220 sym::assert_zero_valid => Some(Self::Zero),
221 sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
222 _ => None,
223 }
224 }
225}
226
227impl fmt::Display for ValidityRequirement {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 Self::Inhabited => f.write_str("is inhabited"),
231 Self::Zero => f.write_str("allows being left zeroed"),
232 Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
233 Self::Uninit => f.write_str("allows being left uninitialized"),
234 }
235 }
236}
237
238#[derive(#[automatically_derived]
impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SimdLayoutError { }
#[automatically_derived]
impl ::core::clone::Clone for SimdLayoutError {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Limit>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SimdLayoutError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::ZeroLength =>
::core::fmt::Formatter::write_str(f, "ZeroLength"),
Self::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)]
239pub enum SimdLayoutError {
240 ZeroLength,
242 TooManyLanes(Limit),
245}
246
247#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutError<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for LayoutError<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutError<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<SimdLayoutError>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<NormalizationError<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LayoutError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Unknown(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Unknown", &__self_0),
Self::SizeOverflow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SizeOverflow", &__self_0),
Self::InvalidSimd { ty: __self_0, kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InvalidSimd", "ty", __self_0, "kind", &__self_1),
Self::TooGeneric(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooGeneric", &__self_0),
Self::NormalizationFailure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NormalizationFailure", __self_0, &__self_1),
Self::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)]
248pub enum LayoutError<'tcx> {
249 Unknown(Ty<'tcx>),
257 SizeOverflow(Ty<'tcx>),
259 InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
261 TooGeneric(Ty<'tcx>),
266 NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
274 ReferencesError(ErrorGuaranteed),
276}
277
278impl<'tcx> fmt::Display for LayoutError<'tcx> {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 match *self {
281 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"),
282 LayoutError::TooGeneric(ty) => {
283 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")
284 }
285 LayoutError::SizeOverflow(ty) => {
286 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")
287 }
288 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
289 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}")
290 }
291 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
292 f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
293 }
294 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!(
295 f,
296 "unable to determine layout for `{}` because `{}` cannot be normalized",
297 t,
298 e.get_type_for_failure()
299 ),
300 LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
301 }
302 }
303}
304
305impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
306 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
307 self.to_string().into_diag_arg(&mut None)
308 }
309}
310
311#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for LayoutCx<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<abi::LayoutCalculator<TyCtxt<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<ty::TypingEnv<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutCx<'tcx> { }Copy)]
312pub struct LayoutCx<'tcx> {
313 pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
314 pub typing_env: ty::TypingEnv<'tcx>,
315}
316
317impl<'tcx> LayoutCx<'tcx> {
318 pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
319 Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
320 }
321}
322
323#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for SizeSkeleton<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for SizeSkeleton<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx> {
#[inline]
fn clone(&self) -> Self {
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 {
Self::Known(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Known",
__self_0, &__self_1),
Self::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)]
328pub enum SizeSkeleton<'tcx> {
329 Known(Size, Option<Align>),
332
333 Pointer {
335 non_zero: bool,
337 tail: Ty<'tcx>,
341 },
342}
343
344impl<'tcx> SizeSkeleton<'tcx> {
345 pub fn compute(
346 ty: Ty<'tcx>,
347 tcx: TyCtxt<'tcx>,
348 typing_env: ty::TypingEnv<'tcx>,
349 span: Span,
350 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
351 Self::compute_inner(ty, tcx, typing_env, span, 0)
352 }
353
354 fn compute_inner(
355 ty: Ty<'tcx>,
356 tcx: TyCtxt<'tcx>,
357 typing_env: ty::TypingEnv<'tcx>,
358 span: Span,
359 depth: usize,
360 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
361 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());
362
363 let recursion_limit = tcx.recursion_limit();
368 if depth >= recursion_limit.0 {
369 let suggested_limit = match recursion_limit {
370 Limit(0) => Limit(2),
371 limit => limit * 2,
372 };
373 let reported =
374 tcx.dcx().emit_err(crate::diagnostics::RecursionLimitReachedSizeSkeleton {
375 span,
376 ty,
377 suggested_limit,
378 });
379 return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
380 }
381
382 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
384 Ok(layout) => {
385 if layout.is_sized() {
386 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
387 } else {
388 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
390 }
391 }
392 Err(err @ LayoutError::TooGeneric(_)) => err,
393 Err(
395 e @ LayoutError::Unknown(_)
396 | e @ LayoutError::SizeOverflow(_)
397 | e @ LayoutError::InvalidSimd { .. }
398 | e @ LayoutError::NormalizationFailure(..)
399 | e @ LayoutError::ReferencesError(_),
400 ) => return Err(e),
401 };
402
403 match *ty.kind() {
404 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
405 let non_zero = !ty.is_raw_ptr();
406
407 tcx.assert_fully_normalized(typing_env, pointee);
408 let tail = tcx.struct_tail_raw(
409 pointee,
410 &ObligationCause::dummy(),
411 |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
412 Ok(ty) => ty,
413 Err(e) => Ty::new_error_with_message(
414 tcx,
415 DUMMY_SP,
416 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
417 "normalization failed for {} but no errors reported",
418 e.get_type_for_failure()
419 ),
420 ),
421 },
422 || {},
423 );
424
425 match tail.kind() {
426 ty::Param(_)
429 | ty::Alias(
430 _,
431 ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
432 ) => {
433 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());
434 Ok(SizeSkeleton::Pointer {
435 non_zero,
436 tail: tcx.erase_and_anonymize_regions(tail),
437 })
438 }
439 ty::Error(guar) => {
440 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
442 }
443 _ => ::rustc_span::macros::bug_impl(None,
format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
ty, err, tail), Location::caller())bug!(
444 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
445 tail `{tail}` is not a type parameter or a projection",
446 ),
447 }
448 }
449 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
450 let len_eval = len.try_to_target_usize(tcx);
451 if len_eval == Some(0) {
452 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
453 }
454
455 match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
456 SizeSkeleton::Known(s, a) => {
459 if let Some(c) = len_eval {
460 let size = s
461 .bytes()
462 .checked_mul(c)
463 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
464 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
466 }
467 Err(err)
468 }
469 SizeSkeleton::Pointer { .. } => Err(err),
470 }
471 }
472
473 ty::Adt(def, args) => {
474 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
476 return Err(err);
477 }
478 {
480 let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
485 def.repr();
486 let mut ignored_flags = ReprFlags::IS_TRANSPARENT
487 | ReprFlags::IS_LINEAR
488 | ReprFlags::RANDOMIZE_LAYOUT;
489 if def.is_struct() {
490 ignored_flags |= ReprFlags::IS_C;
495 }
496 if int.is_some()
497 || align.is_some()
498 || pack.is_some()
499 || flags.difference(ignored_flags) != ReprFlags::default()
500 || scalable.is_some()
501 {
502 return Err(err);
503 }
504 }
505
506 let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
510 let i = VariantIdx::from_usize(i);
511 let fields = def.variant(i).fields.iter().map(|field| {
512 SizeSkeleton::compute_inner(
513 field.ty(tcx, args).skip_norm_wip(),
514 tcx,
515 typing_env,
516 span,
517 depth + 1,
518 )
519 });
520 let mut ptr = None;
521 for field in fields {
522 let field = field?;
523 match field {
524 SizeSkeleton::Known(size, align) => {
525 let is_1zst = size.bytes() == 0
526 && align.is_some_and(|align| align.bytes() == 1);
527 if !is_1zst {
528 return Err(err);
529 }
530 }
531 SizeSkeleton::Pointer { .. } => {
532 if ptr.is_some() {
533 return Err(err);
534 }
535 ptr = Some(field);
536 }
537 }
538 }
539 Ok(ptr)
540 };
541
542 let v0 = zero_or_ptr_variant(0)?;
543 if def.variants().len() == 1 {
546 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
547 return Ok(SizeSkeleton::Pointer { non_zero, tail });
548 } else {
549 return Err(err);
550 }
551 }
552
553 let v1 = zero_or_ptr_variant(1)?;
554 match (v0, v1) {
558 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
559 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
560 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
561 }
562 _ => Err(err),
563 }
564 }
565
566 ty::Alias(..) => {
567 let normalized =
568 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
569 if ty == normalized {
570 Err(err)
571 } else {
572 SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
573 }
574 }
575
576 ty::Pat(base, pat) => {
577 let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
579 match *pat {
580 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
581 ty::PatternKind::NotNull => match base? {
584 SizeSkeleton::Known(..) => base,
585 SizeSkeleton::Pointer { non_zero: _, tail } => {
586 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
587 }
588 },
589 }
590 }
591
592 _ => Err(err),
593 }
594 }
595
596 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
597 match (self, other) {
598 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
599 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
600 a == b
601 }
602 _ => false,
603 }
604 }
605}
606
607pub trait HasTyCtxt<'tcx>: HasDataLayout {
608 fn tcx(&self) -> TyCtxt<'tcx>;
609}
610
611pub trait HasTypingEnv<'tcx> {
612 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
613}
614
615impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
616 #[inline]
617 fn data_layout(&self) -> &TargetDataLayout {
618 &self.data_layout
619 }
620}
621
622impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
623 fn target_spec(&self) -> &Target {
624 &self.sess.target
625 }
626}
627
628impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
629 fn x86_abi_opt(&self) -> X86Abi {
630 X86Abi {
631 regparm: self.sess.opts.unstable_opts.regparm,
632 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
633 }
634 }
635}
636
637impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
638 #[inline]
639 fn tcx(&self) -> TyCtxt<'tcx> {
640 *self
641 }
642}
643
644impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
645 #[inline]
646 fn data_layout(&self) -> &TargetDataLayout {
647 &self.data_layout
648 }
649}
650
651impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
652 fn target_spec(&self) -> &Target {
653 &self.sess.target
654 }
655}
656
657impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
658 #[inline]
659 fn tcx(&self) -> TyCtxt<'tcx> {
660 **self
661 }
662}
663
664impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
665 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
666 self.typing_env
667 }
668}
669
670impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
671 fn data_layout(&self) -> &TargetDataLayout {
672 self.calc.cx.data_layout()
673 }
674}
675
676impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
677 fn target_spec(&self) -> &Target {
678 self.calc.cx.target_spec()
679 }
680}
681
682impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
683 fn x86_abi_opt(&self) -> X86Abi {
684 self.calc.cx.x86_abi_opt()
685 }
686}
687
688impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
689 fn tcx(&self) -> TyCtxt<'tcx> {
690 self.calc.cx
691 }
692}
693
694pub trait MaybeResult<T> {
695 type Error;
696
697 fn from(x: Result<T, Self::Error>) -> Self;
698 fn to_result(self) -> Result<T, Self::Error>;
699}
700
701impl<T> MaybeResult<T> for T {
702 type Error = !;
703
704 fn from(Ok(x): Result<T, Self::Error>) -> Self {
705 x
706 }
707 fn to_result(self) -> Result<T, Self::Error> {
708 Ok(self)
709 }
710}
711
712impl<T, E> MaybeResult<T> for Result<T, E> {
713 type Error = E;
714
715 fn from(x: Result<T, Self::Error>) -> Self {
716 x
717 }
718 fn to_result(self) -> Result<T, Self::Error> {
719 self
720 }
721}
722
723pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
724
725pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
728 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
731
732 #[inline]
735 fn layout_tcx_at_span(&self) -> Span {
736 DUMMY_SP
737 }
738
739 fn handle_layout_err(
747 &self,
748 err: LayoutError<'tcx>,
749 span: Span,
750 ty: Ty<'tcx>,
751 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
752}
753
754pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
756 #[inline]
759 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
760 self.spanned_layout_of(ty, DUMMY_SP)
761 }
762
763 #[inline]
768 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
769 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
770 let tcx = self.tcx().at(span);
771
772 MaybeResult::from(
773 tcx.layout_of(self.typing_env().as_query_input(ty))
774 .map_err(|err| self.handle_layout_err(*err, span, ty)),
775 )
776 }
777}
778
779impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
780
781impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
782 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
783
784 #[inline]
785 fn handle_layout_err(
786 &self,
787 err: LayoutError<'tcx>,
788 _: Span,
789 _: Ty<'tcx>,
790 ) -> &'tcx LayoutError<'tcx> {
791 self.tcx().arena.alloc(err)
792 }
793}
794
795impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
796where
797 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
798{
799 fn ty_and_layout_for_variant(
800 this: TyAndLayout<'tcx>,
801 cx: &C,
802 variant_index: VariantIdx,
803 ) -> TyAndLayout<'tcx> {
804 let layout = match this.variants {
805 Variants::Single { index } if index == variant_index => {
807 return this;
808 }
809
810 Variants::Single { .. } | Variants::Empty => {
811 let tcx = cx.tcx();
816 let typing_env = cx.typing_env();
817
818 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
820 {
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);
821 }
822
823 let fields = match this.ty.kind() {
824 ty::Adt(def, _) if def.variants().is_empty() => {
825 ::rustc_span::macros::bug_impl(None,
format_args!("for_variant called on zero-variant enum {0}", this.ty),
Location::caller())bug!("for_variant called on zero-variant enum {}", this.ty)
826 }
827 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
828 _ => ::rustc_span::macros::bug_impl(None,
format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
this.ty), Location::caller())bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
829 };
830 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
831 }
832
833 Variants::Multiple { .. } => {
834 cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
835 }
836 };
837
838 {
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 });
839
840 TyAndLayout { ty: this.ty, layout }
841 }
842
843 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
844 enum TyMaybeWithLayout<'tcx> {
845 Ty(Ty<'tcx>),
846 TyAndLayout(TyAndLayout<'tcx>),
847 }
848
849 fn field_ty_or_layout<'tcx>(
850 this: TyAndLayout<'tcx>,
851 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
852 i: usize,
853 ) -> TyMaybeWithLayout<'tcx> {
854 let tcx = cx.tcx();
855 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
856 TyAndLayout {
857 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
858 ty: tag.primitive().to_ty(tcx),
859 }
860 };
861
862 match *this.ty.kind() {
863 ty::Bool
864 | ty::Char
865 | ty::Int(_)
866 | ty::Uint(_)
867 | ty::Float(_)
868 | ty::FnPtr(..)
869 | ty::Never
870 | ty::FnDef(..)
871 | ty::CoroutineWitness(..)
872 | ty::Foreign(..)
873 | ty::Dynamic(_, _) => {
874 ::rustc_span::macros::bug_impl(None,
format_args!("TyAndLayout::field({0:?}): not applicable", this),
Location::caller())bug!("TyAndLayout::field({:?}): not applicable", this)
875 }
876
877 ty::Pat(base, _) => {
878 {
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);
879 TyMaybeWithLayout::Ty(base)
880 }
881
882 ty::UnsafeBinder(bound_ty) => {
883 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
884 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
885 }
886
887 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
889 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
890
891 if i == 0 {
896 let nil = tcx.types.unit;
897 let unit_ptr_ty = if this.ty.is_raw_ptr() {
898 Ty::new_mut_ptr(tcx, nil)
899 } else {
900 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
901 };
902
903 let typing_env = ty::TypingEnv::fully_monomorphized();
907 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
908 ty: this.ty,
909 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
910 });
911 }
912
913 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
914 let min_count = ty::vtable_min_entries(
915 tcx,
916 principal.map(|principal| {
917 tcx.instantiate_bound_regions_with_erased(principal)
918 }),
919 );
920 Ty::new_imm_ref(
921 tcx,
922 tcx.lifetimes.re_static,
923 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
925 )
926 };
927
928 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
929 && !pointee.references_error()
932 {
933 let metadata = tcx.normalize_erasing_regions(
934 cx.typing_env(),
935 Unnormalized::new(Ty::new_projection(
936 tcx,
937 ty::IsRigid::No,
938 metadata_def_id,
939 [pointee],
940 )),
941 );
942
943 if let ty::Adt(def, args) = metadata.kind()
948 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
949 && let ty::Dynamic(data, _) = args.type_at(0).kind()
950 {
951 mk_dyn_vtable(data.principal())
952 } else {
953 metadata
954 }
955 } else {
956 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
957 ty::Slice(_) | ty::Str => tcx.types.usize,
958 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
959 _ => ::rustc_span::macros::bug_impl(None,
format_args!("TyAndLayout::field({0:?}): not applicable", this),
Location::caller())bug!("TyAndLayout::field({:?}): not applicable", this),
960 }
961 };
962
963 TyMaybeWithLayout::Ty(metadata)
964 }
965
966 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
968 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
969
970 ty::Closure(_, args) => field_ty_or_layout(
972 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
973 cx,
974 i,
975 ),
976
977 ty::CoroutineClosure(_, args) => field_ty_or_layout(
978 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
979 cx,
980 i,
981 ),
982
983 ty::Coroutine(def_id, args) => match this.variants {
984 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
985 Variants::Single { index } => TyMaybeWithLayout::Ty(
986 args.as_coroutine()
987 .state_tys(def_id, tcx)
988 .nth(index.as_usize())
989 .unwrap()
990 .nth(i)
991 .unwrap(),
992 ),
993 Variants::Multiple { tag, tag_field, .. } => {
994 if FieldIdx::from_usize(i) == tag_field {
995 TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
996 } else {
997 TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
998 }
999 }
1000 },
1001
1002 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
1003
1004 ty::Adt(def, args) => {
1006 match this.variants {
1007 Variants::Single { index } => {
1008 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
1009 TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
1010 }
1011 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"),
1012
1013 Variants::Multiple { tag, .. } => {
1015 {
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);
1016 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1017 }
1018 }
1019 }
1020
1021 ty::Alias(..)
1022 | ty::Bound(..)
1023 | ty::Placeholder(..)
1024 | ty::Param(_)
1025 | ty::Infer(_)
1026 | ty::Error(_) => ::rustc_span::macros::bug_impl(None,
format_args!("TyAndLayout::field: unexpected type `{0}`", this.ty),
Location::caller())bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1027 }
1028 }
1029
1030 match field_ty_or_layout(this, cx, i) {
1031 TyMaybeWithLayout::Ty(field_ty) => {
1032 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1033 ::rustc_span::macros::bug_impl(None,
format_args!("failed to get layout for `{0}`: {1:?},\ndespite it being a field (#{2}) of an existing layout: {3:#?}",
field_ty, e, i, this), Location::caller())bug!(
1034 "failed to get layout for `{field_ty}`: {e:?},\n\
1035 despite it being a field (#{i}) of an existing layout: {this:#?}",
1036 )
1037 })
1038 }
1039 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1040 }
1041 }
1042
1043 fn ty_and_layout_pointee_info_at(
1046 this: TyAndLayout<'tcx>,
1047 cx: &C,
1048 offset: Size,
1049 ) -> Option<PointeeInfo> {
1050 let tcx = cx.tcx();
1051 let typing_env = cx.typing_env();
1052
1053 let optimize = tcx.sess.opts.optimize != OptLevel::No;
1057
1058 let pointee_info = match *this.ty.kind() {
1059 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1060 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1061 }
1062 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1063 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1064 let kind = match mt {
1065 hir::Mutability::Not => {
1066 let frozen = optimize && ty.is_freeze(tcx, typing_env);
1067 PointerKind::SharedRef { frozen }
1068 }
1069 hir::Mutability::Mut => {
1070 let unpin = optimize
1071 && ty.is_unpin(tcx, typing_env)
1072 && ty.is_unsafe_unpin(tcx, typing_env);
1073 PointerKind::MutableRef { unpin }
1074 }
1075 };
1076 PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1077 })
1078 }
1079
1080 ty::Adt(..)
1081 if offset.bytes() == 0
1082 && let Some(pointee) = this.ty.boxed_ty() =>
1083 {
1084 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1085 safe: Some(PointerKind::Box {
1086 unpin: optimize
1088 && pointee.is_unpin(tcx, typing_env)
1089 && pointee.is_unsafe_unpin(tcx, typing_env),
1090 global: this.ty.is_box_global(tcx),
1091 }),
1092 size: layout.size,
1093 align: layout.align.abi,
1094 })
1095 }
1096
1097 _ => {
1098 let mut data_variant = match &this.variants {
1099 Variants::Multiple {
1109 tag_encoding:
1110 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1111 tag_field,
1112 variants,
1113 ..
1114 } if variants.len() == 2
1115 && this.fields.offset(tag_field.as_usize()) == offset =>
1116 {
1117 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1118 VariantIdx::from_u32(1)
1119 } else {
1120 VariantIdx::from_u32(0)
1121 };
1122 {
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);
1123 if *niche_start == 0 {
1124 Some(this.for_variant(cx, *untagged_variant))
1130 } else {
1131 None
1132 }
1133 }
1134 Variants::Multiple { .. } => None,
1135 Variants::Empty | Variants::Single { .. } => Some(this),
1136 };
1137
1138 if let Some(variant) = data_variant
1139 && let FieldsShape::Union(_) = variant.fields
1141 {
1142 data_variant = None;
1143 }
1144
1145 let mut result = None;
1146
1147 if let Some(variant) = data_variant {
1148 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1151 for i in 0..variant.fields.count() {
1152 let field_start = variant.fields.offset(i);
1153 if field_start <= offset {
1154 let field = variant.field(cx, i);
1155 result = field.to_result().ok().and_then(|field| {
1156 if ptr_end <= field_start + field.size {
1157 let field_info =
1159 field.pointee_info_at(cx, offset - field_start);
1160 field_info
1161 } else {
1162 None
1163 }
1164 });
1165 if result.is_some() {
1166 break;
1167 }
1168 }
1169 }
1170 }
1171
1172 if this.ty.is_like_maybe_dangling()
1174 && let Some(info) = result
1175 {
1176 result = Some(PointeeInfo {
1177 safe: None,
1180 size: Size::ZERO,
1182 align: info.align,
1184 });
1185 }
1186
1187 result
1188 }
1189 };
1190
1191 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_middle/src/ty/layout.rs:1191",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1191u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
offset, this.ty.kind(), pointee_info) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1192 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1193 offset,
1194 this.ty.kind(),
1195 pointee_info
1196 );
1197
1198 pointee_info
1199 }
1200
1201 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1202 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1203 }
1204
1205 fn is_enum(this: TyAndLayout<'tcx>) -> bool {
1206 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(def, _) if def.is_enum() => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.is_enum())
1207 }
1208
1209 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1210 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1211 }
1212
1213 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1214 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1215 }
1216
1217 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1218 #[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)
1219 }
1220
1221 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1222 #[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())
1223 }
1224
1225 fn is_complex_number_lang_item(this: TyAndLayout<'tcx>, cx: &C) -> bool {
1227 let Some(def) = this.ty.ty_adt_def() else { return false };
1228 cx.tcx().is_lang_item(def.did(), LangItem::Complex)
1229 }
1230
1231 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1232 this.ty.is_scalable_vector()
1233 }
1234
1235 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1237 #[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))
1238 }
1239}
1240
1241#[inline]
1282{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_can_unwind",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1282u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_def_id")
}> =
::tracing::__macro_support::FieldName::new("fn_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("abi")
}> =
::tracing::__macro_support::FieldName::new("abi");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(did) = fn_def_id {
if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
{
return false;
}
if !tcx.sess.panic_strategy().unwinds() &&
!tcx.is_foreign_item(did) {
return false;
}
if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
tcx.is_lang_item(did, LangItem::DropGlue) {
return false;
}
}
use ExternAbi::*;
match abi {
C { unwind } | System { unwind } | Cdecl { unwind } |
Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
unwind } | SysV64 { unwind } => unwind,
PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
CmseNonSecureCall | CmseNonSecureEntry | Custom |
RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
LlvmIntrinsic => false,
Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
tcx.sess.panic_strategy().unwinds()
}
}
}
}
}#[tracing::instrument(level = "debug", skip(tcx))]
1283pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1284 if let Some(did) = fn_def_id {
1285 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1287 return false;
1288 }
1289
1290 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1295 return false;
1296 }
1297
1298 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1303 && tcx.is_lang_item(did, LangItem::DropGlue)
1304 {
1305 return false;
1306 }
1307 }
1308
1309 use ExternAbi::*;
1316 match abi {
1317 C { unwind }
1318 | System { unwind }
1319 | Cdecl { unwind }
1320 | Stdcall { unwind }
1321 | Fastcall { unwind }
1322 | Vectorcall { unwind }
1323 | Thiscall { unwind }
1324 | Aapcs { unwind }
1325 | Win64 { unwind }
1326 | SysV64 { unwind } => unwind,
1327 PtxKernel
1328 | Msp430Interrupt
1329 | X86Interrupt
1330 | GpuKernel
1331 | EfiApi
1332 | AvrInterrupt
1333 | AvrNonBlockingInterrupt
1334 | CmseNonSecureCall
1335 | CmseNonSecureEntry
1336 | Custom
1337 | RiscvInterruptM
1338 | RiscvInterruptS
1339 | RustInvalid
1340 | Swift
1341 | LlvmIntrinsic => false,
1342 Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1343 tcx.sess.panic_strategy().unwinds()
1344 }
1345 }
1346}
1347
1348#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for FnAbiError<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
#[inline]
fn clone(&self) -> Self {
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 {
Self::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)]
1350pub enum FnAbiError<'tcx> {
1351 Layout(LayoutError<'tcx>),
1353}
1354
1355impl<'a, 'b> Diagnostic<'a> for FnAbiError<'b> {
1356 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1357 match self {
1358 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1359 }
1360 }
1361}
1362
1363#[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 {
Self::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OfFnPtr", "sig", __self_0, "extra_args", &__self_1),
Self::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)]
1366pub enum FnAbiRequest<'tcx> {
1367 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1368 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1369}
1370
1371pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1374 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1377
1378 fn handle_fn_abi_err(
1388 &self,
1389 err: FnAbiError<'tcx>,
1390 span: Span,
1391 fn_abi_request: FnAbiRequest<'tcx>,
1392 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1393}
1394
1395pub fn codegen_handle_fn_abi_err<'tcx>(
1397 tcx: TyCtxt<'tcx>,
1398 err: FnAbiError<'tcx>,
1399 span: Span,
1400 fn_abi_request: FnAbiRequest<'tcx>,
1401) -> ErrorGuaranteed {
1402 match err {
1403 FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::InvalidSimd { .. }) => {
1404 tcx.dcx().emit_err(Spanned { span, node: err })
1405 }
1406 _ => match fn_abi_request {
1407 FnAbiRequest::OfFnPtr { sig, extra_args } => {
1408 ::rustc_span::macros::bug_impl(Some(span),
format_args!("`fn_abi_of_fn_ptr({0}, {1:?})` failed: {2:?}", sig,
extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1409 }
1410 FnAbiRequest::OfInstance { instance, extra_args } => {
1411 ::rustc_span::macros::bug_impl(Some(span),
format_args!("`fn_abi_of_instance({0}, {1:?})` failed: {2:?}", instance,
extra_args, err), Location::caller());span_bug!(span, "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",);
1412 }
1413 },
1414 }
1415}
1416
1417pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1419 #[inline]
1424 fn fn_abi_of_fn_ptr(
1425 &self,
1426 sig: ty::PolyFnSig<'tcx>,
1427 extra_args: &'tcx ty::List<Ty<'tcx>>,
1428 ) -> Self::FnAbiOfResult {
1429 let span = self.layout_tcx_at_span();
1431 let tcx = self.tcx().at(span);
1432
1433 MaybeResult::from(
1434 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1435 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1436 ),
1437 )
1438 }
1439
1440 #[inline]
1452 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_abi_of_instance_no_deduced_attrs",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1452u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("instance")
}> =
::tracing::__macro_support::FieldName::new("instance");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("extra_args")
}> =
::tracing::__macro_support::FieldName::new("extra_args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
return __tracing_attr_fake_return;
}
{
let span = self.layout_tcx_at_span();
let tcx = self.tcx().at(span);
MaybeResult::from(tcx.fn_abi_of_instance_no_deduced_attrs(self.typing_env().as_query_input((instance,
extra_args))).map_err(|err|
{
let span =
if !span.is_dummy() {
span
} else { tcx.def_span(instance.def_id()) };
self.handle_fn_abi_err(*err, span,
FnAbiRequest::OfInstance { instance, extra_args })
}))
}
}
}#[tracing::instrument(level = "debug", skip(self))]
1453 fn fn_abi_of_instance_no_deduced_attrs(
1454 &self,
1455 instance: ty::Instance<'tcx>,
1456 extra_args: &'tcx ty::List<Ty<'tcx>>,
1457 ) -> Self::FnAbiOfResult {
1458 let span = self.layout_tcx_at_span();
1460 let tcx = self.tcx().at(span);
1461
1462 MaybeResult::from(
1463 tcx.fn_abi_of_instance_no_deduced_attrs(
1464 self.typing_env().as_query_input((instance, extra_args)),
1465 )
1466 .map_err(|err| {
1467 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1472 self.handle_fn_abi_err(
1473 *err,
1474 span,
1475 FnAbiRequest::OfInstance { instance, extra_args },
1476 )
1477 }),
1478 )
1479 }
1480
1481 #[inline]
1491 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_abi_of_instance",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1491u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("instance")
}> =
::tracing::__macro_support::FieldName::new("instance");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("extra_args")
}> =
::tracing::__macro_support::FieldName::new("extra_args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Self::FnAbiOfResult = loop {};
return __tracing_attr_fake_return;
}
{
let span = self.layout_tcx_at_span();
let tcx = self.tcx().at(span);
MaybeResult::from(tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance,
extra_args))).map_err(|err|
{
let span =
if !span.is_dummy() {
span
} else { tcx.def_span(instance.def_id()) };
self.handle_fn_abi_err(*err, span,
FnAbiRequest::OfInstance { instance, extra_args })
}))
}
}
}#[tracing::instrument(level = "debug", skip(self))]
1492 fn fn_abi_of_instance(
1493 &self,
1494 instance: ty::Instance<'tcx>,
1495 extra_args: &'tcx ty::List<Ty<'tcx>>,
1496 ) -> Self::FnAbiOfResult {
1497 let span = self.layout_tcx_at_span();
1499 let tcx = self.tcx().at(span);
1500
1501 MaybeResult::from(
1502 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1503 .map_err(|err| {
1504 let span =
1509 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1510 self.handle_fn_abi_err(
1511 *err,
1512 span,
1513 FnAbiRequest::OfInstance { instance, extra_args },
1514 )
1515 }),
1516 )
1517 }
1518}
1519
1520impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}