Next Article in Journal
Multi-Route Search and Adaptive Fusion for Power QA with Small Language Model Guidance
Previous Article in Journal
Remaining Useful Life Prediction for Special Gas Cylinders Based on SSA–PSO–ResNet–LSTM–Attention Framework
 
 
Font Type:
Arial Georgia Verdana
Font Size:
Aa Aa Aa
Line Spacing:
Column Width:
Background:
Article

Exact Pattern-Aware Extraction for Equality Saturation via Bounded-Depth Tree Covering

School of Computer Science, Wuhan University, Wuhan 430072, China
*
Authors to whom correspondence should be addressed.
Algorithms 2026, 19(5), 377; https://doi.org/10.3390/a19050377
Submission received: 8 April 2026 / Revised: 4 May 2026 / Accepted: 5 May 2026 / Published: 11 May 2026
(This article belongs to the Section Combinatorial Optimization, Graph, and Network Algorithms)

Abstract

Equality saturation explores equivalent program expressions via e-graphs, and its extraction step selects one representative per equivalence class to form an output tree. Standard extraction minimizes a decomposable per-node cost function that cannot capture multi-node structural patterns arising in SMT preprocessing and compiler instruction selection. We formalize pattern-aware extraction as a weighted pattern cover problem on AND-OR DAGs and establish its correspondence to tree covering in instruction selection. Three challenges arise when migrating tree covering to e-graphs: annotation ambiguity from multiple candidates per class, context-dependent selection from depth-2 templates, and DAG sharing conflict. We show that the coupled selection–tiling problem reduces to a tree DP with three mutually exclusive tile-role states, generalizing BURS tree covering from fixed trees to AND-OR DAGs. A bottom-up pass computes optimal DP values, and a top-down pass traces back decisions to produce the output tree. For template depth at most two, the algorithm computes an exact optimum in O ( N · K · | P | · C max ) time. The evaluation targets extraction-level coverage, since end-to-end performance additionally depends on rewrite-rule design and saturation completeness. On SMT-COMP benchmarks, the algorithm achieves up to 31 × higher weighted pattern coverage than standard extraction. Depth-2 tiling contributes 45–51% additional improvement, with overhead within 1.5 × of standard extraction.

1. Introduction

Equality graphs (e-graphs) [1] compactly represent congruence-closed equivalence classes of expressions. Equality saturation [2,3] uses this representation as a two-stage rewrite-based optimization framework: saturation applies rewrite rules to add equivalent expressions to the e-graph, and extraction selects one representative expression from the saturated e-graph. Because extraction commits to a concrete expression, its objective determines which equivalent expression is returned.
The egg framework [2] has made equality saturation practical for real-world workloads across several rewriting-based domains, including datapath optimization [4], DSP code generation [5], and CAD program synthesis [6]. With saturation now scaling to production-size rule sets, the extraction step becomes a meaningful optimization decision rather than a trivial readout. Yet the weighted-AST extraction built into egg evaluates candidates by a decomposable per-node cost and cannot express optimization value that depends on multi-node operator configurations. SMT solver preprocessing [7] and compiler instruction selection [8,9] are two domains where such multi-node configurations carry optimization value that individual node costs cannot capture. In compiler instruction selection, each machine instruction typically encodes a single computational step together with its operand access modes, so most matching rules cover one or two IR tree levels [8,9], although deeper patterns may arise in specialized architectures. In SMT preprocessing, theory-specific heuristics trigger simplifications by inspecting the root operator and its immediate argument structure [7]. The dominant local trigger configurations in both domains are therefore concentrated at depths one and two.
This gap between extraction capability and domain need has a structural cause. Standard egg extraction evaluates candidates by a per-node cost function, typically AST size, and commits to one representative per equivalence class, reused wherever that class appears. Two candidates with the same per-node cost are therefore indistinguishable even when only one participates in a high-value local structure. For instance, two implementations of the same operation may have identical AST size yet differ in whether they enable a valuable parent–child pattern match. A per-node objective cannot capture this distinction because the joint value of a multi-node configuration is not decomposable into independent per-node contributions (Section 4).
We formalize pattern-aware extraction as a weighted pattern cover problem on AND-OR DAGs, establishing its correspondence to tree covering in compiler instruction selection [8,9,10]. Three challenges arise when migrating tree covering to e-graphs. First, OR-node annotation ambiguity means that pattern applicability depends on which candidate is selected for each equivalence class rather than being an intrinsic property of the class. Second, context-dependent selection means that a depth-2 template can make a child’s optimal choice depend on its parent’s identity, breaking pure bottom-up evaluation. Third, DAG sharing conflict means that different parents referencing the same equivalence class may require incompatible child selections under a global commitment model. Fully general extraction with arbitrary non-decomposable cost functions is NP-hard [3]. However, in both compiler instruction selection and SMT preprocessing, the dominant pattern types are structurally confined to depth one and two (Section 6.1), and we exploit this structural restriction to obtain an exact, polynomial-time algorithm.
To exploit this structure, we develop a tree DP that assigns each node one of three mutually exclusive tile roles (independent, tile-root, or tile-leaf). The central observation is that the extraction output is a tree, so each reference to a shared equivalence class becomes an independent tree position resolvable with its own parent context. Three roles suffice to encode all non-overlapping tile assignments at depth two, and a two-pass architecture (bottom-up value computation, top-down context-dependent trace-back) separates optimal-value calculation from the final selection decisions.
Although each domain defines its own valuable configurations, the extraction problem they pose is structurally uniform. This paper treats the template vocabulary P as an explicit algorithmic input and focuses on the extraction algorithm in isolation. Template discovery, rewrite-rule design, and end-to-end downstream integration each depend on domain-specific factors outside the extraction algorithm and are left as independent problems. The main contributions are:
1.
We formalize pattern-aware extraction from e-graphs as a weighted pattern cover problem on AND-OR DAGs and establish its structural correspondence to tree covering in compiler instruction selection.
2.
We identify three challenges that arise when extending tree covering to e-graphs (OR-node annotation ambiguity, context-dependent selection, and DAG sharing conflict) and demonstrate how DAG-to-tree unfolding resolves them.
3.
We show that the coupled selection–tiling problem reduces to a tree DP with three mutually exclusive tile-role states and design an exact algorithm generalizing BURS tree covering from fixed trees to AND-OR DAGs in O ( N · K · | P | · C max ) time.
4.
We present experiments comparing the proposed algorithm against standard egg extraction on weighted pattern coverage, exactness, and runtime.
The remainder of this paper is organized as follows. Section 2 reviews related work on e-graph extraction, ILP-based extraction, and classical tree covering. Section 3 formalizes the e-graph model, template definitions, and the weighted pattern cover objective. Section 4 identifies three structural challenges that arise when migrating tree covering to e-graphs. Section 5 presents the three-state tree-covering DP algorithm. Section 6 proves exactness for depth at most two and analyzes time complexity. Section 7 reports experimental evaluation on controlled benchmarks. Section 8 concludes with a discussion of limitations and future directions.

2. Related Work

