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