Skip to main content

logicaffeine_compile/optimize/egraph/
extract.rs

1//! Bottom-up cost extraction (cycle-tolerant).
2//!
3//! LogosCost is a static per-op estimate tuned to the VM/JIT tier: shifts,
4//! adds and compares are unit ops; multiply is a few; divide/modulo are an
5//! order worse. Costs propagate to a per-class fixpoint — cyclic classes
6//! (x ≡ x + 0) simply never beat their finite leaf, so extraction always
7//! terminates with a finite tree.
8
9use 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 subtrees re-emit the original expression; bias against
24        // duplicating them when a modeled form exists.
25        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        // O(n) materialization — the fusion algebra exists to delete these.
34        Copy(..) => 10,
35        Concat(..) => 8,
36        Div(..) | Mod(..) => 12,
37    }
38}
39
40/// Per-class best (cost, representative node id), to fixpoint. Nodes the
41/// `admissible` filter rejects never become representatives — extraction
42/// for one statement must not reuse a STALE variable version or another
43/// statement's opaque (that would duplicate its effect).
44fn 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
102/// The cheapest finite tree representing `root`'s class.
103pub 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
108/// The cheapest finite tree whose every node passes `admissible`, or None
109/// when no such tree exists (the caller keeps the original expression).
110pub 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}