The extraction problem in equality saturation has grown in importance as e-graphs have been applied to compilers [5,11], SMT solvers [12], hardware verification [4], and manufacturing [6]. The standard extraction algorithm implemented in the egg framework [2] performs a single bottom-up traversal that computes a minimum-cost representative under a decomposable, single-node cost function such as abstract syntax tree size. This approach is efficient and provably optimal when costs decompose additively over individual nodes, but it cannot express objectives that depend on multi-node structural context. Earlier, Joshi et al. [11] used e-graphs in the Denali superoptimizer to generate optimal code via goal-directed search, demonstrating the potential of e-graphs for program optimization. However, Denali does not formalize an extraction-time objective. To handle more general, non-decomposable cost functions, Tate et al. [3] formulated extraction as an integer linear program (ILP), enabling global optimality at the expense of NP-hard worst-case complexity that limits scalability to large e-graphs.
The ILP formulation of Tate et al. [3] assigns one binary variable per (e-class, e-node) pair and selects one representative per e-class. This compact global-selection model can be extended with auxiliary binary variables that encode template-aware costs. For example, a template hit variable h for a parent–child pair can be constrained by h x parent , h x child , and h x parent + x child 1 , so that h = 1 exactly when both the parent and the child are selected. The limitation relevant to this paper is not template-cost expressiveness but rather the global-commitment constraint. Because each e-class receives a single representative that is reused at every occurrence, the model cannot express position-dependent decisions when a shared e-class appears under parents with differing contextual requirements (Section 4.3, Figure 1). An alternative position-indexed ILP formulation could encode the same unfolded-tree decisions used by our algorithm. Such a formulation would introduce one selection variable per unfolded tree occurrence and context state and would solve the resulting model with a generic integer solver. This observation shows that the position-dependent objective is expressible in a generic optimization language.
A closely related line of work originates from compiler instruction selection, where the tree covering problem seeks to partition a fixed expression tree into non-overlapping tiles matching instruction patterns at minimum total cost. Aho et al. [9] formalized code generation as tree matching with dynamic programming, and Pelegri-Llopart and Graham [10] established the BURS (Bottom-Up Rewrite System) framework with offline automaton compilation [13]. Both achieve optimal tree covering via bottom-up dynamic programming when the input is a fixed tree. However, extending tree covering from trees to DAGs, as required when expression DAGs contain shared subexpressions, renders the problem NP-complete [8]. Practical compilers such as GCC and LLVM, therefore, resort to unfolding DAGs into trees before applying instruction selection [14]. Our algorithm adopts the same unfolding principle but applies it to the AND-OR DAG structure of e-graphs, where each e-class (OR node) introduces candidate selection on top of the standard tile assignment problem. This additional degree of freedom necessitates a three-state DP that is the minimal extension of classical BURS to explicitly track the tile-leaf role arising from depth-2 mutual exclusivity. When the e-graph degenerates to a single-candidate-per-class tree, the algorithm reduces to the standard BURS.
These three lines of work address adjacent but distinct problems. Standard extraction is optimal for decomposable per-node objectives, yet cannot encode multi-node structural value. The compact global-selection ILP adds template-cost expressiveness but retains the global-commitment constraint analyzed above. Classical tree covering achieves optimal tiling on fixed trees but has not been adapted to the AND-OR DAG setting, where candidate selection and tile assignment must be resolved jointly. Our work occupies this intersection. Rather than targeting arbitrary cost functions with a generic solver, we exploit the bounded-depth, non-overlapping tile structure of the weighted pattern cover objective to obtain a direct polynomial-time extraction algorithm. To our knowledge, no prior work has migrated tree covering techniques to the e-graph extraction setting or formalized this objective on AND-OR DAGs.

3. Preliminaries and Problem Formulation

3.1. E-Graphs and Extraction

An e-graph  G = ( C , N ) consists of a finite set of equivalence classes (e-classes) C and a finite set of e-nodes  N  [1,2]. Each e-node n N has the form Op ( c 1 , , c k ) , where Op is an operator symbol with arity k 0 and c 1 , , c k C are its child e-classes. Every e-node belongs to exactly one e-class, and all e-nodes within the same e-class represent expressions that have been proven equivalent by the rewrite rules applied during saturation. Each e-class additionally carries analysis data, a summary of semantic properties (such as constant values, bit-widths, or variable occurrences) computed by a lattice-based fixed-point procedure over the e-graph [2].
An e-graph admits a natural interpretation as an AND-OR directed acyclic graph. Each e-class acts as an OR node, meaning exactly one of its member e-nodes must be selected, while each e-node acts as an AND node, meaning once selected, all of its child e-classes must be recursively resolved. Extraction is the process of traversing this AND-OR DAG to produce a concrete expression tree. In standard extraction [2], a selection function  ϕ : C N maps each e-class c to a single representative ϕ ( c ) c . The resulting output T ( ϕ ) is a tree obtained by recursively expanding from a designated root e-class. Because ϕ assigns a single e-node to each e-class globally, every reference to the same e-class in the DAG resolves to the same candidate.

3.2. Pattern Templates

To formalize the notion that certain multi-node operator configurations carry value beyond what per-node costs can express, we introduce pattern templates.
Definition 1.
A pattern template is a four-tuple p = ( S p , Π p , d p , w p ) where:
  • S p is a structural schema, a rooted operator tree of depth d p , in which each position is annotated with either a required operator type or a wildcard *;
  • Π p = { π 1 , , π m } is a finite set of predicate constraints. Each π i is a Boolean function over operator types and analysis-data fields at the schema positions. Available inputs include operator identifiers, arities, and per-e-class attributes maintained by the analysis framework (Section 3.1), such as whether an argument is a defined variable ( is _ var ( c ) ), whether it holds a constant value ( val ( c ) = k ), or its bit-width ( bw ( c ) = w ). No predicate requires global e-graph traversal or external solver invocation;
  • d p { 1 , 2 } is the template depth;
  • w p R + is a positive weight quantifying the objective value assigned to the pattern.
Let P denote a finite template vocabulary, that is, a finite set of pattern templates conforming to Definition 1. We treat P as part of the problem input and assume | P | is a moderate constant in practice.
Template depth is the key parameter that governs algorithmic difficulty. A depth-1 template constrains only a single e-node and its immediate children; its match status can be determined from the e-node and its children’s analysis data alone. Structural primitives such as bit-field extraction ( Extract ) or zero-extension ( ZeroExtend ) are recognized as depth-1 templates since the downstream system processes them directly without further transformation. A depth-2 template additionally constrains the parent operator. The canonical example is Eq BvAdd ( x , c ) , k with predicates π 1 : is _ var ( BvAdd . arg 1 ) and π 2 : val ( Eq . arg 2 ) = k . The downstream simplifier can then isolate the variable ( x = k c ), triggering variable elimination. However, this applicability cannot be assessed without examining the parent–child pair together since neither a standalone BvAdd nor a standalone Eq (whose arguments are not bare variables) satisfies any depth-1 template.
The weight w p quantifies how strongly the extraction objective favors a matched pattern. For depth-2 templates, a strict super-additivity constraint is imposed
w p > w 1 max ( Op parent ) + w 1 max ( Op child ) ,
where w 1 max ( Op ) denotes the best depth-1 weight achievable by operator type  Op . Super-additivity encodes the design assumption that a depth-2 parent–child configuration is more valuable than the sum of its component parts. This is the defining characteristic of a non-compositional objective, where the joint value of a multi-node structure exceeds what independent per-node scoring can express. Super-additivity makes a depth-2 tile dominate the two independent depth-1 contributions it replaces, but the DP still chooses globally among competing subtree alternatives. This property enables the ablation experiment (Section 7) to cleanly isolate the incremental contribution of depth-2 tiling.

3.3. Optimization Objective

Given an e-graph G and a vocabulary P as above, the extraction objective is to select a tree T ( ϕ ) that maximizes the total weighted pattern coverage. We formulate this objective as a tree covering problem, directly adopting the classical framework from compiler instruction selection [8,9,10]. Let μ ( v , p ) be a Boolean predicate that evaluates to true if and only if tree node v, together with its parent in T ( ϕ ) when d p = 2 , satisfies the structural schema S p and all predicate constraints Π p of template p.
A covering of a tree T partitions its nodes into non-overlapping tiles, each matching a template from  P . Every node carries a default contribution from a decomposable weighted-AST cost function κ ( Op ) that assigns a per-operator weight. A depth-1 tile covers a single node v with value
w 1 ( v ) = max { w p p P 1 , μ ( v , p ) } { κ ( Op ( v ) ) } .
Because explicit template weights are positive while the default contribution κ ( Op ( v ) ) is non-positive, any matching depth-1 template overrides the weighted-AST fallback. When no template matches, the node retains its default cost κ ( Op ( v ) ) . This formulation makes the pattern-aware objective a strict generalization of standard weighted-AST extraction. When the template vocabulary P is empty, every node evaluates to w 1 ( v ) = κ ( Op ( v ) ) , and maximizing total cover value is equivalent to minimizing total AST cost, recovering standard egg extraction behavior.
A depth-2 tile covers a parent–child pair ( u , v ) with joint value  w p from the matching depth-2 template. This joint value replaces both individual depth-1 contributions w 1 ( u ) and w 1 ( v ) that the tile subsumes. The cover value of a tree is the total weight under its optimal covering:
CoverValue ( T ) = max T Cov ( T ) t T w t ,
where Cov ( T ) denotes the set of valid coverings of T and w t is the weight of tile t. A structural constraint on the template set is mutual exclusivity: for any tree node v with a determined parent context, at most one p P satisfies μ ( v , p ) = true . This is natural since the downstream simplification rules apply disjointly; any residual overlap is resolved by retaining only the highest-weight template for each schema. Because a depth-2 tile covers a parent–child pair, each parent node can participate in at most one depth-2 tile. When depth-2 templates apply at multiple child positions of the same parent, the algorithm selects the single most beneficial option (Section 5).
Under mutual exclusivity, the tile assignment at each tree node reduces to selecting one of three mutually exclusive roles: using a depth-1 tile independently, serving as a root of a depth-2 tile with one child, or being subsumed as a leaf of a parent’s depth-2 tile. This three-way choice with local parent–child coupling admits a tree DP formulation (Section 5). The key difference from classical tree covering is that our problem must simultaneously select the tree from the AND-OR DAG and optimize its covering, as the tree itself is a decision variable, introducing the challenges analyzed in Section 4.

