1use super::{AuError, Span};
10use crate::canon::{MSetCanon, VarCanon};
11use crate::config::{AuIds, EGraphConfig};
12use crate::containers::{DenseId, IndexLike};
13use crate::egraph::EGraph;
14use crate::literal::LitVal;
15use crate::multiplicity::MultiplicityLike;
16use crate::node_types::FLAG_SUBSUMED;
17
18pub type ClassOf<Cfg> = <<Cfg as EGraphConfig>::Au as AuIds>::Class;
20pub type SccOf<Cfg> = <<Cfg as EGraphConfig>::Au as AuIds>::Scc;
22
23pub struct AuSnapshot<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>
35where
36 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
37{
38 pub(crate) eg: &'eg EGraph<Cfg, L, T, P>,
39 repr_to_au: hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
41 pub(crate) au_to_repr: Vec<Cfg::G>,
43 member_spans: Vec<Span<<Cfg::Au as AuIds>::SnapshotMember>>,
45 member_pool: Vec<(Cfg::O, Cfg::G)>,
47 best_size: Vec<u32>,
49 best_node: Vec<Option<Cfg::G>>,
51 reach: Reachability<Cfg::Au>,
53}
54
55#[derive(Debug, Clone)]
57pub struct Reachability<A: AuIds> {
58 class_to_scc: Vec<A::Scc>,
60 scc_spans: Vec<Span<A::ReachBlock>>,
62 bit_blocks: Vec<u64>,
64 scc_reach_count: Vec<u32>,
68 num_classes: u64,
70}
71
72impl<A: AuIds> Reachability<A> {
73 #[inline]
75 pub fn is_reachable(&self, source: A::Class, target: A::Class) -> bool {
76 let scc = self.class_to_scc[source.to_usize()];
77 let start = self.scc_spans[scc.to_usize()].start_usize();
78 let t = target.to_usize();
79 let word = start + t / 64;
80 let bit = t % 64;
81 (self.bit_blocks[word] >> bit) & 1 != 0
82 }
83
84 #[inline]
88 pub fn reach_count(&self, source: A::Class) -> u64 {
89 let scc = self.class_to_scc[source.to_usize()];
90 u64::from(self.scc_reach_count[scc.to_usize()])
91 }
92
93 pub fn num_classes(&self) -> u64 {
95 self.num_classes
96 }
97}
98
99impl<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool> AuSnapshot<'eg, Cfg, L, T, P>
100where
101 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
102{
103 pub fn new(eg: &'eg EGraph<Cfg, L, T, P>) -> Result<Self, AuError> {
106 let n = eg.len();
108 let mut repr_to_au: hashbrown::HashMap<Cfg::G, ClassOf<Cfg>> =
109 hashbrown::HashMap::with_capacity(n / 2);
110 let mut au_to_repr: Vec<Cfg::G> = Vec::new();
111
112 for id in eg.node_ids() {
115 let repr = eg.find_const(id);
116 repr_to_au.entry(repr).or_insert_with(|| {
117 let au = crate::id::id_at::<ClassOf<Cfg>>(au_to_repr.len());
124 au_to_repr.push(repr);
125 au
126 });
127 }
128
129 let num_classes = au_to_repr.len();
130
131 let mut class_members: Vec<Vec<(Cfg::O, Cfg::G)>> = vec![Vec::new(); num_classes];
134
135 for id in eg.node_ids() {
136 let flags = eg.node_flags(id);
137 if flags & FLAG_SUBSUMED != 0 {
138 continue;
139 }
140 let repr = eg.find_const(id);
141 let au_class = repr_to_au[&repr];
142 let op = eg.node_op(id);
143 class_members[au_class.to_usize()].push((op, id));
144 }
145
146 for members in &mut class_members {
148 members.sort_by_key(|&(op, _)| op.to_usize());
149 }
150
151 let total_members: usize = class_members.iter().map(|m| m.len()).sum();
153 let mut member_pool: Vec<(Cfg::O, Cfg::G)> = Vec::with_capacity(total_members);
154 let mut member_spans: Vec<Span<<Cfg::Au as AuIds>::SnapshotMember>> =
155 Vec::with_capacity(num_classes);
156
157 for members in &class_members {
158 let start = member_pool.len();
159 member_pool.extend_from_slice(members);
160 member_spans.push(Span::new(start, members.len()));
161 }
162
163 let (best_size, best_node) = Self::compute_best_terms(eg, &repr_to_au, num_classes)?;
165
166 let reach = Self::compute_reachability(eg, &repr_to_au, &au_to_repr, num_classes);
168
169 Ok(AuSnapshot {
170 eg,
171 repr_to_au,
172 au_to_repr,
173 member_spans,
174 member_pool,
175 best_size,
176 best_node,
177 reach,
178 })
179 }
180
181 pub fn num_classes(&self) -> usize {
185 self.au_to_repr.len()
186 }
187
188 #[inline]
191 pub fn class_id(&self, repr: Cfg::G) -> Option<ClassOf<Cfg>> {
192 self.repr_to_au.get(&repr).copied()
193 }
194
195 #[inline]
197 pub fn class_of(&self, id: Cfg::G) -> Option<ClassOf<Cfg>> {
198 let repr = self.eg.find_const(id);
199 self.repr_to_au.get(&repr).copied()
200 }
201
202 #[inline]
204 pub fn repr(&self, au: ClassOf<Cfg>) -> Cfg::G {
205 self.au_to_repr[au.to_usize()]
206 }
207
208 #[inline]
210 pub fn best_size(&self, au: ClassOf<Cfg>) -> u32 {
211 self.best_size[au.to_usize()]
212 }
213
214 #[inline]
220 pub fn best_node(&self, au: ClassOf<Cfg>) -> Cfg::G {
221 self.best_node[au.to_usize()]
222 .expect("best_node requested for a class without an admissible finite member")
223 }
224
225 #[inline]
227 pub fn members(&self, au: ClassOf<Cfg>) -> &[(Cfg::O, Cfg::G)] {
228 let span = self.member_spans[au.to_usize()];
229 &self.member_pool[span.start_usize()..span.end_usize()]
230 }
231
232 #[inline]
234 pub fn reachability(&self) -> &Reachability<Cfg::Au> {
235 &self.reach
236 }
237
238 #[inline]
240 pub fn egraph(&self) -> &'eg EGraph<Cfg, L, T, P> {
241 self.eg
242 }
243
244 #[inline]
246 pub fn node_op(&self, id: Cfg::G) -> Cfg::O {
247 self.eg.node_op(id)
248 }
249
250 #[inline]
254 pub fn has_finite_member(&self, au: ClassOf<Cfg>) -> bool {
255 self.best_size[au.to_usize()] != u32::MAX
256 }
257
258 pub fn validate_finite_from(&self, root: ClassOf<Cfg>) -> Result<(), AuError> {
262 if !self.has_finite_member(root) {
263 return Err(AuError::NoFiniteRepresentative(root.to_usize() as u64));
264 }
265 for c in crate::id::ids_upto::<ClassOf<Cfg>>(self.num_classes()) {
268 if self.reach.is_reachable(root, c) && !self.has_finite_member(c) {
269 return Err(AuError::NoFiniteRepresentative(c.to_usize() as u64));
270 }
271 }
272 Ok(())
273 }
274
275 pub fn op_identity_class(&self, op: Cfg::O) -> Option<ClassOf<Cfg>> {
285 let unit_node = self.eg.unit_node(op)?;
286 let class = self.class_of(unit_node)?;
287 self.has_finite_member(class).then_some(class)
288 }
289
290 pub fn op_is_commutative(&self, op: Cfg::O) -> bool {
291 matches!(
292 self.eg.ops().info(op).canon_class(),
293 crate::id::ENodeKind::SPair | crate::id::ENodeKind::MSet | crate::id::ENodeKind::Set
294 )
295 }
296
297 fn compute_best_terms(
312 eg: &EGraph<Cfg, L, T, P>,
313 repr_to_au: &hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
314 num_classes: usize,
315 ) -> Result<(Vec<u32>, Vec<Option<Cfg::G>>), AuError> {
316 let mut best_size: Vec<u32> = vec![u32::MAX; num_classes];
317 let mut best_node: Vec<Option<Cfg::G>> = vec![None; num_classes];
318
319 loop {
320 let mut changed = false;
321 for id in eg.node_ids() {
322 let flags = eg.node_flags(id);
323 if flags & FLAG_SUBSUMED != 0 {
324 continue;
325 }
326 let repr = eg.find_const(id);
327 let au_class = match repr_to_au.get(&repr) {
328 Some(&c) => c,
329 None => continue,
330 };
331
332 let mut total: u64 = 1;
336 let mut ok = true;
337 eg.for_each_child(id, |child, mult| {
338 if !ok {
339 return;
340 }
341 let child_repr = eg.find_const(child);
342 match repr_to_au.get(&child_repr) {
343 Some(&child_au) => {
344 let child_cost = best_size[child_au.to_usize()];
345 if child_cost == u32::MAX {
346 ok = false;
347 } else {
348 match u64::from(child_cost)
349 .checked_mul(mult.to_u64())
350 .and_then(|c| total.checked_add(c))
351 {
352 Some(t) => total = t,
353 None => ok = false,
354 }
355 }
356 }
357 None => {
358 ok = false;
359 }
360 }
361 });
362 if !ok || total >= u64::from(u32::MAX) {
365 continue;
366 }
367 let total = total as u32;
368
369 if total < best_size[au_class.to_usize()] {
370 best_size[au_class.to_usize()] = total;
371 best_node[au_class.to_usize()] = Some(id);
372 changed = true;
373 }
374 }
375 if !changed {
376 break;
377 }
378 }
379
380 Ok((best_size, best_node))
381 }
382
383 fn compute_reachability(
387 eg: &EGraph<Cfg, L, T, P>,
388 repr_to_au: &hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
389 au_to_repr: &[Cfg::G],
390 num_classes: usize,
391 ) -> Reachability<Cfg::Au> {
392 let words_per_scc = num_classes.div_ceil(64);
393
394 let mut adj: Vec<Vec<ClassOf<Cfg>>> = vec![Vec::new(); num_classes];
396 for id in eg.node_ids() {
397 let flags = eg.node_flags(id);
398 if flags & FLAG_SUBSUMED != 0 {
399 continue;
400 }
401 let repr = eg.find_const(id);
402 let src = match repr_to_au.get(&repr) {
403 Some(&c) => c,
404 None => continue,
405 };
406 eg.for_each_child(id, |child, _mult| {
407 let child_repr = eg.find_const(child);
408 if let Some(&dst) = repr_to_au.get(&child_repr) {
409 adj[src.to_usize()].push(dst);
410 }
411 });
412 }
413
414 for neighbors in &mut adj {
416 neighbors.sort_unstable();
417 neighbors.dedup();
418 }
419
420 let undefined = <Cfg::Index as IndexLike>::max();
438 assert!(
439 num_classes < undefined.as_usize(),
440 "AU snapshot has {num_classes} classes, leaving EGraphConfig::Index no value \
441 to spare for Tarjan's `undefined` marker; configure a wider index word"
442 );
443 let zero = <Cfg::Index as IndexLike>::min();
444 let mut index_counter = zero;
445 let mut stack: Vec<ClassOf<Cfg>> = Vec::new();
446 let mut on_stack: Vec<bool> = vec![false; num_classes];
447 let mut node_index: Vec<Cfg::Index> = vec![undefined; num_classes];
448 let mut node_lowlink: Vec<Cfg::Index> = vec![zero; num_classes];
449 let mut class_to_scc: Vec<SccOf<Cfg>> = vec![<SccOf<Cfg>>::from_usize(0); num_classes];
452 let mut scc_members: Vec<Vec<ClassOf<Cfg>>> = Vec::new();
453
454 let bump = |c: Cfg::Index| {
457 crate::containers::index_like::checked_incr(c).expect(
458 "Tarjan discovery counter passed EGraphConfig::Index; \
459 it is bounded by the class count, checked above",
460 )
461 };
462
463 #[derive(Clone, Copy)]
465 struct TarjanFrame<C, I> {
466 node: C,
467 neighbor_idx: I,
470 }
471
472 for start_id in crate::id::ids_upto::<ClassOf<Cfg>>(num_classes) {
475 let start = start_id.to_usize();
476 if node_index[start] != undefined {
477 continue;
478 }
479
480 let mut call_stack: Vec<TarjanFrame<ClassOf<Cfg>, Cfg::Index>> = Vec::new();
481 node_index[start] = index_counter;
483 node_lowlink[start] = index_counter;
484 index_counter = bump(index_counter);
485 on_stack[start] = true;
486 stack.push(start_id);
487 call_stack.push(TarjanFrame {
488 node: start_id,
489 neighbor_idx: zero,
490 });
491
492 while let Some(frame) = call_stack.last_mut() {
493 let v = frame.node;
494 let vi = v.to_usize();
495 let neighbors = &adj[vi];
496
497 if frame.neighbor_idx.as_usize() < neighbors.len() {
498 let w = neighbors[frame.neighbor_idx.as_usize()];
499 frame.neighbor_idx = bump(frame.neighbor_idx);
500 let wi = w.to_usize();
501
502 if node_index[wi] == undefined {
503 node_index[wi] = index_counter;
505 node_lowlink[wi] = index_counter;
506 index_counter = bump(index_counter);
507 on_stack[wi] = true;
508 stack.push(w);
509 call_stack.push(TarjanFrame {
510 node: w,
511 neighbor_idx: zero,
512 });
513 } else if on_stack[wi] {
514 node_lowlink[vi] = node_lowlink[vi].min(node_index[wi]);
515 }
516 } else {
517 if node_lowlink[vi] == node_index[vi] {
519 let scc_id = crate::id::id_at::<SccOf<Cfg>>(scc_members.len());
525 let mut members = Vec::new();
526 loop {
527 let w = stack.pop().unwrap();
528 on_stack[w.to_usize()] = false;
529 class_to_scc[w.to_usize()] = scc_id;
530 members.push(w);
531 if w == v {
532 break;
533 }
534 }
535 scc_members.push(members);
536 }
537 let popped = call_stack.pop().unwrap();
539 if let Some(parent) = call_stack.last() {
540 let pi = parent.node.to_usize();
541 node_lowlink[pi] =
542 node_lowlink[pi].min(node_lowlink[popped.node.to_usize()]);
543 }
544 }
545 }
546 }
547
548 let num_sccs = scc_members.len();
549
550 let mut scc_adj: Vec<Vec<SccOf<Cfg>>> = vec![Vec::new(); num_sccs];
552 for (src_class, neighbors) in adj.iter().enumerate() {
553 let src_scc = class_to_scc[src_class];
554 for &dst_class in neighbors {
555 let dst_scc = class_to_scc[dst_class.to_usize()];
556 if src_scc != dst_scc {
557 scc_adj[src_scc.to_usize()].push(dst_scc);
558 }
559 }
560 }
561 for neighbors in &mut scc_adj {
562 neighbors.sort_unstable();
563 neighbors.dedup();
564 }
565
566 let mut in_degree: Vec<Cfg::Index> = vec![zero; num_sccs];
572 for neighbors in &scc_adj {
573 for &dst in neighbors {
574 in_degree[dst.to_usize()] = bump(in_degree[dst.to_usize()]);
575 }
576 }
577 let mut topo_order: Vec<SccOf<Cfg>> = Vec::with_capacity(num_sccs);
578 let mut queue: std::collections::VecDeque<SccOf<Cfg>> = std::collections::VecDeque::new();
579 for (i, scc) in crate::id::ids_upto::<SccOf<Cfg>>(num_sccs).enumerate() {
582 if in_degree[i] == zero {
583 queue.push_back(scc);
584 }
585 }
586 while let Some(scc) = queue.pop_front() {
587 topo_order.push(scc);
588 for &dst in &scc_adj[scc.to_usize()] {
589 in_degree[dst.to_usize()] =
593 crate::containers::index_like::checked_decr(in_degree[dst.to_usize()])
594 .expect("Kahn's decremented an in-degree already at zero");
595 if in_degree[dst.to_usize()] == zero {
596 queue.push_back(dst);
597 }
598 }
599 }
600 topo_order.reverse();
602
603 let mut bit_blocks: Vec<u64> = vec![0u64; num_sccs * words_per_scc];
605 let mut scc_spans: Vec<Span<<Cfg::Au as AuIds>::ReachBlock>> = Vec::with_capacity(num_sccs);
606 for i in 0..num_sccs {
607 scc_spans.push(Span::new(i * words_per_scc, words_per_scc));
608 }
609
610 for &scc in &topo_order {
612 let si = scc.to_usize();
613
614 let is_cyclic = scc_members[si].len() > 1
616 || (scc_members[si].len() == 1 && {
617 let c = scc_members[si][0];
618 adj[c.to_usize()].contains(&c)
619 });
620
621 if is_cyclic {
622 for &member in &scc_members[si] {
623 let bit = member.to_usize();
624 let word = scc_spans[si].start_usize() + bit / 64;
625 bit_blocks[word] |= 1u64 << (bit % 64);
626 }
627 }
628
629 for &dst_scc in &scc_adj[si] {
632 for &member in &scc_members[dst_scc.to_usize()] {
633 let bit = member.to_usize();
634 let word = scc_spans[si].start_usize() + bit / 64;
635 bit_blocks[word] |= 1u64 << (bit % 64);
636 }
637 }
638
639 for &dst_scc in &scc_adj[si] {
641 let dst_start = scc_spans[dst_scc.to_usize()].start_usize();
642 let src_start = scc_spans[si].start_usize();
643 for w in 0..words_per_scc {
644 bit_blocks[src_start + w] |= bit_blocks[dst_start + w];
645 }
646 }
647 }
648
649 let _ = au_to_repr;
651
652 let scc_reach_count: Vec<u32> = scc_spans
653 .iter()
654 .map(|span| {
655 let start = span.start_usize();
656 bit_blocks[start..start + words_per_scc]
657 .iter()
658 .map(|w| w.count_ones())
659 .sum()
660 })
661 .collect();
662
663 Reachability {
664 class_to_scc,
665 scc_spans,
666 bit_blocks,
667 scc_reach_count,
668 num_classes: num_classes as u64,
669 }
670 }
671}
672
673#[cfg(test)]
674mod tests {
675 use super::*;
676 use crate::egraph::EGraph31;
677 use crate::literal::NiraLitVal;
678
679 #[test]
682 fn reachability_self_loop() {
683 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
684 let int = eg.intern_sort("Int");
685 let x_op = eg.register_op0("x", int);
686 let f_op = eg.register_op1("f", int, int);
687
688 let x = eg.add(x_op, &[]);
689 let fx = eg.add(f_op, &[x]);
690 eg.merge(x, fx);
692 eg.rebuild();
693
694 let snap = AuSnapshot::new(&eg).unwrap();
695 let x_class = snap.class_of(x).unwrap();
696
697 assert!(snap.reachability().is_reachable(x_class, x_class));
699 }
700
701 #[test]
703 fn reachability_linear_chain() {
704 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
705 let int = eg.intern_sort("Int");
706 let a_op = eg.register_op0("a", int);
707 let f_op = eg.register_op1("f", int, int);
708 let g_op = eg.register_op1("g", int, int);
709
710 let a = eg.add(a_op, &[]);
711 let fa = eg.add(f_op, &[a]);
712 let gfa = eg.add(g_op, &[fa]);
713 eg.rebuild();
714
715 let snap = AuSnapshot::new(&eg).unwrap();
716 let a_class = snap.class_of(a).unwrap();
717 let fa_class = snap.class_of(fa).unwrap();
718 let gfa_class = snap.class_of(gfa).unwrap();
719
720 assert_ne!(a_class, fa_class);
722 assert_ne!(fa_class, gfa_class);
723
724 assert!(snap.reachability().is_reachable(gfa_class, fa_class));
726 assert!(snap.reachability().is_reachable(gfa_class, a_class));
727
728 assert!(snap.reachability().is_reachable(fa_class, a_class));
730
731 assert!(!snap.reachability().is_reachable(a_class, fa_class));
733 assert!(!snap.reachability().is_reachable(a_class, gfa_class));
734 }
735
736 #[test]
738 fn reachability_mutual_cycle() {
739 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
740 let int = eg.intern_sort("Int");
741 let x_op = eg.register_op0("x", int);
742 let y_op = eg.register_op0("y", int);
743 let f_op = eg.register_op1("f", int, int);
744 let g_op = eg.register_op1("g", int, int);
745
746 let x = eg.add(x_op, &[]);
747 let y = eg.add(y_op, &[]);
748 let fx = eg.add(f_op, &[y]); let gy = eg.add(g_op, &[x]); eg.merge(x, fx);
753 eg.merge(y, gy);
754 eg.rebuild();
755
756 let snap = AuSnapshot::new(&eg).unwrap();
757 let x_class = snap.class_of(x).unwrap();
758 let y_class = snap.class_of(y).unwrap();
759
760 assert!(snap.reachability().is_reachable(x_class, y_class));
762 assert!(snap.reachability().is_reachable(y_class, x_class));
763 assert!(snap.reachability().is_reachable(x_class, x_class));
765 assert!(snap.reachability().is_reachable(y_class, y_class));
766 }
767
768 #[test]
770 fn best_size_basic() {
771 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
772 let int = eg.intern_sort("Int");
773 let a_op = eg.register_op0("a", int);
774 let f_op = eg.register_op1("f", int, int);
775
776 let a = eg.add(a_op, &[]);
777 let fa = eg.add(f_op, &[a]);
778 eg.rebuild();
779
780 let snap = AuSnapshot::new(&eg).unwrap();
781 let a_class = snap.class_of(a).unwrap();
782 let fa_class = snap.class_of(fa).unwrap();
783
784 assert_eq!(snap.best_size(a_class), 1);
785 assert_eq!(snap.best_size(fa_class), 2);
786 }
787
788 #[test]
790 fn best_size_ac_multiplicity() {
791 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
792 let int = eg.intern_sort("Int");
793 let a_op = eg.register_op0("a", int);
794 let plus_op = eg.register_mset("plus", int, int);
795
796 let a = eg.add(a_op, &[]);
797 let plus_aa = eg.add(plus_op, &[a, a]);
798 eg.rebuild();
799
800 let snap = AuSnapshot::new(&eg).unwrap();
801 let a_class = snap.class_of(a).unwrap();
802 let plus_class = snap.class_of(plus_aa).unwrap();
803
804 assert_eq!(snap.best_size(a_class), 1);
805 assert_eq!(snap.best_size(plus_class), 3);
807 }
808
809 #[test]
811 fn members_exclude_subsumed() {
812 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
813 let int = eg.intern_sort("Int");
814 let a_op = eg.register_op0("a", int);
815 let b_op = eg.register_op0("b", int);
816
817 let a = eg.add(a_op, &[]);
818 let b = eg.add(b_op, &[]);
819 eg.merge(a, b);
821 eg.rebuild();
822 eg.subsume(b);
823
824 let snap = AuSnapshot::new(&eg).unwrap();
825 let class = snap.class_of(a).unwrap();
826 let members = snap.members(class);
827
828 assert_eq!(members.len(), 1);
830 }
831
832 #[test]
834 fn num_classes_correct() {
835 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
836 let int = eg.intern_sort("Int");
837 let a_op = eg.register_op0("a", int);
838 let b_op = eg.register_op0("b", int);
839 let c_op = eg.register_op0("c", int);
840
841 let a = eg.add(a_op, &[]);
842 let b = eg.add(b_op, &[]);
843 let _c = eg.add(c_op, &[]);
844 eg.rebuild();
845 let snap = AuSnapshot::new(&eg).unwrap();
847 assert_eq!(snap.num_classes(), 3);
848
849 drop(snap);
851 eg.merge(a, b);
852 eg.rebuild();
853 let snap2 = AuSnapshot::new(&eg).unwrap();
854 assert_eq!(snap2.num_classes(), 2);
855 }
856}