logicaffeine_compile/optimize/egraph/
mod.rs1pub mod convert;
16pub mod enode;
17pub mod extract;
18pub mod rules;
19
20pub use enode::CompilerENode;
21
22use std::collections::HashMap;
23
24use logicaffeine_base::union_find::UnionFind;
25
26use crate::optimize::ScalarKind;
27
28pub type NodeId = usize;
29
30pub const SATURATION_ITERS: usize = 8;
32pub const MAX_NODES: usize = 10_000;
34
35#[derive(Debug, Clone, Copy, Default)]
40pub struct ClassFact {
41 pub scalar: Option<ScalarKind>,
42 pub range: Option<(i64, i64)>,
43 pub collection: bool,
47 pub list: bool,
49}
50
51pub struct CompilerEGraph {
52 uf: UnionFind,
53 nodes: Vec<CompilerENode>,
55 memo: HashMap<CompilerENode, NodeId>,
58 class_nodes: HashMap<NodeId, Vec<NodeId>>,
60 uses: HashMap<NodeId, Vec<NodeId>>,
62 facts: HashMap<NodeId, ClassFact>,
64 dirty: Vec<NodeId>,
66}
67
68impl CompilerEGraph {
69 pub fn new() -> Self {
70 CompilerEGraph {
71 uf: UnionFind::new(),
72 nodes: Vec::new(),
73 memo: HashMap::new(),
74 class_nodes: HashMap::new(),
75 uses: HashMap::new(),
76 facts: HashMap::new(),
77 dirty: Vec::new(),
78 }
79 }
80
81 pub fn node_count(&self) -> usize {
82 self.nodes.len()
83 }
84
85 pub fn find(&mut self, id: NodeId) -> NodeId {
86 self.uf.find(id)
87 }
88
89 pub fn canonical_node(&mut self, id: NodeId) -> CompilerENode {
91 let node = self.nodes[id];
92 node.map_children(|c| self.uf.find(c))
93 }
94
95 pub fn class_members(&mut self, id: NodeId) -> Vec<NodeId> {
97 let root = self.find(id);
98 self.class_nodes.get(&root).cloned().unwrap_or_default()
99 }
100
101 pub fn add(&mut self, node: CompilerENode) -> NodeId {
104 let canonical = node.map_children(|c| self.uf.find(c));
105 if let Some(&existing) = self.memo.get(&canonical) {
106 return self.uf.find(existing);
107 }
108 let id = self.uf.make_set();
109 debug_assert_eq!(id, self.nodes.len());
110 self.nodes.push(canonical);
111 self.memo.insert(canonical, id);
112 self.class_nodes.insert(id, vec![id]);
113 for child in canonical.children() {
114 self.uses.entry(child).or_default().push(id);
115 }
116 match canonical {
117 CompilerENode::Int(k) => {
118 self.facts.insert(
119 id,
120 ClassFact {
121 scalar: Some(ScalarKind::Int),
122 range: Some((k, k)),
123 ..ClassFact::default()
124 },
125 );
126 }
127 CompilerENode::Bool(_) => {
128 self.facts.insert(
129 id,
130 ClassFact {
131 scalar: Some(ScalarKind::Bool),
132 ..ClassFact::default()
133 },
134 );
135 }
136 CompilerENode::Float(_) => {
137 self.facts.insert(
138 id,
139 ClassFact {
140 scalar: Some(ScalarKind::Float),
141 ..ClassFact::default()
142 },
143 );
144 }
145 CompilerENode::Slice(..) => {
147 self.facts.insert(
148 id,
149 ClassFact {
150 collection: true,
151 list: true,
152 ..ClassFact::default()
153 },
154 );
155 }
156 _ => {}
159 }
160 id
161 }
162
163 pub fn union(&mut self, a: NodeId, b: NodeId) -> bool {
166 let ra = self.uf.find(a);
167 let rb = self.uf.find(b);
168 if ra == rb {
169 return false;
170 }
171 let fa = self.facts.remove(&ra);
172 let fb = self.facts.remove(&rb);
173 self.uf.union(ra, rb);
174 let root = self.uf.find(ra);
175 let loser = if root == ra { rb } else { ra };
176
177 let mut members = self.class_nodes.remove(&loser).unwrap_or_default();
178 self.class_nodes
179 .entry(root)
180 .or_default()
181 .append(&mut members);
182 let mut moved_uses = self.uses.remove(&loser).unwrap_or_default();
183 self.uses.entry(root).or_default().append(&mut moved_uses);
184
185 let merged = match (fa, fb) {
186 (Some(x), Some(y)) => ClassFact {
187 scalar: x.scalar.or(y.scalar),
188 range: match (x.range, y.range) {
189 (Some((al, ah)), Some((bl, bh))) => {
190 let lo = al.max(bl);
191 let hi = ah.min(bh);
192 debug_assert!(lo <= hi, "contradictory ranges merged — unsound rule?");
193 if lo <= hi {
194 Some((lo, hi))
195 } else {
196 Some((al, ah))
197 }
198 }
199 (r, None) | (None, r) => r,
200 },
201 collection: x.collection || y.collection,
204 list: x.list || y.list,
205 },
206 (Some(x), None) | (None, Some(x)) => x,
207 (None, None) => ClassFact::default(),
208 };
209 self.facts.insert(root, merged);
210 self.dirty.push(root);
211 true
212 }
213
214 pub fn rebuild(&mut self) {
217 while let Some(r) = self.dirty.pop() {
218 let root = self.uf.find(r);
219 let parents = self.uses.remove(&root).unwrap_or_default();
220 let mut kept: Vec<NodeId> = Vec::with_capacity(parents.len());
221 for p in parents {
222 let canon = self.nodes[p].map_children(|c| self.uf.find(c));
223 if let Some(&q) = self.memo.get(&canon) {
224 if self.uf.find(q) != self.uf.find(p) {
225 self.union(p, q);
226 }
227 }
228 let rep = self.uf.find(p);
229 self.memo.insert(canon, rep);
230 kept.push(p);
231 }
232 let now = self.uf.find(root);
233 self.uses.entry(now).or_default().extend(kept);
234 }
235 }
236
237 pub fn set_scalar(&mut self, id: NodeId, kind: ScalarKind) {
240 let root = self.find(id);
241 self.facts.entry(root).or_default().scalar = Some(kind);
242 }
243
244 pub fn set_int_range(&mut self, id: NodeId, lo: i64, hi: i64) {
245 let root = self.find(id);
246 let fact = self.facts.entry(root).or_default();
247 fact.scalar = Some(ScalarKind::Int);
248 fact.range = Some((lo, hi));
249 }
250
251 pub fn scalar_of(&mut self, id: NodeId) -> Option<ScalarKind> {
252 let root = self.find(id);
253 self.facts.get(&root).and_then(|f| f.scalar)
254 }
255
256 pub fn int_range(&mut self, id: NodeId) -> Option<(i64, i64)> {
257 let root = self.find(id);
258 self.facts.get(&root).and_then(|f| f.range)
259 }
260
261 pub fn int_value(&mut self, id: NodeId) -> Option<i64> {
263 match self.int_range(id) {
264 Some((lo, hi)) if lo == hi => Some(lo),
265 _ => None,
266 }
267 }
268
269 pub fn proven_nonneg(&mut self, id: NodeId) -> bool {
270 matches!(self.int_range(id), Some((lo, _)) if lo >= 0)
271 }
272
273 pub fn set_collection(&mut self, id: NodeId) {
275 let root = self.find(id);
276 self.facts.entry(root).or_default().collection = true;
277 }
278
279 pub fn set_list(&mut self, id: NodeId) {
281 let root = self.find(id);
282 let fact = self.facts.entry(root).or_default();
283 fact.collection = true;
284 fact.list = true;
285 }
286
287 pub fn proven_collection(&mut self, id: NodeId) -> bool {
288 let root = self.find(id);
289 self.facts.get(&root).is_some_and(|f| f.collection)
290 }
291
292 pub fn proven_list(&mut self, id: NodeId) -> bool {
293 let root = self.find(id);
294 self.facts.get(&root).is_some_and(|f| f.list)
295 }
296
297 pub fn class_has_bool(&mut self, id: NodeId, b: bool) -> bool {
299 self.class_members(id)
300 .into_iter()
301 .any(|m| self.nodes[m] == CompilerENode::Bool(b))
302 }
303
304 pub fn provably_total(&mut self, id: NodeId) -> bool {
317 let mut total: HashMap<NodeId, bool> = HashMap::new();
318 loop {
319 let mut changed = false;
320 for n in 0..self.nodes.len() {
321 let node = self.nodes[n];
322 let root = self.uf.find(n);
323 if *total.get(&root).unwrap_or(&false) {
324 continue;
325 }
326 let op_total = match node {
327 CompilerENode::Len(c)
328 | CompilerENode::Copy(c)
329 | CompilerENode::Contains(c, _) => self.proven_collection(c),
330 _ => node.op_is_total(),
331 };
332 if op_total
333 && node
334 .children()
335 .iter()
336 .all(|&c| *total.get(&self.uf.find(c)).unwrap_or(&false))
337 {
338 total.insert(root, true);
339 changed = true;
340 }
341 }
342 if !changed {
343 break;
344 }
345 }
346 let root = self.find(id);
347 *total.get(&root).unwrap_or(&false)
348 }
349
350 pub fn saturate(&mut self, rules: &[rules::Rewrite]) {
356 self.rebuild();
357 'outer: for _ in 0..SATURATION_ITERS {
358 let snapshot = self.nodes.len();
359 let mut changed = false;
360 for id in 0..snapshot {
361 for rule in rules {
362 if self.nodes.len() + 4 > MAX_NODES {
363 self.rebuild();
364 break 'outer;
365 }
366 if let Some(replacement) = (rule.apply)(self, id) {
367 changed |= self.union(id, replacement);
368 }
369 }
370 }
371 self.rebuild();
372 if !changed && self.nodes.len() == snapshot {
373 break;
374 }
375 }
376 }
377}
378
379impl Default for CompilerEGraph {
380 fn default() -> Self {
381 Self::new()
382 }
383}