4. Challenges: Beyond Classical Tree Covering

Classical tree covering [9,10] operates on a fixed expression tree where every node has a predetermined operator, enabling straightforward bottom-up annotation and top-down selection. The AND-OR DAG structure of an e-graph violates this premise in three ways.

4.1. OR-Node Annotation Ambiguity

In a fixed expression tree, each node carries a single operator, and the set of patterns applicable at that node is deterministic. In an e-graph, each e-class (OR node) contains multiple semantically equivalent e-nodes whose operator types may differ entirely. When a bottom-up pass reaches an e-class c, there is no single operator to annotate: one e-node in c may be BvAdd ( c 1 , c 2 ) , another BvOr ( c 1 , c 2 ) (semantically equivalent when the operands have non-overlapping bit ranges). Each exposes a different operator to any parent referencing c. The former can participate in variable-isolation templates under an equality parent, while the latter cannot. Consequently, the pattern-match status of c is not a fixed attribute but a function of the selection decision  ϕ ( c ) , a variable that has not yet been determined at annotation time. A bottom-up pass must therefore retain annotation information for every candidate in every e-class rather than committing to a single best choice, multiplying the state space relative to classical tree covering.

4.2. Context-Dependent Selection

The ambiguity described above could, in principle, be resolved by a single bottom-up pass that evaluates all candidates and selects the one maximizing the depth-1 contribution. Depth-2 pattern templates defeat this strategy by coupling the child’s value to the parent’s identity.
Consider an e-class c containing two candidates: n 1 = BvAdd ( c x , c off ) and n 2 = BvOr ( c x , c off ) , both semantically equivalent because the operands occupy non-overlapping bit ranges. For readability, this example sets the weighted-AST fallback cost κ ( Op ) to zero for all involved operators, so that Equation (2) reduces to w 1 ( n ) = 0 whenever no explicit depth-1 template matches. Evaluating depth-1 templates alone, n 1 receives w 1 ( n 1 ) = 0 (addition does not match any depth-1 template), while n 2 matches a depth-1 bitwise-OR simplification template with w 1 ( n 2 ) = w 1 > 0 . Bitwise OR avoids the carry-chain propagation inherent in addition, making it the preferred operand form, so a single bottom-up pass would commit to  n 2 . Now suppose a parent e-node n parent = Eq ( c , c k ) exists, where c k holds a constant, and neither argument of the equality is a bare variable ( w 1 ( n parent ) = 0 under the simplified fallback). If c selects n 1 = BvAdd instead of the depth-1-optimal  n 2 , the parent–child pair jointly satisfies the depth-2 variable-isolation template described in Section 3.2: the downstream simplifier recognizes Eq ( BvAdd ( x , c off ) , k ) and derives x = k c off , triggering variable elimination with weight  w p > w 1 . This pattern reflects the solve_eqs heuristic in Z3 [7], which eliminates variables by recognizing isolatable arithmetic equalities. Without the addition–equality configuration, this heuristic cannot trigger. Under a different parent (say BvUle ( c , c ) ), no depth-2 template applies, and the depth-1 preference for  n 2 remains optimal.
The crux is that a bottom-up pass processes c before any parent information is available, yet the optimal selection depends on the parent operator breaking the optimal substructure that single-pass dynamic programming requires. Neither a pure bottom-up pass (lacking parent context) nor a pure top-down pass (lacking subtree costs) can resolve this dependency alone.
This context dependence is a structural limitation of decomposable, single-node cost functions, which satisfy three invariants: (i) decomposability (cost decomposes additively over individual nodes); (ii) context independence (evaluation does not depend on the parent operator); and (iii) global commitment (each equivalence class receives a single selection reused at every reference site). Invariant (ii) prevents encoding the joint value of a parent–child pair, and invariant (iii) prevents executing different selections at different tree positions. As Figure 1 illustrates, the two candidates in c have identical AST size, and a depth-1 evaluation globally prefers  n 2 ( w 1 > 0 ), yet only BvAdd enables the depth-2 match under Eq . Neither a decomposable cost function nor a depth-1-only evaluation captures this position-specific opportunity.

4.3. DAG Sharing Conflict

Context-dependent selection is further complicated by DAG sharing, a characteristic that renders optimal covering on shared DAGs NP-complete [8,14]. A single e-class may be referenced by multiple parents imposing different depth-2 requirements. As in Figure 1, Eq ( c , c k ) prefers c to select BvAdd for variable isolation, while BvUle ( c , c ) prefers BvOr . Under global selection, optimizing for one parent context necessarily sacrifices the other.
These three challenges are absent from classical tree covering [9,10] and collectively preclude direct migration of instruction-selection algorithms. Section 5 shows that the tree-shaped nature of the extraction output resolves all three.

5. Extraction Algorithm

The three challenges identified in Section 4 translate into three capability requirements for a pattern-aware extraction algorithm. It must retain structural information for all candidates within each e-class to accommodate annotation ambiguity, encode parent–child context dependency so that a child’s contribution can vary with the referencing parent, and support position-dependent decisions at each reference site to overcome DAG sharing conflict.

5.1. Key Insight: Extraction Output Is a Tree

The extraction output is a concrete expression tree: when the same e-class is referenced at multiple positions, each reference corresponds to an independent tree node. Because all candidates within an e-class are semantically equivalent, different positions may select different candidates without affecting correctness. Unfolding the AND-OR DAG into the output tree ensures that every node has exactly one parent, making the tile-role assignment at each position unambiguous. This mirrors the standard DAG-to-tree unfolding in compiler instruction selection [8,14].
This insight enables a two-pass approach. A bottom-up pass computes optimal subtree values under every possible tile-role assignment, and a top-down pass traces back these pre-computed values to construct the output tree. Table 1 summarizes the design rationale.

5.2. Three-State Tree-Covering DP

Tile-role states. Depth-2 templates introduce only a local dependency between a parent and one child, not arbitrary global constraints. Because tiles are non-overlapping and each covers at most two levels, a node’s covering role reduces to three possibilities: acting independently, initiating a depth-2 tile as root, or being subsumed by a parent’s tile as leaf. These three cases exhaust all tile roles under the depth 2 constraint. The resulting parent–child state coupling ( ) places the problem in the class of tree DPs with constrained state assignment. This well-studied framework encompasses maximum weighted matching and maximum independent sets on trees.
The coupling between candidate selection and tile assignment (Section 4) is resolved by decomposing each node’s role into three mutually exclusive states:
  • State − (independent): The node contributes w 1 ( n ) (Equation (2)), and all children are free (state − or ↓).
  • State ↓ (tile-root): The node forms a depth-2 tile with one selected child; the chosen child enters state ↑, and all others remain free.
  • State ↑ (tile-leaf): The node is committed by its parent’s depth-2 tile and forms no tile of its own; all children are free.
