]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/traversal.rs
Auto merge of #61203 - memoryruins:bare_trait_objects, r=Centril
[rust.git] / src / librustc / mir / traversal.rs
1 use rustc_data_structures::bit_set::BitSet;
2
3 use super::*;
4
5 /// Preorder traversal of a graph.
6 ///
7 /// Preorder traversal is when each node is visited before an of it's
8 /// successors
9 ///
10 /// ```text
11 ///
12 ///         A
13 ///        / \
14 ///       /   \
15 ///      B     C
16 ///       \   /
17 ///        \ /
18 ///         D
19 /// ```
20 ///
21 /// A preorder traversal of this graph is either `A B D C` or `A C D B`
22 #[derive(Clone)]
23 pub struct Preorder<'a, 'tcx: 'a> {
24     mir: &'a Body<'tcx>,
25     visited: BitSet<BasicBlock>,
26     worklist: Vec<BasicBlock>,
27     root_is_start_block: bool,
28 }
29
30 impl<'a, 'tcx> Preorder<'a, 'tcx> {
31     pub fn new(mir: &'a Body<'tcx>, root: BasicBlock) -> Preorder<'a, 'tcx> {
32         let worklist = vec![root];
33
34         Preorder {
35             mir,
36             visited: BitSet::new_empty(mir.basic_blocks().len()),
37             worklist,
38             root_is_start_block: root == START_BLOCK,
39         }
40     }
41 }
42
43 pub fn preorder<'a, 'tcx>(mir: &'a Body<'tcx>) -> Preorder<'a, 'tcx> {
44     Preorder::new(mir, START_BLOCK)
45 }
46
47 impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> {
48     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
49
50     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
51         while let Some(idx) = self.worklist.pop() {
52             if !self.visited.insert(idx) {
53                 continue;
54             }
55
56             let data = &self.mir[idx];
57
58             if let Some(ref term) = data.terminator {
59                 self.worklist.extend(term.successors());
60             }
61
62             return Some((idx, data));
63         }
64
65         None
66     }
67
68     fn size_hint(&self) -> (usize, Option<usize>) {
69         // All the blocks, minus the number of blocks we've visited.
70         let upper = self.mir.basic_blocks().len() - self.visited.count();
71
72         let lower = if self.root_is_start_block {
73             // We will visit all remaining blocks exactly once.
74             upper
75         } else {
76             self.worklist.len()
77         };
78
79         (lower, Some(upper))
80     }
81 }
82
83 /// Postorder traversal of a graph.
84 ///
85 /// Postorder traversal is when each node is visited after all of it's
86 /// successors, except when the successor is only reachable by a back-edge
87 ///
88 ///
89 /// ```text
90 ///
91 ///         A
92 ///        / \
93 ///       /   \
94 ///      B     C
95 ///       \   /
96 ///        \ /
97 ///         D
98 /// ```
99 ///
100 /// A Postorder traversal of this graph is `D B C A` or `D C B A`
101 pub struct Postorder<'a, 'tcx: 'a> {
102     mir: &'a Body<'tcx>,
103     visited: BitSet<BasicBlock>,
104     visit_stack: Vec<(BasicBlock, Successors<'a>)>,
105     root_is_start_block: bool,
106 }
107
108 impl<'a, 'tcx> Postorder<'a, 'tcx> {
109     pub fn new(mir: &'a Body<'tcx>, root: BasicBlock) -> Postorder<'a, 'tcx> {
110         let mut po = Postorder {
111             mir,
112             visited: BitSet::new_empty(mir.basic_blocks().len()),
113             visit_stack: Vec::new(),
114             root_is_start_block: root == START_BLOCK,
115         };
116
117
118         let data = &po.mir[root];
119
120         if let Some(ref term) = data.terminator {
121             po.visited.insert(root);
122             po.visit_stack.push((root, term.successors()));
123             po.traverse_successor();
124         }
125
126         po
127     }
128
129     fn traverse_successor(&mut self) {
130         // This is quite a complex loop due to 1. the borrow checker not liking it much
131         // and 2. what exactly is going on is not clear
132         //
133         // It does the actual traversal of the graph, while the `next` method on the iterator
134         // just pops off of the stack. `visit_stack` is a stack containing pairs of nodes and
135         // iterators over the successors of those nodes. Each iteration attempts to get the next
136         // node from the top of the stack, then pushes that node and an iterator over the
137         // successors to the top of the stack. This loop only grows `visit_stack`, stopping when
138         // we reach a child that has no children that we haven't already visited.
139         //
140         // For a graph that looks like this:
141         //
142         //         A
143         //        / \
144         //       /   \
145         //      B     C
146         //      |     |
147         //      |     |
148         //      D     |
149         //       \   /
150         //        \ /
151         //         E
152         //
153         // The state of the stack starts out with just the root node (`A` in this case);
154         //     [(A, [B, C])]
155         //
156         // When the first call to `traverse_successor` happens, the following happens:
157         //
158         //     [(B, [D]),  // `B` taken from the successors of `A`, pushed to the
159         //                 // top of the stack along with the successors of `B`
160         //      (A, [C])]
161         //
162         //     [(D, [E]),  // `D` taken from successors of `B`, pushed to stack
163         //      (B, []),
164         //      (A, [C])]
165         //
166         //     [(E, []),   // `E` taken from successors of `D`, pushed to stack
167         //      (D, []),
168         //      (B, []),
169         //      (A, [C])]
170         //
171         // Now that the top of the stack has no successors we can traverse, each item will
172         // be popped off during iteration until we get back to `A`. This yields [E, D, B].
173         //
174         // When we yield `B` and call `traverse_successor`, we push `C` to the stack, but
175         // since we've already visited `E`, that child isn't added to the stack. The last
176         // two iterations yield `C` and finally `A` for a final traversal of [E, D, B, C, A]
177         loop {
178             let bb = if let Some(&mut (_, ref mut iter)) = self.visit_stack.last_mut() {
179                 if let Some(&bb) = iter.next() {
180                     bb
181                 } else {
182                     break;
183                 }
184             } else {
185                 break;
186             };
187
188             if self.visited.insert(bb) {
189                 if let Some(term) = &self.mir[bb].terminator {
190                     self.visit_stack.push((bb, term.successors()));
191                 }
192             }
193         }
194     }
195 }
196
197 pub fn postorder<'a, 'tcx>(mir: &'a Body<'tcx>) -> Postorder<'a, 'tcx> {
198     Postorder::new(mir, START_BLOCK)
199 }
200
201 impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> {
202     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
203
204     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
205         let next = self.visit_stack.pop();
206         if next.is_some() {
207             self.traverse_successor();
208         }
209
210         next.map(|(bb, _)| (bb, &self.mir[bb]))
211     }
212
213     fn size_hint(&self) -> (usize, Option<usize>) {
214         // All the blocks, minus the number of blocks we've visited.
215         let upper = self.mir.basic_blocks().len() - self.visited.count();
216
217         let lower = if self.root_is_start_block {
218             // We will visit all remaining blocks exactly once.
219             upper
220         } else {
221             self.visit_stack.len()
222         };
223
224         (lower, Some(upper))
225     }
226 }
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 Body<'tcx>,
256     blocks: Vec<BasicBlock>,
257     idx: usize
258 }
259
260 impl<'a, 'tcx> ReversePostorder<'a, 'tcx> {
261     pub fn new(mir: &'a Body<'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 Body<'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> {}