1use std::fmt::{self, Write};
2use std::num::NonZero;
3use std::ops::Deref;
4use std::range::{RangeFrom, RangeInclusive, RangeToInclusive};
5use std::{cmp, iter};
6
7use rustc_hashes::Hash64;
8use rustc_index::Idx;
9use rustc_index::bit_set::BitMatrix;
10use tracing::{debug, trace};
11
12use crate::{
13 AbiAlign, Align, BackendLaneCount, BackendRepr, FieldsShape, HasDataLayout, IndexSlice,
14 IndexVec, Integer, LayoutData, Niche, NumScalableVectors, Primitive, ReprOptions, Scalar, Size,
15 StructKind, TagEncoding, TargetDataLayout, VariantLayout, Variants, WrappingRange,
16};
17
18mod coroutine;
19mod simple;
20
21#[cfg(feature = "nightly")]
22mod ty;
23
24#[cfg(feature = "nightly")]
25pub use ty::{Layout, TyAbiInterface, TyAndLayout};
26
27impl ::std::fmt::Debug for FieldIdx {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
28 #[stable_hash]
50 #[encodable]
51 #[orderable]
52 #[gate_rustc_only]
53 pub struct FieldIdx {}
54}
55
56impl FieldIdx {
57 pub const ONE: FieldIdx = FieldIdx::from_u32(1);
61}
62
63impl ::std::fmt::Debug for VariantIdx {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
64 #[stable_hash]
75 #[encodable]
76 #[orderable]
77 #[gate_rustc_only]
78 pub struct VariantIdx {
79 const FIRST_VARIANT = 0;
81 }
82}
83
84fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
90where
91 FieldIdx: Idx,
92 VariantIdx: Idx,
93 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
94{
95 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
96 let is_1zst = fields.iter().all(|f| f.is_1zst());
99 uninhabited && is_1zst
100}
101
102enum NicheBias {
104 Start,
105 End,
106}
107
108#[derive(#[automatically_derived]
impl<F: ::core::marker::Copy> ::core::marker::Copy for
LayoutCalculatorError<F> {
}Copy, #[automatically_derived]
impl<F: ::core::clone::Clone> ::core::clone::Clone for
LayoutCalculatorError<F> {
#[inline]
fn clone(&self) -> LayoutCalculatorError<F> {
match self {
LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
LayoutCalculatorError::UnexpectedUnsized(::core::clone::Clone::clone(__self_0)),
LayoutCalculatorError::SizeOverflow =>
LayoutCalculatorError::SizeOverflow,
LayoutCalculatorError::EmptyUnion =>
LayoutCalculatorError::EmptyUnion,
LayoutCalculatorError::ReprConflict =>
LayoutCalculatorError::ReprConflict,
LayoutCalculatorError::ZeroLengthSimdType =>
LayoutCalculatorError::ZeroLengthSimdType,
LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
=>
LayoutCalculatorError::OversizedSimdType {
max_lanes: ::core::clone::Clone::clone(__self_0),
},
LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
LayoutCalculatorError::NonPrimitiveSimdType(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl<F: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculatorError<F> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UnexpectedUnsized", &__self_0),
LayoutCalculatorError::SizeOverflow =>
::core::fmt::Formatter::write_str(f, "SizeOverflow"),
LayoutCalculatorError::EmptyUnion =>
::core::fmt::Formatter::write_str(f, "EmptyUnion"),
LayoutCalculatorError::ReprConflict =>
::core::fmt::Formatter::write_str(f, "ReprConflict"),
LayoutCalculatorError::ZeroLengthSimdType =>
::core::fmt::Formatter::write_str(f, "ZeroLengthSimdType"),
LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
=>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OversizedSimdType", "max_lanes", &__self_0),
LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonPrimitiveSimdType", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
LayoutCalculatorError<F> {
#[inline]
fn eq(&self, other: &LayoutCalculatorError<F>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(LayoutCalculatorError::UnexpectedUnsized(__self_0),
LayoutCalculatorError::UnexpectedUnsized(__arg1_0)) =>
__self_0 == __arg1_0,
(LayoutCalculatorError::OversizedSimdType {
max_lanes: __self_0 },
LayoutCalculatorError::OversizedSimdType {
max_lanes: __arg1_0 }) => __self_0 == __arg1_0,
(LayoutCalculatorError::NonPrimitiveSimdType(__self_0),
LayoutCalculatorError::NonPrimitiveSimdType(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<F: ::core::cmp::Eq> ::core::cmp::Eq for LayoutCalculatorError<F> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<F>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
109pub enum LayoutCalculatorError<F> {
110 UnexpectedUnsized(F),
117
118 SizeOverflow,
120
121 EmptyUnion,
123
124 ReprConflict,
126
127 ZeroLengthSimdType,
129
130 OversizedSimdType { max_lanes: usize },
132
133 NonPrimitiveSimdType(F),
135}
136
137impl<F> LayoutCalculatorError<F> {
138 pub fn without_payload(&self) -> LayoutCalculatorError<()> {
139 use LayoutCalculatorError::*;
140 match *self {
141 UnexpectedUnsized(_) => UnexpectedUnsized(()),
142 SizeOverflow => SizeOverflow,
143 EmptyUnion => EmptyUnion,
144 ReprConflict => ReprConflict,
145 ZeroLengthSimdType => ZeroLengthSimdType,
146 OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
147 NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
148 }
149 }
150
151 pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 use LayoutCalculatorError::*;
156 f.write_str(match self {
157 UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
158 SizeOverflow => "size overflow",
159 EmptyUnion => "type is a union with no fields",
160 ReprConflict => "type has an invalid repr",
161 ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
162 "invalid simd type definition"
163 }
164 })
165 }
166}
167
168type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
169 Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
170
171#[derive(#[automatically_derived]
impl<Cx: ::core::clone::Clone> ::core::clone::Clone for LayoutCalculator<Cx> {
#[inline]
fn clone(&self) -> LayoutCalculator<Cx> {
LayoutCalculator { cx: ::core::clone::Clone::clone(&self.cx) }
}
}Clone, #[automatically_derived]
impl<Cx: ::core::marker::Copy> ::core::marker::Copy for LayoutCalculator<Cx> {
}Copy, #[automatically_derived]
impl<Cx: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculator<Cx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"LayoutCalculator", "cx", &&self.cx)
}
}Debug)]
172pub struct LayoutCalculator<Cx> {
173 pub cx: Cx,
174}
175
176impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
177 pub fn new(cx: Cx) -> Self {
178 Self { cx }
179 }
180
181 pub fn array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
182 &self,
183 element: &LayoutData<FieldIdx, VariantIdx>,
184 count_if_sized: Option<u64>, ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
186 let count = count_if_sized.unwrap_or(0);
187 let size =
188 element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
189
190 Ok(LayoutData {
191 variants: Variants::Single { index: VariantIdx::new(0) },
192 fields: FieldsShape::Array { stride: element.size, count },
193 backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
194 largest_niche: element.largest_niche.filter(|_| count != 0),
195 uninhabited: element.uninhabited && count != 0,
196 align: element.align,
197 size,
198 max_repr_align: None,
199 unadjusted_abi_align: element.align.abi,
200 randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
201 })
202 }
203
204 pub fn scalable_vector_type<FieldIdx, VariantIdx, F>(
205 &self,
206 element: F,
207 count: u64,
208 number_of_vectors: NumScalableVectors,
209 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
210 where
211 FieldIdx: Idx,
212 VariantIdx: Idx,
213 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
214 {
215 vector_type_layout(
216 SimdVectorKind::Scalable(number_of_vectors),
217 self.cx.data_layout(),
218 element,
219 count,
220 )
221 }
222
223 pub fn simd_type<FieldIdx, VariantIdx, F>(
224 &self,
225 element: F,
226 count: u64,
227 repr_packed: bool,
228 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
229 where
230 FieldIdx: Idx,
231 VariantIdx: Idx,
232 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
233 {
234 let kind = if repr_packed { SimdVectorKind::PackedFixed } else { SimdVectorKind::Fixed };
235 vector_type_layout(kind, self.cx.data_layout(), element, count)
236 }
237
238 pub fn coroutine<
243 'a,
244 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
245 VariantIdx: Idx,
246 FieldIdx: Idx,
247 LocalIdx: Idx,
248 >(
249 &self,
250 local_layouts: &IndexSlice<LocalIdx, F>,
251 prefix_layouts: IndexVec<FieldIdx, F>,
252 variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
253 storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
254 tag_to_layout: impl Fn(Scalar) -> F,
255 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
256 coroutine::layout(
257 self,
258 local_layouts,
259 prefix_layouts,
260 variant_fields,
261 storage_conflicts,
262 tag_to_layout,
263 )
264 }
265
266 pub fn univariant<
267 'a,
268 FieldIdx: Idx,
269 VariantIdx: Idx,
270 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
271 >(
272 &self,
273 fields: &IndexSlice<FieldIdx, F>,
274 repr: &ReprOptions,
275 kind: StructKind,
276 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
277 let dl = self.cx.data_layout();
278 let layout = self.univariant_biased(fields, repr, kind, NicheBias::Start);
279 if let Ok(layout) = &layout {
285 if !#[allow(non_exhaustive_omitted_patterns)] match kind {
StructKind::MaybeUnsized => true,
_ => false,
}matches!(kind, StructKind::MaybeUnsized) {
289 if let Some(niche) = layout.largest_niche {
290 let head_space = niche.offset.bytes();
291 let niche_len = niche.value.size(dl).bytes();
292 let tail_space = layout.size.bytes() - head_space - niche_len;
293
294 if fields.len() > 1 && head_space != 0 && tail_space > 0 {
298 let alt_layout = self
299 .univariant_biased(fields, repr, kind, NicheBias::End)
300 .expect("alt layout should always work");
301 let alt_niche = alt_layout
302 .largest_niche
303 .expect("alt layout should have a niche like the regular one");
304 let alt_head_space = alt_niche.offset.bytes();
305 let alt_niche_len = alt_niche.value.size(dl).bytes();
306 let alt_tail_space =
307 alt_layout.size.bytes() - alt_head_space - alt_niche_len;
308
309 if true {
{
match (&layout.size.bytes(), &alt_layout.size.bytes()) {
(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);
}
}
}
};
};debug_assert_eq!(layout.size.bytes(), alt_layout.size.bytes());
310
311 let prefer_alt_layout =
312 alt_head_space > head_space && alt_head_space > tail_space;
313
314 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:314",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(314u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::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!("sz: {0}, default_niche_at: {1}+{2}, default_tail_space: {3}, alt_niche_at/head_space: {4}+{5}, alt_tail: {6}, num_fields: {7}, better: {8}\nlayout: {9}\nalt_layout: {10}\n",
layout.size.bytes(), head_space, niche_len, tail_space,
alt_head_space, alt_niche_len, alt_tail_space,
layout.fields.count(), prefer_alt_layout,
self.format_field_niches(layout, fields),
self.format_field_niches(&alt_layout, fields)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
315 "sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
316 layout: {}\n\
317 alt_layout: {}\n",
318 layout.size.bytes(),
319 head_space,
320 niche_len,
321 tail_space,
322 alt_head_space,
323 alt_niche_len,
324 alt_tail_space,
325 layout.fields.count(),
326 prefer_alt_layout,
327 self.format_field_niches(layout, fields),
328 self.format_field_niches(&alt_layout, fields),
329 );
330
331 if prefer_alt_layout {
332 return Ok(alt_layout);
333 }
334 }
335 }
336 }
337 }
338 layout
339 }
340
341 pub fn layout_of_struct_or_enum<
342 'a,
343 FieldIdx: Idx,
344 VariantIdx: Idx,
345 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
346 >(
347 &self,
348 repr: &ReprOptions,
349 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
350 is_enum: bool,
351 is_special_no_niche: bool,
352 discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
353 discriminants: impl Iterator<Item = (VariantIdx, u128)>,
354 always_sized: bool,
355 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
356 let (present_first, present_second) = {
357 let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
358 if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
359 });
360 (present_variants.next(), present_variants.next())
361 };
362 let present_first = match present_first {
363 Some(present_first) => present_first,
364 None if is_enum => {
366 return Ok(LayoutData::never_type(&self.cx));
367 }
368 None => VariantIdx::new(0),
371 };
372
373 if !is_enum ||
375 (present_second.is_none() && !repr.inhibit_enum_layout_opt())
377 {
378 self.layout_of_struct(
379 repr,
380 variants,
381 is_enum,
382 is_special_no_niche,
383 always_sized,
384 present_first,
385 )
386 } else {
387 if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
391 self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
392 }
393 }
394
395 pub fn layout_of_union<
396 'a,
397 FieldIdx: Idx,
398 VariantIdx: Idx,
399 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
400 >(
401 &self,
402 repr: &ReprOptions,
403 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
404 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
405 let dl = self.cx.data_layout();
406 let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
407 let mut max_repr_align = repr.align;
408
409 struct AbiMismatch;
412 let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
413 Err(AbiMismatch)
415 } else {
416 Ok(None)
417 };
418
419 let mut size = Size::ZERO;
420 let only_variant_idx = VariantIdx::new(0);
421 let only_variant = &variants[only_variant_idx];
422 for field in only_variant {
423 if field.is_unsized() {
424 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
425 }
426
427 align = align.max(field.align.abi);
428 max_repr_align = max_repr_align.max(field.max_repr_align);
429 size = cmp::max(size, field.size);
430
431 if field.is_zst() {
432 continue;
434 }
435
436 if let Ok(common) = common_non_zst_repr_and_align {
437 let field_abi = field.backend_repr.to_union();
439
440 if let Some((common_abi, common_align)) = common {
441 if common_abi != field_abi {
442 common_non_zst_repr_and_align = Err(AbiMismatch);
444 } else {
445 if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
448 {
match (&common_align, &field.align.abi) {
(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::Some(format_args!("non-Aggregate field with matching ABI but differing alignment")));
}
}
}
};assert_eq!(
449 common_align, field.align.abi,
450 "non-Aggregate field with matching ABI but differing alignment"
451 );
452 }
453 }
454 } else {
455 common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
457 }
458 }
459 }
460
461 if let Some(pack) = repr.pack {
462 align = align.min(pack);
463 }
464 let unadjusted_abi_align = align;
467 if let Some(repr_align) = repr.align {
468 align = align.max(repr_align);
469 }
470 let align = align;
472
473 let backend_repr = match common_non_zst_repr_and_align {
476 Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
477 Ok(Some((repr, _))) => match repr {
478 BackendRepr::Scalar(_) | BackendRepr::ScalarPair { .. }
480 if repr.scalar_platform_align(dl).unwrap() != align =>
481 {
482 BackendRepr::Memory { sized: true }
483 }
484 BackendRepr::SimdVector { element, count: _ }
486 if element.default_align(dl).abi > align =>
487 {
488 BackendRepr::Memory { sized: true }
489 }
490 BackendRepr::Scalar(..)
492 | BackendRepr::ScalarPair { .. }
493 | BackendRepr::SimdVector { .. }
494 | BackendRepr::SimdScalableVector { .. }
495 | BackendRepr::Memory { .. } => repr,
496 },
497 };
498
499 let Some(union_field_count) = NonZero::new(only_variant.len()) else {
500 return Err(LayoutCalculatorError::EmptyUnion);
501 };
502
503 let combined_seed = only_variant
504 .iter()
505 .map(|v| v.randomization_seed)
506 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
507
508 Ok(LayoutData {
509 variants: Variants::Single { index: only_variant_idx },
510 fields: FieldsShape::Union(union_field_count),
511 backend_repr,
512 largest_niche: None,
513 uninhabited: false,
514 align: AbiAlign::new(align),
515 size: size.align_to(align),
516 max_repr_align,
517 unadjusted_abi_align,
518 randomization_seed: combined_seed,
519 })
520 }
521
522 fn layout_of_struct<
524 'a,
525 FieldIdx: Idx,
526 VariantIdx: Idx,
527 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
528 >(
529 &self,
530 repr: &ReprOptions,
531 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
532 is_enum: bool,
533 is_special_no_niche: bool,
534 always_sized: bool,
535 present_first: VariantIdx,
536 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
537 let dl = self.cx.data_layout();
541 let v = present_first;
542 let kind = if is_enum || variants[v].is_empty() || always_sized {
543 StructKind::AlwaysSized
544 } else {
545 StructKind::MaybeUnsized
546 };
547
548 let mut st = self.univariant(&variants[v], repr, kind)?;
549 st.variants = Variants::Single { index: v };
550
551 if is_special_no_niche {
552 let hide_niches = |scalar: &mut _| match scalar {
553 Scalar::Initialized { value, valid_range } => {
554 *valid_range = WrappingRange::full(value.size(dl))
555 }
556 Scalar::Union { .. } => {}
558 };
559 match &mut st.backend_repr {
560 BackendRepr::Scalar(scalar) => hide_niches(scalar),
561 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
562 hide_niches(a);
563 hide_niches(b);
564 }
565 BackendRepr::SimdVector { element, .. }
566 | BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
567 BackendRepr::Memory { sized: _ } => {}
568 }
569 st.largest_niche = None;
570 return Ok(st);
571 }
572
573 Ok(st)
574 }
575
576 fn layout_of_enum<
577 'a,
578 FieldIdx: Idx,
579 VariantIdx: Idx,
580 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
581 >(
582 &self,
583 repr: &ReprOptions,
584 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
585 discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
586 discriminants: impl Iterator<Item = (VariantIdx, u128)>,
587 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
588 let dl = self.cx.data_layout();
589 if repr.packed() {
591 return Err(LayoutCalculatorError::ReprConflict);
592 }
593
594 let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
595 struct VariantLayoutInfo {
596 align_abi: Align,
597 }
598
599 if repr.inhibit_enum_layout_opt() {
600 return None;
601 }
602
603 if variants.len() < 2 {
604 return None;
605 }
606
607 let mut align = dl.aggregate_align;
608 let mut max_repr_align = repr.align;
609 let mut unadjusted_abi_align = align;
610 let mut combined_seed = repr.field_shuffle_seed;
611
612 let mut variants_info = IndexVec::<VariantIdx, _>::with_capacity(variants.len());
613 let mut variant_layouts = variants
614 .iter()
615 .map(|v| {
616 let st = self.univariant(v, repr, StructKind::AlwaysSized).ok()?;
617
618 variants_info.push(VariantLayoutInfo { align_abi: st.align.abi });
619
620 align = align.max(st.align.abi);
621 max_repr_align = max_repr_align.max(st.max_repr_align);
622 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
623 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
624
625 Some(VariantLayout::from_layout(st))
626 })
627 .collect::<Option<IndexVec<VariantIdx, _>>>()?;
628
629 let largest_variant_index = variant_layouts
630 .iter_enumerated()
631 .max_by_key(|(_i, layout)| layout.size.bytes())
632 .map(|(i, _layout)| i)?;
633
634 let all_indices = variants.indices();
635 let needs_disc =
636 |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
637 let niche_variants = RangeInclusive {
638 start: all_indices.clone().find(|v| needs_disc(*v)).unwrap(),
639 last: all_indices.rev().find(|v| needs_disc(*v)).unwrap(),
640 };
641
642 let count =
643 (niche_variants.last.index() as u128 - niche_variants.start.index() as u128) + 1;
644
645 let niche = variant_layouts[largest_variant_index].largest_niche?;
647 let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
648 let niche_offset = niche.offset;
649 let niche_size = niche.value.size(dl);
650 let size = variant_layouts[largest_variant_index].size.align_to(align);
651
652 let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
653 if i == largest_variant_index {
654 return true;
655 }
656
657 layout.largest_niche = None;
658
659 if layout.size <= niche_offset {
660 return true;
662 }
663
664 let this_align = variants_info[i].align_abi;
666 let this_offset = (niche_offset + niche_size).align_to(this_align);
667
668 if this_offset + layout.size > size {
669 return false;
670 }
671
672 for offset in layout.field_offsets.iter_mut() {
674 *offset += this_offset;
675 }
676
677 if !layout.is_uninhabited() {
679 layout.backend_repr = BackendRepr::Memory { sized: true };
680 }
681 layout.size += this_offset;
682
683 true
684 });
685
686 if !all_variants_fit {
687 return None;
688 }
689
690 let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
691
692 let others_zst = variant_layouts
693 .iter_enumerated()
694 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
695 let same_size = size == variant_layouts[largest_variant_index].size;
696 let same_align = align == variants_info[largest_variant_index].align_abi;
697
698 let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
699 let abi = if same_size && same_align && others_zst {
700 match variant_layouts[largest_variant_index].backend_repr {
701 BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
704 BackendRepr::ScalarPair { a: first, b: second, b_offset } => {
705 if niche_offset == Size::ZERO {
708 BackendRepr::ScalarPair {
709 a: niche_scalar,
710 b: second.to_union(),
711 b_offset,
712 }
713 } else {
714 BackendRepr::ScalarPair {
715 a: first.to_union(),
716 b: niche_scalar,
717 b_offset,
718 }
719 }
720 }
721 _ => BackendRepr::Memory { sized: true },
722 }
723 } else {
724 BackendRepr::Memory { sized: true }
725 };
726
727 let layout = LayoutData {
728 variants: Variants::Multiple {
729 tag: niche_scalar,
730 tag_encoding: TagEncoding::Niche {
731 untagged_variant: largest_variant_index,
732 niche_variants,
733 niche_start,
734 },
735 tag_field: FieldIdx::new(0),
736 variants: variant_layouts,
737 },
738 fields: FieldsShape::Arbitrary {
739 offsets: [niche_offset].into(),
740 in_memory_order: [FieldIdx::new(0)].into(),
741 },
742 backend_repr: abi,
743 largest_niche,
744 uninhabited,
745 size,
746 align: AbiAlign::new(align),
747 max_repr_align,
748 unadjusted_abi_align,
749 randomization_seed: combined_seed,
750 };
751
752 Some(layout)
753 };
754
755 let niche_filling_layout = calculate_niche_filling_layout();
756
757 let discr_type = repr.discr_type();
758 let discr_size = Integer::from_attr(dl, discr_type).size();
759
760 let necessary_discriminants: Vec<u128> = discriminants
761 .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
762 .map(|(_, val)| val)
763 .collect();
764
765 let (min_negative, max_positive): (i128, u128) = if discr_type.is_signed() {
768 necessary_discriminants.iter().copied().map(|val| discr_size.sign_extend(val)).fold(
769 (0_i128, 0_u128),
770 |(min, max), val| {
771 if let Ok(val) = u128::try_from(val) {
772 (min, max.max(val))
773 } else {
774 (min.min(val), max)
775 }
776 },
777 )
778 } else {
779 (0, necessary_discriminants.iter().copied().max().unwrap_or(0))
781 };
782 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:782",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(782u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("min_negative")
}> =
::tracing::__macro_support::FieldName::new("min_negative");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("max_positive")
}> =
::tracing::__macro_support::FieldName::new("max_positive");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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(&::tracing::field::debug(&min_negative)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&max_positive)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!(?min_negative, ?max_positive);
783
784 let (min_ity, signed) = discr_range_of_repr(
785 RangeFrom { start: min_negative },
786 RangeToInclusive { last: max_positive },
787 ); let mut align = dl.aggregate_align;
790 let mut max_repr_align = repr.align;
791 let mut unadjusted_abi_align = align;
792 let mut combined_seed = repr.field_shuffle_seed;
793
794 let mut size = Size::ZERO;
795
796 let mut start_align = Align::from_bytes(256).unwrap();
798 {
match (&Integer::for_align(dl, start_align), &None) {
(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!(Integer::for_align(dl, start_align), None);
799
800 let mut prefix_align = min_ity.align(dl).abi;
806 if repr.c() {
807 for fields in variants {
808 for field in fields {
809 prefix_align = prefix_align.max(field.align.abi);
810 }
811 }
812 }
813
814 let mut layout_variants = variants
816 .iter()
817 .map(|field_layouts| {
818 let st = self.univariant(
819 field_layouts,
820 repr,
821 StructKind::Prefixed(min_ity.size(), prefix_align),
822 )?;
823 for field_idx in st.fields.index_by_increasing_offset() {
826 let field = &field_layouts[FieldIdx::new(field_idx)];
827 if !field.is_1zst() {
828 start_align = start_align.min(field.align.abi);
829 break;
830 }
831 }
832 size = cmp::max(size, st.size);
833 align = align.max(st.align.abi);
834 max_repr_align = max_repr_align.max(st.max_repr_align);
835 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
836 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
837 Ok(VariantLayout::from_layout(st))
838 })
839 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
840
841 size = size.align_to(align);
843
844 if size.bytes() >= dl.obj_size_bound() {
846 return Err(LayoutCalculatorError::SizeOverflow);
847 }
848
849 let typeck_ity = Integer::from_attr(dl, repr.discr_type());
850 if typeck_ity < min_ity {
851 {
::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
min_ity, typeck_ity));
};panic!(
861 "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
862 );
863 }
866
867 let mut ity = if repr.c() || repr.int.is_some() {
878 min_ity
879 } else {
880 Integer::for_align(dl, start_align).unwrap_or(min_ity)
881 };
882
883 if ity <= min_ity {
886 ity = min_ity;
887 } else {
888 let old_ity_size = min_ity.size();
890 let new_ity_size = ity.size();
891 for variant in &mut layout_variants {
892 for i in &mut variant.field_offsets {
893 if *i <= old_ity_size {
894 {
match (&*i, &old_ity_size) {
(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, old_ity_size);
895 *i = new_ity_size;
896 }
897 }
898 if variant.size <= old_ity_size {
900 variant.size = new_ity_size;
901 }
902 }
903 }
904
905 let tag_valid_range = {
906 let tag_size = ity.size();
907 let tags = necessary_discriminants.into_iter().map(|d| tag_size.truncate(d));
908 WrappingRange::smallest_range_containing(tags, tag_size)
909 .unwrap_or(WrappingRange { start: 0, end: 0 })
911 };
912 let tag = Scalar::Initialized {
913 value: Primitive::Int(ity, signed),
914 valid_range: tag_valid_range,
915 };
916 let mut abi = BackendRepr::Memory { sized: true };
917
918 let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
919 if tag.size(dl) == size {
920 abi = BackendRepr::Scalar(tag);
923 } else {
924 let mut common_prim = None;
927 let mut common_prim_initialized_in_all_variants = true;
928 for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
929 let mut fields = iter::zip(field_layouts, &layout_variant.field_offsets)
932 .filter(|p| !p.0.is_zst());
933 let (field, offset) = match (fields.next(), fields.next()) {
934 (None, None) => {
935 common_prim_initialized_in_all_variants = false;
936 continue;
937 }
938 (Some(pair), None) => pair,
939 _ => {
940 common_prim = None;
941 break;
942 }
943 };
944 let prim = match field.backend_repr {
945 BackendRepr::Scalar(scalar) => {
946 common_prim_initialized_in_all_variants &=
947 #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Initialized { .. } => true,
_ => false,
}matches!(scalar, Scalar::Initialized { .. });
948 scalar.primitive()
949 }
950 _ => {
951 common_prim = None;
952 break;
953 }
954 };
955 if let Some((old_prim, common_offset)) = common_prim {
956 if offset != common_offset {
958 common_prim = None;
959 break;
960 }
961 let new_prim = match (old_prim, prim) {
965 (x, y) if x == y => x,
967 (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
970 (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
974 | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
975 if p.size(dl) == i.size(dl)
976 && p.default_align(dl) == i.default_align(dl) =>
977 {
978 p
979 }
980 _ => {
981 common_prim = None;
982 break;
983 }
984 };
985 common_prim = Some((new_prim, common_offset));
987 } else {
988 common_prim = Some((prim, offset));
989 }
990 }
991 if let Some((prim, offset)) = common_prim {
992 let prim_scalar = if common_prim_initialized_in_all_variants {
993 let size = prim.size(dl);
994 if !(size.bits() <= 128) {
::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
995 Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
996 } else {
997 Scalar::Union { value: prim }
999 };
1000 let pair =
1001 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1002 let pair_offsets = match pair.fields {
1003 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1004 {
match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
(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!(in_memory_order.raw, [FieldIdx::new(0), FieldIdx::new(1)]);
1005 offsets
1006 }
1007 _ => {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1008 };
1009 if pair_offsets[FieldIdx::new(0)] == Size::ZERO
1010 && pair_offsets[FieldIdx::new(1)] == *offset
1011 && align == pair.align.abi
1012 && size == pair.size
1013 {
1014 abi = pair.backend_repr;
1017 }
1018 }
1019 }
1020
1021 if #[allow(non_exhaustive_omitted_patterns)] match abi {
BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } => true,
_ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) {
1025 for variant in &mut layout_variants {
1026 if #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
BackendRepr::Memory { .. } if variant.has_fields() => true,
_ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. } if variant.has_fields())
1029 {
1030 variant.backend_repr = abi;
1031 variant.size = cmp::max(variant.size, size);
1033 }
1034 }
1035 }
1036
1037 let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1038
1039 let tagged_layout = LayoutData {
1040 variants: Variants::Multiple {
1041 tag,
1042 tag_encoding: TagEncoding::Direct,
1043 tag_field: FieldIdx::new(0),
1044 variants: layout_variants,
1045 },
1046 fields: FieldsShape::Arbitrary {
1047 offsets: [Size::ZERO].into(),
1048 in_memory_order: [FieldIdx::new(0)].into(),
1049 },
1050 largest_niche,
1051 uninhabited,
1052 backend_repr: abi,
1053 align: AbiAlign::new(align),
1054 size,
1055 max_repr_align,
1056 unadjusted_abi_align,
1057 randomization_seed: combined_seed,
1058 };
1059
1060 let best_layout = match (tagged_layout, niche_filling_layout) {
1061 (tl, Some(nl)) => {
1062 use cmp::Ordering::*;
1066 let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1067 l.largest_niche.map_or(0, |n| n.available(dl))
1068 };
1069 match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1070 (Greater, _) => nl,
1071 (Equal, Less) => nl,
1072 _ => tl,
1073 }
1074 }
1075 (tl, None) => tl,
1076 };
1077
1078 Ok(best_layout)
1079 }
1080
1081 fn univariant_biased<
1082 'a,
1083 FieldIdx: Idx,
1084 VariantIdx: Idx,
1085 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1086 >(
1087 &self,
1088 fields: &IndexSlice<FieldIdx, F>,
1089 repr: &ReprOptions,
1090 kind: StructKind,
1091 niche_bias: NicheBias,
1092 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
1093 let dl = self.cx.data_layout();
1094 let pack = repr.pack;
1095 let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1096 let mut max_repr_align = repr.align;
1097 let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1098 let optimize_field_order = !repr.inhibit_struct_field_reordering();
1099 let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1100 let optimizing = &mut in_memory_order.raw[..end];
1101 let fields_excluding_tail = &fields.raw[..end];
1102 let field_seed = fields_excluding_tail
1104 .iter()
1105 .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
1106
1107 if optimize_field_order && fields.len() > 1 {
1108 if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1117 #[cfg(feature = "randomize")]
1118 {
1119 use rand::SeedableRng;
1120 use rand::seq::SliceRandom;
1121 let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1124 field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1125 );
1126
1127 optimizing.shuffle(&mut rng);
1129 }
1130 } else {
1132 let max_field_align =
1135 fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1136 let largest_niche_size = fields_excluding_tail
1137 .iter()
1138 .filter_map(|f| f.largest_niche)
1139 .map(|n| n.available(dl))
1140 .max()
1141 .unwrap_or(0);
1142
1143 let alignment_group_key = |layout: &F| {
1146 if let Some(pack) = pack {
1150 layout.align.abi.min(pack).bytes()
1152 } else {
1153 let align = layout.align.bytes();
1156 let size = layout.size.bytes();
1157 let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1158 let size_as_align = align.max(size).trailing_zeros();
1160 let size_as_align = if largest_niche_size > 0 {
1161 match niche_bias {
1162 NicheBias::Start => {
1166 max_field_align.trailing_zeros().min(size_as_align)
1167 }
1168 NicheBias::End if niche_size == largest_niche_size => {
1172 align.trailing_zeros()
1173 }
1174 NicheBias::End => size_as_align,
1175 }
1176 } else {
1177 size_as_align
1178 };
1179 size_as_align as u64
1180 }
1181 };
1182
1183 match kind {
1184 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1185 optimizing.sort_by_key(|&x| {
1194 let f = &fields[x];
1195 let field_size = f.size.bytes();
1196 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1197 let niche_size_key = match niche_bias {
1198 NicheBias::Start => !niche_size,
1200 NicheBias::End => niche_size,
1202 };
1203 let inner_niche_offset_key = match niche_bias {
1204 NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1205 NicheBias::End => f.largest_niche.map_or(0, |n| {
1206 !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1207 }),
1208 };
1209
1210 (
1211 cmp::Reverse(alignment_group_key(f)),
1213 niche_size_key,
1216 inner_niche_offset_key,
1219 )
1220 });
1221 }
1222
1223 StructKind::Prefixed(..) => {
1224 optimizing.sort_by_key(|&x| {
1229 let f = &fields[x];
1230 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1231 (alignment_group_key(f), niche_size)
1232 });
1233 }
1234 }
1235
1236 }
1239 }
1240 let mut unsized_field = None::<&F>;
1245 let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1246 let mut offset = Size::ZERO;
1247 let mut largest_niche = None;
1248 let mut largest_niche_available = 0;
1249 if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1250 let prefix_align =
1251 if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1252 align = align.max(prefix_align);
1253 offset = prefix_size.align_to(prefix_align);
1254 }
1255 for &i in &in_memory_order {
1256 let field = &fields[i];
1257 if let Some(unsized_field) = unsized_field {
1258 return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1259 }
1260
1261 if field.is_unsized() {
1262 if let StructKind::MaybeUnsized = kind {
1263 unsized_field = Some(field);
1264 } else {
1265 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1266 }
1267 }
1268
1269 let field_align = if let Some(pack) = pack {
1271 field.align.min(AbiAlign::new(pack))
1272 } else {
1273 field.align
1274 };
1275 offset = offset.align_to(field_align.abi);
1276 align = align.max(field_align.abi);
1277 max_repr_align = max_repr_align.max(field.max_repr_align);
1278
1279 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1279",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1279u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::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!("univariant offset: {0:?} field: {1:#?}",
offset, field) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("univariant offset: {:?} field: {:#?}", offset, field);
1280 offsets[i] = offset;
1281
1282 if let Some(mut niche) = field.largest_niche {
1283 let available = niche.available(dl);
1284 let prefer_new_niche = match niche_bias {
1286 NicheBias::Start => available > largest_niche_available,
1287 NicheBias::End => available >= largest_niche_available,
1289 };
1290 if prefer_new_niche {
1291 largest_niche_available = available;
1292 niche.offset += offset;
1293 largest_niche = Some(niche);
1294 }
1295 }
1296
1297 offset =
1298 offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1299 }
1300
1301 let unadjusted_abi_align = align;
1304 if let Some(repr_align) = repr.align {
1305 align = align.max(repr_align);
1306 }
1307 let align = align;
1309
1310 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1310",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1310u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::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!("univariant min_size: {0:?}",
offset) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("univariant min_size: {:?}", offset);
1311 let min_size = offset;
1312 let size = min_size.align_to(align);
1313 if size.bytes() >= dl.obj_size_bound() {
1315 return Err(LayoutCalculatorError::SizeOverflow);
1316 }
1317 let mut layout_of_single_non_zst_field = None;
1318 let sized = unsized_field.is_none();
1319 let mut abi = BackendRepr::Memory { sized };
1320
1321 let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1322
1323 if sized && size.bytes() > 0 {
1325 let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
1328
1329 match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1330 (Some((i, field)), None, None) => {
1332 layout_of_single_non_zst_field = Some(field);
1333
1334 if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1336 match field.backend_repr {
1337 BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1340 if optimize_abi =>
1341 {
1342 abi = field.backend_repr;
1343 }
1344 BackendRepr::ScalarPair { .. } => {
1347 abi = field.backend_repr;
1348 }
1349 _ => {}
1350 }
1351 }
1352 }
1353
1354 (Some((i, a)), Some((j, b)), None) => {
1356 match (a.backend_repr, b.backend_repr) {
1357 (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1358 let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1360 ((i, a), (j, b))
1361 } else {
1362 ((j, b), (i, a))
1363 };
1364 let pair =
1365 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1366 let pair_offsets = match pair.fields {
1367 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1368 {
match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
(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!(
1369 in_memory_order.raw,
1370 [FieldIdx::new(0), FieldIdx::new(1)]
1371 );
1372 offsets
1373 }
1374 FieldsShape::Primitive
1375 | FieldsShape::Array { .. }
1376 | FieldsShape::Union(..) => {
1377 {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")
1378 }
1379 };
1380 if offsets[i] == pair_offsets[FieldIdx::new(0)]
1381 && offsets[j] == pair_offsets[FieldIdx::new(1)]
1382 && align == pair.align.abi
1383 && size == pair.size
1384 {
1385 abi = pair.backend_repr;
1388 }
1389 }
1390 _ => {}
1391 }
1392 }
1393
1394 _ => {}
1395 }
1396 }
1397 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
1398
1399 let unadjusted_abi_align = if repr.transparent() {
1400 match layout_of_single_non_zst_field {
1401 Some(l) => l.unadjusted_abi_align,
1402 None => {
1403 align
1405 }
1406 }
1407 } else {
1408 unadjusted_abi_align
1409 };
1410
1411 let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
1412
1413 Ok(LayoutData {
1414 variants: Variants::Single { index: VariantIdx::new(0) },
1415 fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1416 backend_repr: abi,
1417 largest_niche,
1418 uninhabited,
1419 align: AbiAlign::new(align),
1420 size,
1421 max_repr_align,
1422 unadjusted_abi_align,
1423 randomization_seed: seed,
1424 })
1425 }
1426
1427 fn format_field_niches<
1428 'a,
1429 FieldIdx: Idx,
1430 VariantIdx: Idx,
1431 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1432 >(
1433 &self,
1434 layout: &LayoutData<FieldIdx, VariantIdx>,
1435 fields: &IndexSlice<FieldIdx, F>,
1436 ) -> String {
1437 let dl = self.cx.data_layout();
1438 let mut s = String::new();
1439 for i in layout.fields.index_by_increasing_offset() {
1440 let offset = layout.fields.offset(i);
1441 let f = &fields[FieldIdx::new(i)];
1442 s.write_fmt(format_args!("[o{0}a{1}s{2}", offset.bytes(), f.align.bytes(),
f.size.bytes()))write!(s, "[o{}a{}s{}", offset.bytes(), f.align.bytes(), f.size.bytes()).unwrap();
1443 if let Some(n) = f.largest_niche {
1444 s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1445 s,
1446 " n{}b{}s{}",
1447 n.offset.bytes(),
1448 n.available(dl).ilog2(),
1449 n.value.size(dl).bytes()
1450 )
1451 .unwrap();
1452 }
1453 s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1454 }
1455 s
1456 }
1457}
1458
1459enum SimdVectorKind {
1460 Scalable(NumScalableVectors),
1462 PackedFixed,
1464 Fixed,
1466}
1467
1468fn vector_type_layout<FieldIdx, VariantIdx, F>(
1469 kind: SimdVectorKind,
1470 dl: &TargetDataLayout,
1471 element: F,
1472 count: u64,
1473) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1474where
1475 FieldIdx: Idx,
1476 VariantIdx: Idx,
1477 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1478{
1479 let elt = element.as_ref();
1480 let count = BackendLaneCount::new(count)?;
1481
1482 let BackendRepr::Scalar(element) = elt.backend_repr else {
1483 return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1484 };
1485
1486 let size = elt
1488 .size
1489 .checked_mul(count.as_u64(), dl)
1490 .ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
1491 let (repr, size, align) = match kind {
1492 SimdVectorKind::Scalable(number_of_vectors) => (
1493 BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1494 size.checked_mul(number_of_vectors.0 as u64, dl)
1495 .ok_or_else(|| LayoutCalculatorError::SizeOverflow)?,
1496 dl.rust_vector_align(size),
1497 ),
1498 SimdVectorKind::PackedFixed if !count.is_power_of_two() => {
1502 (BackendRepr::Memory { sized: true }, size, Align::max_aligned_factor(size))
1503 }
1504 SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
1505 (BackendRepr::SimdVector { element, count }, size, dl.rust_vector_align(size))
1506 }
1507 };
1508 let size = size.align_to(align);
1509
1510 Ok(LayoutData {
1511 variants: Variants::Single { index: VariantIdx::new(0) },
1512 fields: FieldsShape::Arbitrary {
1513 offsets: [Size::ZERO].into(),
1514 in_memory_order: [FieldIdx::new(0)].into(),
1515 },
1516 backend_repr: repr,
1517 largest_niche: elt.largest_niche,
1518 uninhabited: false,
1519 size,
1520 align: AbiAlign::new(align),
1521 max_repr_align: None,
1522 unadjusted_abi_align: elt.align.abi,
1523 randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count.as_u64())),
1524 })
1525}