]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/alignment.rs
70d6aaf70eb09c87399dbc1e0d5e9e2d825e602f
[rust.git] / src / librustc_mir / util / alignment.rs
1 use rustc::mir::*;
2 use rustc::ty::{self, TyCtxt};
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.as_ref();
42     while let &[ref 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() => return true,
52                     _ => {}
53                 }
54             }
55             _ => {}
56         }
57     }
58
59     false
60 }