A node cannot simultaneously be tile-root and tile-leaf, as this would place it in two overlapping tiles. The assignment of state ↑ is decided by the parent, who evaluates whether committing the child improves the total covering value. This asymmetry resolves depth-2 context dependence (Section 4.2) without violating optimal substructure.
Template compilation. Before the DP begins, the template set P is compiled offline into two hash-indexed lookup tables. T 1 [ Op ] maps each operator to its depth-1 templates, and T 2 [ Op parent , pos , Op child ] maps each (parent operator, child position, child operator) triple to its depth-2 templates. Both support O ( 1 ) lookup. A single key may index multiple templates differing only in predicate constraints  Π p .
Per-e-node structural information. For each e-node n = Op ( c 1 , , c k ) , the bottom-up pass computes three quantities that together characterize n’s potential tile roles before evaluating the DP recurrences. The depth-1 contribution  w 1 ( n ) measures the best value n can achieve as an independent tile. It is computed according to Equation (2) in Section 3.3. The implementation looks up matching depth-1 templates in T 1 [ Op ] and takes the maximum weight among satisfied templates, falling back to the weighted-AST default   κ ( Op ( n ) ) when no explicit template matches. The compatibility signature  σ ( n ) then summarizes which parent operators could form a depth-2 tile with n as tile-leaf. Its computation uses the predicate profile  π ( n ) , a bitvector where π ( n ) [ i ] = 1 if child e-class c i contains only constants or variables. Formally, σ ( n ) [ f parent ] = 1 iff a position i and a template p T 2 [ f parent , i , Op ] exist whose predicates Π p are satisfied. Because the input space ( Op , π ) is finite, the mapping ( Op , π ) σ can be pre-compiled into a static lookup table (analogous to BURS automaton state compilation [10,13]), yielding O ( 1 ) per e-node. Finally, the per-e-class aggregate σ ( c ) = n c σ ( n ) enables pruning of unnecessary depth-2 evaluations. If σ ( c ) [ Op ] = 0 , no candidate in c can serve as tile-leaf for parent operator Op , and the depth-2 evaluation for that child position is skipped entirely.
Bottom-up DP values. Each state’s optimal value depends only on the subtree below the node. The parent determines which state a child enters, but does not affect the optimal value within that state, establishing the optimal substructure that the bottom-up pass exploits.
The bottom-up pass requires an acyclic e-graph. Cyclic e-nodes are removed by a standard preprocessing step [2]. For each e-node n = Op ( c 1 , , c k ) in topological order, after computing structural information, three DP values are computed. In state ↑ (tile-leaf), n is committed by its parent and forms no tile:
V ( n ) = i = 1 k V * ( c i ) .
In state − (independent), n contributes its depth-1 value w 1 ( n ) :
V ( n ) = w 1 ( n ) + V ( n ) .
In state ↓ (tile-root), n selects child position j, template p, and candidate n j c j to form a depth-2 tile; n j enters state ↑, and the other children are free:
V ( n ) = max j , n j c j , p T 2 Π p satisfied w p + V ( n j ) + i j V * ( c i ) .
If no depth-2 template matches, V ( n ) = . After all e-nodes are processed, each e-class aggregates the best free value:
V * ( c ) = max n c max V ( n ) , V ( n ) .
V * ( c ) does not bind a specific candidate. Candidate selection is deferred to trace-back. The complete bottom-up procedure is given in Algorithm 1.
Algorithm 1: Bottom-Up DP Pass
Algorithms 19 00377 i001
Top-down trace-back. Because a single-direction pass cannot simultaneously access parent context and subtree costs (Section 4.2), the bottom-up pass defers all commitment, and the top-down pass resolves each node’s actual state once the parent’s decision is known.
Starting from the root e-class, the trace-back recursively selects candidates and assigns tile roles using pre-computed DP values. When an e-class c is free (not committed by its parent), the procedure selects the candidate n * achieving V * ( c ) and compares V ( n * ) against V ( n * ) . If V ( n * ) > V ( n * ) , n * enters state ↓, forming a depth-2 tile with the recorded best child n j , which enters state ↑, while all other children are recursed as free. Otherwise, n * enters state −, and all children are free. When c is committed with a specific candidate n c , that candidate enters state ↑, meaning no tile is formed, and all children are recursed as free.
Recursive calls carry no visit markers since DAG-to-tree unfolding (Section 5.1) ensures each tree position is an independent subproblem. The complete procedure is given in Algorithm 2.
Algorithm 2: Top-Down Pass: Trace-Back
Algorithms 19 00377 i002

5.3. Illustrative Example

We revisit the running example from Section 4 (Figure 2a). For readability, this toy instance sets the weighted-AST fallback cost κ ( Op ) to zero for all involved operators, so that Equation (2) reduces to w 1 ( n ) = 0 whenever no explicit depth-1 template matches. Nonzero fallback terms κ ( Op ) add the corresponding contributions without changing the parent-context dependency illustrated here.
E-class c contains n 1 = BvAdd ( c x , c off ) and n 2 = BvOr ( c x , c off ) . Candidate  n 1 does not match any depth-1 template, so w 1 ( n 1 ) = 0 under the simplified fallback. Candidate  n 2 matches a depth-1 bitwise-OR simplification template with w 1 ( n 2 ) = w 1 > 0 . Denoting S = V * ( c x ) + V * ( c off ) , the bottom-up pass yields V ( n 1 ) = V ( n 2 ) = S , V ( n 1 ) = S , and V ( n 2 ) = w 1 + S . Neither serves as tile-root, so V ( n 1 ) = V ( n 2 ) = and V * ( c ) = w 1 + S , with n 2 as the best free candidate. Meanwhile, the depth-2 variable-isolation template p fires when an Eq parent pairs with a BvAdd child, so σ ( n 1 ) [ Eq ] = 1 while σ ( n 2 ) [ Eq ] = 0 .
At Position Eq (Figure 2b, left), the parent n parent = Eq ( c , c k ) computes V ( n parent ) = w p + V ( n 1 ) + V * ( c k ) = w p + S + V * ( c k ) and V ( n parent ) = V * ( c ) + V * ( c k ) = w 1 + S + V * ( c k ) (with w 1 ( n parent ) = 0 under the simplified fallback). Since V V = w p w 1 > 0 , the trace-back selects state ↓, committing c to candidate n 1 in state ↑. The depth-2 gain  w p outweighs the forgone depth-1 weight  w 1 of  n 2 .
At Position BvUle (Figure 2b, right), the parent n parent = BvUle ( c , c ) finds no applicable depth-2 template ( V = ), so it selects state −, leaving c free. The trace-back selects n 2 = BvOr , which contributes its depth-1 weight  w 1 . The two decisions are independent: Position Eq selects BvAdd via state ↓ for the depth-2 match, while Position BvUle retains BvOr via state − for the depth-1 match, consistent with the DAG-to-tree unfolding principle of Section 5.1.

6. Theoretical Analysis

This section establishes three results for the algorithm of Section 5. First, it proves the exactness of the optimum for template sets with depth at most two. Second, it analyzes polynomial time complexity. Third, it characterizes the precise applicability boundary of the three-state formulation and the extension path for deeper templates.

6.1. Exactness for Bounded-Depth Templates

Proposition 1.
For any e-graph G and pattern template set P satisfying mutual exclusivity (Section 3.3) with max p P d p 2 , the output tree T produced by Algorithm 2 maximizes CoverValue ( T ) as defined in Equation (3).
Proof. 
The argument establishes that the three-state DP computes an optimal tile covering on the output tree.
Step 1 (Exhaustive state coverage). Every output-tree node is assigned exactly one of the three states { , , } . The DP computes the optimal subtree value under each state (Equations (4)–(6)), and the trace-back (Algorithm 2) selects the best.
Step 2 (Mutual exclusivity). When n enters state ↓ with child n j , the recurrence (Equation (6)) uses V ( n j ) , which excludes any tile for n j itself. Conversely, when n is committed to state ↑ by its parent, V ( n ) excludes any tile-root role for n. The coupling thus correctly enforces non-overlapping tiles.
Step 3 (Optimal substructure). Processing in topological order ensures that all V * ( c i ) values are finalized before any e-node referencing c i is processed. Each state’s value depends only on the subtree below n. The recurrences in Equations (4)–(6) therefore omit the parents’ identity. The parent determines which state n enters, but not the optimal value within each state.
Step 4 (Trace-back exactness). Algorithm 2 selects at each e-class the candidate and state achieving the pre-computed optimum. DAG unfolding ensures that each tree position is an independent subproblem with its own parent context. No heuristic is involved.    □
Proposition 1 guarantees exact optimality for template sets of depth at most two. When no depth-2 template is present, the tile-root state never improves upon the independent state, and the algorithm reduces to decomposable per-node extraction under w 1 . If no explicit depth-1 template overrides the fallback for any node, this further coincides with standard weighted-AST extraction. The three-state formulation is therefore a conservative extension of decomposable-cost extraction.

6.2. Extension Beyond Depth Two

