rustc_codegen_ssa/size_of_val.rs
1//! Computing the size and alignment of a value.
2
3use rustc_abi::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 tracing::{debug, trace};
9
10use crate::common::IntPredicate;
11use crate::traits::*;
12use crate::{common, meth};
13
14pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
15 bx: &mut Bx,
16 t: Ty<'tcx>,
17 info: Option<Bx::Value>,
18) -> (Bx::Value, Bx::Value) {
19 let layout = bx.layout_of(t);
20 trace!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
21 if layout.is_sized() {
22 let size = bx.const_usize(layout.size.bytes());
23 let align = bx.const_usize(layout.align.abi.bytes());
24 return (size, align);
25 }
26 match t.kind() {
27 ty::Dynamic(..) => {
28 // Load size/align from vtable.
29 let vtable = info.unwrap();
30 let size = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE)
31 .get_usize(bx, vtable, t);
32 let align = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN)
33 .get_usize(bx, vtable, t);
34
35 // Size is always <= isize::MAX.
36 let size_bound = bx.data_layout().ptr_sized_integer().signed_max() as u128;
37 bx.range_metadata(size, WrappingRange { start: 0, end: size_bound });
38 // Alignment is always nonzero.
39 bx.range_metadata(align, WrappingRange { start: 1, end: !0 });
40
41 (size, align)
42 }
43 ty::Slice(_) | ty::Str => {
44 let unit = layout.field(bx, 0);
45 // The info in this case is the length of the str, so the size is that
46 // times the unit size.
47 (
48 // All slice sizes must fit into `isize`, so this multiplication cannot
49 // wrap -- neither signed nor unsigned.
50 bx.unchecked_sumul(info.unwrap(), bx.const_usize(unit.size.bytes())),
51 bx.const_usize(unit.align.abi.bytes()),
52 )
53 }
54 ty::Foreign(_) => {
55 // `extern` type. We cannot compute the size, so panic.
56 let msg_str = with_no_visible_paths!({
57 with_no_trimmed_paths!({
58 format!("attempted to compute the size or alignment of extern type `{t}`")
59 })
60 });
61 let msg = bx.const_str(&msg_str);
62
63 // Obtain the panic entry point.
64 let (fn_abi, llfn, _instance) =
65 common::build_langcall(bx, None, LangItem::PanicNounwind);
66
67 // Generate the call. Cannot use `do_call` since we don't have a MIR terminator so we
68 // can't create a `TerminationCodegenHelper`. (But we are in good company, this code is
69 // duplicated plenty of times.)
70 let fn_ty = bx.fn_decl_backend_type(fn_abi);
71
72 bx.call(
73 fn_ty,
74 /* fn_attrs */ None,
75 Some(fn_abi),
76 llfn,
77 &[msg.0, msg.1],
78 None,
79 None,
80 );
81
82 // This function does not return so we can now return whatever we want.
83 let size = bx.const_usize(layout.size.bytes());
84 let align = bx.const_usize(layout.align.abi.bytes());
85 (size, align)
86 }
87 ty::Adt(..) | ty::Tuple(..) => {
88 // First get the size of all statically known fields.
89 // Don't use size_of because it also rounds up to alignment, which we
90 // want to avoid, as the unsized field's alignment could be smaller.
91 assert!(!t.is_simd());
92 debug!("DST {} layout: {:?}", t, layout);
93
94 let i = layout.fields.count() - 1;
95 let unsized_offset_unadjusted = layout.fields.offset(i).bytes();
96 let sized_align = layout.align.abi.bytes();
97 debug!(
98 "DST {} offset of dyn field: {}, statically sized align: {}",
99 t, unsized_offset_unadjusted, sized_align
100 );
101 let unsized_offset_unadjusted = bx.const_usize(unsized_offset_unadjusted);
102 let sized_align = bx.const_usize(sized_align);
103
104 // Recurse to get the size of the dynamically sized field (must be
105 // the last field).
106 let field_ty = layout.field(bx, i).ty;
107 let (unsized_size, mut unsized_align) = size_and_align_of_dst(bx, field_ty, info);
108
109 // # First compute the dynamic alignment
110
111 // For packed types, we need to cap the alignment.
112 if let ty::Adt(def, _) = t.kind()
113 && let Some(packed) = def.repr().pack
114 {
115 if packed.bytes() == 1 {
116 // We know this will be capped to 1.
117 unsized_align = bx.const_usize(1);
118 } else {
119 // We have to dynamically compute `min(unsized_align, packed)`.
120 let packed = bx.const_usize(packed.bytes());
121 let cmp = bx.icmp(IntPredicate::IntULT, unsized_align, packed);
122 unsized_align = bx.select(cmp, unsized_align, packed);
123 }
124 }
125
126 // Choose max of two known alignments (combined value must
127 // be aligned according to more restrictive of the two).
128 let full_align = match (
129 bx.const_to_opt_u128(sized_align, false),
130 bx.const_to_opt_u128(unsized_align, false),
131 ) {
132 (Some(sized_align), Some(unsized_align)) => {
133 // If both alignments are constant, (the sized_align should always be), then
134 // pick the correct alignment statically.
135 bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64)
136 }
137 _ => {
138 let cmp = bx.icmp(IntPredicate::IntUGT, sized_align, unsized_align);
139 bx.select(cmp, sized_align, unsized_align)
140 }
141 };
142
143 // # Then compute the dynamic size
144
145 // The full formula for the size would be:
146 // let unsized_offset_adjusted = unsized_offset_unadjusted.align_to(unsized_align);
147 // let full_size = (unsized_offset_adjusted + unsized_size).align_to(full_align);
148 // However, `unsized_size` is a multiple of `unsized_align`. Therefore, we can
149 // equivalently do the `align_to(unsized_align)` *after* adding `unsized_size`:
150 //
151 // let full_size =
152 // (unsized_offset_unadjusted + unsized_size)
153 // .align_to(unsized_align)
154 // .align_to(full_align);
155 //
156 // Furthermore, `align >= unsized_align`, and therefore we only need to do:
157 // let full_size = (unsized_offset_unadjusted + unsized_size).align_to(full_align);
158
159 let full_size = bx.add(unsized_offset_unadjusted, unsized_size);
160
161 // Issue #27023: must add any necessary padding to `size`
162 // (to make it a multiple of `align`) before returning it.
163 //
164 // Namely, the returned size should be, in C notation:
165 //
166 // `size + ((size & (align-1)) ? align : 0)`
167 //
168 // emulated via the semi-standard fast bit trick:
169 //
170 // `(size + (align-1)) & -align`
171 let one = bx.const_usize(1);
172 let addend = bx.sub(full_align, one);
173 let add = bx.add(full_size, addend);
174 let neg = bx.neg(full_align);
175 let full_size = bx.and(add, neg);
176
177 (full_size, full_align)
178 }
179 _ => bug!("size_and_align_of_dst: {t} not supported"),
180 }
181}