Skip to content

Commit 069f260

Browse files
committed
Walk up the dominator tree to find the first simplification
1 parent e17a570 commit 069f260

File tree

2 files changed

+23
-11
lines changed

2 files changed

+23
-11
lines changed

compiler/noirc_evaluator/src/ssa/ir/dom.rs

+20
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,26 @@ impl DominatorTree {
119119
}
120120
}
121121

122+
/// Walk up the dominator tree until we find one that to which `f` returns `Some` value.
123+
/// Otherwise return `None` when we reach the top.
124+
///
125+
/// Similar to `Iterator::filter_map` but only returns the first hit.
126+
pub(crate) fn find_map_dominator<T>(
127+
&self,
128+
mut block_id: BasicBlockId,
129+
f: impl Fn(BasicBlockId) -> Option<T>,
130+
) -> Option<T> {
131+
loop {
132+
if let Some(value) = f(block_id) {
133+
return Some(value);
134+
}
135+
block_id = match self.immediate_dominator(block_id) {
136+
Some(immediate_dominator) => immediate_dominator,
137+
None => return None,
138+
}
139+
}
140+
}
141+
122142
/// Allocate and compute a dominator tree from a pre-computed control flow graph and
123143
/// post-order counterpart.
124144
pub(crate) fn with_cfg_and_post_order(cfg: &ControlFlowGraph, post_order: &PostOrder) -> Self {

compiler/noirc_evaluator/src/ssa/opt/constant_folding.rs

+3-11
Original file line numberDiff line numberDiff line change
@@ -218,19 +218,11 @@ impl SimplificationCache {
218218

219219
/// Try to find a simplification in a visible block.
220220
fn get(&self, block: BasicBlockId, dom: &mut DominatorTree) -> Option<ValueId> {
221-
// See if we have a direct simplification in this block.
222-
if let Some(value) = self.simplifications.get(&block) {
223-
return Some(*value);
221+
if self.simplifications.is_empty() {
222+
return None;
224223
}
225224
// Check if there is a dominating block we can take a simplification from.
226-
// Going backwards so that we find a constraint closest to what we have already processed
227-
// (assuming block IDs of blocks further down in the SSA are larger).
228-
for (constraining_block, value) in self.simplifications.iter().rev() {
229-
if dom.dominates(*constraining_block, block) {
230-
return Some(*value);
231-
}
232-
}
233-
None
225+
dom.find_map_dominator(block, |b| self.simplifications.get(&b).cloned())
234226
}
235227
}
236228

0 commit comments

Comments
 (0)