The three-state DP of Section 5 is an exact instantiation for d p { 1 , 2 } as defined in Definition 1. Deeper exact extraction requires the state to record not only whether the current node is covered by its parent, but also which suffix of the started template remains to be matched.
A true depth-d tile covers operator nodes across layers 0 through d 1 . Once the tile root has been selected, intermediate layers must propagate a matching obligation downward: each obligation encodes which layer of the started template the current node occupies and what suffix its descendants must still satisfy. For a compiled template set, let Ω ( P ) be the finite set of such obligations induced by all templates in  P . The DP state space becomes
S > 2 = { } Ω ( P ) ,
where state − denotes a free node. The number of obligation states is bounded by the number of distinct template suffixes, which can grow with template depth and branching structure but remains constant for any fixed template set. Per-e-node processing is therefore polynomial in the e-graph size, consistent with classical BURS finite-state tree-automaton results [10,13].
Not every use of deeper information requires this state-space extension. If a template still covers only a two-layer structure but queries descendant summaries through e-class analysis, no additional obligation state is needed; only the local predicate checker changes. Conversely, approximating a true depth-3 tile by several depth-2 proxies can be useful as a heuristic, but it no longer preserves the exact optimum of the original depth-3 covering objective. The obligation-state extension is needed precisely when a single tile physically covers three or more layers of operator nodes.
To verify that the obligation-state extension recovers exact optimality for depth-3 tiles, we construct the synthetic AND-OR DAG shown in Figure 3, with seven e-classes and two depth-3 templates p A = A ( B ( C ( _ ) ) ) and p Q = Q ( B ( D ( _ ) ) ) , each with weight 10. The critical feature is the shared OR node E x , referenced by both A and Q: because each template spans three operator layers, matching requires a three-state obligation chain that propagates from root to leaf.
The witness validates the obligation-state extension on a concrete instance. Standard extraction selects one representative for each e-class globally; for E x , any fixed choice satisfies at most one of the two templates, yielding a score of 10. The optimum requires context-dependent selection: B 1 ( E c ) under A for p A and B 2 ( E d ) under Q for p Q (blue and orange paths in Figure 3). A brute-force oracle over all nine tree unfoldings confirms a score of 20. The obligation-state DP, indexed by e-class and pending template suffix, matches this optimum exactly.

6.3. Time Complexity

Let N denote the number of e-nodes, K the maximum arity, | P | the template set size, C max the maximum e-class size, and M the output tree size. Table 2 summarizes the cost.
The bottom-up pass visits each e-node once. For each e-node n, computing w 1 ( n ) and σ ( n ) inspects templates in T 1 and T 2 . Each predicate π Π p evaluates in constant time because Definition 1 restricts predicate inputs to operator types, arities, and e-class analysis data at schema positions. In the egg framework, every e-class maintains a fixed-size data record summarizing semantic properties of the represented expressions, including constant values, bit-widths, and variable status. This record is updated incrementally during equality saturation through a lattice-based merge operation [2], so querying any field at extraction time is an O ( 1 ) table lookup. When predicates involve nontrivial computation beyond these local lookups, the per-template cost becomes O ( Q max ) and multiplies the bottom-up phase complexity accordingly. Computing V ( n ) and V ( n ) costs O ( K ) . Computing V ( n ) iterates over child positions (K), applicable templates ( | P | ), and candidates within each child e-class ( C max ), yielding O ( K · | P | · C max ) per e-node. Standard egg extraction runs in O ( N · K )  [2]. The overhead is a factor of | P | · C max , both moderate constants in practice.
The top-down pass visits each of the M output-tree nodes once, reading the pre-computed decision at O ( K ) cost per node. No template evaluation occurs during trace-back. The combined worst-case complexity is O ( N · K · | P | · C max + M · K ) , dominated by the bottom-up pass. When C max is bounded, this simplifies to O ( N · K · | P | ) .

7. Experiments

7.1. Experimental Setup

The evaluation targets the extraction algorithm in isolation, measuring its coverage quality, correctness, and runtime rather than end-to-end application performance. Downstream performance depends jointly on the rewrite-rule set, the extraction strategy, and the saturation budget. Attributing gains to any one component requires controlling the other two. Moreover, the current equality saturation ecosystem has not yet provided an end-to-end rewrite optimization pipeline for domains such as SMT preprocessing, so downstream integration remains a problem whose prerequisites do not yet exist. By fixing rewrite rules and saturation parameters, the experiments directly measure the extraction algorithm’s intrinsic contribution. All experiments are implemented in Rust atop egg 0.11 [2]. The three extraction strategies share the same e-graph representation and template infrastructure so that observed differences are attributable solely to the extraction logic. The DP implementation computes finite extraction trees over cyclic e-graphs, matching the finite-RecExpr semantics of standard extraction.
Benchmarks. The main evaluation uses three benchmark groups. A separate set of constructed micro cases in Section 7.4 is used only to illustrate the ILP modeling distinction and is not part of the runtime benchmark suite. SMT-COMP verification formulas (21 instances) are drawn from the QF_BV and QF_ABV divisions of the 2024 SMT-COMP library [15], originating from hardware verification workloads (PicoRV32, VexRiscv, ZipCPU, and arbiter). Each formula is saturated with an iteration budget of 10 and a node limit of 10 5 . Resulting e-graphs range from 10 4 to 2.4 × 10 5 e-classes, with C max = 2 –4. Of these, 13 instances have operator compositions intersecting the template set ( CoverValue > 0 ). Table 3 reports the 10 distinct coverage profiles (three further instances from the same families yield identical ratios and are omitted). The remaining 8 instances contain exclusively non-template operators. Synthetic benchmarks (3 instances; 15–80 assertions) embed known depth-2 patterns (mask-shift, high-mask equality, and addition-equality isolation) alongside depth-1 patterns in QF_BV formulas; after saturation, they contain 88–378 e-classes. A third set of micro instances (29–35 e-classes) supports brute-force correctness verification (Section 7.5).
Templates. The template set comprises three depth-1 templates and three depth-2 templates satisfying the super-additivity constraint of Section 3.2, with | P | = 6 . These templates serve as anti-pattern pressure targets for the extraction objective. They define parent–child operator configurations intended to create controlled conflict with decomposable weighted-AST local selection, so that the experiment tests whether the full extraction mechanism deviates from per-node locally optimal choices when the objective requires it. The degree of actual conflict is validated by the anti-pattern conflict rate R anti reported in Section 7.3. Whether these specific configurations correspond to downstream simplification opportunities is a separate question not addressed by this evaluation. Under the default weight assignment, depth-1 weights range from 3 to 5 and depth-2 weights from 12 to 14.
Strategies. Three strategies are compared: standard extraction (decomposable weighted-AST cost [2]), depth-1 only (Algorithm 1 with V disabled), and full three-state (Algorithms 1 and 2). The weighted-AST cost assigns a per-operator weight to each node and reduces to plain AST-size minimization when all weights equal one. We do not report a compact global-selection ILP [3] as a direct baseline because it optimizes a different feasible set in which each e-class has one representative reused at all occurrences. Section 2 clarifies the distinction between global-selection ILP and position-dependent output-tree extraction. A position-indexed ILP would encode the same unfolded-tree decisions, but would constitute a generic solver formulation rather than a separate extraction algorithm. Section 7.4 provides a micro model comparison that isolates this modeling distinction on constructed examples.

7.2. Extraction Quality

Pattern awareness vs. standard extraction. Table 3 compares CoverValue ( T ) across the three strategies. On the VexRiscv and bv-format benchmark families, pattern-aware extraction (both depth-1-only and full three-state) yields 16–31× higher CoverValue than standard weighted-AST extraction. On PicoRV32 instances, the initial workload does not contain operator compositions that can be rewritten into template-matching forms during saturation, so all three strategies yield identical CoverValue. The algorithm degenerates to standard extraction when no template opportunity exists, demonstrating conservativeness. Coverage gains scale with the density of template-matchable operators in the workload, confirming that the mechanism does not manufacture artificial improvements.
Depth-2 ablation. Table 4 isolates the incremental contribution of the V mechanism on the synthetic benchmarks, which are designed with sufficient depth-2 pattern density to exercise the three-state DP. The full strategy improves CoverValue by 45– 51 % over the depth-1-only baseline, with depth-2 tile hits increasing from 6–28 (incidental matches under depth-1 optimization) to 10–50 (intentional matches under the three-state DP). Following the same separation used in BURS instruction selection [8,9,10], the synthetic benchmarks validate the V mechanism itself. The objective sensitivity experiment in Section 7.3 further confirms that this conclusion is not an artifact of one hand-chosen weight assignment.

7.3. Objective Sensitivity

