rustc_const_eval/util/
alignment.rs

1use rustc_abi::Align;
2use rustc_middle::mir::*;
3use rustc_middle::ty::{self, AdtDef, TyCtxt};
4use tracing::debug;
5
6/// If the place may be less aligned than its type requires
7/// (because it is in a packed type), returns the AdtDef
8/// and packed alignment of its most-unaligned projection.
9pub fn place_unalignment<'tcx, L>(
10    tcx: TyCtxt<'tcx>,
11    local_decls: &L,
12    typing_env: ty::TypingEnv<'tcx>,
13    place: Place<'tcx>,
14) -> Option<(AdtDef<'tcx>, Align)>
15where
16    L: HasLocalDecls<'tcx>,
17{
18    debug!("unalignment({:?})", place);
19    let Some((descr, pack)) = most_packed_projection(tcx, local_decls, place) else {
20        debug!("unalignment({:?}) - not within packed", place);
21        return None;
22    };
23
24    let ty = place.ty(local_decls, tcx).ty;
25    let unsized_tail = || tcx.struct_tail_for_codegen(ty, typing_env);
26    match tcx.layout_of(typing_env.as_query_input(ty)) {
27        Ok(layout)
28            if layout.align.abi <= pack
29                && (layout.is_sized()
30                    || matches!(unsized_tail().kind(), ty::Slice(..) | ty::Str)) =>
31        {
32            // If the packed alignment is greater or equal to the field alignment, the type won't be
33            // further unaligned.
34            // However we need to ensure the field is sized; for unsized fields, `layout.align` is
35            // just an approximation -- except when the unsized tail is a slice, where the alignment
36            // is fully determined by the type.
37            debug!(
38                "unalignment({:?}) - align = {}, packed = {}; not unaligned",
39                place,
40                layout.align.bytes(),
41                pack.bytes()
42            );
43            None
44        }
45        _ => {
46            // We cannot figure out the layout. Conservatively assume that this is unaligned.
47            debug!("unalignment({:?}) - unaligned", place);
48            Some((descr, pack))
49        }
50    }
51}
52
53/// If the place includes a projection from a packed struct,
54/// returns the AdtDef and packed alignment of the projection
55/// with the lowest pack
56pub fn most_packed_projection<'tcx, L>(
57    tcx: TyCtxt<'tcx>,
58    local_decls: &L,
59    place: Place<'tcx>,
60) -> Option<(AdtDef<'tcx>, Align)>
61where
62    L: HasLocalDecls<'tcx>,
63{
64    place
65        .iter_projections()
66        .rev()
67        // Stop at `Deref`; standard ABI alignment applies there.
68        .take_while(|(_base, elem)| !matches!(elem, ProjectionElem::Deref))
69        // Consider the packed alignments at play here...
70        .filter_map(|(base, _elem)| {
71            let adt = base.ty(local_decls, tcx).ty.ty_adt_def()?;
72            let pack = adt.repr().pack?;
73            Some((adt, pack))
74        })
75        // ... and compute their minimum.
76        // The overall smallest alignment is what matters.
77        .min_by_key(|(_, align)| *align)
78}