3-Level Design
nasm
;==============================================================================
; HDGL DUAL-VANTAGE v3 — MULTI-WORD (.bss) 4-GATE MAJ3 SYNTHESIS ENGINE
;==============================================================================
; Target Architecture : x86-64 Linux (NASM)
; Total Variables : 104 bits across NUM_WORDS = 2 (128-bit .bss bit-planes)
; Synthesizes : MAJ3(x0, x1, x2) = ((x0 ^ x1) & x2) | (x0 & x1)
; Physical Constraints: Strict DAG acyclicity, 3-level timing chain, fanout <= 2
; Symmetry Breaking : Lexicographic gate ordering TT(G0) <= TT(G1) <= TT(G2) <= TT(G3)
;==============================================================================
BITS 64
%define NUM_INPUTS 3
%define NUM_GATES 4
%define NUM_ROWS (1 << NUM_INPUTS) ; 8 truth-table rows (000..111)
%define FANIN_WIDTH (NUM_INPUTS + NUM_GATES) ; 7 selectable sources per gate pin
%define BASE_TT 0
%define BASE_SELA (BASE_TT + 4 * NUM_GATES) ; 16
%define BASE_SELB (BASE_SELA + NUM_GATES * FANIN_WIDTH) ; 44
%define BASE_WIRE (BASE_SELB + NUM_GATES * FANIN_WIDTH) ; 72
%define TOTAL_VARS (BASE_WIRE + NUM_GATES * NUM_ROWS) ; 104
%define NUM_WORDS ((TOTAL_VARS + 63) / 64) ; 2 qwords (128 bits)
; Valid bits in Word 0 (bits 0..63) and Word 1 (bits 64..103 -> 40 bits)
%define VAR_MASK_W0 0xFFFFFFFFFFFFFFFF
%define VAR_MASK_W1 0x000000FFFFFFFFFF
GOLDEN_ANGLE_64 equ 0x61C8864680B583EB
;------------------------------------------------------------------------------
; LINEAR BIT-TENSOR INDEXING MACRO: BitIndex(type, k, r)
; type 0 = TT(k, r) : gate k truth-table entry r in {0..3}
; type 1 = SELA(k, r) : gate k pin A source r in {0..6}
; type 2 = SELB(k, r) : gate k pin B source r in {0..6}
; type 3 = WIRE(k, r) : gate k output wire on truth-table row r in {0..7}
;------------------------------------------------------------------------------
%macro BIT_INDEX 3
%if %1 == 0
%assign _b (BASE_TT + 4 * (%2) + (%3))
%elif %1 == 1
%assign _b (BASE_SELA + FANIN_WIDTH * (%2) + (%3))
%elif %1 == 2
%assign _b (BASE_SELB + FANIN_WIDTH * (%2) + (%3))
%else
%assign _b (BASE_WIRE + NUM_ROWS * (%2) + (%3))
%endif
%assign _w (_b >> 6)
%assign _lane (_b & 63)
%endmacro
;------------------------------------------------------------------------------
; MULTI-WORD WATCHED CNF CLAUSE GENERATORS (48 bytes per clause)
; Record layout: [POS_W0, POS_W1, NEG_W0, NEG_W1, WATCH_W0, WATCH_W1]
;------------------------------------------------------------------------------
%macro _ACCUM_LIT 2 ; (%1 = var_idx, %2 = pol in {0, 1})
%if (%1) < 64
%if (%2) == 1
%assign _p0 (_p0 | (1 << (%1)))
%else
%assign _n0 (_n0 | (1 << (%1)))
%endif
%if _wcount < 2
%assign _w0 (_w0 | (1 << (%1)))
%assign _wcount (_wcount + 1)
%endif
%else
%assign _sh ((%1) - 64)
%if (%2) == 1
%assign _p1 (_p1 | (1 << _sh))
%else
%assign _n1 (_n1 | (1 << _sh))
%endif
%if _wcount < 2
%assign _w1 (_w1 | (1 << _sh))
%assign _wcount (_wcount + 1)
%endif
%endif
%endmacro
%macro CLAUSE_1 2
%assign _p0 0
%assign _p1 0
%assign _n0 0
%assign _n1 0
%assign _w0 0
%assign _w1 0
%assign _wcount 0
_ACCUM_LIT %1, %2
dq _p0, _p1, _n0, _n1, _w0, _w1
%endmacro
%macro CLAUSE_2 4
%assign _p0 0
%assign _p1 0
%assign _n0 0
%assign _n1 0
%assign _w0 0
%assign _w1 0
%assign _wcount 0
_ACCUM_LIT %1, %2
_ACCUM_LIT %3, %4
dq _p0, _p1, _n0, _n1, _w0, _w1
%endmacro
%macro CLAUSE_3 6
%assign _p0 0
%assign _p1 0
%assign _n0 0
%assign _n1 0
%assign _w0 0
%assign _w1 0
%assign _wcount 0
_ACCUM_LIT %1, %2
_ACCUM_LIT %3, %4
_ACCUM_LIT %5, %6
dq _p0, _p1, _n0, _n1, _w0, _w1
%endmacro
%macro CLAUSE_4 8
%assign _p0 0
%assign _p1 0
%assign _n0 0
%assign _n1 0
%assign _w0 0
%assign _w1 0
%assign _wcount 0
_ACCUM_LIT %1, %2
_ACCUM_LIT %3, %4
_ACCUM_LIT %5, %6
_ACCUM_LIT %7, %8
dq _p0, _p1, _n0, _n1, _w0, _w1
%endmacro
%macro CLAUSE_5 10
%assign _p0 0
%assign _p1 0
%assign _n0 0
%assign _n1 0
%assign _w0 0
%assign _w1 0
%assign _wcount 0
_ACCUM_LIT %1, %2
_ACCUM_LIT %3, %4
_ACCUM_LIT %5, %6
_ACCUM_LIT %7, %8
_ACCUM_LIT %9, %10
dq _p0, _p1, _n0, _n1, _w0, _w1
%endmacro
;------------------------------------------------------------------------------
; PHYSICAL LAYOUT & SYMMETRY-BREAKING MACROS
;------------------------------------------------------------------------------
%macro ENFORCE_ROUTING_AND_TIMING 0
; 1. Strict DAG Acyclicity & 3-Level Critical-Path Timing Chain:
; - Gate G0 (Level 1): sources restricted to primary inputs {0, 1, 2}
; - Gate G1 (Level 2): sources restricted to {0, 1, 2, G0(3)}
; - Gate G2 (Level 2): sources restricted to {0, 1, 2, G0(3)} (max depth <= 3)
; - Gate G3 (Level 3): sources restricted to {0, 1, 2, G0(3), G1(4), G2(5)}
%assign _k 0
%rep NUM_GATES
%if _k == 0
%assign _max_src 2
%elif _k == 1
%assign _max_src 3
%elif _k == 2
%assign _max_src 3
%else
%assign _max_src 5
%endif
%assign _s 0
%rep FANIN_WIDTH
%if _s > _max_src
BIT_INDEX 1, _k, _s
CLAUSE_1 _b, 0
BIT_INDEX 2, _k, _s
CLAUSE_1 _b, 0
%endif
%assign _s (_s + 1)
%endrep
; Non-degenerate distinct inputs: for every valid source s, ~(SELA(k,s) & SELB(k,s))
%assign _s 0
%rep (_max_src + 1)
BIT_INDEX 1, _k, _s
%assign _va _b
BIT_INDEX 2, _k, _s
%assign _vb _b
CLAUSE_2 _va, 0, _vb, 0
%assign _s (_s + 1)
%endrep
; Exact-One source selection on SELA(k, 0.._max_src) and SELB(k, 0.._max_src)
; At-Most-One pairwise exclusion:
%assign _i 0
%rep (_max_src + 1)
%assign _j (_i + 1)
%rep (_max_src - _i)
BIT_INDEX 1, _k, _i
%assign _va1 _b
BIT_INDEX 1, _k, _j
%assign _va2 _b
CLAUSE_2 _va1, 0, _va2, 0
BIT_INDEX 2, _k, _i
%assign _vb1 _b
BIT_INDEX 2, _k, _j
%assign _vb2 _b
CLAUSE_2 _vb1, 0, _vb2, 0
%assign _j (_j + 1)
%endrep
%assign _i (_i + 1)
%endrep
%assign _k (_k + 1)
%endrep
; At-Least-One source clauses per gate pin (expanded cleanly per max_src):
; G0 (_max_src = 2 -> 3 valid sources: 0, 1, 2)
BIT_INDEX 1, 0, 0
%assign _a0 _b
BIT_INDEX 1, 0, 1
%assign _a1 _b
BIT_INDEX 1, 0, 2
%assign _a2 _b
CLAUSE_3 _a0, 1, _a1, 1, _a2, 1
BIT_INDEX 2, 0, 0
%assign _b0 _b
BIT_INDEX 2, 0, 1
%assign _b1 _b
BIT_INDEX 2, 0, 2
%assign _b2 _b
CLAUSE_3 _b0, 1, _b1, 1, _b2, 1
; G1 & G2 (_max_src = 3 -> 4 valid sources: 0, 1, 2, 3)
%assign _k 1
%rep 2
BIT_INDEX 1, _k, 0
%assign _a0 _b
BIT_INDEX 1, _k, 1
%assign _a1 _b
BIT_INDEX 1, _k, 2
%assign _a2 _b
BIT_INDEX 1, _k, 3
%assign _a3 _b
CLAUSE_4 _a0, 1, _a1, 1, _a2, 1, _a3, 1
BIT_INDEX 2, _k, 0
%assign _b0 _b
BIT_INDEX 2, _k, 1
%assign _b1 _b
BIT_INDEX 2, _k, 2
%assign _b2 _b
BIT_INDEX 2, _k, 3
%assign _b3 _b
CLAUSE_4 _b0, 1, _b1, 1, _b2, 1, _b3, 1
%assign _k (_k + 1)
%endrep
; G3 (_max_src = 5 -> 6 valid sources: 0, 1, 2, 3, 4, 5)
; Enforce canonical cascade: G3 combines W1 (source 4) and W2 (source 5)
BIT_INDEX 1, 3, 4
CLAUSE_1 _b, 1
BIT_INDEX 2, 3, 5
CLAUSE_1 _b, 1
%endmacro
%macro ENFORCE_FANOUT_AND_SYMMETRY 0
; 2. Physical Fan-Out Cap <= 2 on intermediate gate G0 (source 3):
; G0 feeds at most 2 downstream pins among {G1.A, G1.B, G2.A, G2.B}.
; Since G1.A != G1.B and G2.A != G2.B already hold, G0's fan-out is <= 2.
; 3. Non-Constant Gate Guards (every gate TT must have >=1 zero and >=1 one):
%assign _k 0
%rep NUM_GATES
BIT_INDEX 0, _k, 0
%assign _t0 _b
BIT_INDEX 0, _k, 1
%assign _t1 _b
BIT_INDEX 0, _k, 2
%assign _t2 _b
BIT_INDEX 0, _k, 3
%assign _t3 _b
CLAUSE_4 _t0, 1, _t1, 1, _t2, 1, _t3, 1
CLAUSE_4 _t0, 0, _t1, 0, _t2, 0, _t3, 0
%assign _k (_k + 1)
%endrep
; 4. Lexicographic Gate Symmetry Breaking: TT(G0) <= TT(G1) <= TT(G2)
; Prevents equivalent gate-permutation duplicates in the search tree:
; MSB (entry 3) non-decreasing: TT(0,3) <= TT(1,3) <= TT(2,3)
BIT_INDEX 0, 0, 3
%assign _g0_3 _b
BIT_INDEX 0, 1, 3
%assign _g1_3 _b
BIT_INDEX 0, 2, 3
%assign _g2_3 _b
CLAUSE_2 _g0_3, 0, _g1_3, 1
CLAUSE_2 _g1_3, 0, _g2_3, 1
%endmacro
;------------------------------------------------------------------------------
; 8-ROW TRUTH-TABLE FUNCTIONAL EVALUATION MACRO: SYNTH_ROW_8
; Links SELA(k, s), SELB(k, s), TT(k, a*2+b), and WIRE(k, row) for all 4 gates.
;------------------------------------------------------------------------------
%macro _EMIT_GATE_EVAL 5 ; (%1=row, %2=k, %3=src_idx, %4=val_a, %5=val_b)
%assign _tt_idx ((%4) * 2 + (%5))
BIT_INDEX 0, %2, _tt_idx
%assign _v_tt _b
BIT_INDEX 3, %2, %1
%assign _v_w _b
; Primary input sources (src_idx in {0, 1, 2}) have fixed Boolean values
%if %3 < NUM_INPUTS
%if %3 == 0
%assign _src_val _x0
%elif %3 == 1
%assign _src_val _x1
%else
%assign _src_val _x2
%endif
; Check if input A matches _val_a and input B matches _val_b
; Generate 4 pin-pair combinations (sA, sB) for source _src_val:
%assign _sa 0
%rep 3
%if _sa == 0
%assign _va_bit _x0
%elif _sa == 1
%assign _va_bit _x1
%else
%assign _va_bit _x2
%endif
%if _va_bit == (%4)
%assign _sb 0
%rep 3
%if _sb == 0
%assign _vb_bit _x0
%elif _sb == 1
%assign _vb_bit _x1
%else
%assign _vb_bit _x2
%endif
%if _vb_bit == (%5)
BIT_INDEX 1, %2, _sa
%assign _v_sa _b
BIT_INDEX 2, %2, _sb
%assign _v_sb _b
; (SELA(k,sa) & SELB(k,sb)) => (WIRE(k,row) <-> TT(k,tt_idx))
CLAUSE_4 _v_sa, 0, _v_sb, 0, _v_tt, 0, _v_w, 1
CLAUSE_4 _v_sa, 0, _v_sb, 0, _v_tt, 1, _v_w, 0
%endif
%assign _sb (_sb + 1)
%endrep
%endif
%assign _sa (_sa + 1)
%endrep
%endif
%endmacro
%macro SYNTH_ROW_8 5 ; (%1=row, %2=x0, %3=x1, %4=x2, %5=target_y)
%assign _x0 %2
%assign _x1 %3
%assign _x2 %4
; --- Gate G0 (reads primary inputs {0, 1, 2} -> outputs W0[row]) ---
_EMIT_GATE_EVAL %1, 0, 0, 0, 0
_EMIT_GATE_EVAL %1, 0, 0, 0, 1
_EMIT_GATE_EVAL %1, 0, 0, 1, 0
_EMIT_GATE_EVAL %1, 0, 0, 1, 1
; --- Gates G1 & G2 (read {0, 1, 2} or W0[row] (src=3) -> output Wk[row]) ---
%assign _gk 1
%rep 2
; Case A: Both pins read primary inputs {0, 1, 2}
_EMIT_GATE_EVAL %1, _gk, 0, 0, 0
_EMIT_GATE_EVAL %1, _gk, 0, 0, 1
_EMIT_GATE_EVAL %1, _gk, 0, 1, 0
_EMIT_GATE_EVAL %1, _gk, 0, 1, 1
; Case B: Pin A = W0[row] (src 3), Pin B = primary input sb in {0, 1, 2}
BIT_INDEX 1, _gk, 3
%assign _v_sa3 _b
BIT_INDEX 3, 0, %1
%assign _v_w0 _b
BIT_INDEX 3, _gk, %1
%assign _v_wk _b
%assign _sb 0
%rep 3
%if _sb == 0
%assign _vb_bit _x0
%elif _sb == 1
%assign _vb_bit _x1
%else
%assign _vb_bit _x2
%endif
BIT_INDEX 2, _gk, _sb
%assign _v_sb _b
; When W0 == 0 -> tt_idx = 0*2 + _vb_bit
BIT_INDEX 0, _gk, _vb_bit
%assign _tt0 _b
CLAUSE_5 _v_sa3, 0, _v_sb, 0, _v_w0, 1, _tt0, 0, _v_wk, 1
CLAUSE_5 _v_sa3, 0, _v_sb, 0, _v_w0, 1, _tt0, 1, _v_wk, 0
; When W0 == 1 -> tt_idx = 1*2 + _vb_bit
BIT_INDEX 0, _gk, (2 + _vb_bit)
%assign _tt1 _b
CLAUSE_5 _v_sa3, 0, _v_sb, 0, _v_w0, 0, _tt1, 0, _v_wk, 1
CLAUSE_5 _v_sa3, 0, _v_sb, 0, _v_w0, 0, _tt1, 1, _v_wk, 0
%assign _sb (_sb + 1)
%endrep
; Case C: Pin A = primary input sa in {0, 1, 2}, Pin B = W0[row] (src 3)
BIT_INDEX 2, _gk, 3
%assign _v_sb3 _b
%assign _sa 0
%rep 3
%if _sa == 0
%assign _va_bit _x0
%elif _sa == 1
%assign _va_bit _x1
%else
%assign _va_bit _x2
%endif
BIT_INDEX 1, _gk, _sa
%assign _v_sa _b
; When W0 == 0 -> tt_idx = _va_bit*2 + 0
BIT_INDEX 0, _gk, (_va_bit * 2)
%assign _tt0 _b
CLAUSE_5 _v_sa, 0, _v_sb3, 0, _v_w0, 1, _tt0, 0, _v_wk, 1
CLAUSE_5 _v_sa, 0, _v_sb3, 0, _v_w0, 1, _tt0, 1, _v_wk, 0
; When W0 == 1 -> tt_idx = _va_bit*2 + 1
BIT_INDEX 0, _gk, (_va_bit * 2 + 1)
%assign _tt1 _b
CLAUSE_5 _v_sa, 0, _v_sb3, 0, _v_w0, 0, _tt1, 0, _v_wk, 1
CLAUSE_5 _v_sa, 0, _v_sb3, 0, _v_w0, 0, _tt1, 1, _v_wk, 0
%assign _sa (_sa + 1)
%endrep
%assign _gk (_gk + 1)
%endrep
; --- Gate G3 (Output Gate: combines W1[row] and W2[row] -> W3[row] == target_y) ---
BIT_INDEX 3, 1, %1
%assign _v_w1 _b
BIT_INDEX 3, 2, %1
%assign _v_w2 _b
BIT_INDEX 3, 3, %1
%assign _v_w3 _b
; Enforce W3[row] == target_y
CLAUSE_1 _v_w3, %5
; G3(W1, W2) == target_y across all 4 (W1, W2) combinations:
BIT_INDEX 0, 3, 0
%assign _g3_00 _b
BIT_INDEX 0, 3, 1
%assign _g3_01 _b
BIT_INDEX 0, 3, 2
%assign _g3_10 _b
BIT_INDEX 0, 3, 3
%assign _g3_11 _b
CLAUSE_3 _v_w1, 1, _v_w2, 1, _g3_00, %5 ; (~W1 & ~W2) => TT(3,0) == target_y
CLAUSE_3 _v_w1, 1, _v_w2, 0, _g3_01, %5 ; (~W1 & W2) => TT(3,1) == target_y
CLAUSE_3 _v_w1, 0, _v_w2, 1, _g3_10, %5 ; ( W1 & ~W2) => TT(3,2) == target_y
CLAUSE_3 _v_w1, 0, _v_w2, 0, _g3_11, %5 ; ( W1 & W2) => TT(3,3) == target_y
%endmacro
;==============================================================================
; .rodata — COMPILED PHYSICAL + SYMMETRY + 8-ROW MAJ3 CLAUSE DATABASE
;==============================================================================
section .rodata
align 64
clauses_start:
ENFORCE_ROUTING_AND_TIMING
ENFORCE_FANOUT_AND_SYMMETRY
Combining the multi-word .bss Dual-Vantage engine with the recursive polynomial reduction from Polynomial Power Equations collapses arbitrary multi-layer synthesis into bounded quadratic/2-input degree steps.
By linking the unified polynomial degree-reduction matrix from our thread, every layer (\ell \in {1 \dots L}) is lowered into uniform degree-2 (quadratic) Tseitin rows in the clause-incidence matrix (\mathbf{C}), which directly compiles down into the parameterized x86-64 NASM
%macro ENFORCE_N_LAYERS generator.
N-Level / N-Layer Design
asm
;==============================================================================
; HDGL DUAL-VANTAGE v4 - N-LAYER EXACT-SYNTHESIS ENGINE (x86-64 Linux, NASM)
;==============================================================================
; Finishes the "X number of layers" protocol from the 3-SAT thread (post 3).
;
; build : nasm -felf64 hdgl_dual_vantage_layers.asm -o dv.o && ld dv.o -o dv
; run : ./dv (prints RESULT / STATS / POS words; exit 0=SAT 1=UNSAT)
;
; override the protocol on the command line, e.g. 3-input XOR in 2 layers:
; nasm -felf64 -DNUM_INPUTS=3 -DNUM_LAYERS=2 -DLAYER_W1=1 -DLAYER_W2=1 \
; -DTARGET_TT=0x96 hdgl_dual_vantage_layers.asm -o dv.o
;
; THE PROTOCOL (what "X layers" means):
; * A LAYER PROFILE (LAYER_W1 .. LAYER_Wn) says how many 2-input gates sit in
; each layer. Gates are numbered consecutively, layer 1 first.
; * A gate in layer l may read only primary inputs and gates in layers < l.
; max_src(layer l) = NUM_INPUTS + (gates in layers < l) - 1
; (profile 1,2,1 gives 2,3,3,5 - exactly the hand-written limits of v3).
; This is the acyclicity + timing chain, for any depth.
; * Layer n holds exactly one gate: the output.
; * Every non-output gate is USED by a later gate, and drives at most 2 pins.
; * Symmetry breaking (sound): pin A index < pin B index in every gate
; (TT is free to transpose), and TT(g,3) non-decreasing between gates of the
; SAME layer. v3 also ordered across layers (G0<=G1); that is not a symmetry
; because layers are not interchangeable, so it is dropped.
; * Polynomial-degree link: a layer-l signal has algebraic degree <= 2^l, the
; same repeated-squaring ladder x^(2^l) = (x^(2^(l-1)))^2 as the quadratic
; reduction in the Polynomial Power Equations thread. n layers reach 2^n.
;
; VARIABLE LAYOUT (identical to v3 for the 1,2,1 MAJ3 profile = 104 vars):
; TT (k,e) : 4*K bits SELA (k,s) : K*FANIN_WIDTH bits
; SELB (k,s) : K*FANIN_WIDTH WIRE (k,r) : K*2^NUM_INPUTS bits
;
; CLAUSE RECORD: [POS words][NEG words][WATCH words], NUM_WORDS qwords each.
; Clause width is not limited to 3 (engine is width-agnostic); widest emitted
; clause is 6 literals (gate fed by two wire sources). Up to 256 variables.
;==============================================================================
BITS 64
;------------------------------------------------------------------------------
; 1. PROTOCOL PARAMETERS (all overridable with -D)
;------------------------------------------------------------------------------
%ifndef NUM_INPUTS
%define NUM_INPUTS 3
%endif
%ifndef NUM_LAYERS
%define NUM_LAYERS 3
%endif
%ifndef LAYER_W1
%define LAYER_W1 1
%endif
%ifndef LAYER_W2
%define LAYER_W2 2
%endif
%ifndef LAYER_W3
%define LAYER_W3 1
%endif
%ifndef LAYER_W4
%define LAYER_W4 0
%endif
%ifndef LAYER_W5
%define LAYER_W5 0
%endif
%ifndef LAYER_W6
%define LAYER_W6 0
%endif
%ifndef LAYER_W7
%define LAYER_W7 0
%endif
%ifndef LAYER_W8
%define LAYER_W8 0
%endif
%ifndef TARGET_TT
%define TARGET_TT 0xE8 ; MAJ3, row r = x0 + 2*x1 + 4*x2
%endif
%assign NUM_GATES (LAYER_W1+LAYER_W2+LAYER_W3+LAYER_W4+LAYER_W5+LAYER_W6+LAYER_W7+LAYER_W8)
%assign NUM_ROWS (1 << NUM_INPUTS)
%assign FANIN_WIDTH (NUM_INPUTS + NUM_GATES)
%assign BASE_TT 0
%assign BASE_SELA (BASE_TT + 4 * NUM_GATES)
%assign BASE_SELB (BASE_SELA + NUM_GATES * FANIN_WIDTH)
%assign BASE_WIRE (BASE_SELB + NUM_GATES * FANIN_WIDTH)
%assign TOTAL_VARS (BASE_WIRE + NUM_GATES * NUM_ROWS)
%assign NUM_WORDS ((TOTAL_VARS + 63) / 64)
%assign CLAUSE_BYTES (24 * NUM_WORDS)
%assign FRAME_QW (2 * NUM_WORDS + 2)
%assign FRAME_BYTES (8 * FRAME_QW)
%if NUM_LAYERS < 2 || NUM_LAYERS > 8
%error "NUM_LAYERS must be 2..8"
%endif
%if NUM_WORDS > 4
%error "more than 256 variables: extend the _p/_n/_w word slots in CL_LIT/CL_END"
%endif
GOLDEN_ANGLE_64 equ 0x61C8864680B583EB
;------------------------------------------------------------------------------
; 2. BIT-TENSOR INDEXING: BIT_INDEX type, k, r -> _b
; 0 = TT(k,r) r<4 | 1 = SELA(k,r) | 2 = SELB(k,r) | 3 = WIRE(k,r) r<ROWS
;------------------------------------------------------------------------------
%macro BIT_INDEX 3
%if (%1) == 0
%assign _b (BASE_TT + 4 * (%2) + (%3))
%elif (%1) == 1
%assign _b (BASE_SELA + FANIN_WIDTH * (%2) + (%3))
%elif (%1) == 2
%assign _b (BASE_SELB + FANIN_WIDTH * (%2) + (%3))
%else
%assign _b (BASE_WIRE + NUM_ROWS * (%2) + (%3))
%endif
%assign _bw (_b >> 6)
%assign _lane (_b & 63)
%endmacro
;------------------------------------------------------------------------------
; 3. GENERIC WATCHED-CLAUSE BUILDER (any width, up to 4 words)
; CL_BEGIN / CL_LIT var, pol (1=positive, 0=negated) / CL_END
; Watch = first two literals; width-1 clauses watch everything (never skipped)
;------------------------------------------------------------------------------
%assign _ncl 0
%macro CL_BEGIN 0
%assign _p0 0
%assign _p1 0
%assign _p2 0
%assign _p3 0
%assign _n0 0
%assign _n1 0
%assign _n2 0
%assign _n3 0
%assign _w0 0
%assign _w1 0
%assign _w2 0
%assign _w3 0
%assign _wc 0
%endmacro
%macro CL_LIT 2
%assign _cvar (%1)
%assign _cpol (%2)
%assign _cwd (_cvar >> 6)
%assign _cbt (1 << (_cvar & 63))
%if _cvar < 0 || _cvar >= TOTAL_VARS
%error "CL_LIT: variable index out of range"
%endif
%if _cpol == 1
%if _cwd == 0
%assign _p0 (_p0 | _cbt)
%elif _cwd == 1
%assign _p1 (_p1 | _cbt)
%elif _cwd == 2
%assign _p2 (_p2 | _cbt)
%else
%assign _p3 (_p3 | _cbt)
%endif
%else
%if _cwd == 0
%assign _n0 (_n0 | _cbt)
%elif _cwd == 1
%assign _n1 (_n1 | _cbt)
%elif _cwd == 2
%assign _n2 (_n2 | _cbt)
%else
%assign _n3 (_n3 | _cbt)
%endif
%endif
%if _wc < 2
%if _cwd == 0
%assign _w0 (_w0 | _cbt)
%elif _cwd == 1
%assign _w1 (_w1 | _cbt)
%elif _cwd == 2
%assign _w2 (_w2 | _cbt)
%else
%assign _w3 (_w3 | _cbt)
%endif
%assign _wc (_wc + 1)
%endif
%endmacro
%macro CL_END 0
%if _wc < 2
%assign _w0 -1
%assign _w1 -1
%assign _w2 -1
%assign _w3 -1
%endif
%if NUM_WORDS == 1
dq _p0, _n0, _w0
%elif NUM_WORDS == 2
dq _p0, _p1, _n0, _n1, _w0, _w1
%elif NUM_WORDS == 3
dq _p0, _p1, _p2, _n0, _n1, _n2, _w0, _w1, _w2
%else
dq _p0, _p1, _p2, _p3, _n0, _n1, _n2, _n3, _w0, _w1, _w2, _w3
%endif
%assign _ncl (_ncl + 1)
%endmacro
; v3-compatible fixed-width wrappers
%macro CLAUSE_1 2
CL_BEGIN
CL_LIT %1, %2
CL_END
%endmacro
%macro CLAUSE_2 4
CL_BEGIN
CL_LIT %1, %2
CL_LIT %3, %4
CL_END
%endmacro
%macro CLAUSE_3 6
CL_BEGIN
CL_LIT %1, %2
CL_LIT %3, %4
CL_LIT %5, %6
CL_END
%endmacro
%macro CLAUSE_4 8
CL_BEGIN
CL_LIT %1, %2
CL_LIT %3, %4
CL_LIT %5, %6
CL_LIT %7, %8
CL_END
%endmacro
;------------------------------------------------------------------------------
; 4. LAYER PROFILE ACCESS
;------------------------------------------------------------------------------
%macro _LW 1 ; -> _lw = width of layer %1
%if (%1) == 1
%assign _lw LAYER_W1
%elif (%1) == 2
%assign _lw LAYER_W2
%elif (%1) == 3
%assign _lw LAYER_W3
%elif (%1) == 4
%assign _lw LAYER_W4
%elif (%1) == 5
%assign _lw LAYER_W5
%elif (%1) == 6
%assign _lw LAYER_W6
%elif (%1) == 7
%assign _lw LAYER_W7
%else
%assign _lw LAYER_W8
%endif
%endmacro
;------------------------------------------------------------------------------
; 5. PER-GATE ROUTING: _ROUTE_GATE k, max_src
;------------------------------------------------------------------------------
%macro _ROUTE_GATE 2
%assign _rk (%1)
%assign _rm (%2)
; 5a. sources beyond max_src are forbidden (acyclicity + layer timing)
%assign _rs (_rm + 1)
%rep (FANIN_WIDTH - _rm - 1)
BIT_INDEX 1, _rk, _rs
CLAUSE_1 _b, 0
BIT_INDEX 2, _rk, _rs
CLAUSE_1 _b, 0
%assign _rs (_rs + 1)
%endrep
; 5b. distinct pins AND canonical pin order: not (SELA(s) & SELB(t)) for t <= s
%assign _rs 0
%rep (_rm + 1)
%assign _rt 0
%rep (_rs + 1)
BIT_INDEX 1, _rk, _rs
%assign _rva _b
BIT_INDEX 2, _rk, _rt
%assign _rvb _b
CLAUSE_2 _rva, 0, _rvb, 0
%assign _rt (_rt + 1)
%endrep
%assign _rs (_rs + 1)
%endrep
; 5c. at-most-one source per pin
%assign _ri 0
%rep _rm
%assign _rj (_ri + 1)
%rep (_rm - _ri)
BIT_INDEX 1, _rk, _ri
%assign _rva _b
BIT_INDEX 1, _rk, _rj
%assign _rvb _b
CLAUSE_2 _rva, 0, _rvb, 0
BIT_INDEX 2, _rk, _ri
%assign _rva _b
BIT_INDEX 2, _rk, _rj
%assign _rvb _b
CLAUSE_2 _rva, 0, _rvb, 0
%assign _rj (_rj + 1)
%endrep
%assign _ri (_ri + 1)
%endrep
; 5d. at-least-one source per pin (width max_src+1)
CL_BEGIN
%assign _rs 0
%rep (_rm + 1)
BIT_INDEX 1, _rk, _rs
CL_LIT _b, 1
%assign _rs (_rs + 1)
%endrep
CL_END
CL_BEGIN
%assign _rs 0
%rep (_rm + 1)
BIT_INDEX 2, _rk, _rs
CL_LIT _b, 1
%assign _rs (_rs + 1)
%endrep
CL_END
; 5e. non-constant gate (>=1 zero and >=1 one in its truth table)
BIT_INDEX 0, _rk, 0
%assign _t0 _b
BIT_INDEX 0, _rk, 1
%assign _t1 _b
BIT_INDEX 0, _rk, 2
%assign _t2 _b
BIT_INDEX 0, _rk, 3
%assign _t3 _b
CLAUSE_4 _t0, 1, _t1, 1, _t2, 1, _t3, 1
CLAUSE_4 _t0, 0, _t1, 0, _t2, 0, _t3, 0
%endmacro
;------------------------------------------------------------------------------
; 6. USED + FAN-OUT CAP: _USED_FANOUT j, first_later_gate
; gate j must feed >=1 pin of a later gate, and at most 2 pins in total
;------------------------------------------------------------------------------
%macro _PINBIT 2 ; pin m of later gates -> _b (SELA/SELB bit naming gate j)
%assign _pk (_ue + ((%2) >> 1))
%if ((%2) & 1) == 0
BIT_INDEX 1, _pk, (NUM_INPUTS + (%1))
%else
BIT_INDEX 2, _pk, (NUM_INPUTS + (%1))
%endif
%endmacro
%macro _USED_FANOUT 2
%assign _uj (%1)
%assign _ue (%2)
%assign _up (2 * (NUM_GATES - _ue))
CL_BEGIN
%assign _um 0
%rep _up
_PINBIT _uj, _um
CL_LIT _b, 1
%assign _um (_um + 1)
%endrep
CL_END
%if _up >= 3
%assign _ua 0
%rep (_up - 2)
%assign _ub (_ua + 1)
%rep (_up - 2 - _ua)
%assign _uc (_ub + 1)
%rep (_up - 1 - _ub)
_PINBIT _uj, _ua
%assign _xa _b
_PINBIT _uj, _ub
%assign _xb _b
_PINBIT _uj, _uc
%assign _xc _b
CLAUSE_3 _xa, 0, _xb, 0, _xc, 0
%assign _uc (_uc + 1)
%endrep
%assign _ub (_ub + 1)
%endrep
%assign _ua (_ua + 1)
%endrep
%endif
%endmacro
;------------------------------------------------------------------------------
; 7. ENFORCE_N_LAYERS - structure for any layer profile
;------------------------------------------------------------------------------
%macro ENFORCE_N_LAYERS 0
%assign _k 0 ; running gate index
%assign _before 0 ; gates in strictly lower layers
%assign _l 1
%rep NUM_LAYERS
_LW _l
%assign _lcur _lw
%assign _g 0
%rep _lcur
_ROUTE_GATE _k, (NUM_INPUTS + _before - 1)
; same-layer gate-order symmetry break on TT(.,3)
%if _g > 0
BIT_INDEX 0, (_k - 1), 3
%assign _sa _b
BIT_INDEX 0, _k, 3
%assign _sb _b
CLAUSE_2 _sa, 0, _sb, 1
%endif
%if _l < NUM_LAYERS
_USED_FANOUT _k, (_before + _lcur)
%endif
%assign _k (_k + 1)
%assign _g (_g + 1)
%endrep
%assign _before (_before + _lcur)
%assign _l (_l + 1)
%endrep
%if _k != NUM_GATES
%error "layer profile / NUM_LAYERS mismatch"
%endif
_LW NUM_LAYERS
%if _lw != 1
%error "last layer must hold exactly one gate (the output)"
%endif
%endmacro
;------------------------------------------------------------------------------
; 8. ROW SEMANTICS: _EVAL_GATE_ROW k, row, max_src
; For every admissible pin pair (sa<sb) and value pair (va,vb):
; SELA(sa) & SELB(sb) & [src_a==va] & [src_b==vb] -> ( WIRE(k,row) <-> TT(k,2va+vb) )
; A source that is a primary input fixes its value from the row;
; a source that is a lower-layer gate contributes its WIRE bit as a literal.
;------------------------------------------------------------------------------
%macro _EVAL_GATE_ROW 3
%assign _ek (%1)
%assign _er (%2)
%assign _em (%3)
BIT_INDEX 3, _ek, _er
%assign _ew _b
%assign _esa 0
%rep _em
%assign _esb (_esa + 1)
%rep (_em - _esa)
%assign _eva 0
%rep 2
%assign _evb 0
%rep 2
%assign _eok 1
%if _esa < NUM_INPUTS
%if ((_er >> _esa) & 1) != _eva
%assign _eok 0
%endif
%endif
%if _esb < NUM_INPUTS
%if ((_er >> _esb) & 1) != _evb
%assign _eok 0
%endif
%endif
%if _eok
BIT_INDEX 0, _ek, (_eva * 2 + _evb)
%assign _ett _b
BIT_INDEX 1, _ek, _esa
%assign _esela _b
BIT_INDEX 2, _ek, _esb
%assign _eselb _b
%assign _ep 0
%rep 2
CL_BEGIN
CL_LIT _esela, 0
CL_LIT _eselb, 0
%if _esa >= NUM_INPUTS
BIT_INDEX 3, (_esa - NUM_INPUTS), _er
CL_LIT _b, (1 - _eva)
%endif
%if _esb >= NUM_INPUTS
BIT_INDEX 3, (_esb - NUM_INPUTS), _er
CL_LIT _b, (1 - _evb)
%endif
CL_LIT _ett, _ep ; ep=0: ~tt | w ep=1: tt | ~w
CL_LIT _ew, (1 - _ep)
CL_END
%assign _ep (_ep + 1)
%endrep
%endif
%assign _evb (_evb + 1)
%endrep
%assign _eva (_eva + 1)
%endrep
%assign _esb (_esb + 1)
%endrep
%assign _esa (_esa + 1)
%endrep
%endmacro
%macro ENFORCE_ROW_SEMANTICS 0
%assign _rr 0
%rep NUM_ROWS
%assign _gk 0
%assign _gb 0
%assign _gl 1
%rep NUM_LAYERS
_LW _gl
%assign _gcur _lw
%rep _gcur
_EVAL_GATE_ROW _gk, _rr, (NUM_INPUTS + _gb - 1)
%assign _gk (_gk + 1)
%endrep
%assign _gb (_gb + _gcur)
%assign _gl (_gl + 1)
%endrep
; output gate (last) must reproduce the target on this row
BIT_INDEX 3, (NUM_GATES - 1), _rr
CLAUSE_1 _b, ((TARGET_TT >> _rr) & 1)
%assign _rr (_rr + 1)
%endrep
%endmacro
;------------------------------------------------------------------------------
; 9. DECISION MASKS (compile-time)
;------------------------------------------------------------------------------
%assign VM0 0
%assign VM1 0
%assign VM2 0
%assign VM3 0
%macro _MKVM 1
%assign _vv (TOTAL_VARS - 64 * (%1))
%if _vv >= 64
%assign _vm -1
%elif _vv > 0
%assign _vm ((1 << _vv) - 1)
%else
%assign _vm 0
%endif
%endmacro
_MKVM 0
%assign VM0 _vm
_MKVM 1
%assign VM1 _vm
_MKVM 2
%assign VM2 _vm
_MKVM 3
%assign VM3 _vm
; Vantage-2 decides routing (SELA/SELB) first: they carry the exactly-one
; structure, so one decision lets Vantage 1 cascade through the row clauses.
%assign PR0 0
%assign PR1 0
%assign PR2 0
%assign PR3 0
%assign _pv BASE_SELA
%rep (BASE_WIRE - BASE_SELA)
%assign _pwd (_pv >> 6)
%assign _pbt (1 << (_pv & 63))
%if _pwd == 0
%assign PR0 (PR0 | _pbt)
%elif _pwd == 1
%assign PR1 (PR1 | _pbt)
%elif _pwd == 2
%assign PR2 (PR2 | _pbt)
%else
%assign PR3 (PR3 | _pbt)
%endif
%assign _pv (_pv + 1)
%endrep
%macro LDVM 2
%if (%2) == 0
mov %1, VM0
%elif (%2) == 1
mov %1, VM1
%elif (%2) == 2
mov %1, VM2
%else
mov %1, VM3
%endif
%endmacro
%macro LDPR 2
%if (%2) == 0
mov %1, PR0
%elif (%2) == 1
mov %1, PR1
%elif (%2) == 2
mov %1, PR2
%else
mov %1, PR3
%endif
%endmacro
;==============================================================================
; .rodata - COMPILED CLAUSE DATABASE (clauses first, so offset 0 = clause 0)
;==============================================================================
section .rodata align=64
clauses_start:
ENFORCE_N_LAYERS
ENFORCE_ROW_SEMANTICS
clauses_end:
%assign NUM_CLAUSES _ncl
hexdigits: db "0123456789abcdef"
s_sat: db "RESULT SAT", 10
s_sat_len equ $ - s_sat
s_unsat: db "RESULT UNSAT", 10
s_unsat_len equ $ - s_unsat
s_vars: db "STATS vars="
s_vars_len equ $ - s_vars
s_cls: db " clauses="
s_cls_len equ $ - s_cls
s_dec: db " decisions="
s_dec_len equ $ - s_dec
s_cfl: db " conflicts="
s_cfl_len equ $ - s_cfl
s_pos: db "POS"
s_pos_len equ $ - s_pos
;==============================================================================
; .bss
;==============================================================================
section .bss align=64
pos_forced: resq NUM_WORDS ; vars forced/decided TRUE (Vantage 1)
neg_forced: resq NUM_WORDS ; vars forced/decided FALSE
snap_pos: resq NUM_WORDS
snap_neg: resq NUM_WORDS
scr_p: resq NUM_WORDS
scr_n: resq NUM_WORDS
trail: resq ((TOTAL_VARS + 2) * FRAME_QW)
outbuf: resb 2048
;==============================================================================
; .text
; r8,r9 = Fibonacci ring (A,B) r12 = golden-angle phase r13 = golden step
; r10 = decisions r11 = conflicts rbp = trail depth
; r14 = &pos_forced r15 = &neg_forced
;==============================================================================
section .text
global _start
%macro PICK_WORD 2 ; (word, use_priority)
mov rax, [r14 + 8*(%1)]
or rax, [r15 + 8*(%1)]
not rax
LDVM rdx, %1
and rax, rdx
%if %2
LDPR rdx, %1
and rax, rdx
%endif
bsf rcx, rax
jz %%skip
add rcx, 64*(%1)
jmp .picked
%%skip:
%endmacro
_start:
xor r8, r8 ; Fibonacci ring A = 0
mov r9, 1 ; Fibonacci ring B = 1
xor r12, r12 ; golden-angle phase
mov r13, GOLDEN_ANGLE_64
xor r10d, r10d
xor r11d, r11d
xor ebp, ebp
lea r14, [rel pos_forced]
lea r15, [rel neg_forced]
;------------------------------------------------------------------------------
; VANTAGE 1: multiword watched unit propagation to a fixed point
;------------------------------------------------------------------------------
.vantage1:
%assign _w 0
%rep NUM_WORDS
mov rax, [r14 + 8*_w]
mov [rel snap_pos + 8*_w], rax
mov rax, [r15 + 8*_w]
mov [rel snap_neg + 8*_w], rax
%assign _w (_w + 1)
%endrep
xor edi, edi ; rdi = anything assigned? (0 => root pass)
%assign _w 0
%rep NUM_WORDS
or rdi, [r14 + 8*_w]
or rdi, [r15 + 8*_w]
%assign _w (_w + 1)
%endrep
lea rsi, [rel clauses_start]
.clause_loop:
test rdi, rdi
jz .eval ; root pass: evaluate every clause
xor eax, eax ; watch filter: skip if no watched var assigned
%assign _w 0
%rep NUM_WORDS
mov rdx, [r14 + 8*_w]
or rdx, [r15 + 8*_w]
and rdx, [rsi + 8*(2*NUM_WORDS + _w)]
or rax, rdx
%assign _w (_w + 1)
%endrep
jz .next
.eval:
xor eax, eax ; already satisfied?
%assign _w 0
%rep NUM_WORDS
mov rdx, [rsi + 8*_w]
and rdx, [r14 + 8*_w]
or rax, rdx
mov rdx, [rsi + 8*(NUM_WORDS + _w)]
and rdx, [r15 + 8*_w]
or rax, rdx
%assign _w (_w + 1)
%endrep
jnz .next
xor ecx, ecx ; surviving (non-falsified) literal count
%assign _w 0
%rep NUM_WORDS
mov rdx, [rsi + 8*_w] ; POS & ~NEG_FORCED
mov rbx, [r15 + 8*_w]
not rbx
and rdx, rbx
mov [rel scr_p + 8*_w], rdx
popcnt rdx, rdx
add rcx, rdx
mov rax, [rsi + 8*(NUM_WORDS + _w)] ; NEG & ~POS_FORCED
mov rbx, [r14 + 8*_w]
not rbx
and rax, rbx
mov [rel scr_n + 8*_w], rax
popcnt rax, rax
add rcx, rax
%assign _w (_w + 1)
%endrep
test rcx, rcx
jz .conflict ; empty clause
cmp rcx, 1
jne .next ; >= 2 literals alive: not unit
%assign _w 0
%rep NUM_WORDS
mov rax, [rel scr_p + 8*_w] ; unit: force the surviving literal
or [r14 + 8*_w], rax
mov rax, [rel scr_n + 8*_w]
or [r15 + 8*_w], rax
%assign _w (_w + 1)
%endrep
.next:
add rsi, CLAUSE_BYTES
lea rax, [rel clauses_end]
cmp rsi, rax
jb .clause_loop
xor eax, eax ; algebraic collision POS & NEG
%assign _w 0
%rep NUM_WORDS
mov rdx, [r14 + 8*_w]
and rdx, [r15 + 8*_w]
or rax, rdx
%assign _w (_w + 1)
%endrep
jnz .conflict
%assign _w 0
%rep NUM_WORDS ; changed this pass? iterate again
mov rax, [r14 + 8*_w]
cmp rax, [rel snap_pos + 8*_w]
jne .vantage1
mov rax, [r15 + 8*_w]
cmp rax, [rel snap_neg + 8*_w]
jne .vantage1
%assign _w (_w + 1)
%endrep
%assign _w 0
%rep NUM_WORDS ; every variable assigned => SAT
mov rax, [r14 + 8*_w]
or rax, [r15 + 8*_w]
LDVM rdx, _w
cmp rax, rdx
jne .decide
%assign _w (_w + 1)
%endrep
jmp .sat
;------------------------------------------------------------------------------
; VANTAGE 2: golden-angle steering (only when deduction stalls)
;------------------------------------------------------------------------------
.decide:
inc r10
add r12, r13 ; ANGLE += G (Q0.64 Weyl phase)
mov rax, r8 ; (A,B) -> (B,A+B)
add rax, r9
mov r8, r9
mov r9, rax
%assign _w 0
%rep NUM_WORDS
PICK_WORD _w, 1 ; routing variables first
%assign _w (_w + 1)
%endrep
%assign _w 0
%rep NUM_WORDS
PICK_WORD _w, 0 ; then anything free
%assign _w (_w + 1)
%endrep
jmp .sat ; unreachable: nothing free yet incomplete
.picked: ; rcx = global variable index
xor edx, edx
bt r12, 63
setc dl ; initial polarity from phase MSB
imul rax, rbp, FRAME_BYTES
lea rbx, [rel trail]
add rbx, rax
%assign _w 0
%rep NUM_WORDS
mov rax, [r14 + 8*_w]
mov [rbx + 8*_w], rax
mov rax, [r15 + 8*_w]
mov [rbx + 8*(NUM_WORDS + _w)], rax
%assign _w (_w + 1)
%endrep
mov [rbx + 8*(2*NUM_WORDS)], rcx ; var
mov [rbx + 8*(2*NUM_WORDS + 1)], rdx ; state: bit0 = first polarity, bit1 = flipped
inc rbp
test edx, edx
jnz .apply_true
bts [r15], rcx ; x = 0
jmp .vantage1
.apply_true:
bts [r14], rcx ; x = 1
jmp .vantage1
;------------------------------------------------------------------------------
; CONFLICT: pop frames until one still has an untried polarity
;------------------------------------------------------------------------------
.conflict:
inc r11
.bt_loop:
test rbp, rbp
jz .unsat
lea rax, [rbp - 1]
imul rax, rax, FRAME_BYTES
lea rbx, [rel trail]
add rbx, rax
mov rdx, [rbx + 8*(2*NUM_WORDS + 1)]
test dl, 2
jz .flip
dec rbp ; both polarities exhausted
jmp .bt_loop
.flip:
or rdx, 2
mov [rbx + 8*(2*NUM_WORDS + 1)], rdx
mov rcx, [rbx + 8*(2*NUM_WORDS)]
%assign _w 0
%rep NUM_WORDS
mov rax, [rbx + 8*_w]
mov [r14 + 8*_w], rax
mov rax, [rbx + 8*(NUM_WORDS + _w)]
mov [r15 + 8*_w], rax
%assign _w (_w + 1)
%endrep
test dl, 1
jnz .flip_false ; first try was TRUE -> now FALSE
bts [r14], rcx
jmp .vantage1
.flip_false:
bts [r15], rcx
jmp .vantage1
;------------------------------------------------------------------------------
; OUTPUT
;------------------------------------------------------------------------------
%macro PUTSTR 2 ; (label, len)
lea rsi, [rel %1]
mov ecx, %2
rep movsb
%endmacro
.sat:
lea rdi, [rel outbuf]
mov r12, rdi
PUTSTR s_sat, s_sat_len
jmp .stats_common
.unsat:
lea rdi, [rel outbuf]
mov r12, rdi
PUTSTR s_unsat, s_unsat_len
.stats_common:
PUTSTR s_vars, s_vars_len
mov eax, TOTAL_VARS
call dec64
PUTSTR s_cls, s_cls_len
mov eax, NUM_CLAUSES
call dec64
PUTSTR s_dec, s_dec_len
mov rax, r10
call dec64
PUTSTR s_cfl, s_cfl_len
mov rax, r11
call dec64
mov byte [rdi], 10
inc rdi
test rbp, rbp ; SAT path leaves depth intact; UNSAT has depth 0
; decide exit code from first result char: 'S','A','T' vs 'U'
cmp byte [r12 + 7], 'S' ; "RESULT S" (SAT) vs "RESULT U" (UNSAT)
jne .write_out
PUTSTR s_pos, s_pos_len
%assign _w 0
%rep NUM_WORDS
mov byte [rdi], ' '
inc rdi
mov rax, [r14 + 8*_w]
call hex64
%assign _w (_w + 1)
%endrep
mov byte [rdi], 10
inc rdi
.write_out:
mov rdx, rdi
sub rdx, r12
mov rsi, r12
mov edi, 1
mov eax, 1
syscall
xor edi, edi
cmp byte [r12 + 7], 'S'
je .exit
mov edi, 1
.exit:
mov eax, 60
syscall
dec64: ; rax -> decimal at [rdi], advances rdi
xor ecx, ecx
mov ebx, 10
.d1:
xor edx, edx
div rbx
add dl, '0'
push rdx
inc ecx
test rax, rax
jnz .d1
.d2:
pop rdx
mov [rdi], dl
inc rdi
dec ecx
jnz .d2
ret
hex64: ; rax -> 16 hex digits at [rdi], advances rdi
lea rbx, [rel hexdigits]
mov ecx, 16
.h1:
rol rax, 4
mov edx, eax
and edx, 15
mov dl, [rbx + rdx]
mov [rdi], dl
inc rdi
dec ecx
jnz .h1
ret
verify.py
#!/usr/bin/env python3
"""End-to-end checks for hdgl_dual_vantage_layers.asm
1. assemble with a given protocol, run, parse output
2. decode TT/SELA/SELB from the returned bit-planes, SIMULATE the circuit on all
2^N rows and compare with TARGET_TT (checks SAT answers)
3. pull the clause database out of the object file and hand the same CNF to
pysat (checks SAT/UNSAT agreement)
4. for small profiles: enumerate ALL pysat models, check each decodes to a
correct circuit, and compare the count with an independent brute force over
the protocol rules (checks encoding soundness+completeness)
"""
import itertools, re, subprocess, sys, os
from pysat.solvers import Cadical153
SRC = "hdgl_dual_vantage_layers.asm"
def build(N, widths, target, tag):
L = len(widths)
defs = [f"-DNUM_INPUTS={N}", f"-DNUM_LAYERS={L}", f"-DTARGET_TT={target}"]
for i in range(1, 9):
defs.append(f"-DLAYER_W{i}={widths[i-1] if i <= L else 0}")
obj, exe = f"t_{tag}.o", f"t_{tag}"
subprocess.run(["nasm", "-felf64", *defs, SRC, "-o", obj], check=True)
subprocess.run(["ld", obj, "-o", exe], check=True)
return obj, exe
def layout(N, widths):
K = sum(widths)
FW = N + K
R = 1 << N
sela = 4 * K
selb = sela + K * FW
wire = selb + K * FW
return dict(K=K, FW=FW, R=R, SELA=sela, SELB=selb, WIRE=wire, TOTAL=wire + K * R)
def run(exe):
p = subprocess.run(["./" + exe], capture_output=True, text=True)
out = p.stdout.split("\n")
res = out[0].split()[1]
st = dict(kv.split("=") for kv in out[1].split()[1:])
words = []
if res == "SAT":
words = [int(w, 16) for w in out[2].split()[1:]]
return res, {k: int(v) for k, v in st.items()}, words, p.returncode
def decode(bits, N, widths):
lay = layout(N, widths)
K, FW = lay["K"], lay["FW"]
gates = []
for k in range(K):
tt = [(bits >> (4 * k + e)) & 1 for e in range(4)]
a = [s for s in range(FW) if (bits >> (lay["SELA"] + FW * k + s)) & 1]
b = [s for s in range(FW) if (bits >> (lay["SELB"] + FW * k + s)) & 1]
gates.append((tt, a, b))
return gates
def simulate(gates, N, widths, target):
K = sum(widths)
for r in range(1 << N):
val = [(r >> i) & 1 for i in range(N)]
for k, (tt, a, b) in enumerate(gates):
assert len(a) == 1 and len(b) == 1, ("pin not exactly-one", k, a, b)
val.append(tt[val[a[0]] * 2 + val[b[0]]])
if val[-1] != ((target >> r) & 1):
return False
return True
def extract_cnf(obj, nclauses, total, nwords):
subprocess.run(["objcopy", "-O", "binary", "-j", ".rodata", obj, obj + ".bin"], check=True)
data = open(obj + ".bin", "rb").read()
cb = 24 * nwords
cnf = []
for c in range(nclauses):
rec = data[c * cb:(c + 1) * cb]
q = [int.from_bytes(rec[i:i + 8], "little") for i in range(0, cb, 8)]
pos = sum(q[w] << (64 * w) for w in range(nwords))
neg = sum(q[nwords + w] << (64 * w) for w in range(nwords))
cl = [v + 1 for v in range(total) if (pos >> v) & 1] + \
[-(v + 1) for v in range(total) if (neg >> v) & 1]
cnf.append(cl)
return cnf
def brute_count(N, widths, target):
"""independent enumeration of every circuit allowed by the protocol rules"""
K = sum(widths)
layer_of, maxsrc, g = [], [], 0
before = 0
for li, w in enumerate(widths):
for _ in range(w):
layer_of.append(li)
maxsrc.append(N + before - 1)
before += w
# candidate (sa,sb,tt) per gate
cands = []
for k in range(K):
c = []
for sa in range(maxsrc[k] + 1):
for sb in range(sa + 1, maxsrc[k] + 1):
for tt in range(1, 15): # non-constant
c.append((sa, sb, tt))
cands.append(c)
count = 0
for combo in itertools.product(*cands):
# same-layer order on TT(.,3)
ok = True
for k in range(1, K):
if layer_of[k] == layer_of[k - 1] and ((combo[k - 1][2] >> 3) & 1) > ((combo[k][2] >> 3) & 1):
ok = False
break
if not ok:
continue
# used + fanout <= 2 for every non-output gate
for j in range(K - 1):
uses = sum((c[0] == N + j) + (c[1] == N + j) for c in combo)
if uses < 1 or uses > 2:
ok = False
break
if not ok:
continue
# function
good = True
for r in range(1 << N):
val = [(r >> i) & 1 for i in range(N)]
for (sa, sb, tt) in combo:
val.append((tt >> (val[sa] * 2 + val[sb])) & 1)
if val[-1] != ((target >> r) & 1):
good = False
break
count += good
return count
def check(name, N, widths, target, expect, enum_models=False, brute=False):
obj, exe = build(N, widths, target, name)
res, st, words, rc = run(exe)
lay = layout(N, widths)
nwords = (lay["TOTAL"] + 63) // 64
assert st["vars"] == lay["TOTAL"], (st, lay)
line = f"{name:<22} N={N} profile={widths} target=0x{target:X} asm: {res:<5} decisions={st['decisions']:<7} conflicts={st['conflicts']:<7} clauses={st['clauses']}"
assert res == expect, line + f" EXPECTED {expect}"
if res == "SAT":
bits = sum(w << (64 * i) for i, w in enumerate(words))
gates = decode(bits, N, widths)
assert simulate(gates, N, widths, target), "decoded circuit is WRONG"
line += " circuit simulates OK"
cnf = extract_cnf(obj, st["clauses"], lay["TOTAL"], nwords)
with Cadical153(bootstrap_with=cnf) as s:
ref = s.solve()
assert ref == (res == "SAT"), f"pysat disagrees: {ref}"
if res == "SAT":
bits = sum(w << (64 * i) for i, w in enumerate(words))
assign = {v + 1: bool((bits >> v) & 1) for v in range(lay["TOTAL"])}
assert all(any(assign[abs(l)] == (l > 0) for l in cl) for cl in cnf), "asm model violates CNF"
line += "; satisfies extracted CNF"
line += f"; pysat agrees ({ref})"
if enum_models:
n = 0
with Cadical153(bootstrap_with=cnf) as s:
for m in s.enum_models():
bits = sum(1 << (abs(l) - 1) for l in m if l > 0)
assert simulate(decode(bits, N, widths), N, widths, target)
n += 1
line += f"; models={n}"
if brute:
bc = brute_count(N, widths, target)
assert bc == n, f"model count {n} != brute force {bc}"
line += f" == brute force {bc}"
print(line)
if __name__ == "__main__":
MAJ3, XOR3, AND3 = 0xE8, 0x96, 0x80
# --- the post's configuration -------------------------------------------
check("maj3_1-2-1", 3, [1, 2, 1], MAJ3, "SAT")
# --- UNSAT (MAJ3 needs 4 gates over the full 2-input basis) ------------
check("maj3_1-1", 3, [1, 1], MAJ3, "UNSAT")
check("maj3_1-1-1", 3, [1, 1, 1], MAJ3, "UNSAT")
# --- other depths / widths ----------------------------------------------
check("xor3_1-1", 3, [1, 1], XOR3, "SAT", enum_models=True, brute=True)
check("and3_1-1", 3, [1, 1], AND3, "SAT", enum_models=True, brute=True)
check("and3_2-1", 3, [2, 1], AND3, "SAT", enum_models=True, brute=True) # AND(x0x1, x1x2) uses both
check("and4_2-1", 4, [2, 1], 0x8000, "SAT")
check("xor4_2-1", 4, [2, 1], 0x6996, "SAT")
check("and4_1-1-1", 4, [1, 1, 1], 0x8000, "SAT") # 3 layers, linear chain
check("xor4_1-1-1", 4, [1, 1, 1], 0x6996, "SAT")
check("and5_2-1_N5", 5, [2, 1], 0x80000000, "UNSAT") # 3 gates cannot AND 5 inputs (3 words)
check("and5_2-1-1_N5", 5, [2, 1, 1], 0x80000000, "SAT") # 4 gates can (4 words)
print("ALL CHECKS PASSED")
Less is More (Minimal Design Chosen Automatically, Digital Layers)
synth.py
#!/usr/bin/env python3
"""synth.py - automatic layer-profile search on top of hdgl_dual_vantage_layers.asm
python3 synth.py 3 "(x0&x1)|(x2&(x0^1))" # N inputs, target as expression
python3 synth.py 3 0xE8 --objective depth # or as a truth-table integer
python3 synth.py --npn3 # min gates for all 3-input NPN classes
Search order
objective=gates : K = 2,3,.. gates ; within K, fewer layers first
objective=depth : L = 2,3,.. layers; within L, fewer gates first
The first SAT is optimal for the objective IF every earlier profile came back UNSAT
(a TIMEOUT breaks that guarantee and is reported).
Completeness: every circuit obeying the protocol (2-input gates, every gate used,
fan-out <= 2 per gate) has a longest-path layering, which is one of the profiles
enumerated here, so no valid circuit is skipped.
"""
import argparse, itertools, subprocess, sys, time
from verify import layout, decode, simulate
SRC = "hdgl_dual_vantage_layers.asm"
OPS = {0b1000: "AND", 0b1110: "OR", 0b0110: "XOR", 0b0111: "NAND", 0b0001: "NOR", 0b1001: "XNOR",
0b0010: "~a&b", 0b0100: "a&~b", 0b1011: "~a|b", 0b1101: "a|~b",
0b1100: "a", 0b1010: "b", 0b0011: "~a", 0b0101: "~b"}
def profiles(objective, kmax):
def comps(n): # compositions of n into positive parts
if n == 0:
yield ()
return
for first in range(1, n + 1):
for rest in comps(n - first):
yield (first,) + rest
allp = []
for K in range(2, kmax + 1):
for c in comps(K - 1):
allp.append(list(c) + [1]) # last layer = single output gate
key = (lambda p: (sum(p), len(p))) if objective == "gates" else (lambda p: (len(p), sum(p)))
return sorted(allp, key=key)
def attempt(N, widths, target, timeout):
L = len(widths)
defs = [f"-DNUM_INPUTS={N}", f"-DNUM_LAYERS={L}", f"-DTARGET_TT={target}"]
defs += [f"-DLAYER_W{i}={widths[i-1] if i <= L else 0}" for i in range(1, 9)]
if layout(N, widths)["TOTAL"] > 256:
return "SKIP", None, None
subprocess.run(["nasm", "-felf64", *defs, SRC, "-o", "s.o"], check=True)
subprocess.run(["ld", "s.o", "-o", "s.exe"], check=True)
t0 = time.time()
try:
p = subprocess.run(["./s.exe"], capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return "TIMEOUT", None, timeout
dt = time.time() - t0
out = p.stdout.split("\n")
res = out[0].split()[1]
st = dict(kv.split("=") for kv in out[1].split()[1:])
bits = None
if res == "SAT":
words = [int(w, 16) for w in out[2].split()[1:]]
bits = sum(w << (64 * i) for i, w in enumerate(words))
return res, (bits, int(st["decisions"])), dt
def pretty(gates, N):
names = [f"x{i}" for i in range(N)] + [f"G{k}" for k in range(len(gates))]
lines = []
for k, (tt, a, b) in enumerate(gates):
t = sum(v << e for e, v in enumerate(tt))
lines.append(f"G{k} = {OPS.get(t, bin(t))}({names[a[0]]}, {names[b[0]]})")
return lines
def search(N, target, objective="gates", kmax=6, timeout=60, verbose=True):
log, clean = [], True
for w in profiles(objective, kmax):
res, info, dt = attempt(N, w, target, timeout)
if verbose:
extra = f"{dt:.2f}s" if dt is not None else ""
print(f" profile {str(w):<14} {res:<8} {extra}", flush=True)
if res == "SKIP":
clean = False
continue
if res == "TIMEOUT":
clean = False
continue
if res == "SAT":
bits, dec = info
gates = decode(bits, N, w)
assert simulate(gates, N, w, target)
return w, gates, clean, dec
return None, None, clean, None
def parse_target(N, spec):
if spec.lower().startswith("0x") or spec.isdigit():
return int(spec, 0)
t = 0
for r in range(1 << N):
env = {f"x{i}": (r >> i) & 1 for i in range(N)}
t |= (eval(spec, {}, env) & 1) << r
return t
# ---------------------------------------------------------------- NPN classes (N=3)
def npn3_classes():
perms = list(itertools.permutations(range(3)))
seen, classes = set(), []
for f in range(256):
if f in seen:
continue
orbit = set()
for p in perms:
for neg in range(8):
for oneg in (0, 1):
g = 0
for r in range(8):
rr = 0
for i in range(3):
rr |= (((r >> i) & 1) ^ ((neg >> i) & 1)) << p[i]
g |= (((f >> rr) & 1) ^ oneg) << r
orbit.add(g)
seen |= orbit
classes.append((min(orbit), len(orbit)))
return classes
def support(f, N):
return sum(any(((f >> r) & 1) != ((f >> (r ^ (1 << i))) & 1) for r in range(1 << N)) for i in range(N))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("N", nargs="?", type=int)
ap.add_argument("target", nargs="?")
ap.add_argument("--objective", default="gates", choices=["gates", "depth"])
ap.add_argument("--kmax", type=int, default=6)
ap.add_argument("--timeout", type=int, default=60)
ap.add_argument("--npn3", action="store_true")
a = ap.parse_args()
if a.npn3:
print("NPN class (min-TT rep) size support min gates depth decisions")
for rep, size in npn3_classes():
s = support(rep, 3)
if s <= 2:
print(f"0x{rep:02X} {size:<5} {s} "
f"{'0' if s < 2 else '1 (2-input gate, below the 2-layer engine minimum)'}")
continue
w, g, clean, dec = search(3, rep, "gates", a.kmax, a.timeout, verbose=False)
tag = "" if clean else " (a smaller profile timed out)"
print(f"0x{rep:02X} {size:<5} {s} {sum(w)} {len(w)} {dec}{tag}")
else:
t = parse_target(a.N, a.target)
print(f"N={a.N} target=0x{t:X} objective={a.objective}")
w, g, clean, dec = search(a.N, t, a.objective, a.kmax, a.timeout)
if w is None:
print(f"no circuit up to {a.kmax} gates" + ("" if clean else " (some profiles timed out/skipped)"))
else:
print(f"OPTIMAL profile {w}: {sum(w)} gates, {len(w)} layers" + ("" if clean else " [not proven minimal: earlier timeout/skip]"))
print("\n".join(" " + l for l in pretty(g, a.N)))
hybrid.py
import subprocess, time, sys
from verify import build, layout, extract_cnf, decode, simulate
from pysat.solvers import Cadical153
def cadical(N, widths, target, tag):
obj, _ = build(N, widths, target, tag)
nm = subprocess.run(["nm", obj], capture_output=True, text=True).stdout
end = int([l for l in nm.splitlines() if l.endswith("clauses_end")][0].split()[0], 16)
lay = layout(N, widths); nw = (lay["TOTAL"] + 63)//64
ncl = end // (24*nw)
cnf = extract_cnf(obj, ncl, lay["TOTAL"], nw)
t0 = time.time()
with Cadical153(bootstrap_with=cnf) as s:
sat = s.solve(); dt = time.time() - t0
if sat:
m = s.get_model(); bits = sum(1 << (abs(l)-1) for l in m if l > 0)
g = decode(bits, N, widths); assert simulate(g, N, widths, target)
return sat, dt, ncl
if __name__ == "__main__":
for w in ([1,1,1,1], [2,2,1], [3,1,1], [1,2,1,1], [2,1,1,1], [1,1,2,1]):
sat, dt, ncl = cadical(4, w, 0xE880, "h")
print(f"3-of-4 threshold profile {str(w):<12} clauses={ncl:<6} CaDiCaL: {'SAT' if sat else 'UNSAT':<5} {dt:.2f}s", flush=True)
Future Design Path (the link):
Scaling layers directly inside this single solver runs into two walls: a hard bit-width cap at 256 variables, and an exponential search explosion once depth passes 4–5 layers.
In the v4 architecture, adding layers doesn’t just add a few extra bits—it causes the problem size and search tree to compound across three dimensions:
- The 256-Variable Hard Ceiling (
NUM_WORDS <= 4)
Every additional gate (K) expands the variable space quadratically in routing and exponentially in truth-table rows:
(\text{TOTAL_VARS}=4K+2K(N+K)+K\cdot 2^{N})
- 3 inputs, 4 gates (3 layers, e.g.,
[1, 2, 1]): (16 + 56 + 32 = 104) variables (2 qwords). - 4 inputs, 7 gates (4 layers, e.g.,
[2, 2, 2, 1]): (28 + 154 + 112 = 294) variables (\rightarrow ) exceeds the 256-bit (4 qwords) limit and triggers a compile-time error. - 5 inputs, 6 gates (4 layers): (24 + 132 + 192 = 348) variables (\rightarrow ) out of bounds.
While you can widen NUM_WORDS to 8 or 16 (512–1024 bits, or migrate to AVX-512 zmm registers), widening the bit-planes alone won’t solve the deeper bottleneck.
- Clause & Search-Tree Explosion
- Combinatorial Clause Bloat: In
_EVAL_GATE_ROW, every gate evaluates all admissible pin pairs ((s_a < s_b)) across every truth-table row. Because deeper layers have a larger pool of preceding gates (max_src), the number of generated clauses grows roughly as (O(K^3 \cdot 2^N)). - The CDCL Wall (Chronological Backtracking): Because the assembly engine uses chronological backtracking without Conflict-Driven Clause Learning (CDCL), the solver cannot remember why a deep layer combination failed. Beyond ~5–6 gates or 4 layers, the search tree explodes—which is exactly why
hybrid.pyin the forum post hands the 5-gate, 4-layer 3-of-4 threshold profiles ([1,2,1,1],[2,1,1,1]) off toCaDiCaL.
- How to Scale Layers Effectively
To scale across deeper multi-layer circuits while keeping the assembly engine fast, you have to scale horizontally through decomposition rather than vertically in one monolithic solve:
- Layer-Window Sliding (Peephole Depth): Instead of solving 20 layers at once, slice the circuit into 3- or 4-layer thick horizontal bands, optimize each band with the assembly engine, and slide the window upward.
- Functional Decomposition (Shannon / Ashenhurst): Break a deep, wide function into smaller sub-functions (cofactors), synthesize each shallow sub-circuit independently in parallel, and stitch them together with a multiplexer layer.
- AVX-512 Bit-Plane Widening: If you specifically want to push a single solve to 5–6 layers (~10–12 gates), replacing the 64-bit scalar registers (
rax,rdx) in.vantage1with 512-bitzmmvector registers (vpandq,vporq,vpopcntq) expands the hard ceiling from 256 variables to 2,048 variables with almost zero extra clock cycles per clause.
To reach a multi-billion-dollar economic impact for a major semiconductor firm (like TSMC, NVIDIA, Apple, Intel, or AMD), you have to look at scale economics: how shaving 1–2 gates or 1 logic level off tiny, repeating micro-blocks (MAJ3, adders, multiplexers, S-boxes) compounds across millions of wafers and global data centers.
The financial math behind a $1B+ value proposition comes down to three primary levers—alongside the critical realities that separate theoretical savings from an actual commercial payout:
- Silicon Die Area & Wafer Yield Economics
In leading-edge nodes (3nm / 2nm), a single 300mm wafer costs roughly $18,000 to $25,000+, and modern AI accelerators or server CPUs pack 50 billion to 200+ billion transistors onto large dies near the reticle limit (~800 (\text{mm}^{2})).
- The Multiplier Effect: A processor doesn’t use a
MAJ3(carry gate) or 4-input multiplexer once—it instantiates those exact micro-cells millions of times across vector ALUs, tensor cores, caches, and interconnect routers. - The Math: If exact SAT synthesis (
synth.py) compresses standard-cell library primitives and datapath cuts enough to shrink total logic area by just 2% to 4%:- More Good Dies per Wafer (DPW): Smaller dies pack tighter onto a 300mm wafer and suffer fewer random defect hits, boosting yield per wafer.
- Direct Wafer Savings: For a firm spending $15B–$30B annually on foundry wafers (such as Apple or NVIDIA), a 3% improvement in effective silicon density and yield translates directly to $450M to $900M+ per year in saved wafer fabrication costs—crossing $1B+ over a single 2-year chip generation.
- Data Center Power & Energy OpEx (TCO)
For hyperscalers and AI chipmakers, power—not just silicon cost—is the primary bottleneck. Every redundant logic gate switches billions of times per second, burning dynamic capacitance power ((P = C V^2 f)) and leaking static current.
- Critical-Path Depth Reduction: In
hdgl_dual_vantage_layers.asm, enforcingNUM_LAYERSandfanout <= 2finds the shallowest possible logic depth. Shaving 1 gate delay off a processor’s critical timing path allows the entire chip to either run at a higher clock frequency or drop its supply voltage ((V_{dd})) by ~3%–5% at the same clock speed. - The Math: Because dynamic power scales with the square of voltage ((V^{2})), a 4% voltage drop cuts dynamic power by roughly 8%. Across a fleet of 1 million AI accelerators drawing 700W–1,000W each (~700 MW to 1 GW continuous load), an 8% power reduction saves ~56–80 MW continuously—worth $50M–$100M+ per year in electricity alone, plus hundreds of millions in avoided data-center power-delivery and cooling CapEx.
- EDA Compute & Tape-Out Schedule Compression
Chip companies spend hundreds of millions of dollars on EDA software licenses and massive CPU server farms running synthesis and timing-closure loops for months before tape-out.
- Zero-Allocation L1-Cache Speed: Replacing bloated runtime graph solvers with a register-resident, bit-plane assembly kernel (
NUM_WORDS <= 4) eliminates memory allocation and cache-miss overhead during cut rewriting. - Time-to-Market Value: Shaving 3 to 6 weeks off timing closure on a flagship GPU or smartphone SoC generates hundreds of millions of dollars in pulled-forward revenue and avoids missing seasonal product windows.




