@fraczak/k 8.8.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +902 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +6 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +132 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -5
- package/backends/llvm/src/llvm.mjs +4 -111
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +0 -16
- package/backends/wasm/README.md +2 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +10 -56
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/djson.mjs +2 -3
- package/codecs/int.mjs +66 -14
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +482 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +119 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +543 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1376 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4413 -0
- package/ktvm/wasm/test-wasm.mjs +426 -0
- package/ktvm/wire.mjs +489 -0
- package/lib/djson.k +175 -173
- package/lib/generic.k +82 -97
- package/lib/ieee.k +110 -115
- package/lib/integer.k +25 -31
- package/package.json +1 -9
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +275 -0
- package/scripts/perf-ieee.mjs +9 -229
- package/scripts/perf-int.mjs +14 -272
- package/scripts/perf-multiplication.mjs +8 -54
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-djson-methods.mjs +0 -1
- package/tests/test-djson.mjs +0 -1
- package/tests/test-generic.mjs +5 -7
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +27 -20
- package/tests/test-structural-values.mjs +1 -1
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,1105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bit-Chunk / Virtual-Stack / FSM Table Synthesizer with SWAR Don't-Care Bit
|
|
3
|
+
* Compression, Howard MWTR L1 Budget Allocation, and Bisimulation Verification.
|
|
4
|
+
*
|
|
5
|
+
* Implements DOCS/KTVM_SPEC.md §6 & §11.1 Milestone 3:
|
|
6
|
+
* - Synthesizes `chunk_table` (1-2 streaming ports + optional `reg`),
|
|
7
|
+
* `stack_table` (1 streaming port + 1 local LIFO `BitStack` + optional `reg`),
|
|
8
|
+
* and `fsm_table` (acyclic multi-step 1-stream kernels) directly by
|
|
9
|
+
* symbolically simulating each kernel's exact reference CFG (`slow_step`)!
|
|
10
|
+
* - Automatically discovers per-token don't-care bit masks (SWAR compression)
|
|
11
|
+
* when subset of bits suffices for all continuing transitions.
|
|
12
|
+
* - Evaluates worst-case throughput `rho*` via Howard's policy-improvement
|
|
13
|
+
* MWTR algorithm (`mwtr.mjs`) and selects the highest-throughput table set
|
|
14
|
+
* fitting inside `budgetBytes` (default 64 KB L1-resident).
|
|
15
|
+
* - Gracefully skips wide-alphabet kernels (`tagWidth > 4`, e.g. `ascii[]` in
|
|
16
|
+
* `djson.k`), keeping them as clean un-chunked `kernel` CFGs.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { cloneAst, createModule } from "../ast.mjs";
|
|
20
|
+
import { BitDeque, BitStack } from "../bit-deque.mjs";
|
|
21
|
+
import { choiceWidth } from "../../codecs/runtime/prefix-codec.mjs";
|
|
22
|
+
import {
|
|
23
|
+
DEFAULT_L1_BUDGET_BYTES,
|
|
24
|
+
allocateTableBudgets,
|
|
25
|
+
budgetClassForBytes,
|
|
26
|
+
computeMWTR
|
|
27
|
+
} from "./mwtr.mjs";
|
|
28
|
+
|
|
29
|
+
function popcount(x) {
|
|
30
|
+
let c = 0;
|
|
31
|
+
let v = x >>> 0;
|
|
32
|
+
while (v) {
|
|
33
|
+
v &= v - 1;
|
|
34
|
+
c++;
|
|
35
|
+
}
|
|
36
|
+
return c;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function sanitize(raw) {
|
|
40
|
+
const s = String(raw || "").replace(/^[@$%&]/, "").replace(/[^A-Za-z0-9_]/g, "_");
|
|
41
|
+
return /^[A-Za-z_]/.test(s) ? s : `t_${s}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Exact PEXT-style bit compression matching `vm.mjs`'s `applyInputCompress`.
|
|
46
|
+
*/
|
|
47
|
+
export function compressBitsWithMask(rawVal, rawBits, mask) {
|
|
48
|
+
let out = 0;
|
|
49
|
+
let bitPos = 0;
|
|
50
|
+
const m = mask >>> 0;
|
|
51
|
+
for (let i = 0; i < rawBits; i++) {
|
|
52
|
+
if ((m >>> i) & 1) {
|
|
53
|
+
out |= ((rawVal >>> i) & 1) << bitPos;
|
|
54
|
+
bitPos++;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Repeat a per-token `unitMask` (width `w`) across `numTokens` tokens to form a
|
|
62
|
+
* full `W_raw = w * numTokens` bitmask.
|
|
63
|
+
*/
|
|
64
|
+
function repeatUnitMask(unitMask, w, numTokens) {
|
|
65
|
+
let full = 0;
|
|
66
|
+
for (let t = 0; t < numTokens; t++) {
|
|
67
|
+
full = (full << w) | (unitMask & ((1 << w) - 1));
|
|
68
|
+
}
|
|
69
|
+
return full >>> 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Simulate a kernel's reference CFG (`slow_step`) over finite input bit windows
|
|
74
|
+
* (+ optional initial register state and optional initial LIFO BitStack).
|
|
75
|
+
*
|
|
76
|
+
* Returns `{ kind: "CONT"|"EXIT"|"NEED_MORE"|"FAIL", nextQ, shifts, emitWords,
|
|
77
|
+
* emitLens, exitId, stackPop, stackPushWord, stackPushLen, stackCleared }`.
|
|
78
|
+
*/
|
|
79
|
+
export function simulateKernelReferenceCFG({
|
|
80
|
+
kernel,
|
|
81
|
+
blockMap,
|
|
82
|
+
loopHeader,
|
|
83
|
+
slowLabel,
|
|
84
|
+
regName,
|
|
85
|
+
startQ,
|
|
86
|
+
inputNames,
|
|
87
|
+
inputBits,
|
|
88
|
+
inputWidths,
|
|
89
|
+
outputNames,
|
|
90
|
+
stackName = null,
|
|
91
|
+
initStackBits = 0,
|
|
92
|
+
initStackDepth = 0,
|
|
93
|
+
stackWindowTruncated = initStackDepth > 0,
|
|
94
|
+
exitLabelToId,
|
|
95
|
+
failLabel = "err",
|
|
96
|
+
maxSteps = 256
|
|
97
|
+
}) {
|
|
98
|
+
const inDqs = new Map();
|
|
99
|
+
const initLens = new Map();
|
|
100
|
+
for (let p = 0; p < inputNames.length; p++) {
|
|
101
|
+
const dq = new BitDeque(p);
|
|
102
|
+
dq.pushBits(inputBits[p], inputWidths[p]);
|
|
103
|
+
inDqs.set(inputNames[p], dq);
|
|
104
|
+
initLens.set(inputNames[p], inputWidths[p]);
|
|
105
|
+
}
|
|
106
|
+
const outDqs = new Map();
|
|
107
|
+
for (let o = 0; o < outputNames.length; o++) {
|
|
108
|
+
outDqs.set(outputNames[o], new BitDeque(100 + o));
|
|
109
|
+
}
|
|
110
|
+
const regs = new Map((kernel.regs || []).map((r) => [r.name, r.init ?? 0]));
|
|
111
|
+
if (regName) regs.set(regName, startQ);
|
|
112
|
+
|
|
113
|
+
// Track stack operations precisely using a symbolic stack suffix + explicit top bits!
|
|
114
|
+
// We track net pops from the initial stack (`baseDepth`) plus newly pushed bits (`pushed[]`)
|
|
115
|
+
// so we can reconstruct exact `(pop_stack, push_stack_word, push_stack_len)`!
|
|
116
|
+
const stacks = new Map((kernel.stacks || []).map((s) => [s.name, new BitStack()]));
|
|
117
|
+
let initStackRem = initStackDepth;
|
|
118
|
+
let totalPoppedFromInit = 0;
|
|
119
|
+
const pushedBits = []; // bottom-to-top bits pushed above remaining init stack
|
|
120
|
+
let stackCleared = false;
|
|
121
|
+
if (stackName && initStackDepth > 0) {
|
|
122
|
+
stacks.get(stackName).push(initStackBits, initStackDepth);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let curBlock = slowLabel;
|
|
126
|
+
let lastValid = null;
|
|
127
|
+
const temps = new Map();
|
|
128
|
+
|
|
129
|
+
for (let step = 0; step < maxSteps; step++) {
|
|
130
|
+
if (exitLabelToId.has(curBlock)) {
|
|
131
|
+
// `EXIT` table entries do not carry `next_q`: ONLY if this exit block actually
|
|
132
|
+
// reads `regName` (e.g. `switch_reg`) AND an earlier unrolled iteration modified
|
|
133
|
+
// `regName`, stop at `lastValid` (`CONT`) so the exit sees the updated register!
|
|
134
|
+
const exitBlk = blockMap.get(curBlock);
|
|
135
|
+
const exitReadsReg = Boolean(
|
|
136
|
+
regName && exitBlk && exitBlk.term?.op === "switch_reg" && exitBlk.term.reg === regName
|
|
137
|
+
);
|
|
138
|
+
if (exitReadsReg && regs.get(regName) !== startQ) {
|
|
139
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
140
|
+
}
|
|
141
|
+
return snapshot("EXIT", { exitId: exitLabelToId.get(curBlock) });
|
|
142
|
+
}
|
|
143
|
+
if (curBlock === failLabel) {
|
|
144
|
+
return snapshot("FAIL", {});
|
|
145
|
+
}
|
|
146
|
+
if (curBlock === loopHeader) {
|
|
147
|
+
lastValid = snapshot("CONT", {});
|
|
148
|
+
// For acyclic FSMs (`loopHeader === null`), stop immediately; for loops, keep unrolling!
|
|
149
|
+
if (!loopHeader) return lastValid;
|
|
150
|
+
curBlock = slowLabel;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const blk = blockMap.get(curBlock);
|
|
155
|
+
if (!blk) return lastValid || snapshot("NEED_MORE", {});
|
|
156
|
+
let jumped = false;
|
|
157
|
+
|
|
158
|
+
for (const s of blk.stmts) {
|
|
159
|
+
switch (s.op) {
|
|
160
|
+
case "peek_bits": {
|
|
161
|
+
const dq = inDqs.get(s.src);
|
|
162
|
+
if (!dq || s.offset + s.width > dq.length) {
|
|
163
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
164
|
+
}
|
|
165
|
+
temps.set(s.dst, dq.peekBitsAt(s.offset, s.width));
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
case "shift_bits":
|
|
169
|
+
case "shift_tag": {
|
|
170
|
+
const dq = inDqs.get(s.src);
|
|
171
|
+
if (!dq || s.width > dq.length) {
|
|
172
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
173
|
+
}
|
|
174
|
+
dq.shiftBits(s.width);
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
case "push_bits":
|
|
178
|
+
outDqs.get(s.dst).pushBits(parseInt(s.bits, 2), s.width);
|
|
179
|
+
break;
|
|
180
|
+
case "unshift_bits":
|
|
181
|
+
outDqs.get(s.dst).unshiftBits(parseInt(s.bits, 2), s.width);
|
|
182
|
+
break;
|
|
183
|
+
case "set_reg":
|
|
184
|
+
regs.set(s.reg, s.value);
|
|
185
|
+
break;
|
|
186
|
+
case "stack_push": {
|
|
187
|
+
const val = parseInt(s.bits, 2);
|
|
188
|
+
stacks.get(s.stack).push(val, s.width);
|
|
189
|
+
if (s.stack === stackName) {
|
|
190
|
+
for (let b = 0; b < s.width; b++) pushedBits.push((val >>> b) & 1);
|
|
191
|
+
}
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case "stack_pop": {
|
|
195
|
+
const st = stacks.get(s.stack);
|
|
196
|
+
if (st.length < s.width) {
|
|
197
|
+
// Note: if initial stack was truncated (`initStackDepth === W_k`), we don't know if
|
|
198
|
+
// real stack is truly empty or deeper! Return `lastValid` (or `NEED_MORE`)!
|
|
199
|
+
if (s.stack === stackName && stackWindowTruncated && totalPoppedFromInit >= initStackDepth) {
|
|
200
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
201
|
+
}
|
|
202
|
+
curBlock = s.onEmpty;
|
|
203
|
+
jumped = true;
|
|
204
|
+
} else {
|
|
205
|
+
const v = st.pop(s.width);
|
|
206
|
+
temps.set(s.dst, v);
|
|
207
|
+
if (s.stack === stackName) {
|
|
208
|
+
for (let b = 0; b < s.width; b++) {
|
|
209
|
+
if (pushedBits.length > 0) pushedBits.pop();
|
|
210
|
+
else {
|
|
211
|
+
initStackRem--;
|
|
212
|
+
totalPoppedFromInit++;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
case "stack_clear":
|
|
220
|
+
stacks.get(s.stack).clear();
|
|
221
|
+
if (s.stack === stackName) {
|
|
222
|
+
pushedBits.length = 0;
|
|
223
|
+
stackCleared = true;
|
|
224
|
+
}
|
|
225
|
+
break;
|
|
226
|
+
case "drain_guard":
|
|
227
|
+
case "yield":
|
|
228
|
+
break;
|
|
229
|
+
default:
|
|
230
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
231
|
+
}
|
|
232
|
+
if (jumped) break;
|
|
233
|
+
}
|
|
234
|
+
if (jumped) continue;
|
|
235
|
+
|
|
236
|
+
const t = blk.term;
|
|
237
|
+
if (t.op === "goto") {
|
|
238
|
+
curBlock = t.target;
|
|
239
|
+
} else if (t.op === "fail") {
|
|
240
|
+
return snapshot("FAIL", {});
|
|
241
|
+
} else if (t.op === "switch_bits") {
|
|
242
|
+
const val = temps.get(t.src);
|
|
243
|
+
let next = t.defaultTarget;
|
|
244
|
+
for (const c of t.cases) {
|
|
245
|
+
if (parseInt(c.bits, 2) === val) {
|
|
246
|
+
next = c.target;
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
curBlock = next || failLabel;
|
|
251
|
+
} else if (t.op === "switch_reg") {
|
|
252
|
+
const val = regs.get(t.reg);
|
|
253
|
+
const found = t.cases.find((c) => c.value === val);
|
|
254
|
+
curBlock = found ? found.target : failLabel;
|
|
255
|
+
} else {
|
|
256
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return lastValid || snapshot("NEED_MORE", {});
|
|
260
|
+
|
|
261
|
+
function snapshot(kind, extra) {
|
|
262
|
+
const shifts = inputNames.map((n) => initLens.get(n) - inDqs.get(n).length);
|
|
263
|
+
const emitLens = outputNames.map((n) => outDqs.get(n).length);
|
|
264
|
+
const emitWords = outputNames.map((n) => {
|
|
265
|
+
const dq = outDqs.get(n);
|
|
266
|
+
return dq.length > 0 ? dq.peekBits(dq.length) : 0;
|
|
267
|
+
});
|
|
268
|
+
let pushWord = 0;
|
|
269
|
+
for (let i = 0; i < pushedBits.length; i++) {
|
|
270
|
+
if (pushedBits[i]) pushWord |= (1 << i);
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
kind,
|
|
274
|
+
nextQ: regName ? regs.get(regName) : 0,
|
|
275
|
+
shifts,
|
|
276
|
+
emitWords,
|
|
277
|
+
emitLens,
|
|
278
|
+
popStack: totalPoppedFromInit,
|
|
279
|
+
pushStackWord: pushWord >>> 0,
|
|
280
|
+
pushStackLen: pushedBits.length,
|
|
281
|
+
stackCleared,
|
|
282
|
+
...extra
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Test if a per-token bitmask `unitMask` (strict subset of `(1 << w) - 1`) produces
|
|
289
|
+
* 100% identical CFG behavior across all VALID tag ordinals `0 .. tagCounts[p]-1`
|
|
290
|
+
* on port `portIdx` (invalid out-of-range ordinals like `0b11` on 3-tag `$bits` are
|
|
291
|
+
* handled soundly via conservative `NEED_MORE` fallback during compressed synthesis!).
|
|
292
|
+
*/
|
|
293
|
+
function findMinimalUnitMask({
|
|
294
|
+
kernel,
|
|
295
|
+
blockMap,
|
|
296
|
+
loopHeader,
|
|
297
|
+
slowLabel,
|
|
298
|
+
regName,
|
|
299
|
+
numStates,
|
|
300
|
+
inputNames,
|
|
301
|
+
portWidths,
|
|
302
|
+
tagCounts,
|
|
303
|
+
outputNames,
|
|
304
|
+
exitLabelToId,
|
|
305
|
+
portIdx
|
|
306
|
+
}) {
|
|
307
|
+
const w = portWidths[portIdx];
|
|
308
|
+
const fullMask = (1 << w) - 1;
|
|
309
|
+
if (w <= 1) return fullMask;
|
|
310
|
+
|
|
311
|
+
// Test on a 1-token or 2-token probe so multi-token-per-step kernels (e.g. `half_max_tally`
|
|
312
|
+
// which inspects 2 tokens per step!) also reveal exact don't-care bits!
|
|
313
|
+
const probeTokens = (numStates * portWidths.reduce((a, x) => a * (1 << (2 * x)), 1) <= 512) ? 2 : 1;
|
|
314
|
+
const probeWidths = portWidths.map((pw) => pw * probeTokens);
|
|
315
|
+
const validTokCounts = tagCounts.map((c, i) => Math.min(c, 1 << portWidths[i]));
|
|
316
|
+
|
|
317
|
+
// Build list of valid probe values per port (all combinations of valid tag ordinals!)
|
|
318
|
+
const validProbesPerPort = portWidths.map((pw, p) => {
|
|
319
|
+
const vals = [];
|
|
320
|
+
const nTags = validTokCounts[p];
|
|
321
|
+
if (probeTokens === 1) {
|
|
322
|
+
for (let t0 = 0; t0 < nTags; t0++) vals.push(t0);
|
|
323
|
+
} else {
|
|
324
|
+
for (let t0 = 0; t0 < nTags; t0++) {
|
|
325
|
+
for (let t1 = 0; t1 < nTags; t1++) {
|
|
326
|
+
vals.push((t0 << pw) | t1);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return vals;
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
const totalCombos = numStates * validProbesPerPort.reduce((a, vs) => a * vs.length, 1);
|
|
334
|
+
if (totalCombos > 1024) return fullMask;
|
|
335
|
+
|
|
336
|
+
const refBehavior = new Map();
|
|
337
|
+
const enumerate = (q, idx, acc) => {
|
|
338
|
+
if (idx === inputNames.length) {
|
|
339
|
+
const sim = simulateKernelReferenceCFG({
|
|
340
|
+
kernel,
|
|
341
|
+
blockMap,
|
|
342
|
+
loopHeader,
|
|
343
|
+
slowLabel,
|
|
344
|
+
regName,
|
|
345
|
+
startQ: q,
|
|
346
|
+
inputNames,
|
|
347
|
+
inputBits: acc,
|
|
348
|
+
inputWidths: probeWidths,
|
|
349
|
+
outputNames,
|
|
350
|
+
exitLabelToId
|
|
351
|
+
});
|
|
352
|
+
const sig = `${sim.kind}|${sim.nextQ}|${sim.exitId ?? ""}|${sim.shifts.join(",")}|${sim.emitWords.join(",")}|${sim.emitLens.join(",")}`;
|
|
353
|
+
refBehavior.set(`${q}:${acc.join(",")}`, sig);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
for (const v of validProbesPerPort[idx]) {
|
|
357
|
+
acc[idx] = v;
|
|
358
|
+
enumerate(q, idx + 1, acc);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
for (let q = 0; q < numStates; q++) enumerate(q, 0, new Array(inputNames.length));
|
|
362
|
+
|
|
363
|
+
let curMask = fullMask;
|
|
364
|
+
for (let b = 0; b < w; b++) {
|
|
365
|
+
const cand = curMask & ~(1 << b);
|
|
366
|
+
if (cand === 0) continue;
|
|
367
|
+
const probeCandMask = repeatUnitMask(cand, w, probeTokens);
|
|
368
|
+
let identical = true;
|
|
369
|
+
|
|
370
|
+
for (let q = 0; q < numStates && identical; q++) {
|
|
371
|
+
const groups = new Map();
|
|
372
|
+
for (const [k, sig] of refBehavior.entries()) {
|
|
373
|
+
if (!k.startsWith(`${q}:`)) continue;
|
|
374
|
+
const toks = k.slice(k.indexOf(":") + 1).split(",").map(Number);
|
|
375
|
+
toks[portIdx] = compressBitsWithMask(toks[portIdx], probeWidths[portIdx], probeCandMask);
|
|
376
|
+
const gk = toks.join(",");
|
|
377
|
+
if (!groups.has(gk)) groups.set(gk, sig);
|
|
378
|
+
else if (groups.get(gk) !== sig) {
|
|
379
|
+
identical = false;
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (identical) curMask = cand;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
return curMask;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Synthesize static bit-chunk, virtual-stack, and FSM transition tables for
|
|
392
|
+
* eligible kernels in a `mono` kTVM module under a global Howard MWTR byte budget.
|
|
393
|
+
*/
|
|
394
|
+
export function synthesizeTables(
|
|
395
|
+
mod,
|
|
396
|
+
{
|
|
397
|
+
budgetBytes = DEFAULT_L1_BUDGET_BYTES,
|
|
398
|
+
maxEntriesPerTable = 4096,
|
|
399
|
+
maxTagWidth = 4
|
|
400
|
+
} = {}
|
|
401
|
+
) {
|
|
402
|
+
if (mod.layer !== "mono") {
|
|
403
|
+
throw new Error("synthesizeTables requires a concrete 'mono' kTVM module");
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const outMod = cloneAst(mod);
|
|
407
|
+
const existingTableNames = new Set((outMod.tables || []).map((t) => t.name));
|
|
408
|
+
|
|
409
|
+
// Keep `_optMeta` references from the original `mod` (structuredClone preserves plain objects)
|
|
410
|
+
const frontiers = [];
|
|
411
|
+
const kernelReports = [];
|
|
412
|
+
|
|
413
|
+
for (const kernel of outMod.kernels || []) {
|
|
414
|
+
const meta = kernel._optMeta;
|
|
415
|
+
if (!meta) continue;
|
|
416
|
+
// Skip if kernel already dispatches a table
|
|
417
|
+
if (kernel.blocks.some((b) => ["table_step", "stack_table_step", "fsm_table_step"].includes(b.term.op))) {
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const blockMap = new Map(kernel.blocks.map((b) => [b.label, b]));
|
|
422
|
+
const streamPorts = meta.streamPortIndices;
|
|
423
|
+
const regPorts = meta.regPortIndices;
|
|
424
|
+
const stackPorts = meta.stackPortIndices;
|
|
425
|
+
|
|
426
|
+
// Skip kernels with > 1 register (compound state) or 0 / > 2 stream ports
|
|
427
|
+
if (regPorts.length > 1 || streamPorts.length === 0 || streamPorts.length > 2) continue;
|
|
428
|
+
|
|
429
|
+
// Check stream tag widths (graceful fallback on wide alphabets like `ascii[]`!)
|
|
430
|
+
const tagCounts = streamPorts.map((p) => {
|
|
431
|
+
const pl = meta.inLeaves[p].plist;
|
|
432
|
+
if (pl[0][0] !== "closed-union") return 999;
|
|
433
|
+
return pl[0][1].length;
|
|
434
|
+
});
|
|
435
|
+
const tagWidths = tagCounts.map((c) => (c > 256 ? 99 : choiceWidth(c)));
|
|
436
|
+
if (tagWidths.some((w) => w < 1 || w > maxTagWidth)) {
|
|
437
|
+
kernelReports.push({ kernel: kernel.name, status: "cfg_only_wide_alphabet", tagWidths });
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const exitLabelSet = new Set(meta.exitBlocks);
|
|
442
|
+
const exitLabelToId = new Map(meta.exitBlocks.map((lbl, idx) => [lbl, idx]));
|
|
443
|
+
const regDecl = regPorts.length === 1 ? kernel.regs[0] : null;
|
|
444
|
+
const numStates = regDecl ? regDecl.states : 1;
|
|
445
|
+
const regName = regDecl ? regDecl.name : null;
|
|
446
|
+
const inputNames = streamPorts.map((p) => kernel.inputs[p].name);
|
|
447
|
+
|
|
448
|
+
// Filter outputs to ONLY those actually emitted (`push_bits`/`unshift_bits`) inside
|
|
449
|
+
// non-exit loop blocks (so extracted loop-state kernels like `@lsb_add_loop_k` with
|
|
450
|
+
// 4 state ports where only `%o0_acc` is written in the loop get full `chunk_table`s!).
|
|
451
|
+
const loopWrittenOuts = new Set();
|
|
452
|
+
for (const blk of kernel.blocks) {
|
|
453
|
+
if (exitLabelSet.has(blk.label) || blk.label === "entry" || blk.label === "err") continue;
|
|
454
|
+
for (const s of blk.stmts) {
|
|
455
|
+
if (s.op === "push_bits" || s.op === "unshift_bits") loopWrittenOuts.add(s.dst);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const activeOutIndices = meta.isLoop && loopWrittenOuts.size > 0
|
|
459
|
+
? kernel.outputs.map((_, idx) => idx).filter((idx) => loopWrittenOuts.has(kernel.outputs[idx].name))
|
|
460
|
+
: kernel.outputs.map((_, idx) => idx);
|
|
461
|
+
|
|
462
|
+
if (activeOutIndices.length === 0 || activeOutIndices.length > 2) continue;
|
|
463
|
+
|
|
464
|
+
const outputNames = activeOutIndices.map((idx) => kernel.outputs[idx].name);
|
|
465
|
+
const outputModes = activeOutIndices.map((idx) => (meta.outputModes && meta.outputModes[idx]) || "push");
|
|
466
|
+
|
|
467
|
+
// --- Case 1: Streaming Loop Kernel -> `chunk_table` (with SWAR compression!) ---
|
|
468
|
+
if (meta.isLoop && stackPorts.length === 0) {
|
|
469
|
+
// Discover minimal per-token SWAR compression masks!
|
|
470
|
+
const unitMasks = streamPorts.map((_, idx) =>
|
|
471
|
+
findMinimalUnitMask({
|
|
472
|
+
kernel,
|
|
473
|
+
blockMap,
|
|
474
|
+
loopHeader: meta.loopHeaderLabel,
|
|
475
|
+
slowLabel: meta.slowStepLabel,
|
|
476
|
+
regName,
|
|
477
|
+
numStates,
|
|
478
|
+
inputNames,
|
|
479
|
+
portWidths: tagWidths,
|
|
480
|
+
tagCounts,
|
|
481
|
+
outputNames,
|
|
482
|
+
exitLabelToId,
|
|
483
|
+
portIdx: idx
|
|
484
|
+
})
|
|
485
|
+
);
|
|
486
|
+
const effPerTok = unitMasks.map(popcount);
|
|
487
|
+
|
|
488
|
+
// Generate candidate token counts (k0, [k1])
|
|
489
|
+
const tokenConfigs = [];
|
|
490
|
+
if (streamPorts.length === 1) {
|
|
491
|
+
for (let k0 = 1; k0 <= 4; k0++) {
|
|
492
|
+
const eff = k0 * effPerTok[0];
|
|
493
|
+
const entries = numStates * (1 << eff);
|
|
494
|
+
if (entries <= maxEntriesPerTable && k0 * tagWidths[0] <= 16) {
|
|
495
|
+
tokenConfigs.push([k0]);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
} else {
|
|
499
|
+
for (let k = 1; k <= 3; k++) {
|
|
500
|
+
const eff0 = k * effPerTok[0];
|
|
501
|
+
const eff1 = k * effPerTok[1];
|
|
502
|
+
const entries = numStates * (1 << (eff0 + eff1));
|
|
503
|
+
if (entries <= maxEntriesPerTable && k * tagWidths[0] <= 12 && k * tagWidths[1] <= 12) {
|
|
504
|
+
tokenConfigs.push([k, k]);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const candidates = [];
|
|
510
|
+
for (const cfg of tokenConfigs) {
|
|
511
|
+
const cand = buildChunkTableCandidate({
|
|
512
|
+
kernel,
|
|
513
|
+
meta,
|
|
514
|
+
blockMap,
|
|
515
|
+
regName,
|
|
516
|
+
numStates,
|
|
517
|
+
inputNames,
|
|
518
|
+
outputNames,
|
|
519
|
+
outputModes,
|
|
520
|
+
tagWidths,
|
|
521
|
+
unitMasks,
|
|
522
|
+
effPerTok,
|
|
523
|
+
tokenCounts: cfg,
|
|
524
|
+
exitLabelToId
|
|
525
|
+
});
|
|
526
|
+
if (cand && cand.rho > 0 && Number.isFinite(cand.rho)) {
|
|
527
|
+
candidates.push(cand);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
if (candidates.length > 0) {
|
|
532
|
+
frontiers.push({ kernelName: kernel.name, candidates });
|
|
533
|
+
}
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// --- Case 2: Virtual-Stack Kernel -> `stack_table` ---
|
|
538
|
+
if (meta.isLoop && stackPorts.length === 1 && streamPorts.length === 1) {
|
|
539
|
+
const stackName = kernel.stacks[0].name;
|
|
540
|
+
const candidates = [];
|
|
541
|
+
for (let kStream = 1; kStream <= 2; kStream++) {
|
|
542
|
+
const wStream = kStream * tagWidths[0];
|
|
543
|
+
if (wStream > 6) continue;
|
|
544
|
+
for (let wStack = 1; wStack <= 3; wStack++) {
|
|
545
|
+
const stackStride = (1 << (wStack + 1)) - 1;
|
|
546
|
+
if (numStates * (1 << wStream) * stackStride > maxEntriesPerTable) continue;
|
|
547
|
+
const cand = buildStackTableCandidate({
|
|
548
|
+
kernel,
|
|
549
|
+
meta,
|
|
550
|
+
blockMap,
|
|
551
|
+
regName,
|
|
552
|
+
numStates,
|
|
553
|
+
inputName: inputNames[0],
|
|
554
|
+
outputName: outputNames[0],
|
|
555
|
+
stackName,
|
|
556
|
+
wStream,
|
|
557
|
+
wStack,
|
|
558
|
+
exitLabelToId
|
|
559
|
+
});
|
|
560
|
+
if (cand && cand.rho > 0 && Number.isFinite(cand.rho)) {
|
|
561
|
+
candidates.push(cand);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (candidates.length > 0) {
|
|
566
|
+
frontiers.push({ kernelName: kernel.name, candidates });
|
|
567
|
+
}
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// --- Case 3: Acyclic Multi-Step 1-Stream Kernel -> `fsm_table` ---
|
|
572
|
+
if (!meta.isLoop && streamPorts.length === 1 && stackPorts.length === 0 && regPorts.length === 0) {
|
|
573
|
+
const wRaw = tagWidths[0];
|
|
574
|
+
if ((1 << wRaw) <= 64) {
|
|
575
|
+
const cand = buildFsmTableCandidate({
|
|
576
|
+
kernel,
|
|
577
|
+
meta,
|
|
578
|
+
blockMap,
|
|
579
|
+
inputName: inputNames[0],
|
|
580
|
+
outputNames,
|
|
581
|
+
wRaw,
|
|
582
|
+
exitLabelToId
|
|
583
|
+
});
|
|
584
|
+
if (cand) {
|
|
585
|
+
frontiers.push({ kernelName: kernel.name, candidates: [cand] });
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// Run global Howard MWTR L1 budget allocation across ALL kernels!
|
|
592
|
+
const allocation = allocateTableBudgets(frontiers, { budgetBytes });
|
|
593
|
+
let tablesSynthesized = 0;
|
|
594
|
+
|
|
595
|
+
for (const kernel of outMod.kernels || []) {
|
|
596
|
+
const picked = allocation.chosen.get(kernel.name);
|
|
597
|
+
if (!picked) continue;
|
|
598
|
+
|
|
599
|
+
let tName = `&tab_${sanitize(kernel.name)}`;
|
|
600
|
+
let tSeq = 0;
|
|
601
|
+
while (existingTableNames.has(tName)) tName = `&tab_${sanitize(kernel.name)}_${tSeq++}`;
|
|
602
|
+
existingTableNames.add(tName);
|
|
603
|
+
|
|
604
|
+
const meta = kernel._optMeta;
|
|
605
|
+
const exits = { short: meta.slowStepLabel, fail: "err" };
|
|
606
|
+
meta.exitBlocks.forEach((lbl, idx) => { exits[String(idx)] = lbl; });
|
|
607
|
+
|
|
608
|
+
// Ensure kernel has a register if `table_step` needs one (dummy 1-state reg if stateless)
|
|
609
|
+
let regName = picked.regName;
|
|
610
|
+
if ((picked.kind === "chunk_table" || picked.kind === "stack_table") && !regName) {
|
|
611
|
+
regName = "q0";
|
|
612
|
+
kernel.regs = [...(kernel.regs || []), { name: regName, states: 1, init: 0 }];
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Wire `table_step` / `stack_table_step` / `fsm_table_step` into loop header block!
|
|
616
|
+
const hdrBlk = kernel.blocks.find((b) => b.label === meta.loopHeaderLabel);
|
|
617
|
+
if (!hdrBlk) continue;
|
|
618
|
+
|
|
619
|
+
if (picked.kind === "chunk_table") {
|
|
620
|
+
hdrBlk.term = {
|
|
621
|
+
op: "table_step",
|
|
622
|
+
table: tName,
|
|
623
|
+
reg: regName,
|
|
624
|
+
inputs: picked.inputNames,
|
|
625
|
+
outputs: picked.outputNames,
|
|
626
|
+
exits
|
|
627
|
+
};
|
|
628
|
+
} else if (picked.kind === "stack_table") {
|
|
629
|
+
hdrBlk.term = {
|
|
630
|
+
op: "stack_table_step",
|
|
631
|
+
table: tName,
|
|
632
|
+
reg: regName,
|
|
633
|
+
input: picked.inputName,
|
|
634
|
+
stack: picked.stackName,
|
|
635
|
+
output: picked.outputName,
|
|
636
|
+
exits
|
|
637
|
+
};
|
|
638
|
+
} else if (picked.kind === "fsm_table") {
|
|
639
|
+
hdrBlk.term = {
|
|
640
|
+
op: "fsm_table_step",
|
|
641
|
+
table: tName,
|
|
642
|
+
input: picked.inputName,
|
|
643
|
+
outputs: picked.outputNames,
|
|
644
|
+
exits
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
outMod.tables.push({
|
|
649
|
+
name: tName,
|
|
650
|
+
kind: picked.kind,
|
|
651
|
+
props: {
|
|
652
|
+
...picked.props,
|
|
653
|
+
verified_against: { proc: kernel.name },
|
|
654
|
+
mwtr: {
|
|
655
|
+
rho: Number(picked.rho.toFixed(4)),
|
|
656
|
+
bytes: picked.bytes,
|
|
657
|
+
budget_class: budgetClassForBytes(picked.bytes)
|
|
658
|
+
}
|
|
659
|
+
},
|
|
660
|
+
entries: picked.entries,
|
|
661
|
+
packedBase64: null
|
|
662
|
+
});
|
|
663
|
+
|
|
664
|
+
tablesSynthesized += 1;
|
|
665
|
+
kernelReports.push({
|
|
666
|
+
kernel: kernel.name,
|
|
667
|
+
table: tName,
|
|
668
|
+
kind: picked.kind,
|
|
669
|
+
entries: picked.entries.length,
|
|
670
|
+
bytes: picked.bytes,
|
|
671
|
+
rho: Number(picked.rho.toFixed(4)),
|
|
672
|
+
compressed: Boolean(picked.compressed)
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Strip internal `_optMeta` before returning clean canonical AST
|
|
677
|
+
for (const k of outMod.kernels || []) delete k._optMeta;
|
|
678
|
+
|
|
679
|
+
return {
|
|
680
|
+
module: outMod,
|
|
681
|
+
stats: {
|
|
682
|
+
tablesSynthesized,
|
|
683
|
+
totalTableBytes: allocation.usedBytes,
|
|
684
|
+
budgetBytes,
|
|
685
|
+
kernelReports
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function buildChunkTableCandidate({
|
|
691
|
+
kernel,
|
|
692
|
+
meta,
|
|
693
|
+
blockMap,
|
|
694
|
+
regName,
|
|
695
|
+
numStates,
|
|
696
|
+
inputNames,
|
|
697
|
+
outputNames,
|
|
698
|
+
outputModes,
|
|
699
|
+
tagWidths,
|
|
700
|
+
unitMasks,
|
|
701
|
+
effPerTok,
|
|
702
|
+
tokenCounts,
|
|
703
|
+
exitLabelToId
|
|
704
|
+
}) {
|
|
705
|
+
const rawBits = tokenCounts.map((k, i) => k * tagWidths[i]);
|
|
706
|
+
const effBits = tokenCounts.map((k, i) => k * effPerTok[i]);
|
|
707
|
+
const fullMasks = tokenCounts.map((k, i) => repeatUnitMask(unitMasks[i], tagWidths[i], k));
|
|
708
|
+
const isCompressed = tokenCounts.map((k, i) => effBits[i] < rawBits[i]);
|
|
709
|
+
const totalEff = effBits.reduce((a, b) => a + b, 0);
|
|
710
|
+
const numEntries = numStates * (1 << totalEff);
|
|
711
|
+
|
|
712
|
+
const entries = [];
|
|
713
|
+
const mwtrEdges = [];
|
|
714
|
+
let maxEmitBits = 0;
|
|
715
|
+
let contCount = 0;
|
|
716
|
+
|
|
717
|
+
if (!isCompressed.some(Boolean)) {
|
|
718
|
+
for (let idx = 0; idx < numEntries; idx++) {
|
|
719
|
+
let rem = idx;
|
|
720
|
+
const rawVals = new Array(inputNames.length);
|
|
721
|
+
for (let p = inputNames.length - 1; p >= 0; p--) {
|
|
722
|
+
rawVals[p] = rem & ((1 << rawBits[p]) - 1);
|
|
723
|
+
rem >>>= rawBits[p];
|
|
724
|
+
}
|
|
725
|
+
const startQ = rem;
|
|
726
|
+
|
|
727
|
+
const sim = simulateKernelReferenceCFG({
|
|
728
|
+
kernel,
|
|
729
|
+
blockMap,
|
|
730
|
+
loopHeader: meta.loopHeaderLabel,
|
|
731
|
+
slowLabel: meta.slowStepLabel,
|
|
732
|
+
regName,
|
|
733
|
+
startQ,
|
|
734
|
+
inputNames,
|
|
735
|
+
inputBits: rawVals,
|
|
736
|
+
inputWidths: rawBits,
|
|
737
|
+
outputNames,
|
|
738
|
+
exitLabelToId
|
|
739
|
+
});
|
|
740
|
+
|
|
741
|
+
if (sim.kind === "CONT") {
|
|
742
|
+
contCount++;
|
|
743
|
+
const totalShifted = sim.shifts.reduce((a, b) => a + b, 0);
|
|
744
|
+
if (totalShifted === 0) return null;
|
|
745
|
+
for (const el of sim.emitLens) if (el > maxEmitBits) maxEmitBits = el;
|
|
746
|
+
mwtrEdges.push({ from: startQ, to: sim.nextQ, w: totalShifted, t: 1 });
|
|
747
|
+
entries.push({
|
|
748
|
+
index: idx,
|
|
749
|
+
value: {
|
|
750
|
+
kind: { ident: "CONT" },
|
|
751
|
+
next_q: sim.nextQ,
|
|
752
|
+
shift: sim.shifts,
|
|
753
|
+
emit_word: sim.emitWords,
|
|
754
|
+
emit_len: sim.emitLens
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
} else if (sim.kind === "EXIT") {
|
|
758
|
+
for (const el of sim.emitLens) if (el > maxEmitBits) maxEmitBits = el;
|
|
759
|
+
entries.push({
|
|
760
|
+
index: idx,
|
|
761
|
+
value: {
|
|
762
|
+
kind: { ident: "EXIT" },
|
|
763
|
+
exit: sim.exitId,
|
|
764
|
+
shift: sim.shifts,
|
|
765
|
+
emit_word: sim.emitWords,
|
|
766
|
+
emit_len: sim.emitLens
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
} else if (sim.kind === "NEED_MORE") {
|
|
770
|
+
entries.push({ index: idx, value: { kind: { ident: "NEED_MORE" } } });
|
|
771
|
+
} else {
|
|
772
|
+
entries.push({ index: idx, value: { kind: { ident: "FAIL" } } });
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
} else {
|
|
776
|
+
// Compressed table synthesis: exhaustively group ALL raw windows by compressed key!
|
|
777
|
+
// Any compressed key where ALL raw windows agree gets the exact CONT/EXIT/FAIL entry;
|
|
778
|
+
// any key where raw windows disagree (e.g. valid `_` vs invalid `0b11` on 3-tag `$bits`)
|
|
779
|
+
// soundly stores `NEED_MORE`, punting the boundary/error case directly to `slow_step`!
|
|
780
|
+
const rawSpace = numStates * rawBits.reduce((a, w) => a * (1 << w), 1);
|
|
781
|
+
if (rawSpace > 16384) return null;
|
|
782
|
+
|
|
783
|
+
const bucketSim = new Array(numEntries).fill(null);
|
|
784
|
+
const bucketConflict = new Uint8Array(numEntries);
|
|
785
|
+
|
|
786
|
+
const sameOutcome = (a, b) => {
|
|
787
|
+
if (a.kind !== b.kind) return false;
|
|
788
|
+
if (a.kind === "CONT") {
|
|
789
|
+
if (a.nextQ !== b.nextQ) return false;
|
|
790
|
+
if (a.shifts.some((v, i) => v !== b.shifts[i])) return false;
|
|
791
|
+
if (a.emitLens.some((v, i) => v !== b.emitLens[i])) return false;
|
|
792
|
+
if (a.emitWords.some((v, i) => v !== b.emitWords[i])) return false;
|
|
793
|
+
} else if (a.kind === "EXIT") {
|
|
794
|
+
if (a.exitId !== b.exitId) return false;
|
|
795
|
+
if (a.shifts.some((v, i) => v !== b.shifts[i])) return false;
|
|
796
|
+
if (a.emitLens.some((v, i) => v !== b.emitLens[i])) return false;
|
|
797
|
+
if (a.emitWords.some((v, i) => v !== b.emitWords[i])) return false;
|
|
798
|
+
}
|
|
799
|
+
return true;
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
const walkRaw = (q, p, rawAcc) => {
|
|
803
|
+
if (p === inputNames.length) {
|
|
804
|
+
let cIdx = q;
|
|
805
|
+
for (let i = 0; i < inputNames.length; i++) {
|
|
806
|
+
const eff = isCompressed[i]
|
|
807
|
+
? compressBitsWithMask(rawAcc[i], rawBits[i], fullMasks[i])
|
|
808
|
+
: rawAcc[i];
|
|
809
|
+
cIdx = (cIdx << effBits[i]) | eff;
|
|
810
|
+
}
|
|
811
|
+
if (bucketConflict[cIdx]) return;
|
|
812
|
+
const sim = simulateKernelReferenceCFG({
|
|
813
|
+
kernel,
|
|
814
|
+
blockMap,
|
|
815
|
+
loopHeader: meta.loopHeaderLabel,
|
|
816
|
+
slowLabel: meta.slowStepLabel,
|
|
817
|
+
regName,
|
|
818
|
+
startQ: q,
|
|
819
|
+
inputNames,
|
|
820
|
+
inputBits: rawAcc,
|
|
821
|
+
inputWidths: rawBits,
|
|
822
|
+
outputNames,
|
|
823
|
+
exitLabelToId
|
|
824
|
+
});
|
|
825
|
+
if (bucketSim[cIdx] === null) {
|
|
826
|
+
bucketSim[cIdx] = sim;
|
|
827
|
+
} else if (!sameOutcome(bucketSim[cIdx], sim)) {
|
|
828
|
+
bucketConflict[cIdx] = 1;
|
|
829
|
+
}
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
for (let r = 0; r < (1 << rawBits[p]); r++) {
|
|
833
|
+
rawAcc[p] = r;
|
|
834
|
+
walkRaw(q, p + 1, rawAcc);
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
for (let q = 0; q < numStates; q++) walkRaw(q, 0, new Array(inputNames.length));
|
|
838
|
+
|
|
839
|
+
for (let idx = 0; idx < numEntries; idx++) {
|
|
840
|
+
const startQ = idx >>> totalEff;
|
|
841
|
+
const sim = bucketConflict[idx] ? { kind: "NEED_MORE" } : bucketSim[idx];
|
|
842
|
+
if (!sim || sim.kind === "NEED_MORE") {
|
|
843
|
+
entries.push({ index: idx, value: { kind: { ident: "NEED_MORE" } } });
|
|
844
|
+
} else if (sim.kind === "CONT") {
|
|
845
|
+
contCount++;
|
|
846
|
+
const totalShifted = sim.shifts.reduce((a, b) => a + b, 0);
|
|
847
|
+
if (totalShifted === 0) return null;
|
|
848
|
+
for (const el of sim.emitLens) if (el > maxEmitBits) maxEmitBits = el;
|
|
849
|
+
mwtrEdges.push({ from: startQ, to: sim.nextQ, w: totalShifted, t: 1 });
|
|
850
|
+
entries.push({
|
|
851
|
+
index: idx,
|
|
852
|
+
value: {
|
|
853
|
+
kind: { ident: "CONT" },
|
|
854
|
+
next_q: sim.nextQ,
|
|
855
|
+
shift: sim.shifts,
|
|
856
|
+
emit_word: sim.emitWords,
|
|
857
|
+
emit_len: sim.emitLens
|
|
858
|
+
}
|
|
859
|
+
});
|
|
860
|
+
} else if (sim.kind === "EXIT") {
|
|
861
|
+
for (const el of sim.emitLens) if (el > maxEmitBits) maxEmitBits = el;
|
|
862
|
+
entries.push({
|
|
863
|
+
index: idx,
|
|
864
|
+
value: {
|
|
865
|
+
kind: { ident: "EXIT" },
|
|
866
|
+
exit: sim.exitId,
|
|
867
|
+
shift: sim.shifts,
|
|
868
|
+
emit_word: sim.emitWords,
|
|
869
|
+
emit_len: sim.emitLens
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
} else {
|
|
873
|
+
entries.push({ index: idx, value: { kind: { ident: "FAIL" } } });
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (contCount === 0 || maxEmitBits > 30) return null;
|
|
879
|
+
|
|
880
|
+
const mwtr = computeMWTR(numStates, mwtrEdges);
|
|
881
|
+
const bytesPerEntry = 4 + 4 * outputNames.length; // compact native entry size
|
|
882
|
+
const bytes = numEntries * bytesPerEntry;
|
|
883
|
+
|
|
884
|
+
return {
|
|
885
|
+
kind: "chunk_table",
|
|
886
|
+
regName,
|
|
887
|
+
inputNames,
|
|
888
|
+
outputNames,
|
|
889
|
+
entries,
|
|
890
|
+
bytes,
|
|
891
|
+
rho: mwtr.rho,
|
|
892
|
+
compressed: isCompressed.some(Boolean),
|
|
893
|
+
props: {
|
|
894
|
+
states: numStates,
|
|
895
|
+
inputs: inputNames.map((_, p) => ({
|
|
896
|
+
port: p,
|
|
897
|
+
raw_bits: rawBits[p],
|
|
898
|
+
eff_bits: effBits[p],
|
|
899
|
+
compress: isCompressed[p] ? { mask: fullMasks[p] } : { ident: "none" }
|
|
900
|
+
})),
|
|
901
|
+
outputs: outputNames.map((_, o) => ({
|
|
902
|
+
port: o,
|
|
903
|
+
mode: { ident: (outputModes && outputModes[o]) || "push" },
|
|
904
|
+
max_emit_bits: maxEmitBits
|
|
905
|
+
}))
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function buildStackTableCandidate({
|
|
911
|
+
kernel,
|
|
912
|
+
meta,
|
|
913
|
+
blockMap,
|
|
914
|
+
regName,
|
|
915
|
+
numStates,
|
|
916
|
+
inputName,
|
|
917
|
+
outputName,
|
|
918
|
+
stackName,
|
|
919
|
+
wStream,
|
|
920
|
+
wStack,
|
|
921
|
+
exitLabelToId
|
|
922
|
+
}) {
|
|
923
|
+
const stackStride = (1 << (wStack + 1)) - 1; // bijective depth+bits encoding
|
|
924
|
+
const numEntries = numStates * (1 << wStream) * stackStride;
|
|
925
|
+
if (numEntries > 4096) return null;
|
|
926
|
+
|
|
927
|
+
const entries = [];
|
|
928
|
+
const mwtrEdges = [];
|
|
929
|
+
let maxEmitBits = 0;
|
|
930
|
+
let contCount = 0;
|
|
931
|
+
|
|
932
|
+
for (let q = 0; q < numStates; q++) {
|
|
933
|
+
for (let sBits = 0; sBits < (1 << wStream); sBits++) {
|
|
934
|
+
for (let stCode = 0; stCode < stackStride; stCode++) {
|
|
935
|
+
// Decode bijective stack code -> (depth, topBits)
|
|
936
|
+
let depth = 0;
|
|
937
|
+
let topBits = 0;
|
|
938
|
+
if (stCode > 0) {
|
|
939
|
+
let rem = stCode;
|
|
940
|
+
for (let d = 1; d <= wStack; d++) {
|
|
941
|
+
const count = 1 << d;
|
|
942
|
+
if (rem <= count) {
|
|
943
|
+
depth = d;
|
|
944
|
+
topBits = rem - 1;
|
|
945
|
+
break;
|
|
946
|
+
}
|
|
947
|
+
rem -= count;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
const idx = (((q << wStream) | sBits) * stackStride) + stCode;
|
|
951
|
+
|
|
952
|
+
const sim = simulateKernelReferenceCFG({
|
|
953
|
+
kernel,
|
|
954
|
+
blockMap,
|
|
955
|
+
loopHeader: meta.loopHeaderLabel,
|
|
956
|
+
slowLabel: meta.slowStepLabel,
|
|
957
|
+
regName,
|
|
958
|
+
startQ: q,
|
|
959
|
+
inputNames: [inputName],
|
|
960
|
+
inputBits: [sBits],
|
|
961
|
+
inputWidths: [wStream],
|
|
962
|
+
outputNames: [outputName],
|
|
963
|
+
stackName,
|
|
964
|
+
initStackBits: topBits,
|
|
965
|
+
initStackDepth: depth,
|
|
966
|
+
stackWindowTruncated: wStack > 0 && depth === wStack,
|
|
967
|
+
exitLabelToId
|
|
968
|
+
});
|
|
969
|
+
|
|
970
|
+
if (sim.stackCleared && sim.kind === "CONT") return null;
|
|
971
|
+
|
|
972
|
+
if (sim.kind === "CONT") {
|
|
973
|
+
contCount++;
|
|
974
|
+
const sh = sim.shifts[0];
|
|
975
|
+
const progress = sh + sim.popStack;
|
|
976
|
+
if (progress === 0) return null;
|
|
977
|
+
if (sim.emitLens[0] > maxEmitBits) maxEmitBits = sim.emitLens[0];
|
|
978
|
+
// Amortized cycle weight: input bits shifted + popped bits (2b emitted per popped stack bit)
|
|
979
|
+
mwtrEdges.push({ from: q, to: sim.nextQ, w: sh + sim.popStack * 2, t: 1 });
|
|
980
|
+
entries.push({
|
|
981
|
+
index: idx,
|
|
982
|
+
value: {
|
|
983
|
+
kind: { ident: "CONT" },
|
|
984
|
+
next_q: sim.nextQ,
|
|
985
|
+
shift_stream: sh,
|
|
986
|
+
pop_stack: sim.popStack,
|
|
987
|
+
push_stack_word: sim.pushStackWord,
|
|
988
|
+
push_stack_len: sim.pushStackLen,
|
|
989
|
+
emit_word: sim.emitWords[0],
|
|
990
|
+
emit_len: sim.emitLens[0]
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
} else if (sim.kind === "EXIT") {
|
|
994
|
+
if (sim.emitLens[0] > maxEmitBits) maxEmitBits = sim.emitLens[0];
|
|
995
|
+
entries.push({
|
|
996
|
+
index: idx,
|
|
997
|
+
value: {
|
|
998
|
+
kind: { ident: "EXIT" },
|
|
999
|
+
exit: sim.exitId,
|
|
1000
|
+
shift_stream: sim.shifts[0],
|
|
1001
|
+
pop_stack: sim.popStack,
|
|
1002
|
+
push_stack_word: sim.pushStackWord,
|
|
1003
|
+
push_stack_len: sim.pushStackLen,
|
|
1004
|
+
emit_word: sim.emitWords[0],
|
|
1005
|
+
emit_len: sim.emitLens[0]
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
} else if (sim.kind === "NEED_MORE") {
|
|
1009
|
+
entries.push({ index: idx, value: { kind: { ident: "NEED_MORE" } } });
|
|
1010
|
+
} else {
|
|
1011
|
+
entries.push({ index: idx, value: { kind: { ident: "FAIL" } } });
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
if (contCount === 0 || maxEmitBits > 30) return null;
|
|
1018
|
+
const mwtr = computeMWTR(numStates, mwtrEdges);
|
|
1019
|
+
const bytes = numEntries * 8;
|
|
1020
|
+
|
|
1021
|
+
return {
|
|
1022
|
+
kind: "stack_table",
|
|
1023
|
+
regName,
|
|
1024
|
+
inputName,
|
|
1025
|
+
outputName,
|
|
1026
|
+
stackName,
|
|
1027
|
+
entries,
|
|
1028
|
+
bytes,
|
|
1029
|
+
rho: mwtr.rho,
|
|
1030
|
+
compressed: false,
|
|
1031
|
+
props: {
|
|
1032
|
+
states: numStates,
|
|
1033
|
+
stream_bits: wStream,
|
|
1034
|
+
stack_bits: wStack,
|
|
1035
|
+
stack_encoding: { ident: "bits" },
|
|
1036
|
+
output_mode: { ident: "push" }
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
function buildFsmTableCandidate({
|
|
1042
|
+
kernel,
|
|
1043
|
+
meta,
|
|
1044
|
+
blockMap,
|
|
1045
|
+
inputName,
|
|
1046
|
+
outputNames,
|
|
1047
|
+
wRaw,
|
|
1048
|
+
exitLabelToId
|
|
1049
|
+
}) {
|
|
1050
|
+
const numEntries = 1 << wRaw;
|
|
1051
|
+
const entries = [];
|
|
1052
|
+
let maxEmitBits = 0;
|
|
1053
|
+
let exitCount = 0;
|
|
1054
|
+
|
|
1055
|
+
for (let idx = 0; idx < numEntries; idx++) {
|
|
1056
|
+
const sim = simulateKernelReferenceCFG({
|
|
1057
|
+
kernel,
|
|
1058
|
+
blockMap,
|
|
1059
|
+
loopHeader: null,
|
|
1060
|
+
slowLabel: meta.slowStepLabel,
|
|
1061
|
+
regName: null,
|
|
1062
|
+
startQ: 0,
|
|
1063
|
+
inputNames: [inputName],
|
|
1064
|
+
inputBits: [idx],
|
|
1065
|
+
inputWidths: [wRaw],
|
|
1066
|
+
outputNames,
|
|
1067
|
+
exitLabelToId
|
|
1068
|
+
});
|
|
1069
|
+
if (sim.kind === "EXIT") {
|
|
1070
|
+
exitCount++;
|
|
1071
|
+
for (const el of sim.emitLens) if (el > maxEmitBits) maxEmitBits = el;
|
|
1072
|
+
entries.push({
|
|
1073
|
+
index: idx,
|
|
1074
|
+
value: {
|
|
1075
|
+
kind: { ident: "EXIT" },
|
|
1076
|
+
exit: sim.exitId,
|
|
1077
|
+
shift: sim.shifts,
|
|
1078
|
+
emit_word: sim.emitWords,
|
|
1079
|
+
emit_len: sim.emitLens
|
|
1080
|
+
}
|
|
1081
|
+
});
|
|
1082
|
+
} else if (sim.kind === "NEED_MORE") {
|
|
1083
|
+
entries.push({ index: idx, value: { kind: { ident: "NEED_MORE" } } });
|
|
1084
|
+
} else {
|
|
1085
|
+
entries.push({ index: idx, value: { kind: { ident: "FAIL" } } });
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
if (exitCount === 0 || maxEmitBits > 30) return null;
|
|
1090
|
+
const bytes = numEntries * (4 + 4 * outputNames.length);
|
|
1091
|
+
return {
|
|
1092
|
+
kind: "fsm_table",
|
|
1093
|
+
regName: null,
|
|
1094
|
+
inputName,
|
|
1095
|
+
outputNames,
|
|
1096
|
+
entries,
|
|
1097
|
+
bytes,
|
|
1098
|
+
rho: wRaw,
|
|
1099
|
+
compressed: false,
|
|
1100
|
+
props: {
|
|
1101
|
+
input_bits: wRaw,
|
|
1102
|
+
output_modes: outputNames.map(() => ({ ident: "push" }))
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
}
|