1//! Computing the size and alignment of a value.
23use rustc_abi::{Align, WrappingRange};
4use rustc_hir::LangItem;
5use rustc_middle::bug;
6use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
7use rustc_middle::ty::{self, Ty};
8use rustc_span::DUMMY_SP;
9use tracing::{debug, trace};
1011use crate::common::IntPredicate;
12use crate::traits::*;
13use crate::{common, meth};
1415pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
16 bx: &mut Bx,
17 t: Ty<'tcx>,
18 info: Option<Bx::Value>,
19) -> (Bx::Value, Bx::Value) {
20let layout = bx.layout_of(t);
21{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/size_of_val.rs:21",
"rustc_codegen_ssa::size_of_val", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/size_of_val.rs"),
::tracing_core::__macro_support::Option::Some(21u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::size_of_val"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("size_and_align_of_dst(ty={0}, info={1:?}): layout: {2:?}",
t, info, layout) as &dyn Value))])
});
} else { ; }
};trace!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
22if layout.is_sized() {
23let size = bx.const_usize(layout.size.bytes());
24let align = bx.const_usize(layout.align.bytes());
25return (size, align);
26 }
27match t.kind() {
28 ty::Dynamic(..) => {
29// Load size/align from vtable.
30let vtable = info.unwrap();
31let size = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
32 .get_usize(bx, vtable, t);
33let align = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
34 .get_usize(bx, vtable, t);
3536// Size is always <= isize::MAX.
37let size_bound = bx.data_layout().ptr_sized_integer().signed_max() as u128;
38bx.range_metadata(size, WrappingRange { start: 0, end: size_bound });
39// Alignment is always a power of two, thus 1..=0x800…000,
40 // but also bounded by the maximum we support in type layout.
41let align_bound = Align::max_for_target(bx.data_layout()).bytes().into();
42bx.range_metadata(align, WrappingRange { start: 1, end: align_bound });
4344 (size, align)
45 }
46 ty::Slice(_) | ty::Str => {
47let unit = layout.field(bx, 0);
48// The info in this case is the length of the str, so the size is that
49 // times the unit size.
50(
51// All slice sizes must fit into `isize`, so this multiplication cannot
52 // wrap -- neither signed nor unsigned.
53bx.unchecked_sumul(info.unwrap(), bx.const_usize(unit.size.bytes())),
54bx.const_usize(unit.align.bytes()),
55 )
56 }
57 ty::Foreign(_) => {
58// `extern` type. We cannot compute the size, so panic.
59let msg_str = {
let _guard = NoVisibleGuard::new();
{
{
let _guard = NoTrimmedGuard::new();
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to compute the size or alignment of extern type `{0}`",
t))
})
}
}
}
}with_no_visible_paths!({
60with_no_trimmed_paths!({
61format!("attempted to compute the size or alignment of extern type `{t}`")
62 })
63 });
64let msg = bx.const_str(&msg_str);
6566// Obtain the panic entry point.
67let (fn_abi, llfn, _instance) =
68 common::build_langcall(bx, DUMMY_SP, LangItem::PanicNounwind);
6970// Generate the call. Cannot use `do_call` since we don't have a MIR terminator so we
71 // can't create a `TerminationCodegenHelper`. (But we are in good company, this code is
72 // duplicated plenty of times.)
73let fn_ty = bx.fn_decl_backend_type(fn_abi);
7475bx.call(
76fn_ty,
77/* fn_attrs */ None,
78Some(fn_abi),
79llfn,
80&[msg.0, msg.1],
81None,
82None,
83 );
8485// This function does not return so we can now return whatever we want.
86let size = bx.const_usize(layout.size.bytes());
87let align = bx.const_usize(layout.align.bytes());
88 (size, align)
89 }
90 ty::Adt(..) | ty::Tuple(..) => {
91// First get the size of all statically known fields.
92 // Don't use size_of because it also rounds up to alignment, which we
93 // want to avoid, as the unsized field's alignment could be smaller.
94if !!t.is_simd() {
::core::panicking::panic("assertion failed: !t.is_simd()")
};assert!(!t.is_simd());
95{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/size_of_val.rs:95",
"rustc_codegen_ssa::size_of_val", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/size_of_val.rs"),
::tracing_core::__macro_support::Option::Some(95u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::size_of_val"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DST {0} layout: {1:?}",
t, layout) as &dyn Value))])
});
} else { ; }
};debug!("DST {} layout: {:?}", t, layout);
9697let i = layout.fields.count() - 1;
98let unsized_offset_unadjusted = layout.fields.offset(i).bytes();
99let sized_align = layout.align.bytes();
100{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/size_of_val.rs:100",
"rustc_codegen_ssa::size_of_val", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/size_of_val.rs"),
::tracing_core::__macro_support::Option::Some(100u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::size_of_val"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DST {0} offset of dyn field: {1}, statically sized align: {2}",
t, unsized_offset_unadjusted, sized_align) as &dyn Value))])
});
} else { ; }
};debug!(
101"DST {} offset of dyn field: {}, statically sized align: {}",
102 t, unsized_offset_unadjusted, sized_align
103 );
104let unsized_offset_unadjusted = bx.const_usize(unsized_offset_unadjusted);
105let sized_align = bx.const_usize(sized_align);
106107// Recurse to get the size of the dynamically sized field (must be
108 // the last field).
109let field_ty = layout.field(bx, i).ty;
110let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
111112// # First compute the dynamic alignment
113114 // For packed types, we need to cap the alignment.
115if let ty::Adt(def, _) = t.kind()
116 && let Some(packed) = def.repr().pack
117 {
118if packed.bytes() == 1 {
119// We know this will be capped to 1.
120unsized_align = bx.const_usize(1);
121 } else {
122// We have to dynamically compute `min(unsized_align, packed)`.
123let packed = bx.const_usize(packed.bytes());
124let cmp = bx.icmp(IntPredicate::IntULT, unsized_align, packed);
125unsized_align = bx.select(cmp, unsized_align, packed);
126 }
127 }
128129// Choose max of two known alignments (combined value must
130 // be aligned according to more restrictive of the two).
131let full_align = match (
132bx.const_to_opt_u128(sized_align, false),
133bx.const_to_opt_u128(unsized_align, false),
134 ) {
135 (Some(sized_align), Some(unsized_align)) => {
136// If both alignments are constant, (the sized_align should always be), then
137 // pick the correct alignment statically.
138bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
139 }
140_ => {
141let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
142bx.select(cmp, sized_align, unsized_align)
143 }
144 };
145146// # Then compute the dynamic size
147148 // The full formula for the size would be:
149 // let unsized_offset_adjusted = unsized_offset_unadjusted.align_to(unsized_align);
150 // let full_size = (unsized_offset_adjusted + unsized_size).align_to(full_align);
151 // However, `unsized_size` is a multiple of `unsized_align`. Therefore, we can
152 // equivalently do the `align_to(unsized_align)` *after* adding `unsized_size`:
153 //
154 // let full_size =
155 // (unsized_offset_unadjusted + unsized_size)
156 // .align_to(unsized_align)
157 // .align_to(full_align);
158 //
159 // Furthermore, `align >= unsized_align`, and therefore we only need to do:
160 // let full_size = (unsized_offset_unadjusted + unsized_size).align_to(full_align);
161162let full_size = bx.add(unsized_offset_unadjusted, unsized_size);
163164// Issue #27023: must add any necessary padding to `size`
165 // (to make it a multiple of `align`) before returning it.
166 //
167 // Namely, the returned size should be, in C notation:
168 //
169 // `size + ((size & (align-1)) ? align : 0)`
170 //
171 // emulated via the semi-standard fast bit trick:
172 //
173 // `(size + (align-1)) & -align`
174let one = bx.const_usize(1);
175let addend = bx.sub(full_align, one);
176let add = bx.add(full_size, addend);
177let neg = bx.neg(full_align);
178let full_size = bx.and(add, neg);
179180 (full_size, full_align)
181 }
182_ => ::rustc_middle::util::bug::bug_fmt(format_args!("size_and_align_of_dst: {0} not supported",
t))bug!("size_and_align_of_dst: {t} not supported"),
183 }
184}