rustc_mir_dataflow/impls/
storage_liveness.rs

1use std::borrow::Cow;
2
3use rustc_index::bit_set::DenseBitSet;
4use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
5use rustc_middle::mir::*;
6
7use super::MaybeBorrowedLocals;
8use crate::{Analysis, GenKill, ResultsCursor};
9
10/// The set of locals in a MIR body that do not have `StorageLive`/`StorageDead` annotations.
11///
12/// These locals have fixed storage for the duration of the body.
13pub fn always_storage_live_locals(body: &Body<'_>) -> DenseBitSet<Local> {
14    let mut always_live_locals = DenseBitSet::new_filled(body.local_decls.len());
15
16    for block in &*body.basic_blocks {
17        for statement in &block.statements {
18            if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = statement.kind {
19                always_live_locals.remove(l);
20            }
21        }
22    }
23
24    always_live_locals
25}
26
27pub struct MaybeStorageLive<'a> {
28    always_live_locals: Cow<'a, DenseBitSet<Local>>,
29}
30
31impl<'a> MaybeStorageLive<'a> {
32    pub fn new(always_live_locals: Cow<'a, DenseBitSet<Local>>) -> Self {
33        MaybeStorageLive { always_live_locals }
34    }
35}
36
37impl<'a, 'tcx> Analysis<'tcx> for MaybeStorageLive<'a> {
38    type Domain = DenseBitSet<Local>;
39
40    const NAME: &'static str = "maybe_storage_live";
41
42    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
43        // bottom = dead
44        DenseBitSet::new_empty(body.local_decls.len())
45    }
46
47    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
48        state.union(&*self.always_live_locals);
49
50        for arg in body.args_iter() {
51            state.insert(arg);
52        }
53    }
54
55    fn apply_primary_statement_effect(
56        &mut self,
57        state: &mut Self::Domain,
58        stmt: &Statement<'tcx>,
59        _: Location,
60    ) {
61        match stmt.kind {
62            StatementKind::StorageLive(l) => state.gen_(l),
63            StatementKind::StorageDead(l) => state.kill(l),
64            _ => (),
65        }
66    }
67}
68
69pub struct MaybeStorageDead<'a> {
70    always_live_locals: Cow<'a, DenseBitSet<Local>>,
71}
72
73impl<'a> MaybeStorageDead<'a> {
74    pub fn new(always_live_locals: Cow<'a, DenseBitSet<Local>>) -> Self {
75        MaybeStorageDead { always_live_locals }
76    }
77}
78
79impl<'a, 'tcx> Analysis<'tcx> for MaybeStorageDead<'a> {
80    type Domain = DenseBitSet<Local>;
81
82    const NAME: &'static str = "maybe_storage_dead";
83
84    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
85        // bottom = live
86        DenseBitSet::new_empty(body.local_decls.len())
87    }
88
89    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
90        assert_eq!(body.local_decls.len(), self.always_live_locals.domain_size());
91        // Do not iterate on return place and args, as they are trivially always live.
92        for local in body.vars_and_temps_iter() {
93            if !self.always_live_locals.contains(local) {
94                state.insert(local);
95            }
96        }
97    }
98
99    fn apply_primary_statement_effect(
100        &mut self,
101        state: &mut Self::Domain,
102        stmt: &Statement<'tcx>,
103        _: Location,
104    ) {
105        match stmt.kind {
106            StatementKind::StorageLive(l) => state.kill(l),
107            StatementKind::StorageDead(l) => state.gen_(l),
108            _ => (),
109        }
110    }
111}
112
113type BorrowedLocalsResults<'mir, 'tcx> = ResultsCursor<'mir, 'tcx, MaybeBorrowedLocals>;
114
115/// Dataflow analysis that determines whether each local requires storage at a
116/// given location; i.e. whether its storage can go away without being observed.
117pub struct MaybeRequiresStorage<'mir, 'tcx> {
118    borrowed_locals: BorrowedLocalsResults<'mir, 'tcx>,
119}
120
121impl<'mir, 'tcx> MaybeRequiresStorage<'mir, 'tcx> {
122    pub fn new(borrowed_locals: BorrowedLocalsResults<'mir, 'tcx>) -> Self {
123        MaybeRequiresStorage { borrowed_locals }
124    }
125}
126
127impl<'tcx> Analysis<'tcx> for MaybeRequiresStorage<'_, 'tcx> {
128    type Domain = DenseBitSet<Local>;
129
130    const NAME: &'static str = "requires_storage";
131
132    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
133        // bottom = dead
134        DenseBitSet::new_empty(body.local_decls.len())
135    }
136
137    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
138        // The resume argument is live on function entry (we don't care about
139        // the `self` argument)
140        for arg in body.args_iter().skip(1) {
141            state.insert(arg);
142        }
143    }
144
145    fn apply_early_statement_effect(
146        &mut self,
147        state: &mut Self::Domain,
148        stmt: &Statement<'tcx>,
149        loc: Location,
150    ) {
151        // If a place is borrowed in a statement, it needs storage for that statement.
152        MaybeBorrowedLocals::transfer_function(state).visit_statement(stmt, loc);
153
154        match &stmt.kind {
155            StatementKind::StorageDead(l) => state.kill(*l),
156
157            // If a place is assigned to in a statement, it needs storage for that statement.
158            StatementKind::Assign(box (place, _))
159            | StatementKind::SetDiscriminant { box place, .. } => {
160                state.gen_(place.local);
161            }
162
163            // Nothing to do for these. Match exhaustively so this fails to compile when new
164            // variants are added.
165            StatementKind::AscribeUserType(..)
166            | StatementKind::PlaceMention(..)
167            | StatementKind::Coverage(..)
168            | StatementKind::FakeRead(..)
169            | StatementKind::ConstEvalCounter
170            | StatementKind::Nop
171            | StatementKind::Retag(..)
172            | StatementKind::Intrinsic(..)
173            | StatementKind::BackwardIncompatibleDropHint { .. }
174            | StatementKind::StorageLive(..) => {}
175        }
176    }
177
178    fn apply_primary_statement_effect(
179        &mut self,
180        state: &mut Self::Domain,
181        _: &Statement<'tcx>,
182        loc: Location,
183    ) {
184        // If we move from a place then it only stops needing storage *after*
185        // that statement.
186        self.check_for_move(state, loc);
187    }
188
189    fn apply_early_terminator_effect(
190        &mut self,
191        state: &mut Self::Domain,
192        terminator: &Terminator<'tcx>,
193        loc: Location,
194    ) {
195        // If a place is borrowed in a terminator, it needs storage for that terminator.
196        MaybeBorrowedLocals::transfer_function(state).visit_terminator(terminator, loc);
197
198        match &terminator.kind {
199            TerminatorKind::Call { destination, .. } => {
200                state.gen_(destination.local);
201            }
202
203            // Note that we do *not* gen the `resume_arg` of `Yield` terminators. The reason for
204            // that is that a `yield` will return from the function, and `resume_arg` is written
205            // only when the coroutine is later resumed. Unlike `Call`, this doesn't require the
206            // place to have storage *before* the yield, only after.
207            TerminatorKind::Yield { .. } => {}
208
209            TerminatorKind::InlineAsm { operands, .. } => {
210                for op in operands {
211                    match op {
212                        InlineAsmOperand::Out { place, .. }
213                        | InlineAsmOperand::InOut { out_place: place, .. } => {
214                            if let Some(place) = place {
215                                state.gen_(place.local);
216                            }
217                        }
218                        InlineAsmOperand::In { .. }
219                        | InlineAsmOperand::Const { .. }
220                        | InlineAsmOperand::SymFn { .. }
221                        | InlineAsmOperand::SymStatic { .. }
222                        | InlineAsmOperand::Label { .. } => {}
223                    }
224                }
225            }
226
227            // Nothing to do for these. Match exhaustively so this fails to compile when new
228            // variants are added.
229            TerminatorKind::UnwindTerminate(_)
230            | TerminatorKind::Assert { .. }
231            | TerminatorKind::Drop { .. }
232            | TerminatorKind::FalseEdge { .. }
233            | TerminatorKind::FalseUnwind { .. }
234            | TerminatorKind::CoroutineDrop
235            | TerminatorKind::Goto { .. }
236            | TerminatorKind::UnwindResume
237            | TerminatorKind::Return
238            | TerminatorKind::TailCall { .. }
239            | TerminatorKind::SwitchInt { .. }
240            | TerminatorKind::Unreachable => {}
241        }
242    }
243
244    fn apply_primary_terminator_effect<'t>(
245        &mut self,
246        state: &mut Self::Domain,
247        terminator: &'t Terminator<'tcx>,
248        loc: Location,
249    ) -> TerminatorEdges<'t, 'tcx> {
250        match terminator.kind {
251            // For call terminators the destination requires storage for the call
252            // and after the call returns successfully, but not after a panic.
253            // Since `propagate_call_unwind` doesn't exist, we have to kill the
254            // destination here, and then gen it again in `call_return_effect`.
255            TerminatorKind::Call { destination, .. } => {
256                state.kill(destination.local);
257            }
258
259            // The same applies to InlineAsm outputs.
260            TerminatorKind::InlineAsm { ref operands, .. } => {
261                CallReturnPlaces::InlineAsm(operands).for_each(|place| state.kill(place.local));
262            }
263
264            // Nothing to do for these. Match exhaustively so this fails to compile when new
265            // variants are added.
266            TerminatorKind::Yield { .. }
267            | TerminatorKind::UnwindTerminate(_)
268            | TerminatorKind::Assert { .. }
269            | TerminatorKind::Drop { .. }
270            | TerminatorKind::FalseEdge { .. }
271            | TerminatorKind::FalseUnwind { .. }
272            | TerminatorKind::CoroutineDrop
273            | TerminatorKind::Goto { .. }
274            | TerminatorKind::UnwindResume
275            | TerminatorKind::Return
276            | TerminatorKind::TailCall { .. }
277            | TerminatorKind::SwitchInt { .. }
278            | TerminatorKind::Unreachable => {}
279        }
280
281        self.check_for_move(state, loc);
282        terminator.edges()
283    }
284
285    fn apply_call_return_effect(
286        &mut self,
287        state: &mut Self::Domain,
288        _block: BasicBlock,
289        return_places: CallReturnPlaces<'_, 'tcx>,
290    ) {
291        return_places.for_each(|place| state.gen_(place.local));
292    }
293}
294
295impl<'tcx> MaybeRequiresStorage<'_, 'tcx> {
296    /// Kill locals that are fully moved and have not been borrowed.
297    fn check_for_move(&mut self, state: &mut <Self as Analysis<'tcx>>::Domain, loc: Location) {
298        let body = self.borrowed_locals.body();
299        let mut visitor = MoveVisitor { state, borrowed_locals: &mut self.borrowed_locals };
300        visitor.visit_location(body, loc);
301    }
302}
303
304struct MoveVisitor<'a, 'mir, 'tcx> {
305    borrowed_locals: &'a mut BorrowedLocalsResults<'mir, 'tcx>,
306    state: &'a mut DenseBitSet<Local>,
307}
308
309impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, 'tcx> {
310    fn visit_local(&mut self, local: Local, context: PlaceContext, loc: Location) {
311        if PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) == context {
312            self.borrowed_locals.seek_before_primary_effect(loc);
313            if !self.borrowed_locals.get().contains(local) {
314                self.state.kill(local);
315            }
316        }
317    }
318}