From 2c85a6968c1ed8ea3f1b5dd5854f741aef33a4ef Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:22:39 +0900 Subject: [PATCH] perf(native): reuse clobber walks across reload queries of one byte range Each reload snapshot ran a fresh clobber walk from its start: the walker memoized results only within one query session, and the reload clobber cache kept only the final answer per (load, start). Walks from different starts re-scanned the same memory definitions, running the alias oracle over each definition's write effects every time. On C906 the oracle took about 35% of the time after the frontend. A ClobberMemo now keeps, per queried byte range, the clobbers of accesses whose walk met no unresolved cycle. Such a walk covers an acyclic part of the graph, which determines its result whatever the start points, so later sessions reuse it without walking again. Accesses whose walk met a cycle depend on the MemoryPhi being resolved and are walked in each session as before, so every query resolves exactly as it did and the reload recipes do not change. Closes #1994 Change-Id: I93e7a99f5d74451307b5249b6e22f1c591f9e047 --- crates/celox-analysis/src/memory_ssa.rs | 208 ++++++++++++++++-- .../src/backend/native/regalloc/reload.rs | 14 +- 2 files changed, 198 insertions(+), 24 deletions(-) diff --git a/crates/celox-analysis/src/memory_ssa.rs b/crates/celox-analysis/src/memory_ssa.rs index 45a7fffac7f..39b4a803895 100644 --- a/crates/celox-analysis/src/memory_ssa.rs +++ b/crates/celox-analysis/src/memory_ssa.rs @@ -180,9 +180,25 @@ pub struct ClobberWalker { epochs: Vec, states: Vec, results: Vec>, + /// Whether a resolved access's walk met an unresolved cycle. + cyclic: Vec, epoch: u32, frames: Vec, - values: Vec, + /// Results with whether their walk met an unresolved cycle. + values: Vec<(ClobberResolution, bool)>, +} + +/// Clobbers of one alias query over one graph, kept across query sessions. +/// +/// It holds only accesses whose walk met no unresolved cycle. Such a walk +/// covers an acyclic part of the graph, which determines its result whatever +/// the session's start points, so a later session resolves the access to the +/// same result without walking it again. Accesses whose walk met a cycle +/// depend on the MemoryPhi being resolved and are walked again in each +/// session, as without the memo. +#[derive(Debug, Default)] +pub struct ClobberMemo { + results: fxhash::FxHashMap, } impl ClobberWalker { @@ -223,20 +239,40 @@ impl ClobberWalker { self.epochs.fill(0); self.epoch = 1; } + self.cyclic.resize(graph.nodes.len(), false); ClobberQuery { walker: self, graph, query, alias_oracle, + memo: None, } } + /// Like [`Self::query`], reusing and extending `memo`, which must only + /// ever be used with this graph and an equal query and alias oracle. + pub fn query_memoized<'a, D, Q, A>( + &'a mut self, + graph: &'a MemoryAccessGraph, + query: &'a Q, + alias_oracle: &'a A, + memo: &'a mut ClobberMemo, + ) -> ClobberQuery<'a, D, Q, A> + where + A: AliasOracle, + { + let mut session = self.query(graph, query, alias_oracle); + session.memo = Some(memo); + session + } + fn find_clobber( &mut self, nodes: &[MemoryAccessNode], start: usize, query: &Q, alias_oracle: &impl AliasOracle, + mut memo: Option<&mut ClobberMemo>, ) -> MemoryClobber { let current_epoch = self.epoch; self.frames.clear(); @@ -248,24 +284,32 @@ impl ClobberWalker { ResolveFrame::Enter(access) => { if self.epochs[access] == current_epoch && self.states[access] != 0 { match self.states[access] { - 1 => self.values.push(ClobberResolution::Cycle), - 2 => self.values.push( + 1 => self.values.push((ClobberResolution::Cycle, true)), + 2 => self.values.push(( self.results[access] .expect("a resolved clobber node retains its result"), - ), + self.cyclic[access], + )), _ => unreachable!("current-epoch clobber state is valid"), } continue; } self.epochs[access] = current_epoch; + if let Some(&result) = memo.as_ref().and_then(|memo| memo.results.get(&access)) + { + let result = ClobberResolution::Access(result); + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = false; + self.values.push((result, false)); + continue; + } self.states[access] = 1; self.results[access] = None; match &nodes[access] { MemoryAccessNode::LiveOnEntry => { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } MemoryAccessNode::Definition { definition, @@ -273,9 +317,7 @@ impl ClobberWalker { } => { if alias_oracle.may_alias(definition, query) { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } else { self.frames.push(ResolveFrame::FinishDefinition(access)); self.frames.push(ResolveFrame::Enter(previous.0)); @@ -296,7 +338,7 @@ impl ClobberWalker { } } ResolveFrame::FinishDefinition(access) => { - let result = self + let (result, cyclic) = self .values .pop() .expect("a MemoryDef predecessor produces one clobber result"); @@ -305,11 +347,10 @@ impl ClobberWalker { // resolved independently of the active MemoryPhi. self.states[access] = 0; self.results[access] = None; + self.values.push((result, cyclic)); } else { - self.states[access] = 2; - self.results[access] = Some(result); + self.resolve(access, result, cyclic, &mut memo); } - self.values.push(result); } ResolveFrame::FinishPhi { access, inputs } => { let first = self @@ -319,7 +360,9 @@ impl ClobberWalker { .expect("every MemoryPhi input produces one clobber result"); let mut common = None::; let mut diverged = false; - for result in self.values.drain(first..) { + let mut cyclic = false; + for (result, input_cyclic) in self.values.drain(first..) { + cyclic |= input_cyclic; if result == ClobberResolution::Cycle { continue; } @@ -334,14 +377,12 @@ impl ClobberWalker { } else { common.unwrap_or(ClobberResolution::Access(access)) }; - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, cyclic, &mut memo); } } } - let resolution = self + let (resolution, _) = self .values .pop() .expect("one clobber query produces one result"); @@ -351,6 +392,24 @@ impl ClobberWalker { ClobberResolution::Cycle => MemoryClobber::Indeterminate, } } + + /// Record `access` as resolved to `result` in this session, and in `memo` + /// when its walk met no unresolved cycle. + fn resolve( + &mut self, + access: usize, + result: ClobberResolution, + cyclic: bool, + memo: &mut Option<&mut ClobberMemo>, + ) { + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = cyclic; + if let (false, ClobberResolution::Access(result), Some(memo)) = (cyclic, result, memo) { + memo.results.insert(access, result); + } + self.values.push((result, cyclic)); + } } /// Multi-point clobber query for one immutable alias query. Resolving a phi @@ -361,6 +420,7 @@ pub struct ClobberQuery<'a, D, Q, A> { graph: &'a MemoryAccessGraph, query: &'a Q, alias_oracle: &'a A, + memo: Option<&'a mut ClobberMemo>, } impl ClobberQuery<'_, D, Q, A> @@ -369,8 +429,13 @@ where { pub fn clobber(&mut self, start: MemoryAccessId) -> Option { (start.0 < self.graph.nodes.len()).then(|| { - self.walker - .find_clobber(&self.graph.nodes, start.0, self.query, self.alias_oracle) + self.walker.find_clobber( + &self.graph.nodes, + start.0, + self.query, + self.alias_oracle, + self.memo.as_deref_mut(), + ) }) } } @@ -1005,6 +1070,107 @@ mod tests { assert_eq!(analysis.graph.access_count(), 2); } + /// Sessions sharing a memo resolve every start exactly as fresh + /// sessions do, over random CFGs with loops, joins and disjoint, + /// overlapping and repeated stores. + #[test] + fn memoized_sessions_match_fresh_sessions() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + let mut cases = 0; + let mut memo_calls = 0; + let mut fresh_calls = 0; + for _ in 0..400 { + let blocks = 1 + next(7); + let successors = (0..blocks) + .map(|block| { + let mut outgoing = Vec::new(); + if block + 1 < blocks { + outgoing.push(block + 1); + } + for _ in 0..next(3) { + outgoing.push(next(blocks)); + } + outgoing + }) + .collect::>(); + let Ok(cfg) = ControlFlowGraph::analyze(successors, 0) else { + continue; + }; + let events = (0..blocks) + .map(|block| { + (0..next(4)) + .map(|index| { + let writes = if next(3) == 0 { + vec![] + } else { + vec![exact(1, 4 * next(4) as i64, 4 * (1 + next(2)))] + }; + event((block, index), vec![], writes) + }) + .collect::>() + }) + .collect::>(); + let analysis = analyze(&cfg, &events); + let accesses = analysis.graph.access_count(); + let calls = std::cell::Cell::new(0usize); + let oracle = |definition: &Instruction, query: &MemoryEffect| { + calls.set(calls.get() + 1); + analysis.writes[definition] + .iter() + .copied() + .any(|write| effects_may_alias(write, *query)) + }; + for _ in 0..4 { + let query = exact(1, 4 * next(4) as i64, 4 * (1 + next(2))); + let sessions = (0..1 + next(6)) + .map(|_| { + (0..1 + next(4)) + .map(|_| MemoryAccessId(next(accesses))) + .collect::>() + }) + .collect::>(); + let mut fresh_walker = ClobberWalker::new(); + calls.set(0); + let fresh = sessions + .iter() + .map(|starts| { + let mut session = fresh_walker.query(&analysis.graph, &query, &oracle); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + fresh_calls += calls.get(); + let mut walker = ClobberWalker::new(); + let mut memo = ClobberMemo::default(); + calls.set(0); + let memoized = sessions + .iter() + .map(|starts| { + let mut session = + walker.query_memoized(&analysis.graph, &query, &oracle, &mut memo); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + memo_calls += calls.get(); + assert_eq!(memoized, fresh, "{sessions:?} {query:?} {events:?}"); + } + cases += 1; + } + assert!(cases > 200, "{cases}"); + assert!(memo_calls < fresh_calls, "{memo_calls} {fresh_calls}"); + } + #[test] fn custom_alias_domain_needs_no_memory_effect_types() { let cfg = ControlFlowGraph::analyze(vec![vec![]], 0).unwrap(); diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs index b925852f893..50255234cc7 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs @@ -11,8 +11,8 @@ use std::fmt; use celox_analysis::memory::{MemoryEffect, MemoryLocation, effects_may_alias}; use celox_analysis::memory_ssa::{ - self, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, MemoryAccessId, - MemoryClobber, MemoryPointMap, + self, ClobberMemo, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, + MemoryAccessId, MemoryClobber, MemoryPointMap, }; use crate::HashMap; @@ -1221,6 +1221,9 @@ struct ReloadMemorySsa { block_ids: Vec, walker: ClobberWalker, clobber_cache: HashMap<(StateLoad, MemoryAccessId), MemoryAccessId>, + /// Clobbers already walked for each queried byte range, so queries from + /// different starts do not walk the same definitions again. + clobber_memos: HashMap<(i64, usize), ClobberMemo>, } impl ReloadMemorySsa { @@ -1273,6 +1276,10 @@ impl ReloadMemorySsa { let writes = &self.writes; let block_ids = &self.block_ids; let clobber_cache = &mut self.clobber_cache; + let memo = self + .clobber_memos + .entry((bytes.start, byte_len)) + .or_default(); let oracle = |definition: &MemoryDefinition, query: &MemoryEffect| { writes .get(definition.write_index..definition.write_end) @@ -1283,7 +1290,7 @@ impl ReloadMemorySsa { .any(|write| effects_may_alias(write, *query)) }) }; - let mut clobber_query = self.walker.query(graph, &query, &oracle); + let mut clobber_query = self.walker.query_memoized(graph, &query, &oracle, memo); let mut clobber_access = |start| { if let Some(&access) = clobber_cache.get(&(load, start)) { return Ok(access); @@ -2228,6 +2235,7 @@ fn build_reload_memory_ssa( writes, block_ids: func.blocks.iter().map(|block| block.id).collect(), walker: ClobberWalker::new(), + clobber_memos: HashMap::default(), clobber_cache: HashMap::default(), }) }