]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/alignment.rs
Rollup merge of #65763 - ObsidianMinor:diag/65642, r=varkor
[rust.git] / src / librustc_mir / util / alignment.rs
1 use rustc::ty::{self, TyCtxt};
2 use rustc::mir::*;
3
4 /// Returns `true` if this place is allowed to be less aligned
5 /// than its containing struct (because it is within a packed
6 /// struct).
7 pub fn is_disaligned<'tcx, L>(
8     tcx: TyCtxt<'tcx>,
9     local_decls: &L,
10     param_env: ty::ParamEnv<'tcx>,
11     place: &Place<'tcx>,
12 ) -> bool
13 where
14     L: HasLocalDecls<'tcx>,
15 {
16     debug!("is_disaligned({:?})", place);
17     if !is_within_packed(tcx, local_decls, place) {
18         debug!("is_disaligned({:?}) - not within packed", place);
19         return false
20     }
21
22     let ty = place.ty(local_decls, tcx).ty;
23     match tcx.layout_raw(param_env.and(ty)) {
24         Ok(layout) if layout.align.abi.bytes() == 1 => {
25             // if the alignment is 1, the type can't be further
26             // disaligned.
27             debug!("is_disaligned({:?}) - align = 1", place);
28             false
29         }
30         _ => {
31             debug!("is_disaligned({:?}) - true", place);
32             true
33         }
34     }
35 }
36
37 fn is_within_packed<'tcx, L>(tcx: TyCtxt<'tcx>, local_decls: &L, place: &Place<'tcx>) -> bool
38 where
39     L: HasLocalDecls<'tcx>,
40 {
41     let mut cursor = &*place.projection;
42     while let [proj_base @ .., elem] = cursor {
43         cursor = proj_base;
44
45         match elem {
46             // encountered a Deref, which is ABI-aligned
47             ProjectionElem::Deref => break,
48             ProjectionElem::Field(..) => {
49                 let ty = Place::ty_from(&place.base, proj_base, local_decls, tcx).ty;
50                 match ty.kind {
51                     ty::Adt(def, _) if def.repr.packed() => {
52                         return true
53                     }
54                     _ => {}
55                 }
56             }
57             _ => {}
58         }
59     }
60
61     false
62 }