]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/liveness.rs
Rollup merge of #66612 - Nadrieril:or-patterns-initial, r=varkor
[rust.git] / src / librustc_mir / util / liveness.rs
1 //! Liveness analysis which computes liveness of MIR local variables at the boundary of basic
2 //! blocks.
3 //!
4 //! This analysis considers references as being used only at the point of the
5 //! borrow. This means that this does not track uses because of references that
6 //! already exist:
7 //!
8 //! ```rust
9 //! fn foo() {
10 //!     x = 0;
11 //!     // `x` is live here ...
12 //!     GLOBAL = &x: *const u32;
13 //!     // ... but not here, even while it can be accessed through `GLOBAL`.
14 //!     foo();
15 //!     x = 1;
16 //!     // `x` is live again here, because it is assigned to `OTHER_GLOBAL`.
17 //!     OTHER_GLOBAL = &x: *const u32;
18 //!     // ...
19 //! }
20 //! ```
21 //!
22 //! This means that users of this analysis still have to check whether
23 //! pre-existing references can be used to access the value (e.g., at movable
24 //! generator yield points, all pre-existing references are invalidated, so this
25 //! doesn't matter).
26
27 use rustc::mir::visit::{
28     PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext, NonUseContext,
29 };
30 use rustc::mir::Local;
31 use rustc::mir::*;
32 use rustc::ty::{self, TyCtxt};
33 use rustc_index::bit_set::BitSet;
34 use rustc_index::vec::{Idx, IndexVec};
35 use rustc_data_structures::work_queue::WorkQueue;
36 use std::fs;
37 use std::io::{self, Write};
38 use std::path::{Path, PathBuf};
39 use crate::transform::MirSource;
40 use crate::util::pretty::{dump_enabled, write_basic_block, write_mir_intro};
41
42 pub type LiveVarSet = BitSet<Local>;
43
44 /// This gives the result of the liveness analysis at the boundary of
45 /// basic blocks.
46 ///
47 /// The `V` type defines the set of variables that we computed
48 /// liveness for. This is often `Local`, in which case we computed
49 /// liveness for all variables -- but it can also be some other type,
50 /// which indicates a subset of the variables within the graph.
51 pub struct LivenessResult {
52     /// Live variables on exit to each basic block. This is equal to
53     /// the union of the `ins` for each successor.
54     pub outs: IndexVec<BasicBlock, LiveVarSet>,
55 }
56
57 /// Computes which local variables are live within the given function
58 /// `mir`, including drops.
59 pub fn liveness_of_locals(
60     body: &Body<'_>,
61 ) -> LivenessResult {
62     let num_live_vars = body.local_decls.len();
63
64     let def_use: IndexVec<_, DefsUses> = body
65         .basic_blocks()
66         .iter()
67         .map(|b| block(b, num_live_vars))
68         .collect();
69
70     let mut outs: IndexVec<_, LiveVarSet> = body
71         .basic_blocks()
72         .indices()
73         .map(|_| LiveVarSet::new_empty(num_live_vars))
74         .collect();
75
76     let mut bits = LiveVarSet::new_empty(num_live_vars);
77
78     // The dirty queue contains the set of basic blocks whose entry sets have changed since they
79     // were last processed. At the start of the analysis, we initialize the queue in post-order to
80     // make it more likely that the entry set for a given basic block will have the effects of all
81     // its successors in the CFG applied before it is processed.
82     //
83     // FIXME(ecstaticmorse): Reverse post-order on the reverse CFG may generate a better iteration
84     // order when cycles are present, but the overhead of computing the reverse CFG may outweigh
85     // any benefits. Benchmark this and find out.
86     let mut dirty_queue: WorkQueue<BasicBlock> = WorkQueue::with_none(body.basic_blocks().len());
87     for (bb, _) in traversal::postorder(body) {
88         dirty_queue.insert(bb);
89     }
90
91     // Add blocks which are not reachable from START_BLOCK to the work queue. These blocks will
92     // be processed after the ones added above.
93     for bb in body.basic_blocks().indices() {
94         dirty_queue.insert(bb);
95     }
96
97     let predecessors = body.predecessors();
98
99     while let Some(bb) = dirty_queue.pop() {
100         // bits = use ∪ (bits - def)
101         bits.overwrite(&outs[bb]);
102         def_use[bb].apply(&mut bits);
103
104         // `bits` now contains the live variables on entry. Therefore,
105         // add `bits` to the `out` set for each predecessor; if those
106         // bits were not already present, then enqueue the predecessor
107         // as dirty.
108         //
109         // (note that `union` returns true if the `self` set changed)
110         for &pred_bb in &predecessors[bb] {
111             if outs[pred_bb].union(&bits) {
112                 dirty_queue.insert(pred_bb);
113             }
114         }
115     }
116
117     LivenessResult { outs }
118 }
119
120 #[derive(Eq, PartialEq, Clone)]
121 pub enum DefUse {
122     Def,
123     Use,
124     Drop,
125 }
126
127 pub fn categorize(context: PlaceContext) -> Option<DefUse> {
128     match context {
129         ///////////////////////////////////////////////////////////////////////////
130         // DEFS
131
132         PlaceContext::MutatingUse(MutatingUseContext::Store) |
133
134         // This is potentially both a def and a use...
135         PlaceContext::MutatingUse(MutatingUseContext::AsmOutput) |
136
137         // We let Call define the result in both the success and
138         // unwind cases. This is not really correct, however it
139         // does not seem to be observable due to the way that we
140         // generate MIR. To do things properly, we would apply
141         // the def in call only to the input from the success
142         // path and not the unwind path. -nmatsakis
143         PlaceContext::MutatingUse(MutatingUseContext::Call) |
144
145         // Storage live and storage dead aren't proper defines, but we can ignore
146         // values that come before them.
147         PlaceContext::NonUse(NonUseContext::StorageLive) |
148         PlaceContext::NonUse(NonUseContext::StorageDead) => Some(DefUse::Def),
149
150         ///////////////////////////////////////////////////////////////////////////
151         // REGULAR USES
152         //
153         // These are uses that occur *outside* of a drop. For the
154         // purposes of NLL, these are special in that **all** the
155         // lifetimes appearing in the variable must be live for each regular use.
156
157         PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) |
158         PlaceContext::MutatingUse(MutatingUseContext::Projection) |
159
160         // Borrows only consider their local used at the point of the borrow.
161         // This won't affect the results since we use this analysis for generators
162         // and we only care about the result at suspension points. Borrows cannot
163         // cross suspension points so this behavior is unproblematic.
164         PlaceContext::MutatingUse(MutatingUseContext::Borrow) |
165         PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) |
166         PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow) |
167         PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow) |
168
169         PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect) |
170         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
171         PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) |
172         PlaceContext::NonUse(NonUseContext::AscribeUserTy) |
173         PlaceContext::MutatingUse(MutatingUseContext::Retag) =>
174             Some(DefUse::Use),
175
176         ///////////////////////////////////////////////////////////////////////////
177         // DROP USES
178         //
179         // These are uses that occur in a DROP (a MIR drop, not a
180         // call to `std::mem::drop()`). For the purposes of NLL,
181         // uses in drop are special because `#[may_dangle]`
182         // attributes can affect whether lifetimes must be live.
183
184         PlaceContext::MutatingUse(MutatingUseContext::Drop) =>
185             Some(DefUse::Drop),
186
187         // Debug info is neither def nor use.
188         PlaceContext::NonUse(NonUseContext::VarDebugInfo) => None,
189     }
190 }
191
192 struct DefsUsesVisitor
193 {
194     defs_uses: DefsUses,
195 }
196
197 #[derive(Eq, PartialEq, Clone)]
198 struct DefsUses {
199     defs: LiveVarSet,
200     uses: LiveVarSet,
201 }
202
203 impl DefsUses {
204     fn apply(&self, bits: &mut LiveVarSet) -> bool {
205         bits.subtract(&self.defs) | bits.union(&self.uses)
206     }
207
208     fn add_def(&mut self, index: Local) {
209         // If it was used already in the block, remove that use
210         // now that we found a definition.
211         //
212         // Example:
213         //
214         //     // Defs = {X}, Uses = {}
215         //     X = 5
216         //     // Defs = {}, Uses = {X}
217         //     use(X)
218         self.uses.remove(index);
219         self.defs.insert(index);
220     }
221
222     fn add_use(&mut self, index: Local) {
223         // Inverse of above.
224         //
225         // Example:
226         //
227         //     // Defs = {}, Uses = {X}
228         //     use(X)
229         //     // Defs = {X}, Uses = {}
230         //     X = 5
231         //     // Defs = {}, Uses = {X}
232         //     use(X)
233         self.defs.remove(index);
234         self.uses.insert(index);
235     }
236 }
237
238 impl<'tcx> Visitor<'tcx> for DefsUsesVisitor
239 {
240     fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
241         match categorize(context) {
242             Some(DefUse::Def) => self.defs_uses.add_def(local),
243             Some(DefUse::Use) | Some(DefUse::Drop) => self.defs_uses.add_use(local),
244             _ => (),
245         }
246     }
247 }
248
249 fn block(
250     b: &BasicBlockData<'_>,
251     locals: usize,
252 ) -> DefsUses {
253     let mut visitor = DefsUsesVisitor {
254         defs_uses: DefsUses {
255             defs: LiveVarSet::new_empty(locals),
256             uses: LiveVarSet::new_empty(locals),
257         },
258     };
259
260     let dummy_location = Location {
261         block: BasicBlock::new(0),
262         statement_index: 0,
263     };
264
265     // Visit the various parts of the basic block in reverse. If we go
266     // forward, the logic in `add_def` and `add_use` would be wrong.
267     visitor.visit_terminator(b.terminator(), dummy_location);
268     for statement in b.statements.iter().rev() {
269         visitor.visit_statement(statement, dummy_location);
270     }
271
272     visitor.defs_uses
273 }
274
275 pub fn dump_mir<'tcx>(
276     tcx: TyCtxt<'tcx>,
277     pass_name: &str,
278     source: MirSource<'tcx>,
279     body: &Body<'tcx>,
280     result: &LivenessResult,
281 ) {
282     if !dump_enabled(tcx, pass_name, source) {
283         return;
284     }
285     let node_path = ty::print::with_forced_impl_filename_line(|| {
286         // see notes on #41697 below
287         tcx.def_path_str(source.def_id())
288     });
289     dump_matched_mir_node(tcx, pass_name, &node_path, source, body, result);
290 }
291
292 fn dump_matched_mir_node<'tcx>(
293     tcx: TyCtxt<'tcx>,
294     pass_name: &str,
295     node_path: &str,
296     source: MirSource<'tcx>,
297     body: &Body<'tcx>,
298     result: &LivenessResult,
299 ) {
300     let mut file_path = PathBuf::new();
301     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
302     let item_id = tcx.hir().as_local_hir_id(source.def_id()).unwrap();
303     let file_name = format!("rustc.node{}{}-liveness.mir", item_id, pass_name);
304     file_path.push(&file_name);
305     let _ = fs::File::create(&file_path).and_then(|mut file| {
306         writeln!(file, "// MIR local liveness analysis for `{}`", node_path)?;
307         writeln!(file, "// source = {:?}", source)?;
308         writeln!(file, "// pass_name = {}", pass_name)?;
309         writeln!(file, "")?;
310         write_mir_fn(tcx, source, body, &mut file, result)?;
311         Ok(())
312     });
313 }
314
315 pub fn write_mir_fn<'tcx>(
316     tcx: TyCtxt<'tcx>,
317     src: MirSource<'tcx>,
318     body: &Body<'tcx>,
319     w: &mut dyn Write,
320     result: &LivenessResult,
321 ) -> io::Result<()> {
322     write_mir_intro(tcx, src, body, w)?;
323     for block in body.basic_blocks().indices() {
324         let print = |w: &mut dyn Write, prefix, result: &IndexVec<BasicBlock, LiveVarSet>| {
325             let live: Vec<String> = result[block]
326                 .iter()
327                 .map(|local| format!("{:?}", local))
328                 .collect();
329             writeln!(w, "{} {{{}}}", prefix, live.join(", "))
330         };
331         write_basic_block(tcx, block, body, &mut |_, _| Ok(()), w)?;
332         print(w, "   ", &result.outs)?;
333         if block.index() + 1 != body.basic_blocks().len() {
334             writeln!(w, "")?;
335         }
336     }
337
338     writeln!(w, "}}")?;
339     Ok(())
340 }