The preceding ablation uses one hand-chosen weight assignment. Two concerns motivate further investigation. First, the CoverValue gain could depend on the specific numerical weights rather than on the extraction mechanism itself. Second, one must verify that the full extractor is genuinely resolving conflicts with per-node local selection rather than exploiting structures that decomposable extraction already selects. This section varies the weight function w p while holding the saturated e-graphs and template predicates fixed and reports two structural diagnostics alongside the weighted objective.
Metrics. Three quantities are recorded for each benchmark and weight condition. The normalized objective gain
G obj = CoverValue Full CoverValue D 1 max ( 1 , CoverValue D 1 )
measures the relative advantage of the full extractor under a given weight setting. The depth-2 exposure gap
G 2 = O 2 ( T Full ) O 2 ( T D 1 )
counts how many additional depth-2 parent–child structures the full extractor exposes compared to depth-1-only extraction. The anti-pattern conflict rate  R anti measures the fraction of depth-2 tiles selected by the full extractor whose parent or child e-node differs from the choice made by decomposable weighted-AST extraction on the same e-class. A high R anti confirms that the templates create genuine conflict with per-node local selection, validating the pressure-test design. Neither G 2 nor R anti uses template weights in its definition, but both are evaluated on extracted trees that may differ across weight conditions because the extraction itself depends on weights. Whether these structural metrics remain stable is therefore an empirical question answered below.
Weight conditions. Four fixed conditions are evaluated: low-D2 (depth-2 weights just above the super-additivity boundary), original (default weights from Table 4), mid-D2 (moderate margin), and high-D2 (large margin). Additionally, 30 random admissible assignments are generated by sampling depth-1 weights from [ 1 , 5 ] and setting each depth-2 weight as
w p = α · B ( p ) , α U ( 1.1 , 3.0 ) ,
where B ( p ) is the super-additivity boundary.
Results. The structural metrics remain invariant across all fixed weight conditions on the synthetic benchmarks. Table 5 reports the results. The depth-2 exposure gap G 2 stays at 4, 10, and 22 on the small, medium, and large instances, respectively, regardless of the weight condition, and the anti-pattern conflict rate R anti remains stable at 78– 80 % . The normalized objective gain G obj varies from + 70 % to + 153 % across instances and weight conditions but remains positive under every admissible parameterization.
Table 6 summarizes the 30 random-weight runs. The CoverValue delta varies with the sampled weights, yet the depth-2 exposure gap and anti-pattern conflict rate again show zero variance across all 30 profiles. This confirms that the structural advantage of the full extractor is determined by the e-graph topology and template predicates rather than by the numerical weight assignment.
On SMT-COMP instances where core templates produce no legal depth-2 parent–child pair, the full extractor yields G 2 = 0 and matches depth-1-only extraction exactly, consistent with the conservativeness observed in Section 7.2.
Interpretation. The invariance of G 2 and R anti across 34 weight conditions shows that the full extractor’s advantage is a structural property of the three-state DP rather than a consequence of weight tuning. Because the anti-pattern conflict rate exceeds 78 % in all conditions, a high fraction of selected depth-2 tiles involve parent or child choices that differ from decomposable weighted-AST local selection, confirming that the pressure templates create genuine non-compositional conflict.

7.4. Micro Model Comparison with ILP Formulations

Compact global-selection ILP and position-dependent unfolded-tree extraction optimize over different feasible sets. This subsection isolates the modeling distinction on constructed micro instances rather than providing a runtime benchmark.
Setup. Three deterministic micro e-graph cases are constructed, each containing a shared e-class S with two candidates A and B. Multiple parent e-nodes reference S. In the no-conflict case, every parent context rewards the same candidate. In the two sharing-conflict cases, different parent contexts reward different candidates of S, so that a single global representative cannot satisfy all contexts simultaneously. The depth-2 reward predicates used here are abstract structural indicators designed to expose the distinction between global commitment and position-dependent selection. These cases are separate from the brute-force correctness micro instances in Section 7.5.
Formulations. Two ILP formulations are compared alongside exhaustive enumeration. The first is a compact global-selection ILP in which each e-class selects one global e-node representative, and template hits are encoded with auxiliary binary variables constrained so that a hit is counted only when both the parent and the child are selected. The second is a position-indexed ILP in which each unfolded tree occurrence selects an e-node independently, so the same e-class may receive different representatives under different parent contexts. Both formulations are verified by exhaustive enumeration that separately enumerates global selections and unfolded-occurrence selections to confirm the ILP objectives.
Results. Each rewarded parent–context match contributes 10 abstract objective units, and the reported value is the sum of depth-2 rewards across all parent positions. Table 7 reports the objective values. In the no-conflict case, both formulations agree because every parent context rewards the same candidate of S. In the sharing-conflict cases, compact global-selection loses objective value because it must commit to one representative of S across all parent contexts, whereas the position-indexed formulation matches the unfolded-tree exhaustive optimum by selecting different candidates at different tree positions. The position-indexed ILP achieves the same optimum as the unfolded-tree enumeration on all three cases, confirming that it encodes the same feasible set. However, its variables are indexed by unfolded occurrences rather than by e-classes, so it is not the same compact global-selection baseline.
Interpretation. The objective gap arises from the modeling constraint of global commitment, not from any inability to express template costs.

7.5. Correctness Validation

A brute-force enumerator traverses all feasible extraction trees on the micro instances and computes the globally optimal CoverValue by exhaustive search. Table 8 reports the results: the three-state algorithm matches the brute-force optimum on all three instances, empirically confirming the exactness guarantee of Proposition 1 and validating the implementation.

7.6. Runtime Efficiency

Extraction-only measurements show that the full three-state strategy adds a modest runtime penalty on the selected SMT-COMP benchmarks. Table 9 reports wall-clock time for the selection or DP solve phase together with output-tree materialization, measured after equality saturation completes. Diagnostic coverage evaluation, anti-conflict analysis, and statistics collection are excluded. On these rows, Full extraction costs 1.34 1.47 × standard weighted-AST extraction, and the largest selected instance completes in under 0.27 s. Synthetic instances remain sub-millisecond across all three strategies, so their absolute times do not provide stable timing separation.
The overhead has two sources. In the DP solve phase, each e-node carries tile-state values beyond the weighted-AST value, and candidate checks fire whenever the parent operator, child position, and child operator match a template key, adding per-e-node work proportional to the number of matching keys. The DP table is computed once and shared across all roots, whereas output-tree materialization runs separately for each root. The overhead factor in Table 9, therefore, reflects both per-e-node DP cost and per-root materialization cost.
The timing in Table 9 reflects a direct DP realization without systematic engineering tuning, so the reported overhead represents the cost of a straightforward implementation rather than an optimized extractor. In the DP phase, operator-key prefiltering can skip e-nodes whose operator pair cannot match any depth-2 template, and caching of child-value sums and predicate outcomes can eliminate redundant computation across candidate checks. In the materialization phase, independent root reconstructions can be parallelized once the shared DP table is available. These are engineering improvements that preserve both the DP recurrence and the extraction semantics.

8. Conclusions

This paper formalized pattern-aware extraction from e-graphs as a weighted pattern cover problem on AND-OR DAGs and identified three challenges (OR-node annotation ambiguity, context-dependent selection, and DAG sharing conflict) that distinguish this setting from classical tree covering. Exploiting the tree-shaped nature of the extraction output, we designed an algorithm based on three-state tree DP, generalizing BURS tree covering from fixed trees to AND-OR DAGs, that computes an exact optimum for bounded-depth templates in O ( N · K · | P | · C max ) time.
Experiments on controlled anti-pattern pressure templates demonstrate that the full three-state extractor consistently exposes depth-2 parent–child structures, and a high fraction of selected depth-2 tiles conflict with decomposable per-node local selection ( R anti > 78 % ). Structural depth-2 exposure and anti-pattern conflict metrics remain invariant across 34 admissible weight parameterizations. An ablation study further confirms that the depth-2 tiling mechanism contributes an additional 45–51% CoverValue improvement when depth-2 template opportunities are present, with extraction overhead remaining within 1.5 × of standard weighted-AST extraction on selected SMT-COMP rows.
The current evaluation validates the extraction mechanism under a controlled non-compositional objective. Translating this capability into downstream performance requires addressing two independent problems. The first is designing domain-derived template vocabularies validated against genuine downstream objectives. The second is engineering rewrite rules and saturation strategies that produce e-graphs containing the targeted structures. Both problems are outside the scope of this work.
Several directions remain for future investigation. As analyzed in Section 6.2, exact support for deeper templates requires replacing the three tile-role states with obligation states that propagate template-suffix requirements through intermediate layers. The depth-3 witness shows that this extension can handle parent-dependent choices inside a nontrivial AND-OR DAG and match the brute-force optimum on that instance. Scaling it to larger template sets and understanding how the state space grows in practice remain open problems. Integrating pattern-aware extraction with the saturation phase itself, for instance, by guiding rewrite rule application toward regions where high-value templates are likely to match, could further improve overall optimization quality. Finally, evaluation on a broader range of application domains, including compiler middle-end optimization [5] and hardware synthesis [4], would help characterize the generality of bounded-depth pattern coverage as an extraction objective.

Author Contributions

Conceptualization, Z.C. and M.Y.; methodology, Z.C.; software, Z.C.; formal analysis, Z.C.; writing—original draft preparation, Z.C.; writing—review and editing, M.Y. and L.Z.; supervision, M.Y. and L.Z. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Institutional Review Board Statement

Not applicable.

