logicaffeine_compile/optimize/egraph/
extract.rs1use std::collections::HashMap;
10
11use super::{CompilerEGraph, CompilerENode, NodeId};
12
13#[derive(Debug)]
14pub struct ExtractTree {
15 pub node: CompilerENode,
16 pub children: Vec<ExtractTree>,
17}
18
19fn op_cost(node: &CompilerENode) -> u64 {
20 use CompilerENode::*;
21 match node {
22 Int(_) | Bool(_) | Float(_) | Var(..) => 1,
23 Opaque(_) => 4,
26 Add(..) | Sub(..) | Shl(..) | Shr(..) | BitXor(..) | BitAnd(..) | BitOr(..) | And(..)
27 | Or(..) | Not(..) | Eq(..) | Ne(..) | Lt(..) | Le(..) | Gt(..) | Ge(..) => 1,
28 Len(..) => 2,
29 Index(..) => 3,
30 Mul(..) => 4,
31 Contains(..) => 6,
32 Slice(..) => 8,
33 Copy(..) => 10,
35 Concat(..) => 8,
36 Div(..) | Mod(..) => 12,
37 }
38}
39
40fn best_costs(
45 eg: &mut CompilerEGraph,
46 admissible: &dyn Fn(&CompilerENode) -> bool,
47) -> HashMap<NodeId, (u64, NodeId)> {
48 let mut best: HashMap<NodeId, (u64, NodeId)> = HashMap::new();
49 loop {
50 let mut changed = false;
51 for id in 0..eg.node_count() {
52 let node = eg.canonical_node(id);
53 if !admissible(&node) {
54 continue;
55 }
56 let mut total = op_cost(&node);
57 let mut ready = true;
58 for c in node.children() {
59 match best.get(&c) {
60 Some(&(cc, _)) => total = total.saturating_add(cc),
61 None => {
62 ready = false;
63 break;
64 }
65 }
66 }
67 if !ready {
68 continue;
69 }
70 let root = eg.find(id);
71 match best.get(&root) {
72 Some(&(old, _)) if old <= total => {}
73 _ => {
74 best.insert(root, (total, id));
75 changed = true;
76 }
77 }
78 }
79 if !changed {
80 break;
81 }
82 }
83 best
84}
85
86fn build_tree(
87 eg: &mut CompilerEGraph,
88 best: &HashMap<NodeId, (u64, NodeId)>,
89 class: NodeId,
90) -> Option<ExtractTree> {
91 let root = eg.find(class);
92 let (_, rep) = *best.get(&root)?;
93 let node = eg.canonical_node(rep);
94 let children = node
95 .children()
96 .into_iter()
97 .map(|c| build_tree(eg, best, c))
98 .collect::<Option<Vec<_>>>()?;
99 Some(ExtractTree { node, children })
100}
101
102pub fn best_tree(eg: &mut CompilerEGraph, root: NodeId) -> ExtractTree {
104 let best = best_costs(eg, &|_| true);
105 build_tree(eg, &best, root).unwrap_or_else(|| panic!("class has no finite-cost representative"))
106}
107
108pub fn best_tree_filtered(
111 eg: &mut CompilerEGraph,
112 root: NodeId,
113 admissible: &dyn Fn(&CompilerENode) -> bool,
114) -> Option<ExtractTree> {
115 let best = best_costs(eg, admissible);
116 build_tree(eg, &best, root)
117}