rustc_mir_transform/
check_alignment.rs

1use rustc_abi::Align;
2use rustc_index::IndexVec;
3use rustc_middle::mir::interpret::Scalar;
4use rustc_middle::mir::visit::PlaceContext;
5use rustc_middle::mir::*;
6use rustc_middle::ty::{Ty, TyCtxt};
7use rustc_session::Session;
8
9use crate::check_pointers::{BorrowedFieldProjectionMode, PointerCheck, check_pointers};
10
11pub(super) struct CheckAlignment;
12
13impl<'tcx> crate::MirPass<'tcx> for CheckAlignment {
14    fn is_enabled(&self, sess: &Session) -> bool {
15        sess.ub_checks()
16    }
17
18    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
19        // Skip trivially aligned place types.
20        let excluded_pointees = [tcx.types.bool, tcx.types.i8, tcx.types.u8];
21
22        // When checking the alignment of references to field projections (`&(*ptr).a`),
23        // we need to make sure that the reference is aligned according to the field type
24        // and not to the pointer type.
25        check_pointers(
26            tcx,
27            body,
28            &excluded_pointees,
29            insert_alignment_check,
30            BorrowedFieldProjectionMode::FollowProjections,
31        );
32    }
33
34    fn is_required(&self) -> bool {
35        true
36    }
37}
38
39/// Inserts the actual alignment check's logic. Returns a
40/// [AssertKind::MisalignedPointerDereference] on failure.
41fn insert_alignment_check<'tcx>(
42    tcx: TyCtxt<'tcx>,
43    pointer: Place<'tcx>,
44    pointee_ty: Ty<'tcx>,
45    _context: PlaceContext,
46    local_decls: &mut IndexVec<Local, LocalDecl<'tcx>>,
47    stmts: &mut Vec<Statement<'tcx>>,
48    source_info: SourceInfo,
49) -> PointerCheck<'tcx> {
50    // Cast the pointer to a *const ().
51    let const_raw_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit);
52    let rvalue = Rvalue::Cast(CastKind::PtrToPtr, Operand::Copy(pointer), const_raw_ptr);
53    let thin_ptr = local_decls.push(LocalDecl::with_source_info(const_raw_ptr, source_info)).into();
54    stmts.push(Statement::new(source_info, StatementKind::Assign(Box::new((thin_ptr, rvalue)))));
55
56    // Transmute the pointer to a usize (equivalent to `ptr.addr()`).
57    let rvalue = Rvalue::Cast(CastKind::Transmute, Operand::Copy(thin_ptr), tcx.types.usize);
58    let addr = local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
59    stmts.push(Statement::new(source_info, StatementKind::Assign(Box::new((addr, rvalue)))));
60
61    // Get the alignment of the pointee
62    let alignment =
63        local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
64    let rvalue = Rvalue::NullaryOp(NullOp::AlignOf, pointee_ty);
65    stmts.push(Statement::new(source_info, StatementKind::Assign(Box::new((alignment, rvalue)))));
66
67    // Subtract 1 from the alignment to get the alignment mask
68    let alignment_mask =
69        local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
70    let one = Operand::Constant(Box::new(ConstOperand {
71        span: source_info.span,
72        user_ty: None,
73        const_: Const::Val(ConstValue::Scalar(Scalar::from_target_usize(1, &tcx)), tcx.types.usize),
74    }));
75    stmts.push(Statement::new(
76        source_info,
77        StatementKind::Assign(Box::new((
78            alignment_mask,
79            Rvalue::BinaryOp(BinOp::Sub, Box::new((Operand::Copy(alignment), one))),
80        ))),
81    ));
82
83    // If this target does not have reliable alignment, further limit the mask by anding it with
84    // the mask for the highest reliable alignment.
85    #[allow(irrefutable_let_patterns)]
86    if let max_align = tcx.sess.target.max_reliable_alignment()
87        && max_align < Align::MAX
88    {
89        let max_mask = max_align.bytes() - 1;
90        let max_mask = Operand::Constant(Box::new(ConstOperand {
91            span: source_info.span,
92            user_ty: None,
93            const_: Const::Val(
94                ConstValue::Scalar(Scalar::from_target_usize(max_mask, &tcx)),
95                tcx.types.usize,
96            ),
97        }));
98        stmts.push(Statement::new(
99            source_info,
100            StatementKind::Assign(Box::new((
101                alignment_mask,
102                Rvalue::BinaryOp(
103                    BinOp::BitAnd,
104                    Box::new((Operand::Copy(alignment_mask), max_mask)),
105                ),
106            ))),
107        ));
108    }
109
110    // BitAnd the alignment mask with the pointer
111    let alignment_bits =
112        local_decls.push(LocalDecl::with_source_info(tcx.types.usize, source_info)).into();
113    stmts.push(Statement::new(
114        source_info,
115        StatementKind::Assign(Box::new((
116            alignment_bits,
117            Rvalue::BinaryOp(
118                BinOp::BitAnd,
119                Box::new((Operand::Copy(addr), Operand::Copy(alignment_mask))),
120            ),
121        ))),
122    ));
123
124    // Check if the alignment bits are all zero
125    let is_ok = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into();
126    let zero = Operand::Constant(Box::new(ConstOperand {
127        span: source_info.span,
128        user_ty: None,
129        const_: Const::Val(ConstValue::Scalar(Scalar::from_target_usize(0, &tcx)), tcx.types.usize),
130    }));
131    stmts.push(Statement::new(
132        source_info,
133        StatementKind::Assign(Box::new((
134            is_ok,
135            Rvalue::BinaryOp(BinOp::Eq, Box::new((Operand::Copy(alignment_bits), zero.clone()))),
136        ))),
137    ));
138
139    // Emit a check that asserts on the alignment and otherwise triggers a
140    // AssertKind::MisalignedPointerDereference.
141    PointerCheck {
142        cond: Operand::Copy(is_ok),
143        assert_kind: Box::new(AssertKind::MisalignedPointerDereference {
144            required: Operand::Copy(alignment),
145            found: Operand::Copy(addr),
146        }),
147    }
148}