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
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
block::Block, context::Context, error::IrError, function::Function, instruction::Instruction,
value::ValueDatum, AnalysisResults, BranchToWithArgs, Pass, PassMutability, ScopedPass, Value,
};
pub const SIMPLIFYCFG_NAME: &str = "simplifycfg";
pub fn create_simplify_cfg_pass() -> Pass {
Pass {
name: SIMPLIFYCFG_NAME,
descr: "merge or remove redundant blocks.",
deps: vec![],
runner: ScopedPass::FunctionPass(PassMutability::Transform(simplify_cfg)),
}
}
pub fn simplify_cfg(
context: &mut Context,
_: &AnalysisResults,
function: Function,
) -> Result<bool, IrError> {
let mut modified = false;
modified |= remove_dead_blocks(context, &function)?;
modified |= merge_blocks(context, &function)?;
modified |= unlink_empty_blocks(context, &function)?;
Ok(modified)
}
fn unlink_empty_blocks(context: &mut Context, function: &Function) -> Result<bool, IrError> {
let mut modified = false;
let candidates: Vec<_> = function
.block_iter(context)
.skip(1)
.filter_map(|block| {
match block.get_terminator(context) {
Some(Instruction::Branch(to_block)) if block.num_instructions(context) <= 1 => {
Some((block, to_block.clone()))
}
_ => None,
}
})
.collect();
for (
block,
BranchToWithArgs {
block: to_block,
args: cur_params,
},
) in candidates
{
if to_block.num_args(context) > 0
&& to_block.pred_iter(context).any(|to_block_pred| {
block
.pred_iter(context)
.any(|block_pred| block_pred == to_block_pred)
})
{
continue;
}
let preds: Vec<_> = block.pred_iter(context).copied().collect();
for pred in preds {
let params_from_pred = pred.get_succ_params(context, &block);
let new_params = cur_params
.iter()
.map(|cur_param| match &context.values[cur_param.0].value {
ValueDatum::Argument(arg) if arg.block == block => {
params_from_pred[arg.idx]
}
_ => *cur_param,
})
.collect();
pred.replace_successor(context, block, to_block, new_params);
modified = true;
}
}
Ok(modified)
}
fn remove_dead_blocks(context: &mut Context, function: &Function) -> Result<bool, IrError> {
let mut worklist = Vec::<Block>::new();
let mut reachable = std::collections::HashSet::<Block>::new();
let entry_block = function.get_entry_block(context);
reachable.insert(entry_block);
worklist.push(entry_block);
while !worklist.is_empty() {
let block = worklist.pop().unwrap();
let succs = block.successors(context);
for BranchToWithArgs { block: succ, .. } in succs {
if !reachable.contains(&succ) {
reachable.insert(succ);
worklist.push(succ);
}
}
}
let mut modified = false;
for block in function.block_iter(context) {
if !reachable.contains(&block) {
modified = true;
for BranchToWithArgs { block: succ, .. } in block.successors(context) {
succ.remove_pred(context, &block);
}
function.remove_block(context, &block)?;
}
}
Ok(modified)
}
fn merge_blocks(context: &mut Context, function: &Function) -> Result<bool, IrError> {
fn check_candidate(context: &Context, from_block: Block) -> Option<(Block, Block)> {
from_block
.get_terminator(context)
.and_then(|term| match term {
Instruction::Branch(BranchToWithArgs {
block: to_block, ..
}) if to_block.num_predecessors(context) == 1 => Some((from_block, *to_block)),
_ => None,
})
}
let blocks: Vec<_> = function.block_iter(context).collect();
let mut deleted_blocks = FxHashSet::<Block>::default();
let mut replace_map: FxHashMap<Value, Value> = FxHashMap::default();
let mut modified = false;
for from_block in blocks {
if deleted_blocks.contains(&from_block) {
continue;
}
let twin_blocks = check_candidate(context, from_block);
let mut block_chain = match twin_blocks {
Some((from_block, to_block)) => vec![from_block, to_block],
None => continue,
};
loop {
match check_candidate(context, block_chain.last().copied().unwrap()) {
None => {
break;
}
Some(next_pair) => {
block_chain.push(next_pair.1);
}
}
}
let final_to_block = block_chain.last().copied().unwrap();
let final_to_block_succs = final_to_block.successors(context);
let mut block_chain = block_chain.into_iter();
let from_block = block_chain.next().unwrap();
for to_block in block_chain {
let from_params = from_block.get_succ_params(context, &to_block);
let to_blocks: Vec<_> = to_block.arg_iter(context).copied().enumerate().collect();
for (arg_idx, to_block_arg) in to_blocks {
replace_map.insert(to_block_arg, from_params[arg_idx]);
}
let (from_contents, to_contents) = context.blocks.get2_mut(from_block.0, to_block.0);
let from_contents = from_contents.unwrap();
let to_contents = to_contents.unwrap();
from_contents.instructions.pop();
from_contents
.instructions
.append(&mut to_contents.instructions);
function.remove_block(context, &to_block)?;
deleted_blocks.insert(to_block);
}
for BranchToWithArgs { block: succ, .. } in final_to_block_succs {
succ.replace_pred(context, &final_to_block, &from_block)
}
modified = true;
}
if !replace_map.is_empty() {
assert!(modified);
function.replace_values(context, &replace_map, None);
}
Ok(modified)
}