-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtwo_way.rs
More file actions
303 lines (267 loc) · 11 KB
/
two_way.rs
File metadata and controls
303 lines (267 loc) · 11 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
use crate::function::structure::{ControlFlowGraph, Loop, LoopKind};
use crate::graph::{NodeId, NodeMap, NodeSet, Order};
/// Returns all pre-tested loop header nodes and post-tested loop latching nodes that should be
/// excluded from two-way conditional (if-statement) structuring.
///
/// Note a post-tested loop may have a if-statement as a header (e.g. `do { if (...) {`).
/// A pre-tested loop may have an if-statement as a latching, but a placeholder node will be
/// inserted in this case (see [`ControlFlowGraph::insert_placeholder_nodes`]).
pub fn ignored_loop_headers(loops: &NodeMap<Loop>) -> NodeSet {
loops
.values()
.map(|l| match l.kind {
LoopKind::PreTested => l.header,
LoopKind::PostTested => l.latching,
})
.collect()
}
impl ControlFlowGraph {
/// Identifies all 2-way conditionals (`if`-statements) in the control flow graph, returning a
/// map of header nodes to their corresponding follow nodes, using the algorithm described in
/// Figure 6.31 of "Cristina Cifuentes. Reverse Compilation Techniques. PhD thesis, Queensland
/// University of Technology, 1994".
///
/// Note multiple headers may share the same follow node if they are nested.
///
/// This should be called after structuring compound short-circuit conditionals, as these might
/// be used in header nodes (e.g. `if (a && b) { ... }`).
///
/// # Overview
///
/// The analysis uses [immediate dominators](crate::graph::Graph::immediate_dominators).
/// The graph is traversed in depth-first post-order (reverse) so nested structures are handled
/// first. An `unresolved` set records header nodes for which follow nodes haven't yet been
/// found. The follow node is the maximum node with the header as its immediate dominator, and
/// at least 2 predecessors (for 2 paths from the header). If this follow cannot be found, the
/// header is added to `unresolved`. When a follow node is found, all `unresolved` header nodes
/// are assigned that follow node.
pub fn find_2_way_conditionals(&self, ignored_headers: &NodeSet) -> NodeMap<NodeId> {
// Find immediate dominators
let idom = self.immediate_dominators();
// Nodes for which the follow node has not yet been found
let mut unresolved = NodeSet::new();
// Maps header nodes to follow nodes where branches join back together
let mut follow = NodeMap::with_capacity_for(self);
let post_order = self.depth_first(Order::PostOrder);
for &m in &post_order.traversal {
if self[m].out_degree() == 2 && !ignored_headers.contains(m) {
let n = self
.iter_id()
.filter(|&i| idom[i] == m && self[i].in_degree() >= 2)
// Look for "lowest" node in graph
.max_by(|&a, &b| post_order.cmp(a, b).reverse());
match n {
Some(n) => {
follow.insert(m, n);
for x in unresolved.iter() {
follow.insert(x, n);
}
unresolved.clear();
}
None => {
unresolved.insert(m);
}
}
}
}
follow
}
}
#[cfg(test)]
mod tests {
use crate::function::structure::{ignored_loop_headers, ConditionalKind, Structure};
use crate::graph::NodeSet;
use crate::tests::load_basic_blocks;
#[test]
fn conditional_if() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"if (n > 1) { n = 1; }
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let conditionals = g.find_2_way_conditionals(&NodeSet::new());
assert_eq!(conditionals.iter().count(), 1);
// Extract key nodes
let entry = g.entry.unwrap();
assert_eq!(g[entry].successors.len(), 2);
let false_node = g[entry].successors[0];
let true_node = g[entry].successors[1];
assert_eq!(g[false_node].successors, [true_node]);
// Check conditional
assert_eq!(conditionals[entry], true_node);
Ok(())
}
#[test]
fn conditional_if_else() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"if (n > 1) { n = 1; } else { n = 0; }
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let conditionals = g.find_2_way_conditionals(&NodeSet::new());
assert_eq!(conditionals.iter().count(), 1);
// Extract key nodes
let entry = g.entry.unwrap();
assert_eq!(g[entry].successors.len(), 2);
let false_node = g[entry].successors[0];
let true_node = g[entry].successors[1];
assert_eq!(g[false_node].successors, g[true_node].successors);
assert_eq!(g[false_node].successors.len(), 1);
let follow = g[false_node].successors[0];
// Check conditional
assert_eq!(conditionals[entry], follow);
Ok(())
}
#[test]
fn conditional_multiple_if_else() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"
if (n > 2) { n = 2; }
if (n > 1) { n = 1; } else { n = 0; }
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let conditionals = g.find_2_way_conditionals(&NodeSet::new());
assert_eq!(conditionals.iter().count(), 2);
// Extract key nodes
let entry = g.entry.unwrap();
assert_eq!(g[entry].successors.len(), 2);
let false_node1 = g[entry].successors[0];
let true_node1 = g[entry].successors[1];
assert_eq!(g[false_node1].successors, [true_node1]);
assert_eq!(g[true_node1].successors.len(), 2);
let false_node2 = g[true_node1].successors[0];
let true_node2 = g[true_node1].successors[1];
assert_eq!(g[false_node2].successors, g[true_node2].successors);
assert_eq!(g[false_node2].successors.len(), 1);
let follow2 = g[false_node2].successors[0];
// Check conditionals
assert_eq!(conditionals[entry], true_node1);
assert_eq!(conditionals[true_node1], follow2);
Ok(())
}
#[test]
fn conditional_nested_if_else() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"int a = 0, b = 0;
if (a == b) {
n = 0;
} else {
if (a < b) {
n = -1;
} else {
n = 1;
}
}
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let conditionals = g.find_2_way_conditionals(&NodeSet::new());
assert_eq!(conditionals.iter().count(), 2);
// Extract key nodes
let entry = g.entry.unwrap();
assert_eq!(g[entry].successors.len(), 2);
let false_node1 = g[entry].successors[0];
let true_node1 = g[entry].successors[1];
assert_eq!(g[true_node1].successors.len(), 2);
let false_node2 = g[true_node1].successors[0];
let true_node2 = g[true_node1].successors[1];
assert_eq!(g[false_node1].successors, g[false_node2].successors);
assert_eq!(g[false_node1].successors, g[true_node2].successors);
assert_eq!(g[false_node1].successors.len(), 1);
let follow = g[false_node1].successors[0];
// Check conditionals
assert_eq!(conditionals[entry], follow);
assert_eq!(conditionals[true_node1], follow);
Ok(())
}
#[test]
fn conditional_if_compound() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"boolean a = false; boolean b = false;
if (a || b) { n--; }
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let conditionals = g.find_2_way_conditionals(&NodeSet::new());
assert_eq!(conditionals.iter().count(), 1);
// Extract key nodes
let entry = g.entry.unwrap();
assert_eq!(g[entry].successors.len(), 2);
let false_node = g[entry].successors[0];
let true_node = g[entry].successors[1];
assert_eq!(g[false_node].successors, [true_node]);
// Check conditional
assert_eq!(conditionals[entry], true_node);
assert!(matches!(
g[entry].value,
Structure::CompoundConditional {
left_negated: true,
kind: ConditionalKind::Conjunction,
..
}
));
Ok(())
}
#[test]
fn conditional_nested_if_at_end_of_pre_tested() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"while (n > 2) {
if (n > 1) { n--; }
}
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let loops = g.find_loops()?;
let ignored_headers = ignored_loop_headers(&loops);
let conditionals = g.find_2_way_conditionals(&ignored_headers);
assert_eq!(conditionals.iter().count(), 1);
// Extract key nodes
let entry = g.entry.unwrap(); // while (n > 2) {
assert_eq!(g[entry].successors.len(), 2);
let header = g[entry].successors[0]; // if (n > 1) {
assert_eq!(g[header].successors.len(), 2);
let false_node = g[header].successors[0];
let true_node = g[header].successors[1];
assert_eq!(g[false_node].successors, [true_node]);
// Check conditional
assert_eq!(conditionals[header], true_node);
assert_eq!(g[true_node].value, Structure::default()); // placeholder
Ok(())
}
#[test]
fn conditional_nested_if_else_at_end_of_pre_tested() -> anyhow::Result<()> {
let mut g = load_basic_blocks(
"while (n > 1) {
if (n > 2) { n -= 2; } else { n--; }
}
return n;",
)?;
g.insert_placeholder_nodes();
g.structure_compound_conditionals();
let loops = g.find_loops()?;
let ignored_headers = ignored_loop_headers(&loops);
let conditionals = g.find_2_way_conditionals(&ignored_headers);
assert_eq!(conditionals.iter().count(), 1);
// Extract key nodes
let entry = g.entry.unwrap(); // while (n > 1)
assert_eq!(g[entry].successors.len(), 2);
let header = g[entry].successors[0];
assert_eq!(g[header].successors.len(), 2);
let false_node = g[header].successors[0];
let true_node = g[header].successors[1];
assert_eq!(g[false_node].successors, g[true_node].successors);
assert_eq!(g[false_node].successors.len(), 1);
let follow = g[false_node].successors[0];
// Check conditional
assert_eq!(conditionals[header], follow);
assert_eq!(g[follow].value, Structure::default()); // placeholder
Ok(())
}
}