Skip to main content

rustc_mir_transform/
add_moves_for_packed_drops.rs

1use rustc_middle::mir::*;
2use rustc_middle::ty::TyCtxt;
3use tracing::debug;
4
5use crate::patch::MirPatch;
6use crate::{PassPolicy, util};
7
8/// This pass moves values being dropped that are within a packed
9/// struct to a separate local before dropping them, to ensure that
10/// they are dropped from an aligned address.
11///
12/// For example, if we have something like
13///
14/// ```ignore (illustrative)
15/// #[repr(packed)]
16/// struct Foo {
17///     dealign: u8,
18///     data: Vec<u8>
19/// }
20///
21/// let foo = ...;
22/// ```
23///
24/// We want to call `drop_glue::<Vec<u8>>` with a reference to `data`, which must be aligned.
25/// This means we can't simply drop `foo.data` directly, because its address is not aligned.
26///
27/// Instead, we move `foo.data` to a local and drop that:
28/// ```ignore (illustrative)
29///     storage.live(drop_temp)
30///     drop_temp = foo.data;
31///     drop(drop_temp) -> next
32/// next:
33///     storage.dead(drop_temp)
34/// ```
35///
36/// The storage instructions are required to avoid stack space
37/// blowup.
38pub(super) struct AddMovesForPackedDrops;
39
40impl<'tcx> crate::MirPass<'tcx> for AddMovesForPackedDrops {
41    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
42        debug!("add_moves_for_packed_drops({:?} @ {:?})", body.source, body.span);
43        let mut patch = MirPatch::new(body);
44        let typing_env = body.typing_env(tcx);
45
46        for (bb, data) in body.basic_blocks.iter_enumerated() {
47            let loc = Location { block: bb, statement_index: data.statements.len() };
48            let terminator = data.terminator();
49
50            match terminator.kind {
51                TerminatorKind::Drop { place, .. }
52                    if util::place_unalignment(tcx, body, typing_env, place).is_some() =>
53                {
54                    add_move_for_packed_drop(
55                        tcx,
56                        body,
57                        &mut patch,
58                        terminator,
59                        loc,
60                        data.is_cleanup,
61                    );
62                }
63                _ => {}
64            }
65        }
66
67        patch.apply(body);
68    }
69
70    fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
71        // Implements part of MIR semantics by making implicit packed-drop handling explicit.
72        PassPolicy::Required
73    }
74}
75
76fn add_move_for_packed_drop<'tcx>(
77    tcx: TyCtxt<'tcx>,
78    body: &Body<'tcx>,
79    patch: &mut MirPatch<'tcx>,
80    terminator: &Terminator<'tcx>,
81    loc: Location,
82    is_cleanup: bool,
83) {
84    debug!("add_move_for_packed_drop({:?} @ {:?})", terminator, loc);
85    let TerminatorKind::Drop { ref place, target, unwind, replace, drop } = terminator.kind else {
86        unreachable!();
87    };
88
89    let source_info = terminator.source_info;
90    let ty = place.ty(body, tcx).ty;
91    let temp = patch.new_temp(ty, source_info.span);
92
93    let storage_dead_block = patch.new_block(BasicBlockData::new_stmts(
94        vec![Statement::new(source_info, StatementKind::StorageDead(temp))],
95        Terminator { source_info, kind: TerminatorKind::goto(target) },
96        is_cleanup,
97    ));
98
99    patch.add_statement(loc, StatementKind::StorageLive(temp));
100    patch.add_assign(loc, Place::from(temp), Rvalue::Use(Operand::Move(*place), WithRetag::Yes));
101    patch.patch_terminator(
102        loc.block,
103        TerminatorKind::Drop {
104            place: Place::from(temp),
105            target: storage_dead_block,
106            unwind,
107            replace,
108            drop,
109        },
110    );
111}