Skip to main content

logicaffeine_compile/codegen_sva/
bitblast.rs

1//! Bit-blasting: `BoundedExpr` datapath (bitvector) operations → boolean `ProofExpr`.
2//!
3//! A bitvector is represented LSB-first as a `Vec<Bit>`, each `Bit` either a known constant
4//! or a boolean `ProofExpr` (a signal bit `name#i`, or a gate). Every combinator
5//! constant-folds, so a constant operand collapses gates instead of emitting them — the CNF
6//! stays small. Each operation is the textbook circuit: ripple-carry add/sub, array
7//! multiplier, barrel shifters, magnitude/signed comparators, slice and concat.
8//!
9//! This is the data-path half of the certified-prover seam: combined with the Boolean
10//! lowering in [`super::sva_to_proof`], multi-bit hardware obligations reduce to a
11//! propositional formula our CDCL→RUP tiers discharge — in the browser, no Z3.
12
13use std::collections::{HashMap, HashSet};
14use std::rc::Rc;
15
16use super::sva_to_verify::{BitVecBoundedOp, BoundedExpr, CmpBoundedOp};
17use logicaffeine_proof::cdcl::Lit;
18use logicaffeine_proof::cnf::Cnf;
19use logicaffeine_proof::ProofExpr;
20
21/// One blasted bit: a known constant, or a node of the shared gate DAG.
22///
23/// The dynamic payload is an `Rc<Gate>`, NOT a `ProofExpr` — because a datapath is a **DAG**, not a
24/// tree. An array multiplier reads every bit of its operand `w` times, and a multiply CHAIN feeds
25/// that already-shared result into the next multiplier: with an owned `ProofExpr` per bit, `clone()`
26/// deep-copies the whole operand once per read and the blast is EXPONENTIAL in the chain length (a
27/// six-step fast-doubling body reached 44 GB and was still climbing). Sharing the gate by pointer
28/// makes `Bit::clone` O(1), so the blast is linear in the number of gate operations the circuit
29/// performs — the DAG size, which [`BlastSize::dag_nodes`] reports.
30///
31/// The tree is materialised exactly ONCE, at the boundary, by [`bit_to_proof`], and the gate
32/// variants are a transliteration of the `ProofExpr` shapes the tree-shaped blaster used to emit —
33/// so the materialised formula is BYTE-IDENTICAL to the one it produced. Sharing is a performance
34/// property here, never a semantic one.
35#[derive(Clone)]
36enum Bit {
37    Const(bool),
38    Dyn(Rc<Gate>),
39}
40
41/// A gate in the shared DAG. One variant per `ProofExpr` shape [`bit_to_proof`] emits.
42enum Gate {
43    Atom(String),
44    Not(Bit),
45    And(Bit, Bit),
46    Or(Bit, Bit),
47    Iff(Bit, Bit),
48}
49
50/// Tearing down the DAG is ITERATIVE, for the same reason every walk over it is: the DAG's depth
51/// is the datapath's, and the derived `Drop` recurses once per level. A chained multiplier is tens
52/// of thousands of gate levels deep, so letting the compiler write this would turn a successful
53/// certificate into a stack overflow the moment the circuit went out of scope — a crash with no
54/// bad input and no failing assertion to point at.
55///
56/// Each gate's children are MOVED onto an explicit worklist and replaced by leaves, so the gate
57/// that is actually dropped owns nothing that can recurse. Only the LAST owner of a gate takes it
58/// apart; a gate still shared by another root is left alone, exactly as the refcount says.
59impl Drop for Gate {
60    fn drop(&mut self) {
61        let mut work: Vec<Bit> = Vec::new();
62        take_children(self, &mut work);
63        while let Some(b) = work.pop() {
64            let Bit::Dyn(rc) = b else { continue };
65            if let Some(mut g) = Rc::into_inner(rc) {
66                take_children(&mut g, &mut work);
67            }
68        }
69    }
70}
71
72/// Move a gate's DYNAMIC children onto `out`, leaving leaves behind. Constant children are left in
73/// place — they own nothing, and pushing them would force the worklist to allocate for a gate that
74/// cannot recurse anyway.
75fn take_children(g: &mut Gate, out: &mut Vec<Bit>) {
76    let take = |b: &mut Bit, out: &mut Vec<Bit>| {
77        if matches!(b, Bit::Dyn(_)) {
78            out.push(std::mem::replace(b, Bit::Const(false)));
79        }
80    };
81    match g {
82        Gate::Atom(_) => {}
83        Gate::Not(x) => take(x, out),
84        Gate::And(x, y) | Gate::Or(x, y) | Gate::Iff(x, y) => {
85            take(x, out);
86            take(y, out);
87        }
88    }
89}
90
91/// The reserved atom a folded constant is spelled over: `Or(c, ¬c)` is always true, `And(c, ¬c)`
92/// always false. `ProofExpr` has no Boolean literal, so every materialisation of a constant — and
93/// every clausification of one — goes through this one name.
94const BIT_CONST_ATOM: &str = "__bit_const";
95
96fn gate(g: Gate) -> Bit {
97    count(|w| w.gates += 1);
98    Bit::Dyn(Rc::new(g))
99}
100
101/// ★ THE BLASTER'S WORK, COUNTED — not timed. What a blast costs is three walks: the datapath expression it is handed
102/// (every node blasted once — a node blasted twice doubles the work per level above it), the gates it allocates (no
103/// gate is shared by value, so every allocation is a gate), and the memoised walk that prices the result (every gate
104/// visited once per edge into it — a walk that forgot its memo walks the tree). Each is a count a lock can bound by the
105/// size of what it walks, and none of them moves when the machine is busy.
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
107pub struct BlastWork {
108    /// Datapath expression nodes blasted.
109    pub exprs: u64,
110    /// Gates allocated.
111    pub gates: u64,
112    /// Steps of the memoised pricing walk.
113    pub walked: u64,
114}
115
116thread_local! {
117    static WORK: std::cell::Cell<BlastWork> = const { std::cell::Cell::new(BlastWork { exprs: 0, gates: 0, walked: 0 }) };
118}
119
120fn count(f: impl FnOnce(&mut BlastWork)) {
121    WORK.with(|w| {
122        let mut v = w.get();
123        f(&mut v);
124        w.set(v);
125    });
126}
127
128/// Run `f` and return what it returns with the blaster work it did on this thread.
129pub fn blast_work<T>(f: impl FnOnce() -> T) -> (T, BlastWork) {
130    let before = WORK.with(|w| w.get());
131    let out = f();
132    let after = WORK.with(|w| w.get());
133    (
134        out,
135        BlastWork {
136            exprs: after.exprs - before.exprs,
137            gates: after.gates - before.gates,
138            walked: after.walked - before.walked,
139        },
140    )
141}
142
143fn b_atom(name: String) -> Bit {
144    gate(Gate::Atom(name))
145}
146
147fn b_not(x: Bit) -> Bit {
148    match x {
149        Bit::Const(c) => Bit::Const(!c),
150        e => gate(Gate::Not(e)),
151    }
152}
153
154fn b_and(a: Bit, b: Bit) -> Bit {
155    match (a, b) {
156        (Bit::Const(false), _) | (_, Bit::Const(false)) => Bit::Const(false),
157        (Bit::Const(true), y) | (y, Bit::Const(true)) => y,
158        (x, y) => gate(Gate::And(x, y)),
159    }
160}
161
162fn b_or(a: Bit, b: Bit) -> Bit {
163    match (a, b) {
164        (Bit::Const(true), _) | (_, Bit::Const(true)) => Bit::Const(true),
165        (Bit::Const(false), y) | (y, Bit::Const(false)) => y,
166        (x, y) => gate(Gate::Or(x, y)),
167    }
168}
169
170/// XNOR / equality of two bits.
171fn b_iff(a: Bit, b: Bit) -> Bit {
172    match (a, b) {
173        (Bit::Const(c), Bit::Const(d)) => Bit::Const(c == d),
174        (Bit::Const(true), y) | (y, Bit::Const(true)) => y,
175        (Bit::Const(false), y) | (y, Bit::Const(false)) => b_not(y),
176        (x, y) => gate(Gate::Iff(x, y)),
177    }
178}
179
180fn b_xor(a: Bit, b: Bit) -> Bit {
181    b_not(b_iff(a, b))
182}
183
184/// If-then-else (a 1-bit mux): `s ? t : e`.
185fn b_ite(s: Bit, t: Bit, e: Bit) -> Bit {
186    match s {
187        Bit::Const(true) => t,
188        Bit::Const(false) => e,
189        s => b_or(b_and(s.clone(), t), b_and(b_not(s), e)),
190    }
191}
192
193/// Force a bit into the DAG as a GATE, materialising a folded constant as the reserved-atom
194/// literal (`c ∨ ¬c` / `c ∧ ¬c`). The predicate of a `BitVecIte` goes through here so a
195/// constant-foldable predicate still emits the full mux — the formula the tree-shaped blaster
196/// emitted, unchanged. Sharing is a performance property of this module, never a semantic one.
197fn as_gate(b: Bit) -> Bit {
198    match b {
199        Bit::Dyn(_) => b,
200        Bit::Const(v) => {
201            let c = b_atom(BIT_CONST_ATOM.to_string());
202            let nc = b_not(c.clone());
203            if v {
204                gate(Gate::Or(c, nc))
205            } else {
206                gate(Gate::And(c, nc))
207            }
208        }
209    }
210}
211
212// ── Pricing the materialisation ─────────────────────────────────────────────────────────
213
214/// The cost of turning one blasted obligation into a `ProofExpr`.
215///
216/// `dag_nodes` is what the blaster ALLOCATES (gates, shared); `tree_nodes` is what materialising it
217/// into the `Box`-tree `ProofExpr` WOULD allocate — the two diverge exponentially on a multiply
218/// chain, which is exactly the blow-up [`BLAST_BUDGET_NODES`] refuses.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub struct BlastSize {
221    /// Distinct gates in the shared DAG — the blaster's real allocation.
222    pub dag_nodes: u64,
223    /// Nodes the materialised `ProofExpr` tree would hold (saturating at `u128::MAX`).
224    pub tree_nodes: u128,
225}
226
227impl BlastSize {
228    /// The tree count hit the saturation ceiling: the real tree is at LEAST `tree_nodes` big.
229    pub fn saturated(&self) -> bool {
230        self.tree_nodes == u128::MAX
231    }
232
233    /// Would materialising this obligation exceed the production certificate budget?
234    pub fn over_budget(&self) -> bool {
235        self.tree_nodes > BLAST_BUDGET_NODES
236    }
237}
238
239/// How many `ProofExpr` nodes we are willing to materialise for ONE bit-blasted obligation.
240///
241/// A `ProofExpr` node costs ~100 bytes once its `Box` is counted, so this ceiling is ~200 MB of
242/// formula. It is calibrated from the measured blast of the RDU demo corpus's ALU bodies (the
243/// `Eq(placed grid, body datapath)` obligation at the certified 8-bit bound):
244///
245/// | obligation                  | gates in the DAG | nodes in the tree |
246/// |-----------------------------|-----------------:|------------------:|
247/// | 8-bit MAC PE (`MatmulTiles`)|              851 |           107 247 |
248/// | `mix` (2 inputs, 4 cells)   |            1 041 |            10 631 |
249/// | fib, 1 doubling block       |               75 |                75 |
250/// | fib, 2 doubling blocks      |            1 235 |            65 363 |
251/// | fib, 3 doubling blocks      |           13 591 |       354 787 747 |
252/// | fib, 4 doubling blocks      |          122 515 |    50 957 299 143 |
253/// | fib, 6 — the demo `fib.lg`  |        9 350 207 | 102 116 468 174 507 |
254///
255/// ★ AND THE RECONFIG OBLIGATION, WHICH THE FIRST CALIBRATION MISSED:
256///
257/// | obligation                                      | gates in the DAG | nodes in the tree |
258/// |-------------------------------------------------|-----------------:|------------------:|
259/// | `certify_config_table`, 3 islands at width 8     |            8 600 |           173 430 |
260/// | `certify_config_table`, 5 islands at width 8     |          167 366 |         2 767 042 |
261///
262/// That second row is why this constant is 8 000 000 and not 2 000 000. The ceiling was first chosen
263/// from the ALU bodies ALONE, and `certify_config_table` blasts a much larger obligation on the same
264/// ceiling — a time-mux of every island against one of them, growing SUPERLINEARLY in the island count
265/// (three islands cost 173 k, five cost 2.77 M). At 2 000 000 a long-standing proof
266/// (`fabric_whole_program_lock`) began failing, which is what a ceiling calibrated from one workload
267/// does to another.
268///
269/// So the budget clears the widest obligation that certifies today (the 5-island reconfig, 2.77 M) by
270/// ~2.9× and still refuses the third doubling block (3.5 × 10^8) by ~44×. There is deliberately no
271/// ceiling that "just fits" a multiply chain: each doubling block multiplies the encoding by ~70, so
272/// past the knee the only honest answer is a refusal BY NAME, and the band between a legitimate
273/// obligation and a runaway is five orders of magnitude wide. The DAG is priced first
274/// ([`BlastSize`]), so a refusal costs the DAG, never the tree. `bitblast_budget_lock` re-measures
275/// every row of both tables, against the REAL corpus rather than a smaller stand-in.
276pub const BLAST_BUDGET_NODES: u128 = 8_000_000;
277
278/// Why a bit-blast produced no formula.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum BlastRefusal {
281    /// The expression is not a supported bounded/bitvector obligation (wrong widths, an Int, a
282    /// construct with no circuit).
283    NotBounded,
284    /// The circuit blasts, but its `ProofExpr` materialisation is bigger than `budget`.
285    Budget { size: BlastSize, budget: u128 },
286    /// The circuit itself — the SHARED gate DAG, not its unfolding — is bigger than `budget`.
287    /// The ceiling that bounds a path which never materialises a tree.
288    GateBudget { dag_nodes: u64, budget: u64 },
289}
290
291impl BlastRefusal {
292    /// The prose a certificate carries when it declines this obligation — it names the cause AND
293    /// the budget, so a reader can tell "we cannot express this" from "we will not pay for this".
294    pub fn reason(&self) -> String {
295        match self {
296            BlastRefusal::NotBounded => {
297                "the obligation escaped the propositional fragment".to_string()
298            }
299            BlastRefusal::Budget { size, budget } => format!(
300                "the bit-blast of this ALU body exceeds the certificate budget ({}{} nodes > {} \
301                 budget, from a {}-gate circuit) — a multiply chain blows up the propositional \
302                 encoding",
303                if size.saturated() { "≥" } else { "" },
304                size.tree_nodes,
305                budget,
306                size.dag_nodes
307            ),
308            BlastRefusal::GateBudget { dag_nodes, budget } => format!(
309                "the shared gate DAG of this ALU body exceeds the certificate budget \
310                 ({dag_nodes} gates > {budget} budget) — the datapath is larger than one \
311                 certificate is allowed to encode"
312            ),
313        }
314    }
315}
316
317/// A gate's identity in the shared DAG — its `Rc` address. Two `Bit`s name the same gate exactly
318/// when this matches, which is what every memoised walk below keys on.
319fn gate_key(g: &Rc<Gate>) -> usize {
320    Rc::as_ptr(g) as usize
321}
322
323/// The distinct gates reachable from `root`, in POST-ORDER: every gate appears after both of its
324/// children and exactly once, in the same order a recursive descent of the materialised tree would
325/// first reach them. That last clause is load-bearing — it is what makes a DAG-driven
326/// clausification emit byte-identically to a tree-driven one.
327///
328/// Iterative, not recursive, because the DAG's depth is the datapath's: a chained 8-bit multiplier
329/// is thousands of gate levels deep, and a recursive walk blows the thread stack long before the
330/// circuit is large enough to matter. Every consumer of the DAG (pricing, clausification) folds
331/// over this one order, so none of them can grow a stack bug the others do not have.
332fn dag_postorder<'a>(roots: &[&'a Bit]) -> Vec<(usize, &'a Gate)> {
333    let mut order: Vec<(usize, &Gate)> = Vec::new();
334    let mut seen: HashSet<usize> = HashSet::new();
335    let mut stack: Vec<(&Bit, bool)> = roots.iter().rev().map(|b| (*b, false)).collect();
336    while let Some((b, expanded)) = stack.pop() {
337        count(|w| w.walked += 1);
338        let Bit::Dyn(g) = b else { continue };
339        let key = gate_key(g);
340        if seen.contains(&key) {
341            continue;
342        }
343        if !expanded {
344            stack.push((b, true));
345            // Pushed right-then-left so the LEFT child is popped first.
346            match &**g {
347                Gate::Atom(_) => {}
348                Gate::Not(x) => stack.push((x, false)),
349                Gate::And(x, y) | Gate::Or(x, y) | Gate::Iff(x, y) => {
350                    stack.push((y, false));
351                    stack.push((x, false));
352                }
353            }
354            continue;
355        }
356        seen.insert(key);
357        order.push((key, &**g));
358    }
359    order
360}
361
362/// Count the gates `roots` SHARE and the tree they would materialise into, visiting each shared
363/// gate ONCE across all of them. Both counts come from one memoised walk, so pricing an obligation
364/// costs the DAG, not the tree.
365fn measure_all(roots: &[&Bit]) -> BlastSize {
366    // A constant materialises as `Or(c, Not(c))` / `And(c, Not(c))`: 4 nodes.
367    fn nodes_of(sizes: &HashMap<usize, u128>, b: &Bit) -> u128 {
368        match b {
369            Bit::Const(_) => 4,
370            Bit::Dyn(g) => sizes.get(&gate_key(g)).copied().unwrap_or(4),
371        }
372    }
373    let order = dag_postorder(roots);
374    let mut sizes: HashMap<usize, u128> = HashMap::with_capacity(order.len());
375    for (key, g) in &order {
376        let n = match g {
377            Gate::Atom(_) => 1,
378            Gate::Not(x) => nodes_of(&sizes, x).saturating_add(1),
379            Gate::And(x, y) | Gate::Or(x, y) | Gate::Iff(x, y) => nodes_of(&sizes, x)
380                .saturating_add(nodes_of(&sizes, y))
381                .saturating_add(1),
382        };
383        sizes.insert(*key, n);
384    }
385    let tree_nodes = roots
386        .iter()
387        .fold(0u128, |acc, r| acc.saturating_add(nodes_of(&sizes, r)));
388    BlastSize {
389        dag_nodes: order.len() as u64,
390        tree_nodes,
391    }
392}
393
394fn measure(b: &Bit) -> BlastSize {
395    measure_all(&[b])
396}
397
398fn bit_to_proof(b: &Bit) -> ProofExpr {
399    match b {
400        // `ProofExpr` has no Boolean literal; encode constants as a tautology / contradiction
401        // over a reserved atom (`Or(c,¬c)` is always true, `And(c,¬c)` always false).
402        Bit::Const(true) => {
403            let c = ProofExpr::Atom(BIT_CONST_ATOM.to_string());
404            ProofExpr::Or(Box::new(c.clone()), Box::new(ProofExpr::Not(Box::new(c))))
405        }
406        Bit::Const(false) => {
407            let c = ProofExpr::Atom(BIT_CONST_ATOM.to_string());
408            ProofExpr::And(Box::new(c.clone()), Box::new(ProofExpr::Not(Box::new(c))))
409        }
410        Bit::Dyn(g) => match &**g {
411            Gate::Atom(n) => ProofExpr::Atom(n.clone()),
412            Gate::Not(x) => ProofExpr::Not(Box::new(bit_to_proof(x))),
413            Gate::And(x, y) => ProofExpr::And(Box::new(bit_to_proof(x)), Box::new(bit_to_proof(y))),
414            Gate::Or(x, y) => ProofExpr::Or(Box::new(bit_to_proof(x)), Box::new(bit_to_proof(y))),
415            Gate::Iff(x, y) => ProofExpr::Iff(Box::new(bit_to_proof(x)), Box::new(bit_to_proof(y))),
416        },
417    }
418}
419
420// ── Bitvector circuits (operands LSB-first, equal width) ────────────────────────────────
421
422/// Ripple-carry add: returns `(sum bits, carry-out)`.
423fn ripple_add(a: &[Bit], b: &[Bit], carry_in: Bit) -> (Vec<Bit>, Bit) {
424    let mut carry = carry_in;
425    let mut out = Vec::with_capacity(a.len());
426    for i in 0..a.len() {
427        let axb = b_xor(a[i].clone(), b[i].clone());
428        let sum = b_xor(axb.clone(), carry.clone());
429        let carry_next = b_or(b_and(a[i].clone(), b[i].clone()), b_and(carry.clone(), axb));
430        out.push(sum);
431        carry = carry_next;
432    }
433    (out, carry)
434}
435
436fn bv_add(a: &[Bit], b: &[Bit]) -> Vec<Bit> {
437    ripple_add(a, b, Bit::Const(false)).0
438}
439
440/// Two's-complement subtract: `a - b = a + ¬b + 1`.
441fn bv_sub(a: &[Bit], b: &[Bit]) -> Vec<Bit> {
442    let nb: Vec<Bit> = b.iter().cloned().map(b_not).collect();
443    ripple_add(a, &nb, Bit::Const(true)).0
444}
445
446/// Shift-and-add array multiplier, truncated to the operand width.
447fn bv_mul(a: &[Bit], b: &[Bit]) -> Vec<Bit> {
448    let w = a.len();
449    let mut acc: Vec<Bit> = vec![Bit::Const(false); w];
450    for i in 0..w {
451        // Partial product: (a << i) gated by b[i], truncated to width w.
452        let mut pp: Vec<Bit> = vec![Bit::Const(false); w];
453        for j in i..w {
454            pp[j] = b_and(a[j - i].clone(), b[i].clone());
455        }
456        acc = bv_add(&acc, &pp);
457    }
458    acc
459}
460
461/// Shift left by a constant `k` (zero-fill), width-preserving.
462fn shl_const(a: &[Bit], k: usize) -> Vec<Bit> {
463    let w = a.len();
464    (0..w)
465        .map(|j| {
466            if j >= k {
467                a[j - k].clone()
468            } else {
469                Bit::Const(false)
470            }
471        })
472        .collect()
473}
474
475/// Shift right by a constant `k`, filling the vacated top bits with `fill`.
476fn shr_const(a: &[Bit], k: usize, fill: Bit) -> Vec<Bit> {
477    let w = a.len();
478    (0..w)
479        .map(|j| {
480            if j + k < w {
481                a[j + k].clone()
482            } else {
483                fill.clone()
484            }
485        })
486        .collect()
487}
488
489/// Barrel shifter for a variable amount: compose constant shifts of `1<<s` gated by the
490/// amount's bit `s`. `fill` is the vacated-bit value (0 for logical, sign for arithmetic);
491/// `left` selects direction.
492fn barrel_shift(a: &[Bit], amount: &[Bit], left: bool, fill: Bit) -> Vec<Bit> {
493    let w = a.len();
494    let mut cur = a.to_vec();
495    for (s, amt_bit) in amount.iter().enumerate() {
496        let dist = 1usize << s;
497        if dist >= w {
498            // Any set bit at or beyond this position shifts everything out.
499            let shifted = vec![fill.clone(); w];
500            cur = (0..w)
501                .map(|j| b_ite(amt_bit.clone(), shifted[j].clone(), cur[j].clone()))
502                .collect();
503            continue;
504        }
505        let shifted = if left {
506            shl_const(&cur, dist)
507        } else {
508            shr_const(&cur, dist, fill.clone())
509        };
510        cur = (0..w)
511            .map(|j| b_ite(amt_bit.clone(), shifted[j].clone(), cur[j].clone()))
512            .collect();
513    }
514    cur
515}
516
517/// `a == b` over equal-width bitvectors → a single bit.
518fn bv_eq(a: &[Bit], b: &[Bit]) -> Bit {
519    let mut acc = Bit::Const(true);
520    for i in 0..a.len() {
521        acc = b_and(acc, b_iff(a[i].clone(), b[i].clone()));
522    }
523    acc
524}
525
526/// Unsigned `a < b` → a single bit (LSB→MSB magnitude comparator).
527fn bv_ult(a: &[Bit], b: &[Bit]) -> Bit {
528    let mut lt = Bit::Const(false);
529    for i in 0..a.len() {
530        // a<b on bits 0..=i  ≡  (a[i]<b[i]) ∨ (a[i]=b[i] ∧ a<b on bits below i)
531        let bit_lt = b_and(b_not(a[i].clone()), b[i].clone());
532        let bit_eq = b_iff(a[i].clone(), b[i].clone());
533        lt = b_or(bit_lt, b_and(bit_eq, lt));
534    }
535    lt
536}
537
538/// Signed (two's-complement) `a < b` → a single bit.
539fn bv_slt(a: &[Bit], b: &[Bit]) -> Bit {
540    let w = a.len();
541    let sa = a[w - 1].clone();
542    let sb = b[w - 1].clone();
543    // Differing signs: the negative one (sign bit 1) is smaller, so result = a's sign.
544    // Same sign: the unsigned ordering coincides with the signed ordering.
545    b_ite(b_xor(sa.clone(), sb), sa, bv_ult(a, b))
546}
547
548/// Two's-complement negate: `-x = ~x + 1`.
549fn bv_neg(a: &[Bit]) -> Vec<Bit> {
550    let notx: Vec<Bit> = a.iter().cloned().map(b_not).collect();
551    let one: Vec<Bit> = (0..a.len()).map(|i| Bit::Const(i == 0)).collect();
552    bv_add(&notx, &one)
553}
554
555/// UNSIGNED restoring division — `(quotient, remainder)`, LSB-first, `W` bits each. Standard
556/// shift/compare/conditional-subtract: for each bit MSB→LSB bring it into a running remainder, and if
557/// `rem ≥ b` subtract and set the quotient bit. Guarantees `q·b + r = a` and `r < b` (for `b ≠ 0`).
558fn bv_udiv_urem(a: &[Bit], b: &[Bit]) -> (Vec<Bit>, Vec<Bit>) {
559    let w = a.len();
560    let mut q = vec![Bit::Const(false); w];
561    let mut rem: Vec<Bit> = vec![Bit::Const(false); w]; // running remainder stays < b, fits in W bits
562    for i in (0..w).rev() {
563        // ext = (rem << 1) | a[i], as W+1 bits (LSB-first): [a[i], rem[0..w]]
564        let mut ext: Vec<Bit> = Vec::with_capacity(w + 1);
565        ext.push(a[i].clone());
566        ext.extend(rem.iter().cloned());
567        let mut bext: Vec<Bit> = b.to_vec();
568        bext.push(Bit::Const(false)); // b zero-extended to W+1 bits
569        let ge = b_not(bv_ult(&ext, &bext)); // ext >= b
570        let sub = bv_sub(&ext, &bext);
571        rem = (0..w)
572            .map(|j| b_ite(ge.clone(), sub[j].clone(), ext[j].clone()))
573            .collect();
574        q[i] = ge;
575    }
576    (q, rem)
577}
578
579/// The our-SAT obligation that the SIGNED truncating divider (Rust/VM `/` and `%`) is CORRECT over all
580/// `W`-bit inputs: for every `b ≠ 0` (excluding the single `MIN / −1` two's-complement overflow that
581/// `/` itself rejects) the reconstruction `q·b + r == a` holds and the remainder is in range `|r| < |b|`.
582/// `prove_unsat` REFUTES the returned expression iff the divider is correct. Pass `include_remainder =
583/// false` to drop the `+ r` term — the obligation then becomes SATISFIABLE (a non-divisible input is a
584/// counterexample), proving the check is not vacuous. Bit-level; needs no `BitVecBoundedOp` variant.
585/// This is the `ProofExpr` tree of the obligation, which grows exponentially with `width` (the restoring
586/// steps share their remainder bits, and the tree copies them); past W=3 refute
587/// [`signed_divider_correct`] from the gate DAG instead.
588pub(crate) fn signed_divider_obligation(width: usize, include_remainder: bool) -> ProofExpr {
589    bit_to_proof(&signed_divider_bad(width, include_remainder))
590}
591
592/// The signed divider's correctness over all `W`-bit inputs as a gate-DAG predicate: it holds on every
593/// input iff the divider is correct (the complement of [`signed_divider_obligation`]). `assert_not` it
594/// into a `Cnf` and refute: the clauses are linear in the circuit, where the tree is exponential.
595pub(crate) fn signed_divider_correct(width: usize, include_remainder: bool) -> Pred {
596    Pred(b_not(signed_divider_bad(width, include_remainder)))
597}
598
599/// The input set on which the signed divider is wrong, as one gate of the shared DAG.
600fn signed_divider_bad(width: usize, include_remainder: bool) -> Bit {
601    let w = width;
602    let a = blast_bits(&BoundedExpr::BitVecVar("a".into(), w as u32)).unwrap();
603    let b = blast_bits(&BoundedExpr::BitVecVar("b".into(), w as u32)).unwrap();
604    let sa = a[w - 1].clone();
605    let sb = b[w - 1].clone();
606    let abs = |x: &[Bit], s: &Bit| -> Vec<Bit> {
607        let n = bv_neg(x);
608        (0..w)
609            .map(|j| b_ite(s.clone(), n[j].clone(), x[j].clone()))
610            .collect()
611    };
612    let ua = abs(&a, &sa);
613    let ub = abs(&b, &sb);
614    let (uq, ur) = bv_udiv_urem(&ua, &ub);
615    // Truncating-toward-zero signs: quotient negative iff signs differ; remainder sign = dividend sign.
616    let qsign = b_xor(sa.clone(), sb.clone());
617    let nq = bv_neg(&uq);
618    let q: Vec<Bit> = (0..w)
619        .map(|j| b_ite(qsign.clone(), nq[j].clone(), uq[j].clone()))
620        .collect();
621    let nr = bv_neg(&ur);
622    let r: Vec<Bit> = (0..w)
623        .map(|j| b_ite(sa.clone(), nr[j].clone(), ur[j].clone()))
624        .collect();
625    let recon = if include_remainder {
626        bv_add(&bv_mul(&q, &b), &r)
627    } else {
628        bv_mul(&q, &b)
629    };
630    let ok = bv_eq(&recon, &a);
631    let in_range = bv_ult(&ur, &ub); // |r| < |b|
632    let bnz = b.iter().cloned().fold(Bit::Const(false), b_or); // b != 0
633                                                               // overflow: a == MIN (100..0) and b == -1 (all ones) — excluded.
634    let mut a_is_min = sa.clone();
635    for j in 0..w - 1 {
636        a_is_min = b_and(a_is_min, b_not(a[j].clone()));
637    }
638    let b_neg1 = b.iter().cloned().fold(Bit::Const(true), b_and);
639    let overflow = b_and(a_is_min, b_neg1);
640    let good = b_and(ok, in_range);
641    b_and(b_and(bnz, b_not(overflow)), b_not(good))
642}
643
644/// SIGNED truncating div/mod (toward zero) as bits — `(q, r)` with `q·b + r = a`, `sign(r)=sign(a)`.
645/// The shared core of the divider obligations (built on the unsigned restoring divider + sign fix-up).
646fn signed_trunc_divmod(a: &[Bit], b: &[Bit]) -> (Vec<Bit>, Vec<Bit>) {
647    let w = a.len();
648    let sa = a[w - 1].clone();
649    let sb = b[w - 1].clone();
650    let abs = |x: &[Bit], s: &Bit| -> Vec<Bit> {
651        let n = bv_neg(x);
652        (0..w)
653            .map(|j| b_ite(s.clone(), n[j].clone(), x[j].clone()))
654            .collect()
655    };
656    let ua = abs(a, &sa);
657    let ub = abs(b, &sb);
658    let (uq, ur) = bv_udiv_urem(&ua, &ub);
659    let qsign = b_xor(sa.clone(), sb.clone());
660    let nq = bv_neg(&uq);
661    let q: Vec<Bit> = (0..w)
662        .map(|j| b_ite(qsign.clone(), nq[j].clone(), uq[j].clone()))
663        .collect();
664    let nr = bv_neg(&ur);
665    let r: Vec<Bit> = (0..w)
666        .map(|j| b_ite(sa.clone(), nr[j].clone(), ur[j].clone()))
667        .collect();
668    (q, r)
669}
670
671/// The our-SAT obligation that FLOOR division (`FloorDiv` — round toward −∞) is CORRECT: for every
672/// `b ≠ 0` (MIN/−1 excluded) the floor quotient `fq = trunc − [rem≠0 ∧ signs differ]` and floor
673/// remainder `fr = trunc_rem + [correction]·b` satisfy `fq·b + fr == a`, the remainder takes the
674/// DIVISOR's sign (or is 0), and `|fr| < |b|` — the defining properties of floored division. `fq`/`fr`
675/// are derived from the trunc divider's INDEPENDENT remainder (not from `a`), so the reconstruction is
676/// a real check. `include_remainder = false` drops `+fr` → SATISFIABLE, proving non-vacuity.
677pub(crate) fn floor_divider_obligation(width: usize, include_remainder: bool) -> ProofExpr {
678    let w = width;
679    let a = blast_bits(&BoundedExpr::BitVecVar("a".into(), w as u32)).unwrap();
680    let b = blast_bits(&BoundedExpr::BitVecVar("b".into(), w as u32)).unwrap();
681    let sa = a[w - 1].clone();
682    let sb = b[w - 1].clone();
683    let (tq, tr) = signed_trunc_divmod(&a, &b);
684    // Correction: floor differs from trunc by 1 when the remainder is nonzero and the signs differ.
685    let tr_nz = tr.iter().cloned().fold(Bit::Const(false), b_or);
686    let signs_differ = b_xor(sa.clone(), sb.clone());
687    let corr = b_and(tr_nz, signs_differ);
688    let one: Vec<Bit> = (0..w).map(|i| Bit::Const(i == 0)).collect();
689    let tq_m1 = bv_sub(&tq, &one);
690    let fq: Vec<Bit> = (0..w)
691        .map(|j| b_ite(corr.clone(), tq_m1[j].clone(), tq[j].clone()))
692        .collect();
693    // Floor remainder from the INDEPENDENT trunc remainder: fr = tr + (corr ? b : 0).
694    let corr_b: Vec<Bit> = (0..w)
695        .map(|j| b_ite(corr.clone(), b[j].clone(), Bit::Const(false)))
696        .collect();
697    let fr = bv_add(&tr, &corr_b);
698    let recon = if include_remainder {
699        bv_add(&bv_mul(&fq, &b), &fr)
700    } else {
701        bv_mul(&fq, &b)
702    };
703    let ok = bv_eq(&recon, &a);
704    // Floor remainder takes the divisor's sign (or is 0), and |fr| < |b|.
705    let fr_nz = fr.iter().cloned().fold(Bit::Const(false), b_or);
706    let sign_ok = b_or(b_not(fr_nz), b_iff(fr[w - 1].clone(), sb.clone()));
707    let abs = |x: &[Bit], s: &Bit| -> Vec<Bit> {
708        let n = bv_neg(x);
709        (0..w)
710            .map(|j| b_ite(s.clone(), n[j].clone(), x[j].clone()))
711            .collect()
712    };
713    let afr = abs(&fr, &fr[w - 1].clone());
714    let ab = abs(&b, &sb);
715    let range = bv_ult(&afr, &ab);
716    let bnz = b.iter().cloned().fold(Bit::Const(false), b_or);
717    let mut a_is_min = sa.clone();
718    for j in 0..w - 1 {
719        a_is_min = b_and(a_is_min, b_not(a[j].clone()));
720    }
721    let b_neg1 = b.iter().cloned().fold(Bit::Const(true), b_and);
722    let overflow = b_and(a_is_min, b_neg1);
723    let good = b_and(b_and(ok, sign_ok), range);
724    let bad = b_and(b_and(bnz, b_not(overflow)), b_not(good));
725    bit_to_proof(&bad)
726}
727
728/// The our-SAT obligation that the SHIFT-based `DivPow2` (signed `a / 2^k`, round toward zero via a
729/// negative-bias then arithmetic shift) equals the reference signed truncating divider by `2^k`, for
730/// every `k` in `1..W` over all W-bit `a`. Proves the cheap shift form is EXACTLY `Div` by a power of
731/// two. `prove_unsat` REFUTES the returned expression iff the fast form is correct. `include_bias =
732/// false` drops the round-toward-zero bias → SATISFIABLE (a negative non-divisible `a` is a
733/// counterexample), proving the check is not vacuous.
734pub(crate) fn divpow2_obligation(width: usize, include_bias: bool) -> ProofExpr {
735    let w = width;
736    let a = blast_bits(&BoundedExpr::BitVecVar("a".into(), w as u32)).unwrap();
737    let sign = a[w - 1].clone();
738    let mut bad = Bit::Const(false);
739    // k in 1..w-1: `2^k` must be a POSITIVE signed W-bit value (the top bit `2^(w-1)` is the negative
740    // sign bit, and the VM never emits `DivPow2` for a divisor that isn't a positive power of two).
741    for k in 1..w - 1 {
742        // bias = a<0 ? (2^k − 1) : 0  ==  low-k bits set to the sign bit (0 when `include_bias` is off).
743        let bias: Vec<Bit> = (0..w)
744            .map(|j| {
745                if include_bias && j < k {
746                    sign.clone()
747                } else {
748                    Bit::Const(false)
749                }
750            })
751            .collect();
752        let biased = bv_add(&a, &bias);
753        // arithmetic shift right by k: bits down by k, fill the top k with `biased`'s sign bit.
754        let fill = biased[w - 1].clone();
755        let fast: Vec<Bit> = (0..w)
756            .map(|j| {
757                if j + k < w {
758                    biased[j + k].clone()
759                } else {
760                    fill.clone()
761                }
762            })
763            .collect();
764        // reference: signed trunc div by 2^k.
765        let two_k = blast_bits(&BoundedExpr::BitVecConst {
766            width: w as u32,
767            value: 1u64 << k,
768        })
769        .unwrap();
770        let (refq, _refr) = signed_trunc_divmod(&a, &two_k);
771        bad = b_or(bad, b_not(bv_eq(&fast, &refq)));
772    }
773    bit_to_proof(&bad)
774}
775
776/// Round-up unsigned magic for `a / d` at width `w`: the smallest total shift `s` and
777/// `magic = ceil(2^s / d)` such that `(a * magic) >> s == a / d` for EVERY `w`-bit `a` (verified
778/// exhaustively over the `2^w` inputs — `w` is small). This is the Granlund–Montgomery reciprocal,
779/// the mathematical content of the VM's `MagicDivU`.
780fn unsigned_magic(d: u64, w: usize) -> (u64, u32) {
781    for s in (w as u32)..(4 * w as u32 + 4) {
782        let magic = ((1u128 << s) + d as u128 - 1) / d as u128; // ceil(2^s / d)
783        if magic >> (w + 3) != 0 {
784            continue; // keep the multiply width bounded
785        }
786        let m = magic as u64;
787        if (0..(1u64 << w)).all(|a| ((a as u128 * magic) >> s) as u64 == a / d) {
788            return (m, s);
789        }
790    }
791    panic!("no round-up magic for d={d} at w={w}");
792}
793
794/// The our-SAT obligation that the ROUND-UP MAGIC form of unsigned division by a constant `d`
795/// (`(a * magic) >> s`) equals `a / d` (the reference `bv_udiv`) for every `w`-bit `a` — the semantics
796/// of `MagicDivU` (the VM's mul-hi + Knuth-fixup encoding in `compiler.rs::magic_eval` is an
797/// implementation of this identity). `prove_unsat` REFUTES it iff correct. `correct = false` shifts by
798/// `s+1` (a wrong magic) → SATISFIABLE, proving non-vacuity.
799pub(crate) fn magicdiv_obligation(width: usize, d: u64, correct: bool) -> ProofExpr {
800    let w = width;
801    let (magic, s0) = unsigned_magic(d, w);
802    let s = if correct { s0 } else { s0 + 1 } as usize;
803    let pw = s + w + 1; // product width holds `a * magic` and the `>> s`
804    let a = blast_bits(&BoundedExpr::BitVecVar("a".into(), w as u32)).unwrap();
805    let a_ext: Vec<Bit> = (0..pw)
806        .map(|j| {
807            if j < w {
808                a[j].clone()
809            } else {
810                Bit::Const(false)
811            }
812        })
813        .collect();
814    let magic_bits = blast_bits(&BoundedExpr::BitVecConst {
815        width: pw as u32,
816        value: magic,
817    })
818    .unwrap();
819    let prod = bv_mul(&a_ext, &magic_bits); // pw bits
820    let q: Vec<Bit> = (0..w)
821        .map(|j| {
822            if j + s < pw {
823                prod[j + s].clone()
824            } else {
825                Bit::Const(false)
826            }
827        })
828        .collect();
829    let d_bits = blast_bits(&BoundedExpr::BitVecConst {
830        width: w as u32,
831        value: d,
832    })
833    .unwrap();
834    let (refq, _) = bv_udiv_urem(&a, &d_bits);
835    bit_to_proof(&b_not(bv_eq(&q, &refq)))
836}
837
838/// `a^e` by NAIVE repeated multiply (the spec), wrapping at width `w`.
839fn bv_pow_naive(a: &[Bit], e: u32) -> Vec<Bit> {
840    let w = a.len();
841    let mut acc: Vec<Bit> = (0..w).map(|i| Bit::Const(i == 0)).collect(); // 1
842    for _ in 0..e {
843        acc = bv_mul(&acc, a);
844    }
845    acc
846}
847
848/// `a^e` by SQUARE-AND-MULTIPLY (the efficient multi-cycle hardware form), wrapping at width `w`.
849fn bv_pow_sqmul(a: &[Bit], e: u32) -> Vec<Bit> {
850    let w = a.len();
851    let mut result: Vec<Bit> = (0..w).map(|i| Bit::Const(i == 0)).collect(); // 1
852    let mut base = a.to_vec();
853    let mut ee = e;
854    while ee > 0 {
855        if ee & 1 == 1 {
856            result = bv_mul(&result, &base);
857        }
858        base = bv_mul(&base, &base);
859        ee >>= 1;
860    }
861    result
862}
863
864/// The our-SAT obligation that `Pow` by SQUARE-AND-MULTIPLY (the multi-cycle hardware) equals the naive
865/// repeated-multiply spec (both wrapping — matching the VM's fixed-width `checked_pow` on a chip), for
866/// every exponent `e` in `0..=maxe` over all `w`-bit `a`. `prove_unsat` REFUTES it iff correct.
867/// `correct = false` compares against `a^(e+1)` → SATISFIABLE, proving non-vacuity. Heavy (chains of
868/// multipliers) — run on purpose, not in the routine gate.
869pub(crate) fn pow_obligation(width: usize, maxe: u32, correct: bool) -> ProofExpr {
870    let a = blast_bits(&BoundedExpr::BitVecVar("a".into(), width as u32)).unwrap();
871    let mut bad = Bit::Const(false);
872    for e in 0..=maxe {
873        let sq = bv_pow_sqmul(&a, e);
874        let nv = bv_pow_naive(&a, if correct { e } else { e + 1 });
875        bad = b_or(bad, b_not(bv_eq(&sq, &nv)));
876    }
877    bit_to_proof(&bad)
878}
879
880// ── BoundedExpr → bits / bool ───────────────────────────────────────────────────────────
881
882/// Blast a bitvector-VALUED `BoundedExpr` into its bits (LSB-first), or `None` if it is not a
883/// supported bitvector expression (e.g. an Int, a comparison, or mismatched widths).
884fn blast_bits(e: &BoundedExpr) -> Option<Vec<Bit>> {
885    count(|w| w.exprs += 1);
886    match e {
887        BoundedExpr::BitVecConst { width, value } => Some(
888            (0..*width)
889                .map(|i| Bit::Const((value >> i) & 1 == 1))
890                .collect(),
891        ),
892        BoundedExpr::BitVecVar(name, width) => {
893            Some((0..*width).map(|i| b_atom(format!("{name}#{i}"))).collect())
894        }
895        BoundedExpr::BitVecExtract { high, low, operand } => {
896            let bits = blast_bits(operand)?;
897            let (lo, hi) = (*low as usize, *high as usize);
898            if hi >= bits.len() || lo > hi {
899                return None;
900            }
901            Some(bits[lo..=hi].to_vec())
902        }
903        BoundedExpr::BitVecConcat(a, b) => {
904            // SVA `{a, b}`: `a` is the high half. LSB-first ⇒ b's bits then a's bits.
905            let mut bits = blast_bits(b)?;
906            bits.extend(blast_bits(a)?);
907            Some(bits)
908        }
909        BoundedExpr::BitVecIte { cond, then, else_ } => {
910            // The predicated SELECT / mux tile: lower the boolean predicate to ONE bit, then mux
911            // each bit of the two same-width operands through the existing 1-bit `b_ite`. Branchy
912            // dataflow collapses to a per-bit select — no control divergence.
913            let s = as_gate(lower_bit(cond)?);
914            let t = blast_bits(then)?;
915            let e = blast_bits(else_)?;
916            if t.len() != e.len() {
917                return None;
918            }
919            Some(
920                t.into_iter()
921                    .zip(e)
922                    .map(|(tb, eb)| b_ite(s.clone(), tb, eb))
923                    .collect(),
924            )
925        }
926        BoundedExpr::BitVecBinary { op, left, right } => {
927            let a = blast_bits(left)?;
928            let b = blast_bits(right)?;
929            match op {
930                BitVecBoundedOp::Not => Some(a.into_iter().map(b_not).collect()),
931                // Width-preserving binary circuits require matching widths.
932                _ if a.len() != b.len() => None,
933                BitVecBoundedOp::And => Some(zip_map(a, b, b_and)),
934                BitVecBoundedOp::Or => Some(zip_map(a, b, b_or)),
935                BitVecBoundedOp::Xor => Some(zip_map(a, b, b_xor)),
936                BitVecBoundedOp::Add => Some(bv_add(&a, &b)),
937                BitVecBoundedOp::Sub => Some(bv_sub(&a, &b)),
938                BitVecBoundedOp::Mul => Some(bv_mul(&a, &b)),
939                BitVecBoundedOp::Shl => Some(barrel_shift(&a, &b, true, Bit::Const(false))),
940                BitVecBoundedOp::Shr => Some(barrel_shift(&a, &b, false, Bit::Const(false))),
941                BitVecBoundedOp::AShr => {
942                    let sign = a[a.len() - 1].clone();
943                    Some(barrel_shift(&a, &b, false, sign))
944                }
945                // Comparison ops are boolean-valued — not a bit vector.
946                BitVecBoundedOp::Eq | BitVecBoundedOp::ULt | BitVecBoundedOp::SLt => None,
947            }
948        }
949        _ => None,
950    }
951}
952
953fn zip_map(a: Vec<Bit>, b: Vec<Bit>, f: fn(Bit, Bit) -> Bit) -> Vec<Bit> {
954    a.into_iter().zip(b).map(|(x, y)| f(x, y)).collect()
955}
956
957/// Lower a boolean-VALUED datapath comparison into the shared gate DAG, or `None` if unsupported.
958/// Comparisons over bitvectors are unsigned unless the op is explicitly signed (`SLt`).
959fn lower_bit(e: &BoundedExpr) -> Option<Bit> {
960    count(|w| w.exprs += 1);
961    let bit = match e {
962        BoundedExpr::BitVecBinary { op, left, right } => {
963            let a = blast_bits(left)?;
964            let b = blast_bits(right)?;
965            if a.len() != b.len() {
966                return None;
967            }
968            match op {
969                BitVecBoundedOp::Eq => bv_eq(&a, &b),
970                BitVecBoundedOp::ULt => bv_ult(&a, &b),
971                BitVecBoundedOp::SLt => bv_slt(&a, &b),
972                _ => return None,
973            }
974        }
975        BoundedExpr::Eq(l, r) => {
976            let a = blast_bits(l)?;
977            let b = blast_bits(r)?;
978            if a.len() != b.len() {
979                return None;
980            }
981            bv_eq(&a, &b)
982        }
983        BoundedExpr::Lt(l, r)
984        | BoundedExpr::Gt(l, r)
985        | BoundedExpr::Lte(l, r)
986        | BoundedExpr::Gte(l, r) => bv_compare(e, l, r)?,
987        BoundedExpr::Comparison { op, left, right } => {
988            let a = blast_bits(left)?;
989            let b = blast_bits(right)?;
990            if a.len() != b.len() {
991                return None;
992            }
993            match op {
994                CmpBoundedOp::Lt => bv_ult(&a, &b),
995                CmpBoundedOp::Gt => bv_ult(&b, &a),
996                CmpBoundedOp::Lte => b_not(bv_ult(&b, &a)),
997                CmpBoundedOp::Gte => b_not(bv_ult(&a, &b)),
998            }
999        }
1000        _ => return None,
1001    };
1002    Some(bit)
1003}
1004
1005/// Lower a boolean-VALUED datapath comparison to a `ProofExpr`, or `None` if it has no circuit or
1006/// its materialisation is over [`BLAST_BUDGET_NODES`]. Use [`lower_bool_bounded`] when the caller
1007/// must tell those two apart by name.
1008pub fn lower_bool(e: &BoundedExpr) -> Option<ProofExpr> {
1009    lower_bool_bounded(e).ok()
1010}
1011
1012/// [`lower_bool`] with the refusal NAMED. The circuit is built in the shared DAG and PRICED before
1013/// anything is materialised, so an obligation past the budget costs the DAG — never the tree, and
1014/// never the allocator.
1015pub fn lower_bool_bounded(e: &BoundedExpr) -> Result<ProofExpr, BlastRefusal> {
1016    lower_bool_within(e, BLAST_BUDGET_NODES)
1017}
1018
1019/// [`lower_bool_bounded`] against an EXPLICIT ceiling. The production ceiling is
1020/// [`BLAST_BUDGET_NODES`]; a caller passing its own is how a lock proves the guard is live code —
1021/// shrink the ceiling and an obligation that certifies must come back `Budget`, with the same
1022/// arithmetic, not a special case.
1023pub fn lower_bool_within(e: &BoundedExpr, budget: u128) -> Result<ProofExpr, BlastRefusal> {
1024    let bit = lower_bit(e).ok_or(BlastRefusal::NotBounded)?;
1025    let size = measure(&bit);
1026    if size.tree_nodes > budget {
1027        return Err(BlastRefusal::Budget { size, budget });
1028    }
1029    Ok(bit_to_proof(&bit))
1030}
1031
1032/// What blasting `e` costs — gates allocated vs. `ProofExpr` nodes a materialisation would hold —
1033/// without materialising it. `None` when `e` has no circuit. The instrument the budget reads, and
1034/// the one a lock reads to prove the blast stays linear in the datapath.
1035pub fn blast_size(e: &BoundedExpr) -> Option<BlastSize> {
1036    Some(measure(&lower_bit(e)?))
1037}
1038
1039/// Unsigned magnitude comparison for the top-level `Lt/Gt/Lte/Gte` BoundedExpr variants.
1040fn bv_compare(e: &BoundedExpr, l: &BoundedExpr, r: &BoundedExpr) -> Option<Bit> {
1041    let a = blast_bits(l)?;
1042    let b = blast_bits(r)?;
1043    if a.len() != b.len() {
1044        return None;
1045    }
1046    Some(match e {
1047        BoundedExpr::Lt(..) => bv_ult(&a, &b),
1048        BoundedExpr::Gt(..) => bv_ult(&b, &a),
1049        BoundedExpr::Lte(..) => b_not(bv_ult(&b, &a)),
1050        BoundedExpr::Gte(..) => b_not(bv_ult(&a, &b)),
1051        _ => return None,
1052    })
1053}
1054
1055// ── The DAG front door: build a datapath circuit WITHOUT a `BoundedExpr` tree ───────────
1056//
1057// `BoundedExpr` is a `Box` tree, so a producer that reads a subterm twice must CLONE it — and a
1058// dataflow body whose cells read each other's results is a DAG, so the tree is the DAG unfolded.
1059// `fib.lg`'s 75-cell fast-doubling body unfolds to 1 657 763 `BoundedExpr` nodes; ten cells more
1060// and there is no machine that holds it. The blaster's own sharing cannot help, because by the
1061// time it is called the explosion has already happened upstream.
1062//
1063// So the producers below (`fabric_grid::cells_to_gates`, `fabric_grid::grid_output_to_gates`)
1064// build into the SHARED gate DAG directly: a `Word` is a vector of `Bit`s, cloning one is a
1065// refcount bump per bit, and a body's bounded form stays linear in its CELLS. The same DAG is
1066// then clausified in place ([`assert_not`]) — the `ProofExpr` tree, which is exponentially larger
1067// than the circuit for a reconvergent datapath, is never materialised at all.
1068//
1069// This is a performance property, never a semantic one: [`assert_not`] emits the SAME clauses, in
1070// the same order, that `Cnf::assert(&Not(bit_to_proof(b)))` emits — proven by
1071// `the_gate_path_and_the_tree_path_clausify_identically` in this module's tests.
1072
1073/// A blasted datapath VALUE — its bits, LSB-first, in the shared gate DAG. Cloning is a refcount
1074/// bump per bit, never a copy of the circuit.
1075#[derive(Clone)]
1076pub struct Word(Vec<Bit>);
1077
1078impl Word {
1079    /// The width in bits.
1080    pub fn width(&self) -> usize {
1081        self.0.len()
1082    }
1083}
1084
1085impl std::fmt::Debug for Word {
1086    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1087        write!(f, "Word({} bits)", self.0.len())
1088    }
1089}
1090
1091/// A blasted PREDICATE — one bit of the shared gate DAG.
1092#[derive(Clone)]
1093pub struct Pred(Bit);
1094
1095impl std::fmt::Debug for Pred {
1096    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1097        write!(f, "Pred({:?})", measure(&self.0))
1098    }
1099}
1100
1101/// A named input word: the bits `name#0 .. name#(width-1)`, the same signal spelling
1102/// [`blast_word`] gives a `BitVecVar` — so a circuit built here and one blasted from a
1103/// `BoundedExpr` share a variable namespace and can be mitered against each other.
1104pub fn word_var(name: &str, width: u32) -> Word {
1105    Word((0..width).map(|i| b_atom(format!("{name}#{i}"))).collect())
1106}
1107
1108/// A constant word, truncated to `width`.
1109pub fn word_const(width: u32, value: u64) -> Word {
1110    Word(
1111        (0..width)
1112            .map(|i| Bit::Const((value >> i) & 1 == 1))
1113            .collect(),
1114    )
1115}
1116
1117/// One of the width-preserving binary circuits (`And..AShr`, and unary `Not` on `a`). `None` when
1118/// the widths disagree or the op is boolean-valued — use [`word_compare`] for those.
1119pub fn word_binary(op: BitVecBoundedOp, a: &Word, b: &Word) -> Option<Word> {
1120    let (a, b) = (&a.0, &b.0);
1121    let bits = match op {
1122        BitVecBoundedOp::Not => a.iter().cloned().map(b_not).collect(),
1123        _ if a.len() != b.len() => return None,
1124        BitVecBoundedOp::And => zip_map(a.clone(), b.clone(), b_and),
1125        BitVecBoundedOp::Or => zip_map(a.clone(), b.clone(), b_or),
1126        BitVecBoundedOp::Xor => zip_map(a.clone(), b.clone(), b_xor),
1127        BitVecBoundedOp::Add => bv_add(a, b),
1128        BitVecBoundedOp::Sub => bv_sub(a, b),
1129        BitVecBoundedOp::Mul => bv_mul(a, b),
1130        BitVecBoundedOp::Shl => barrel_shift(a, b, true, Bit::Const(false)),
1131        BitVecBoundedOp::Shr => barrel_shift(a, b, false, Bit::Const(false)),
1132        BitVecBoundedOp::AShr => {
1133            let sign = a[a.len() - 1].clone();
1134            barrel_shift(a, b, false, sign)
1135        }
1136        BitVecBoundedOp::Eq | BitVecBoundedOp::ULt | BitVecBoundedOp::SLt => return None,
1137    };
1138    Some(Word(bits))
1139}
1140
1141/// One of the boolean-valued comparisons (`Eq`, `ULt`, `SLt`). `None` for a value-producing op or
1142/// a width mismatch.
1143pub fn word_compare(op: BitVecBoundedOp, a: &Word, b: &Word) -> Option<Pred> {
1144    if a.0.len() != b.0.len() {
1145        return None;
1146    }
1147    Some(Pred(match op {
1148        BitVecBoundedOp::Eq => bv_eq(&a.0, &b.0),
1149        BitVecBoundedOp::ULt => bv_ult(&a.0, &b.0),
1150        BitVecBoundedOp::SLt => bv_slt(&a.0, &b.0),
1151        _ => return None,
1152    }))
1153}
1154
1155/// The mux tile: `cond ? t : e`, bit by bit — the same 1-bit select `BitVecIte` blasts through, so
1156/// a predicated select built here and one built from a `BoundedExpr` are the same circuit.
1157pub fn word_select(cond: &Pred, t: &Word, e: &Word) -> Option<Word> {
1158    if t.0.len() != e.0.len() {
1159        return None;
1160    }
1161    let s = as_gate(cond.0.clone());
1162    Some(Word(
1163        t.0.iter()
1164            .cloned()
1165            .zip(e.0.iter().cloned())
1166            .map(|(tb, eb)| b_ite(s.clone(), tb, eb))
1167            .collect(),
1168    ))
1169}
1170
1171/// The miter: `a == b` over every bit. `None` on a width mismatch.
1172pub fn words_equal(a: &Word, b: &Word) -> Option<Pred> {
1173    word_compare(BitVecBoundedOp::Eq, a, b)
1174}
1175
1176/// What this predicate's circuit costs — gates allocated vs. the `ProofExpr` tree a
1177/// materialisation would hold. The instrument a budget reads.
1178pub fn pred_size(p: &Pred) -> BlastSize {
1179    measure(&p.0)
1180}
1181
1182/// What a whole WORD's circuit costs, counting the DAG the bits SHARE exactly once — an adder's
1183/// carry chain feeds every bit above it, so pricing the bits separately would count the same gates
1184/// over and over. The instrument a datapath budget reads before a miter exists.
1185pub fn word_size(w: &Word) -> BlastSize {
1186    let roots: Vec<&Bit> = w.0.iter().collect();
1187    measure_all(&roots)
1188}
1189
1190/// Blast a bitvector-VALUED `BoundedExpr` into the shared DAG — the bridge for a caller that still
1191/// speaks the tree form.
1192pub fn blast_word(e: &BoundedExpr) -> Option<Word> {
1193    Some(Word(blast_bits(e)?))
1194}
1195
1196/// Blast a boolean-VALUED `BoundedExpr` into the shared DAG.
1197pub fn blast_pred(e: &BoundedExpr) -> Option<Pred> {
1198    Some(Pred(lower_bit(e)?))
1199}
1200
1201/// Materialise a predicate's `ProofExpr` tree. The escape hatch for a consumer that genuinely
1202/// needs the tree (an SMT printer, a `ProofExpr`-shaped prover call) — and the thing every path
1203/// that only wants a CNF must NOT call, because the tree is exponentially larger than the circuit.
1204pub fn pred_to_proof(p: &Pred) -> ProofExpr {
1205    bit_to_proof(&p.0)
1206}
1207
1208/// Tseitin-encode one gate DAG into `cnf`, defining each distinct gate EXACTLY once, and return
1209/// the literal that equals the root. Linear in the DAG.
1210fn encode_bit(root: &Bit, cnf: &mut Cnf) -> Lit {
1211    fn lit_of(cnf: &mut Cnf, lits: &HashMap<usize, Lit>, b: &Bit) -> Lit {
1212        match b {
1213            // `bit_to_proof` spells a constant `Or(c, ¬c)` / `And(c, ¬c)` over the reserved atom;
1214            // both are cached by the Tseitin table, so repeating one is free.
1215            Bit::Const(v) => {
1216                let c = cnf.atom_lit(BIT_CONST_ATOM);
1217                if *v {
1218                    cnf.encode_or(c, c.negated())
1219                } else {
1220                    cnf.encode_and(c, c.negated())
1221                }
1222            }
1223            Bit::Dyn(g) => lits[&gate_key(g)],
1224        }
1225    }
1226    let order = dag_postorder(&[root]);
1227    let mut lits: HashMap<usize, Lit> = HashMap::with_capacity(order.len());
1228    for (key, g) in &order {
1229        let l = match g {
1230            Gate::Atom(n) => cnf.atom_lit(n),
1231            Gate::Not(x) => lit_of(cnf, &lits, x).negated(),
1232            Gate::And(x, y) => {
1233                let (a, b) = (lit_of(cnf, &lits, x), lit_of(cnf, &lits, y));
1234                cnf.encode_and(a, b)
1235            }
1236            Gate::Or(x, y) => {
1237                let (a, b) = (lit_of(cnf, &lits, x), lit_of(cnf, &lits, y));
1238                cnf.encode_or(a, b)
1239            }
1240            Gate::Iff(x, y) => {
1241                let (a, b) = (lit_of(cnf, &lits, x), lit_of(cnf, &lits, y));
1242                cnf.encode_iff(a, b)
1243            }
1244        };
1245        lits.insert(*key, l);
1246    }
1247    lit_of(cnf, &lits, root)
1248}
1249
1250/// The literals of the clause `b`, mirroring `Cnf::clause_lits` on `bit_to_proof(b)`: flatten a
1251/// disjunction, De-Morgan a negated conjunction, literalise an atom, and Tseitin anything else
1252/// into ONE auxiliary. Structure-aware clausification (Plaisted & Greenbaum) is what keeps the
1253/// certificate small, so the gate path must reproduce it exactly — not merely something sound.
1254fn clause_lits(b: &Bit, cnf: &mut Cnf) -> Vec<Lit> {
1255    match b {
1256        // `Or(c, ¬c)` flattens into a (tautological) two-literal clause.
1257        Bit::Const(true) => {
1258            let c = cnf.atom_lit(BIT_CONST_ATOM);
1259            vec![c, c.negated()]
1260        }
1261        // `And(c, ¬c)` is not a clause: one auxiliary.
1262        Bit::Const(false) => vec![encode_bit(b, cnf)],
1263        Bit::Dyn(g) => match &**g {
1264            Gate::Atom(n) => vec![cnf.atom_lit(n)],
1265            Gate::Or(x, y) => {
1266                let mut v = clause_lits(x, cnf);
1267                v.extend(clause_lits(y, cnf));
1268                v
1269            }
1270            Gate::Not(inner) => match inner {
1271                // ¬(a ∧ b) ≡ ¬a ∨ ¬b, and ¬¬x ≡ x — both stay ONE clause with no auxiliary.
1272                Bit::Dyn(ig) => match &**ig {
1273                    Gate::Atom(n) => vec![cnf.atom_lit(n).negated()],
1274                    Gate::And(x, y) => {
1275                        let mut v = clause_lits_of_negation(x, cnf);
1276                        v.extend(clause_lits_of_negation(y, cnf));
1277                        v
1278                    }
1279                    Gate::Not(x) => clause_lits(x, cnf),
1280                    _ => vec![encode_bit(b, cnf)],
1281                },
1282                Bit::Const(_) => vec![encode_bit(b, cnf)],
1283            },
1284            _ => vec![encode_bit(b, cnf)],
1285        },
1286    }
1287}
1288
1289/// The literals of the clause `¬b` — `clause_lits` composed with `Cnf`'s `negate_expr`, which
1290/// cancels a leading `Not` rather than stacking one.
1291fn clause_lits_of_negation(b: &Bit, cnf: &mut Cnf) -> Vec<Lit> {
1292    match b {
1293        // ¬(c ∧ ¬c) De-Morgans into a (tautological) two-literal clause.
1294        Bit::Const(false) => {
1295            let c = cnf.atom_lit(BIT_CONST_ATOM);
1296            vec![c.negated(), c]
1297        }
1298        Bit::Const(true) => vec![encode_bit(b, cnf).negated()],
1299        Bit::Dyn(g) => match &**g {
1300            // negate_expr(Not(p)) = p
1301            Gate::Not(x) => clause_lits(x, cnf),
1302            Gate::Atom(n) => vec![cnf.atom_lit(n).negated()],
1303            Gate::And(x, y) => {
1304                let mut v = clause_lits_of_negation(x, cnf);
1305                v.extend(clause_lits_of_negation(y, cnf));
1306                v
1307            }
1308            _ => vec![encode_bit(b, cnf).negated()],
1309        },
1310    }
1311}
1312
1313/// Assert `¬p` into `cnf` — the refutation obligation for a miter, clausified STRAIGHT FROM THE
1314/// GATE DAG. Emits exactly the clauses `Cnf::assert(&Not(pred_to_proof(p)))` emits, in the same
1315/// order, over the same variables; it just never builds the tree to read them off.
1316pub fn assert_not(p: &Pred, cnf: &mut Cnf) {
1317    let lits = clause_lits_of_negation(&p.0, cnf);
1318    cnf.add_clause(lits);
1319}
1320
1321#[cfg(test)]
1322#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/bitblast/tests.rs"]
1323mod tests;