]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/liveness.rs
Changes the type `mir::Mir` into `mir::Body`
[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_data_structures::bit_set::BitSet;
34 use rustc_data_structures::indexed_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<'tcx>(
60     mir: &Body<'tcx>,
61 ) -> LivenessResult {
62     let num_live_vars = mir.local_decls.len();
63
64     let def_use: IndexVec<_, DefsUses> = mir
65         .basic_blocks()
66         .iter()
67         .map(|b| block(b, num_live_vars))
68         .collect();
69
70     let mut outs: IndexVec<_, LiveVarSet> = mir
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     // queue of things that need to be re-processed, and a set containing
79     // the things currently in the queue
80     let mut dirty_queue: WorkQueue<BasicBlock> = WorkQueue::with_all(mir.basic_blocks().len());
81
82     let predecessors = mir.predecessors();
83
84     while let Some(bb) = dirty_queue.pop() {
85         // bits = use ∪ (bits - def)
86         bits.overwrite(&outs[bb]);
87         def_use[bb].apply(&mut bits);
88
89         // `bits` now contains the live variables on entry. Therefore,
90         // add `bits` to the `out` set for each predecessor; if those
91         // bits were not already present, then enqueue the predecessor
92         // as dirty.
93         //
94         // (note that `union` returns true if the `self` set changed)
95         for &pred_bb in &predecessors[bb] {
96             if outs[pred_bb].union(&bits) {
97                 dirty_queue.insert(pred_bb);
98             }
99         }
100     }
101
102     LivenessResult { outs }
103 }
104
105 #[derive(Eq, PartialEq, Clone)]
106 pub enum DefUse {
107     Def,
108     Use,
109     Drop,
110 }
111
112 pub fn categorize<'tcx>(context: PlaceContext) -> Option<DefUse> {
113     match context {
114         ///////////////////////////////////////////////////////////////////////////
115         // DEFS
116
117         PlaceContext::MutatingUse(MutatingUseContext::Store) |
118
119         // This is potentially both a def and a use...
120         PlaceContext::MutatingUse(MutatingUseContext::AsmOutput) |
121
122         // We let Call define the result in both the success and
123         // unwind cases. This is not really correct, however it
124         // does not seem to be observable due to the way that we
125         // generate MIR. To do things properly, we would apply
126         // the def in call only to the input from the success
127         // path and not the unwind path. -nmatsakis
128         PlaceContext::MutatingUse(MutatingUseContext::Call) |
129
130         // Storage live and storage dead aren't proper defines, but we can ignore
131         // values that come before them.
132         PlaceContext::NonUse(NonUseContext::StorageLive) |
133         PlaceContext::NonUse(NonUseContext::StorageDead) => Some(DefUse::Def),
134
135         ///////////////////////////////////////////////////////////////////////////
136         // REGULAR USES
137         //
138         // These are uses that occur *outside* of a drop. For the
139         // purposes of NLL, these are special in that **all** the
140         // lifetimes appearing in the variable must be live for each regular use.
141
142         PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) |
143         PlaceContext::MutatingUse(MutatingUseContext::Projection) |
144
145         // Borrows only consider their local used at the point of the borrow.
146         // This won't affect the results since we use this analysis for generators
147         // and we only care about the result at suspension points. Borrows cannot
148         // cross suspension points so this behavior is unproblematic.
149         PlaceContext::MutatingUse(MutatingUseContext::Borrow) |
150         PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) |
151         PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow) |
152         PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow) |
153
154         PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect) |
155         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
156         PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) |
157         PlaceContext::NonUse(NonUseContext::AscribeUserTy) |
158         PlaceContext::MutatingUse(MutatingUseContext::Retag) =>
159             Some(DefUse::Use),
160
161         ///////////////////////////////////////////////////////////////////////////
162         // DROP USES
163         //
164         // These are uses that occur in a DROP (a MIR drop, not a
165         // call to `std::mem::drop()`). For the purposes of NLL,
166         // uses in drop are special because `#[may_dangle]`
167         // attributes can affect whether lifetimes must be live.
168
169         PlaceContext::MutatingUse(MutatingUseContext::Drop) =>
170             Some(DefUse::Drop),
171     }
172 }
173
174 struct DefsUsesVisitor
175 {
176     defs_uses: DefsUses,
177 }
178
179 #[derive(Eq, PartialEq, Clone)]
180 struct DefsUses {
181     defs: LiveVarSet,
182     uses: LiveVarSet,
183 }
184
185 impl DefsUses {
186     fn apply(&self, bits: &mut LiveVarSet) -> bool {
187         bits.subtract(&self.defs) | bits.union(&self.uses)
188     }
189
190     fn add_def(&mut self, index: Local) {
191         // If it was used already in the block, remove that use
192         // now that we found a definition.
193         //
194         // Example:
195         //
196         //     // Defs = {X}, Uses = {}
197         //     X = 5
198         //     // Defs = {}, Uses = {X}
199         //     use(X)
200         self.uses.remove(index);
201         self.defs.insert(index);
202     }
203
204     fn add_use(&mut self, index: Local) {
205         // Inverse of above.
206         //
207         // Example:
208         //
209         //     // Defs = {}, Uses = {X}
210         //     use(X)
211         //     // Defs = {X}, Uses = {}
212         //     X = 5
213         //     // Defs = {}, Uses = {X}
214         //     use(X)
215         self.defs.remove(index);
216         self.uses.insert(index);
217     }
218 }
219
220 impl<'tcx> Visitor<'tcx> for DefsUsesVisitor
221 {
222     fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
223         match categorize(context) {
224             Some(DefUse::Def) => self.defs_uses.add_def(local),
225             Some(DefUse::Use) | Some(DefUse::Drop) => self.defs_uses.add_use(local),
226             _ => (),
227         }
228     }
229 }
230
231 fn block<'tcx>(
232     b: &BasicBlockData<'tcx>,
233     locals: usize,
234 ) -> DefsUses {
235     let mut visitor = DefsUsesVisitor {
236         defs_uses: DefsUses {
237             defs: LiveVarSet::new_empty(locals),
238             uses: LiveVarSet::new_empty(locals),
239         },
240     };
241
242     let dummy_location = Location {
243         block: BasicBlock::new(0),
244         statement_index: 0,
245     };
246
247     // Visit the various parts of the basic block in reverse. If we go
248     // forward, the logic in `add_def` and `add_use` would be wrong.
249     visitor.visit_terminator(b.terminator(), dummy_location);
250     for statement in b.statements.iter().rev() {
251         visitor.visit_statement(statement, dummy_location);
252     }
253
254     visitor.defs_uses
255 }
256
257 pub fn dump_mir<'a, 'tcx>(
258     tcx: TyCtxt<'a, 'tcx, 'tcx>,
259     pass_name: &str,
260     source: MirSource<'tcx>,
261     mir: &Body<'tcx>,
262     result: &LivenessResult,
263 ) {
264     if !dump_enabled(tcx, pass_name, source) {
265         return;
266     }
267     let node_path = ty::print::with_forced_impl_filename_line(|| {
268         // see notes on #41697 below
269         tcx.def_path_str(source.def_id())
270     });
271     dump_matched_mir_node(tcx, pass_name, &node_path, source, mir, result);
272 }
273
274 fn dump_matched_mir_node<'a, 'tcx>(
275     tcx: TyCtxt<'a, 'tcx, 'tcx>,
276     pass_name: &str,
277     node_path: &str,
278     source: MirSource<'tcx>,
279     mir: &Body<'tcx>,
280     result: &LivenessResult,
281 ) {
282     let mut file_path = PathBuf::new();
283     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
284     let item_id = tcx.hir().as_local_hir_id(source.def_id()).unwrap();
285     let file_name = format!("rustc.node{}{}-liveness.mir", item_id, pass_name);
286     file_path.push(&file_name);
287     let _ = fs::File::create(&file_path).and_then(|mut file| {
288         writeln!(file, "// MIR local liveness analysis for `{}`", node_path)?;
289         writeln!(file, "// source = {:?}", source)?;
290         writeln!(file, "// pass_name = {}", pass_name)?;
291         writeln!(file, "")?;
292         write_mir_fn(tcx, source, mir, &mut file, result)?;
293         Ok(())
294     });
295 }
296
297 pub fn write_mir_fn<'a, 'tcx>(
298     tcx: TyCtxt<'a, 'tcx, 'tcx>,
299     src: MirSource<'tcx>,
300     mir: &Body<'tcx>,
301     w: &mut dyn Write,
302     result: &LivenessResult,
303 ) -> io::Result<()> {
304     write_mir_intro(tcx, src, mir, w)?;
305     for block in mir.basic_blocks().indices() {
306         let print = |w: &mut dyn Write, prefix, result: &IndexVec<BasicBlock, LiveVarSet>| {
307             let live: Vec<String> = result[block]
308                 .iter()
309                 .map(|local| format!("{:?}", local))
310                 .collect();
311             writeln!(w, "{} {{{}}}", prefix, live.join(", "))
312         };
313         write_basic_block(tcx, block, mir, &mut |_, _| Ok(()), w)?;
314         print(w, "   ", &result.outs)?;
315         if block.index() + 1 != mir.basic_blocks().len() {
316             writeln!(w, "")?;
317         }
318     }
319
320     writeln!(w, "}}")?;
321     Ok(())
322 }