]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/traversal.rs
Auto merge of #52681 - pnkfelix:z-borrowck-migrate, r=nikomatsakis
[rust.git] / src / librustc / mir / traversal.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc_data_structures::bitvec::BitVector;
12
13 use super::*;
14
15 /// Preorder traversal of a graph.
16 ///
17 /// Preorder traversal is when each node is visited before an of it's
18 /// successors
19 ///
20 /// ```text
21 ///
22 ///         A
23 ///        / \
24 ///       /   \
25 ///      B     C
26 ///       \   /
27 ///        \ /
28 ///         D
29 /// ```
30 ///
31 /// A preorder traversal of this graph is either `A B D C` or `A C D B`
32 #[derive(Clone)]
33 pub struct Preorder<'a, 'tcx: 'a> {
34     mir: &'a Mir<'tcx>,
35     visited: BitVector<BasicBlock>,
36     worklist: Vec<BasicBlock>,
37 }
38
39 impl<'a, 'tcx> Preorder<'a, 'tcx> {
40     pub fn new(mir: &'a Mir<'tcx>, root: BasicBlock) -> Preorder<'a, 'tcx> {
41         let worklist = vec![root];
42
43         Preorder {
44             mir,
45             visited: BitVector::new(mir.basic_blocks().len()),
46             worklist,
47         }
48     }
49 }
50
51 pub fn preorder<'a, 'tcx>(mir: &'a Mir<'tcx>) -> Preorder<'a, 'tcx> {
52     Preorder::new(mir, START_BLOCK)
53 }
54
55 impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> {
56     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
57
58     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
59         while let Some(idx) = self.worklist.pop() {
60             if !self.visited.insert(idx) {
61                 continue;
62             }
63
64             let data = &self.mir[idx];
65
66             if let Some(ref term) = data.terminator {
67                 for &succ in term.successors() {
68                     self.worklist.push(succ);
69                 }
70             }
71
72             return Some((idx, data));
73         }
74
75         None
76     }
77
78     fn size_hint(&self) -> (usize, Option<usize>) {
79         // All the blocks, minus the number of blocks we've visited.
80         let remaining = self.mir.basic_blocks().len() - self.visited.count();
81
82         // We will visit all remaining blocks exactly once.
83         (remaining, Some(remaining))
84     }
85 }
86
87 impl<'a, 'tcx> ExactSizeIterator for Preorder<'a, 'tcx> {}
88
89 /// Postorder traversal of a graph.
90 ///
91 /// Postorder traversal is when each node is visited after all of it's
92 /// successors, except when the successor is only reachable by a back-edge
93 ///
94 ///
95 /// ```text
96 ///
97 ///         A
98 ///        / \
99 ///       /   \
100 ///      B     C
101 ///       \   /
102 ///        \ /
103 ///         D
104 /// ```
105 ///
106 /// A Postorder traversal of this graph is `D B C A` or `D C B A`
107 pub struct Postorder<'a, 'tcx: 'a> {
108     mir: &'a Mir<'tcx>,
109     visited: BitVector<BasicBlock>,
110     visit_stack: Vec<(BasicBlock, Successors<'a>)>
111 }
112
113 impl<'a, 'tcx> Postorder<'a, 'tcx> {
114     pub fn new(mir: &'a Mir<'tcx>, root: BasicBlock) -> Postorder<'a, 'tcx> {
115         let mut po = Postorder {
116             mir,
117             visited: BitVector::new(mir.basic_blocks().len()),
118             visit_stack: Vec::new()
119         };
120
121
122         let data = &po.mir[root];
123
124         if let Some(ref term) = data.terminator {
125             po.visited.insert(root);
126             po.visit_stack.push((root, term.successors()));
127             po.traverse_successor();
128         }
129
130         po
131     }
132
133     fn traverse_successor(&mut self) {
134         // This is quite a complex loop due to 1. the borrow checker not liking it much
135         // and 2. what exactly is going on is not clear
136         //
137         // It does the actual traversal of the graph, while the `next` method on the iterator
138         // just pops off of the stack. `visit_stack` is a stack containing pairs of nodes and
139         // iterators over the sucessors of those nodes. Each iteration attempts to get the next
140         // node from the top of the stack, then pushes that node and an iterator over the
141         // successors to the top of the stack. This loop only grows `visit_stack`, stopping when
142         // we reach a child that has no children that we haven't already visited.
143         //
144         // For a graph that looks like this:
145         //
146         //         A
147         //        / \
148         //       /   \
149         //      B     C
150         //      |     |
151         //      |     |
152         //      D     |
153         //       \   /
154         //        \ /
155         //         E
156         //
157         // The state of the stack starts out with just the root node (`A` in this case);
158         //     [(A, [B, C])]
159         //
160         // When the first call to `traverse_sucessor` happens, the following happens:
161         //
162         //     [(B, [D]),  // `B` taken from the successors of `A`, pushed to the
163         //                 // top of the stack along with the successors of `B`
164         //      (A, [C])]
165         //
166         //     [(D, [E]),  // `D` taken from successors of `B`, pushed to stack
167         //      (B, []),
168         //      (A, [C])]
169         //
170         //     [(E, []),   // `E` taken from successors of `D`, pushed to stack
171         //      (D, []),
172         //      (B, []),
173         //      (A, [C])]
174         //
175         // Now that the top of the stack has no successors we can traverse, each item will
176         // be popped off during iteration until we get back to `A`. This yeilds [E, D, B].
177         //
178         // When we yield `B` and call `traverse_successor`, we push `C` to the stack, but
179         // since we've already visited `E`, that child isn't added to the stack. The last
180         // two iterations yield `C` and finally `A` for a final traversal of [E, D, B, C, A]
181         loop {
182             let bb = if let Some(&mut (_, ref mut iter)) = self.visit_stack.last_mut() {
183                 if let Some(&bb) = iter.next() {
184                     bb
185                 } else {
186                     break;
187                 }
188             } else {
189                 break;
190             };
191
192             if self.visited.insert(bb) {
193                 if let Some(term) = &self.mir[bb].terminator {
194                     self.visit_stack.push((bb, term.successors()));
195                 }
196             }
197         }
198     }
199 }
200
201 pub fn postorder<'a, 'tcx>(mir: &'a Mir<'tcx>) -> Postorder<'a, 'tcx> {
202     Postorder::new(mir, START_BLOCK)
203 }
204
205 impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> {
206     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
207
208     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
209         let next = self.visit_stack.pop();
210         if next.is_some() {
211             self.traverse_successor();
212         }
213
214         next.map(|(bb, _)| (bb, &self.mir[bb]))
215     }
216
217     fn size_hint(&self) -> (usize, Option<usize>) {
218         // All the blocks, minus the number of blocks we've visited.
219         let remaining = self.mir.basic_blocks().len() - self.visited.count();
220
221         // We will visit all remaining blocks exactly once.
222         (remaining, Some(remaining))
223     }
224 }
225
226 impl<'a, 'tcx> ExactSizeIterator for Postorder<'a, 'tcx> {}
227
228 /// Reverse postorder traversal of a graph
229 ///
230 /// Reverse postorder is the reverse order of a postorder traversal.
231 /// This is different to a preorder traversal and represents a natural
232 /// linearization of control-flow.
233 ///
234 /// ```text
235 ///
236 ///         A
237 ///        / \
238 ///       /   \
239 ///      B     C
240 ///       \   /
241 ///        \ /
242 ///         D
243 /// ```
244 ///
245 /// A reverse postorder traversal of this graph is either `A B C D` or `A C B D`
246 /// Note that for a graph containing no loops (i.e. A DAG), this is equivalent to
247 /// a topological sort.
248 ///
249 /// Construction of a `ReversePostorder` traversal requires doing a full
250 /// postorder traversal of the graph, therefore this traversal should be
251 /// constructed as few times as possible. Use the `reset` method to be able
252 /// to re-use the traversal
253 #[derive(Clone)]
254 pub struct ReversePostorder<'a, 'tcx: 'a> {
255     mir: &'a Mir<'tcx>,
256     blocks: Vec<BasicBlock>,
257     idx: usize
258 }
259
260 impl<'a, 'tcx> ReversePostorder<'a, 'tcx> {
261     pub fn new(mir: &'a Mir<'tcx>, root: BasicBlock) -> ReversePostorder<'a, 'tcx> {
262         let blocks : Vec<_> = Postorder::new(mir, root).map(|(bb, _)| bb).collect();
263
264         let len = blocks.len();
265
266         ReversePostorder {
267             mir,
268             blocks,
269             idx: len
270         }
271     }
272
273     pub fn reset(&mut self) {
274         self.idx = self.blocks.len();
275     }
276 }
277
278
279 pub fn reverse_postorder<'a, 'tcx>(mir: &'a Mir<'tcx>) -> ReversePostorder<'a, 'tcx> {
280     ReversePostorder::new(mir, START_BLOCK)
281 }
282
283 impl<'a, 'tcx> Iterator for ReversePostorder<'a, 'tcx> {
284     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
285
286     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
287         if self.idx == 0 { return None; }
288         self.idx -= 1;
289
290         self.blocks.get(self.idx).map(|&bb| (bb, &self.mir[bb]))
291     }
292
293     fn size_hint(&self) -> (usize, Option<usize>) {
294         (self.idx, Some(self.idx))
295     }
296 }
297
298 impl<'a, 'tcx> ExactSizeIterator for ReversePostorder<'a, 'tcx> {}