Informed Consent Statement

Not applicable.

Data Availability Statement

The original contributions presented in this study are included in the article. The source code and benchmark data supporting the conclusions of this article will be made available by the authors on request.

Acknowledgments

The authors thank the anonymous reviewers for their constructive feedback.

Conflicts of Interest

The authors declare no conflicts of interest.

Abbreviations

The following abbreviations are used in this manuscript:
BURSBottom-Up Rewrite System
DAGDirected Acyclic Graph
DPDynamic Programming
ILPInteger Linear Programming
SMTSatisfiability Modulo Theories

References

  1. Nelson, G.; Oppen, D.C. Fast Decision Procedures Based on Congruence Closure. J. ACM 1980, 27, 356–364. [Google Scholar] [CrossRef] [Scilit]
  2. Willsey, M.; Nandi, C.; Wang, Y.R.; Flatt, O.; Tatlock, Z.; Panchekha, P. Egg: Fast and Extensible Equality Saturation. Proc. ACM Program. Lang. 2021, 5, 23. [Google Scholar] [CrossRef] [Scilit]
  3. Tate, R.; Stepp, M.; Tatlock, Z.; Lerner, S. Equality Saturation: A New Approach to Optimization. In Proceedings of the 36th Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ’09), Savannah, GA, USA, 21–23 January 2009; ACM: New York, NY, USA, 2009; pp. 264–276. [Google Scholar]
  4. Coward, S.; Constantinides, G.A.; Drane, T. Automating Constraint-Aware Datapath Optimization Using E-Graphs. In Proceedings of the 60th ACM/IEEE Design Automation Conference (DAC ’23), San Francisco, CA, USA, 9–13 July 2023; IEEE: Piscataway, NJ, USA, 2023; pp. 1–6. [Google Scholar]
  5. VanHattum, A.; Nigam, R.; Lee, V.T.; Bornholt, J.; Sampson, A. Vectorization for Digital Signal Processors via Equality Saturation. In Proceedings of the 26th ACM International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS ’21), Lausanne, Switzerland, 19–23 April 2021; ACM: New York, NY, USA, 2021; pp. 874–886. [Google Scholar]
  6. Nandi, C.; Willsey, M.; Anderson, A.; Wilcox, J.R.; Darulova, E.; Grossman, D.; Tatlock, Z. Synthesizing Structured CAD Models with Equality Saturation and Inverse Transformations. In Proceedings of the 41st ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI ’20), London, UK, 15–20 June 2020; ACM: New York, NY, USA, 2020; pp. 31–44. [Google Scholar]
  7. De Moura, L.; Bjørner, N. Z3: An Efficient SMT Solver. In Proceedings of the International Conference on Tools and Algorithms for the Construction and Analysis of Systems (TACAS ’08), Budapest, Hungary, 29 March–6 April 2008; Springer: Berlin/Heidelberg, Germany, 2008; pp. 337–340. [Google Scholar]
  8. Blindell, H. Instruction Selection; Springer International Publishing: Cham, Switzerland, 2016. [Google Scholar]
  9. Aho, A.V.; Ganapathi, M.; Tjiang, S.W. Code Generation Using Tree Matching and Dynamic Programming. ACM Trans. Program. Lang. Syst. 1989, 11, 491–516. [Google Scholar] [CrossRef] [Scilit]
  10. Pelegri-Llopart, E.; Graham, S.L. Optimal Code Generation for Expression Trees: An Application of BURS Theory. In Proceedings of the 15th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ’88), San Diego, CA, USA, 10–13 January 1988; ACM: New York, NY, USA, 1988; pp. 294–308. [Google Scholar]
  11. Joshi, R.; Nelson, G.; Randall, K. Denali: A Goal-Directed Superoptimizer. ACM SIGPLAN Not. 2002, 37, 304–314. [Google Scholar] [CrossRef] [Scilit]
  12. Flatt, O.; Coward, S.; Willsey, M.; Tatlock, Z.; Panchekha, P. Small Proofs from Congruence Closure. In Proceedings of the 2022 Formal Methods in Computer-Aided Design (FMCAD ’22), Trento, Italy, 17–21 October 2022; IEEE: Piscataway, NJ, USA, 2022; pp. 75–83. [Google Scholar]
  13. Proebsting, T.A. BURS Automata Generation. ACM Trans. Program. Lang. Syst. 1995, 17, 461–486. [Google Scholar] [CrossRef] [Scilit]
  14. Koes, D.R.; Goldstein, S.C. Near-Optimal Instruction Selection on DAGs. In Proceedings of the 6th Annual IEEE/ACM International Symposium on Code Generation and Optimization (CGO ’08), Boston, MA, USA, 5–9 April 2008; ACM: New York, NY, USA, 2008; pp. 45–54. [Google Scholar]
  15. Barrett, C.; Fontaine, P.; Tinelli, C. The SMT-LIB Standard: Version 2.6; Technical Report; Department of Computer Science, The University of Iowa: Iowa City, IA, USA, 2017; Available online: https://www.SMT-LIB.org (accessed on 7 April 2026).
