forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_tree.rs
More file actions
347 lines (277 loc) · 11.1 KB
/
Copy pathloop_tree.rs
File metadata and controls
347 lines (277 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use id_arena::{Arena, Id};
use fxhash::FxHashMap;
use super::{cfg::ControlFlowGraph, domtree::DomTree};
use crate::ir::BasicBlockId;
#[derive(Debug, Default, Clone)]
pub struct LoopTree {
/// Stores loops.
/// The index of an outer loops is guaranteed to be lower than its inner
/// loops because loops are found in RPO.
loops: Arena<Loop>,
/// Maps blocks to its contained loop.
/// If the block is contained by multiple nested loops, then the block is
/// mapped to the innermost loop.
block_to_loop: FxHashMap<BasicBlockId, LoopId>,
}
pub type LoopId = Id<Loop>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Loop {
/// A header of the loop.
pub header: BasicBlockId,
/// A parent loop that includes the loop.
pub parent: Option<LoopId>,
/// Child loops that the loop includes.
pub children: Vec<LoopId>,
}
impl LoopTree {
pub fn compute(cfg: &ControlFlowGraph, domtree: &DomTree) -> Self {
let mut tree = LoopTree::default();
// Find loop headers in RPO, this means outer loops are guaranteed to be
// inserted first, then its inner loops are inserted.
for &block in domtree.rpo() {
for &pred in cfg.preds(block) {
if domtree.dominates(block, pred) {
let loop_data = Loop {
header: block,
parent: None,
children: Vec::new(),
};
tree.loops.alloc(loop_data);
break;
}
}
}
tree.analyze_loops(cfg, domtree);
tree
}
/// Returns all blocks in the loop.
pub fn iter_blocks_post_order<'a, 'b>(
&'a self,
cfg: &'b ControlFlowGraph,
lp: LoopId,
) -> BlocksInLoopPostOrder<'a, 'b> {
BlocksInLoopPostOrder::new(self, cfg, lp)
}
/// Returns all loops in a function body.
/// An outer loop is guaranteed to be iterated before its inner loops.
pub fn loops(&self) -> impl Iterator<Item = LoopId> + '_ {
self.loops.iter().map(|(id, _)| id)
}
/// Returns number of loops found.
pub fn loop_num(&self) -> usize {
self.loops.len()
}
/// Returns `true` if the `block` is in the `lp`.
pub fn is_block_in_loop(&self, block: BasicBlockId, lp: LoopId) -> bool {
let mut loop_of_block = self.loop_of_block(block);
while let Some(cur_lp) = loop_of_block {
if lp == cur_lp {
return true;
}
loop_of_block = self.parent_loop(cur_lp);
}
false
}
/// Returns header block of the `lp`.
pub fn loop_header(&self, lp: LoopId) -> BasicBlockId {
self.loops[lp].header
}
/// Get parent loop of the `lp` if exists.
pub fn parent_loop(&self, lp: LoopId) -> Option<LoopId> {
self.loops[lp].parent
}
/// Returns the loop that the `block` belongs to.
/// If the `block` belongs to multiple loops, then returns the innermost
/// loop.
pub fn loop_of_block(&self, block: BasicBlockId) -> Option<LoopId> {
self.block_to_loop.get(&block).copied()
}
/// Analyze loops. This method does
/// 1. Mapping each blocks to its contained loop.
/// 2. Setting parent and child of the loops.
fn analyze_loops(&mut self, cfg: &ControlFlowGraph, domtree: &DomTree) {
let mut worklist = vec![];
// Iterate loops reversely to ensure analyze inner loops first.
let loops_rev: Vec<_> = self.loops.iter().rev().map(|(id, _)| id).collect();
for cur_lp in loops_rev {
let cur_lp_header = self.loop_header(cur_lp);
// Add predecessors of the loop header to worklist.
for &block in cfg.preds(cur_lp_header) {
if domtree.dominates(cur_lp_header, block) {
worklist.push(block);
}
}
while let Some(block) = worklist.pop() {
match self.block_to_loop.get(&block).copied() {
Some(lp_of_block) => {
let outermost_parent = self.outermost_parent(lp_of_block);
// If outermost parent is current loop, then the block is already visited.
if outermost_parent == cur_lp {
continue;
} else {
self.loops[cur_lp].children.push(outermost_parent);
self.loops[outermost_parent].parent = cur_lp.into();
let lp_header_of_block = self.loop_header(lp_of_block);
worklist.extend(cfg.preds(lp_header_of_block));
}
}
// If the block is not mapped to any loops, then map it to the loop.
None => {
self.map_block(block, cur_lp);
// If block is not loop header, then add its predecessors to the worklist.
if block != cur_lp_header {
worklist.extend(cfg.preds(block));
}
}
}
}
}
}
/// Returns the outermost parent loop of `lp`. If `lp` doesn't have any
/// parent, then returns `lp` itself.
fn outermost_parent(&self, mut lp: LoopId) -> LoopId {
while let Some(parent) = self.parent_loop(lp) {
lp = parent;
}
lp
}
/// Map `block` to `lp`.
fn map_block(&mut self, block: BasicBlockId, lp: LoopId) {
self.block_to_loop.insert(block, lp);
}
}
pub struct BlocksInLoopPostOrder<'a, 'b> {
lpt: &'a LoopTree,
cfg: &'b ControlFlowGraph,
lp: LoopId,
stack: Vec<BasicBlockId>,
block_state: FxHashMap<BasicBlockId, BlockState>,
}
impl<'a, 'b> BlocksInLoopPostOrder<'a, 'b> {
fn new(lpt: &'a LoopTree, cfg: &'b ControlFlowGraph, lp: LoopId) -> Self {
let loop_header = lpt.loop_header(lp);
Self {
lpt,
cfg,
lp,
stack: vec![loop_header],
block_state: FxHashMap::default(),
}
}
}
impl<'a, 'b> Iterator for BlocksInLoopPostOrder<'a, 'b> {
type Item = BasicBlockId;
fn next(&mut self) -> Option<Self::Item> {
while let Some(&block) = self.stack.last() {
match self.block_state.get(&block) {
// The block is already visited, but not returned from the iterator,
// so mark the block as `Finished` and return the block.
Some(BlockState::Visited) => {
let block = self.stack.pop().unwrap();
self.block_state.insert(block, BlockState::Finished);
return Some(block);
}
// The block is already returned, so just remove the block from the stack.
Some(BlockState::Finished) => {
self.stack.pop().unwrap();
}
// The block is not visited yet, so push its unvisited in-loop successors to the
// stack and mark the block as `Visited`.
None => {
self.block_state.insert(block, BlockState::Visited);
for &succ in self.cfg.succs(block) {
if self.block_state.get(&succ).is_none()
&& self.lpt.is_block_in_loop(succ, self.lp)
{
self.stack.push(succ);
}
}
}
}
}
None
}
}
enum BlockState {
Visited,
Finished,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::{body_builder::BodyBuilder, FunctionBody, FunctionId, SourceInfo, TypeId};
fn compute_loop(func: &FunctionBody) -> LoopTree {
let cfg = ControlFlowGraph::compute(func);
let domtree = DomTree::compute(&cfg);
LoopTree::compute(&cfg, &domtree)
}
fn body_builder() -> BodyBuilder {
BodyBuilder::new(FunctionId(0), SourceInfo::dummy())
}
#[test]
fn simple_loop() {
let mut builder = body_builder();
let entry = builder.current_block();
let block1 = builder.make_block();
let block2 = builder.make_block();
let dummy_ty = TypeId(0);
let v0 = builder.make_imm_from_bool(false, dummy_ty);
builder.branch(v0, block1, block2, SourceInfo::dummy());
builder.move_to_block(block1);
builder.jump(entry, SourceInfo::dummy());
builder.move_to_block(block2);
let dummy_value = builder.make_unit(dummy_ty);
builder.ret(dummy_value, SourceInfo::dummy());
let func = builder.build();
let lpt = compute_loop(&func);
assert_eq!(lpt.loop_num(), 1);
let lp = lpt.loops().next().unwrap();
assert!(lpt.is_block_in_loop(entry, lp));
assert_eq!(lpt.loop_of_block(entry), Some(lp));
assert!(lpt.is_block_in_loop(block1, lp));
assert_eq!(lpt.loop_of_block(block1), Some(lp));
assert!(!lpt.is_block_in_loop(block2, lp));
assert!(lpt.loop_of_block(block2).is_none());
assert_eq!(lpt.loop_header(lp), entry);
}
#[test]
fn nested_loop() {
let mut builder = body_builder();
let entry = builder.current_block();
let block1 = builder.make_block();
let block2 = builder.make_block();
let block3 = builder.make_block();
let dummy_ty = TypeId(0);
let v0 = builder.make_imm_from_bool(false, dummy_ty);
builder.branch(v0, block1, block3, SourceInfo::dummy());
builder.move_to_block(block1);
builder.branch(v0, entry, block2, SourceInfo::dummy());
builder.move_to_block(block2);
builder.jump(block1, SourceInfo::dummy());
builder.move_to_block(block3);
let dummy_value = builder.make_unit(dummy_ty);
builder.ret(dummy_value, SourceInfo::dummy());
let func = builder.build();
let lpt = compute_loop(&func);
assert_eq!(lpt.loop_num(), 2);
let mut loops = lpt.loops();
let outer_lp = loops.next().unwrap();
let inner_lp = loops.next().unwrap();
assert!(lpt.is_block_in_loop(entry, outer_lp));
assert!(!lpt.is_block_in_loop(entry, inner_lp));
assert_eq!(lpt.loop_of_block(entry), Some(outer_lp));
assert!(lpt.is_block_in_loop(block1, outer_lp));
assert!(lpt.is_block_in_loop(block1, inner_lp));
assert_eq!(lpt.loop_of_block(block1), Some(inner_lp));
assert!(lpt.is_block_in_loop(block2, outer_lp));
assert!(lpt.is_block_in_loop(block2, inner_lp));
assert_eq!(lpt.loop_of_block(block2), Some(inner_lp));
assert!(!lpt.is_block_in_loop(block3, outer_lp));
assert!(!lpt.is_block_in_loop(block3, inner_lp));
assert!(lpt.loop_of_block(block3).is_none());
assert!(lpt.parent_loop(outer_lp).is_none());
assert_eq!(lpt.parent_loop(inner_lp), Some(outer_lp));
assert_eq!(lpt.loop_header(outer_lp), entry);
assert_eq!(lpt.loop_header(inner_lp), block1);
}
}