Figure 1. Running example illustrating context-dependent selection. The dashed box denotes an OR node. The blue dashed region highlights the local context in which one of the two equivalent e-nodes should be chosen. E-class c contains two equivalent candidates: n 1 = BvAdd ( x , 5 ) and n 2 = BvOr ( x , 5 ) . The dashed blue region marks the depth-2 template linking Eq with BvAdd ; under the BvUle parent, no depth-2 template applies, and n 2 is preferred for its carry-free depth-1 match. A decomposable cost function must commit to one global selection; the proposed algorithm resolves each tree position independently.
Figure 1. Running example illustrating context-dependent selection. The dashed box denotes an OR node. The blue dashed region highlights the local context in which one of the two equivalent e-nodes should be chosen. E-class c contains two equivalent candidates: n 1 = BvAdd ( x , 5 ) and n 2 = BvOr ( x , 5 ) . The dashed blue region marks the depth-2 template linking Eq with BvAdd ; under the BvUle parent, no depth-2 template applies, and n 2 is preferred for its carry-free depth-1 match. A decomposable cost function must commit to one global selection; the proposed algorithm resolves each tree position independently.
Algorithms 19 00377 g001
Figure 2. Algorithm walkthrough on the running example. (a) e-graph with template annotations: depth-2 template p (EqBvAdd) with weight  w p and depth-1 template for BvOr with weight  w 1 . (b) Output trees at two positions: Position Eq applies the depth-2 tile (blue), committing c to BvAdd; Position BvUle applies the depth-1 tile on BvOr (green).
Figure 2. Algorithm walkthrough on the running example. (a) e-graph with template annotations: depth-2 template p (EqBvAdd) with weight  w p and depth-1 template for BvOr with weight  w 1 . (b) Output trees at two positions: Position Eq applies the depth-2 tile (blue), committing c to BvAdd; Position BvUle applies the depth-1 tile on BvOr (green).
Algorithms 19 00377 g002
Figure 3. Minimal AND-OR DAG witness for depth-3 obligation-state extraction. Dashed rounded rectangles denote e-classes (OR nodes); solid boxes denote e-nodes (AND nodes). The e-class E x is shared by both A E left and Q E right . Blue and orange paths trace templates p A = A ( B 1 ( C ( _ ) ) ) and p Q = Q ( B 2 ( D ( _ ) ) ) , each with weight 10.
Figure 3. Minimal AND-OR DAG witness for depth-3 obligation-state extraction. Dashed rounded rectangles denote e-classes (OR nodes); solid boxes denote e-nodes (AND nodes). The e-class E x is shared by both A E left and Q E right . Blue and orange paths trace templates p A = A ( B 1 ( C ( _ ) ) ) and p Q = Q ( B 2 ( D ( _ ) ) ) , each with weight 10.
Algorithms 19 00377 g003
Table 1. Each algorithmic mechanism resolves a specific structural limitation of decomposable cost functions. Here, w 1 ( n ) denotes the local contribution of candidate n, σ ( n ) encodes its compatibility with possible parent contexts, and V and V denotes the DP state/value for template.
Table 1. Each algorithmic mechanism resolves a specific structural limitation of decomposable cost functions. Here, w 1 ( n ) denotes the local contribution of candidate n, σ ( n ) encodes its compatibility with possible parent contexts, and V and V denotes the DP state/value for template.
LimitationResolutionAlgorithm Component
Annotation ambiguityPer-candidate structural info w 1 ( n ) , σ ( n ) retained for all n c
Context independenceThree-state tile-role DP V and V
Global commitmentPosition-dependent selectionDAG-to-tree unfolding
Table 2. Time complexity of each phase. N: e-nodes; K: max arity; M: output tree size; C max : max e-class size.
Table 2. Time complexity of each phase. N: e-nodes; K: max arity; M: output tree size; C max : max e-class size.
PhaseDomainComplexityNotes
Template compilationOffline O ( | P | ) One-time
Bottom-up passe-graph O ( N · K · | P | · C max ) Structural info + DP
Top-down passOutput tree O ( M · K ) Read decisions
Table 3. Pattern awareness on SMT-COMP benchmarks. CoverValue: weighted pattern cover objective value (higher is better). | C | : e-classes after saturation. Standard: decomposable weighted-AST extraction. Pattern-aware: combined depth-1 and depth-2 template extraction (full three-state). Ratio: Pattern-aware divided by Standard. Instances sharing identical coverage ratios within a family are deduplicated. Eight further instances with exclusively non-template operators yield CoverValue = 0 across all strategies.
Table 3. Pattern awareness on SMT-COMP benchmarks. CoverValue: weighted pattern cover objective value (higher is better). | C | : e-classes after saturation. Standard: decomposable weighted-AST extraction. Pattern-aware: combined depth-1 and depth-2 template extraction (full three-state). Ratio: Pattern-aware divided by Standard. Instances sharing identical coverage ratios within a family are deduplicated. Eight further instances with exclusively non-template operators yield CoverValue = 0 across all strategies.
FamilyBenchmark | C | StandardPattern-AwareRatio
VexRiscvregch0-30-nomem66,19340512,555 31 ×
regch0-30-mem56,2421053255 31 ×
regch0-20-nomem44,9334058505 21 ×
regch0-20-mem38,1821052205 21 ×
regch0-15-nomem34,3034056480 16 ×
regch0-15-mem29,1521051680 16 ×
bv-formathex42,7044058505 21 ×
binary42,7044058505 21 ×
PicoRV32check-mem60,560174174 1 ×
pcregs-mem47,128114114 1 ×
Table 4. Depth-2 ablation on synthetic benchmarks. D1-only: depth-1 extraction with V disabled. Full: three-state DP. | C | : e-classes. D2: number of depth-2 tile hits in the extracted tree. Δ : absolute CoverValue difference (Full minus D1-only). Gain: relative improvement of Full over D1-only.
Table 4. Depth-2 ablation on synthetic benchmarks. D1-only: depth-1 extraction with V disabled. Full: three-state DP. | C | : e-classes. D2: number of depth-2 tile hits in the extracted tree. Δ : absolute CoverValue difference (Full minus D1-only). Gain: relative improvement of Full over D1-only.
D1-OnlyFull
Instance | C | CoverValue D2 CoverValue D2 Δ Gain
synth_small8895614310 + 48 50.5%
synth_medium2112801840628 + 126 45.0%
synth_large3784882871250 + 224 45.9%
Table 5. Objective sensitivity under fixed weight conditions (synthetic benchmarks). G obj : normalized objective gain of Full over D1-only; G 2 : depth-2 exposure gap (weight-independent); R anti : anti-pattern conflict rate.
Table 5. Objective sensitivity under fixed weight conditions (synthetic benchmarks). G obj : normalized objective gain of Full over D1-only; G 2 : depth-2 exposure gap (weight-independent); R anti : anti-pattern conflict rate.
InstanceWeightD1 CoverValueFull CoverValue G 2 R anti
synth_smalllow-D2255740.80
original5210840.80
mid-D25010640.80
high-D212623040.80
synth_mediumlow-D258126100.79
original160306100.79
mid-D2150290100.79
high-D2386658100.79
synth_largelow-D289225220.78
original266510220.78
mid-D2246490220.78
high-D26221130220.78
Table 6. Random-weight sensitivity (30 admissible assignments, synthetic benchmarks). Min/Median/Max: range of CoverValue Full CoverValue D 1 across the 30 runs. G 2 (all): depth-2 exposure gap, identical across all 30 runs. R anti (all): anti-pattern conflict rate, identical across all 30 runs. The CoverValue delta varies with sampled weights, while structural metrics remain invariant.
Table 6. Random-weight sensitivity (30 admissible assignments, synthetic benchmarks). Min/Median/Max: range of CoverValue Full CoverValue D 1 across the 30 runs. G 2 (all): depth-2 exposure gap, identical across all 30 runs. R anti (all): anti-pattern conflict rate, identical across all 30 runs. The CoverValue delta varies with sampled weights, while structural metrics remain invariant.
CoverValue Full CoverValue D 1
Instance Min Median Max G 2 (All) R anti (All)
synth_small20447640.80
synth_medium5397154100.79
synth_large134210458220.78
Table 7. Micro model comparison on constructed examples. Compact: compact global-selection ILP objective. Position: position-indexed ILP objective. Unfolded-tree: exhaustive unfolded-tree enumeration optimum. The abstract depth-2 reward predicates are used only to isolate the modeling distinction between global e-class selection and position-dependent unfolded-tree selection. This comparison is not a runtime benchmark.
Table 7. Micro model comparison on constructed examples. Compact: compact global-selection ILP objective. Position: position-indexed ILP objective. Unfolded-tree: exhaustive unfolded-tree enumeration optimum. The abstract depth-2 reward predicates are used only to isolate the modeling distinction between global e-class selection and position-dependent unfolded-tree selection. This comparison is not a runtime benchmark.
CaseCompactPositionUnfolded-Tree
No conflict, 2 parents202020
Sharing conflict, 2 parents102020
Sharing conflict, 4 parents204040
Table 8. Brute-force correctness verification on micro instances. | C | : e-classes. BF CoverValue: Globally optimal objective value found by exhaustive enumeration of all feasible extraction trees. DP CoverValue: Objective value produced by the three-state algorithm. Match: Whether BF and DP agree.
Table 8. Brute-force correctness verification on micro instances. | C | : e-classes. BF CoverValue: Globally optimal objective value found by exhaustive enumeration of all feasible extraction trees. DP CoverValue: Objective value produced by the three-state algorithm. Match: Whether BF and DP agree.
Instance | C | BF CoverValueDP CoverValueMatch
micro_1332929
micro_2292929
micro_3354141
Table 9. Extraction time (ms). Sat.: Equality saturation phase; Std.: Standard weighted-AST extraction; D1: depth-1-only pattern-aware extraction; Full: Full three-state extraction; F/S: Full divided by Std. | C | : e-classes after saturation; R: Assertion roots. Ratios use raw times before sub-millisecond entries are rounded to <1.
Table 9. Extraction time (ms). Sat.: Equality saturation phase; Std.: Standard weighted-AST extraction; D1: depth-1-only pattern-aware extraction; Full: Full three-state extraction; F/S: Full divided by Std. | C | : e-classes after saturation; R: Assertion roots. Ratios use raw times before sub-millisecond entries are rounded to <1.
SourceBenchmark | C | RSat.Std.D1FullF/S
Synth.small8815 <1 <1 <1 <1 2.66 ×
medium21142 <1 <1 <1 <1 2.80 ×
large37880 <1 <1 <1 <1 2.12 ×
SMT-COMPVexRiscv-30-nomem66,193160283476163 1.34 ×
bv-format-hex42,704110202263739 1.47 ×
picorv32-pcregs47,12813996294440 1.40 ×
zipcpu-pfcache236,290500123188250260 1.38 ×
arbiter-b3031,440208154242933 1.38 ×
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

MDPI and ACS Style

Cheng, Z.; Yuan, M.; Zhang, L. Exact Pattern-Aware Extraction for Equality Saturation via Bounded-Depth Tree Covering. Algorithms 2026, 19, 377. https://doi.org/10.3390/a19050377

AMA Style

Cheng Z, Yuan M, Zhang L. Exact Pattern-Aware Extraction for Equality Saturation via Bounded-Depth Tree Covering. Algorithms. 2026; 19(5):377. https://doi.org/10.3390/a19050377

Chicago/Turabian Style

Cheng, Zi, Mengting Yuan, and Lefei Zhang. 2026. "Exact Pattern-Aware Extraction for Equality Saturation via Bounded-Depth Tree Covering" Algorithms 19, no. 5: 377. https://doi.org/10.3390/a19050377

APA Style

Cheng, Z., Yuan, M., & Zhang, L. (2026). Exact Pattern-Aware Extraction for Equality Saturation via Bounded-Depth Tree Covering. Algorithms, 19(5), 377. https://doi.org/10.3390/a19050377

Note that from the first issue of 2016, this journal uses article numbers instead of page numbers. See further details here.

Article Metrics

Back to TopTop