wuica-cli 0.0.0-stage → 0.1.9

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.
Files changed (48) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +546 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.bin.br +0 -0
  6. package/dist/data/arch/BDW.bin.br +0 -0
  7. package/dist/data/arch/CFL.bin.br +0 -0
  8. package/dist/data/arch/CLX.bin.br +0 -0
  9. package/dist/data/arch/HSW.bin.br +0 -0
  10. package/dist/data/arch/ICL.bin.br +0 -0
  11. package/dist/data/arch/ICX.bin.br +0 -0
  12. package/dist/data/arch/IVB.bin.br +0 -0
  13. package/dist/data/arch/KBL.bin.br +0 -0
  14. package/dist/data/arch/RKL.bin.br +0 -0
  15. package/dist/data/arch/SKL.bin.br +0 -0
  16. package/dist/data/arch/SKX.bin.br +0 -0
  17. package/dist/data/arch/SNB.bin.br +0 -0
  18. package/dist/data/arch/TGL.bin.br +0 -0
  19. package/dist/data/arch/ZEN3.bin.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +160 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +410 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +693 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/examples.js +26 -0
  30. package/lib/files.js +40 -0
  31. package/lib/index.js +577 -0
  32. package/lib/insights.js +100 -0
  33. package/lib/mcp.js +366 -0
  34. package/lib/objfile.js +216 -0
  35. package/lib/thread-worker.js +49 -0
  36. package/lib/threads.js +235 -0
  37. package/lib/wasm.js +246 -0
  38. package/lib/web/accum.js +202 -0
  39. package/lib/web/asm-regions.js +415 -0
  40. package/lib/web/assembler.js +188 -0
  41. package/lib/web/caveats.js +214 -0
  42. package/lib/web/examples.js +99 -0
  43. package/lib/web/loop-find.js +492 -0
  44. package/lib/web/showcase.js +368 -0
  45. package/lib/whatif.js +136 -0
  46. package/licenses/LICENSE-LLVM.txt +279 -0
  47. package/licenses/LICENSE-XED.txt +178 -0
  48. package/package.json +58 -4
package/lib/wasm.js ADDED
@@ -0,0 +1,246 @@
1
+ // Thin synchronous wrappers around the two WebAssembly modules:
2
+ // Analyzer wuica_wasm.wasm (docs/WASM-API.md in the wuica repository)
3
+ // Assembler wuica_asm.wasm (assembler/README.md)
4
+ // Neither module has imports. A trap (any exception thrown out of a call into a module) leaves the instance unusable:
5
+ // it is dropped, and the next call instantiates the compiled module again (the analyzer also reloads its tables).
6
+ // Nothing in here writes to stdout (the MCP server speaks JSON-RPC on stdout).
7
+
8
+ const enc = new TextEncoder();
9
+ const dec = new TextDecoder();
10
+
11
+ export class Analyzer {
12
+ #module;
13
+ #x = null;
14
+ #uarch = null; // bytes of uarch.json, kept to reload after a trap
15
+ #tables = new Map(); // table name -> its bytes, or a function that reads them again (for a reload after a trap)
16
+ #binary = false; // the module reads binary tables (wuica_load_arch_bin)
17
+ restarts = 0;
18
+
19
+ constructor(module) {
20
+ this.#module = module;
21
+ this.#live();
22
+ for (const n of ['memory', 'wuica_alloc', 'wuica_free', 'wuica_result_ptr', 'wuica_load_uarch', 'wuica_load_arch', 'wuica_analyze']) {
23
+ if (!this.#x[n]) throw new Error(`not a wuica analyzer module: export "${n}" is missing`);
24
+ }
25
+ this.#binary = typeof this.#x.wuica_load_arch_bin === 'function';
26
+ }
27
+
28
+ // Arguments are byte arrays passed as (pointer, length); the result is the text at wuica_result_ptr(). Views of the
29
+ // memory are created after each call into the module, since any call can grow the memory.
30
+ #call(name, inputs) {
31
+ const x = this.#x;
32
+ try {
33
+ const args = [], allocated = [];
34
+ for (const bytes of inputs) {
35
+ const ptr = x.wuica_alloc(bytes.length);
36
+ new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
37
+ allocated.push([ptr, bytes.length]);
38
+ args.push(ptr, bytes.length);
39
+ }
40
+ const len = x[name](...args);
41
+ const text = dec.decode(new Uint8Array(x.memory.buffer, x.wuica_result_ptr(), len));
42
+ for (const [p, l] of allocated) x.wuica_free(p, l);
43
+ return JSON.parse(text);
44
+ } catch (e) {
45
+ this.#x = null;
46
+ throw e;
47
+ }
48
+ }
49
+
50
+ #live() {
51
+ if (this.#x) return;
52
+ if (this.#uarch) this.restarts++;
53
+ this.#x = new WebAssembly.Instance(this.#module, {}).exports;
54
+ if (this.#uarch) this.#load('wuica_load_uarch', [this.#uarch], 'uarch.json');
55
+ for (const [name, t] of this.#tables) this.#loadTable(name, typeof t === 'function' ? t() : t);
56
+ }
57
+
58
+ #load(fn, inputs, what) {
59
+ const r = this.#call(fn, inputs);
60
+ if (r?.ok !== true) throw new Error(`${what}: ${r?.error ?? 'not loaded'}`);
61
+ }
62
+
63
+ loadUarch(bytes) {
64
+ this.#live();
65
+ this.#load('wuica_load_uarch', [bytes], 'uarch.json');
66
+ this.#uarch = bytes;
67
+ }
68
+
69
+ // bytes: the binary form of the table (data/arch/<name>.bin, see crates/wuica-core/src/table_bin.rs) or its JSON.
70
+ // reload: a function that returns the bytes again (then they are not kept: they are only needed after a trap)
71
+ loadArch(name, bytes, reload = null) {
72
+ this.#live();
73
+ this.#loadTable(name, bytes);
74
+ this.#tables.set(name, reload ?? bytes);
75
+ }
76
+
77
+ #loadTable(name, bytes) {
78
+ if (!isBinaryTable(bytes)) return this.#load('wuica_load_arch', [enc.encode(name), bytes], `instruction table ${name}`);
79
+ if (!this.#binary) throw new Error(`instruction table ${name}: a binary table, and this analyzer module reads only JSON tables`);
80
+ this.#load('wuica_load_arch_bin', [enc.encode(name), bytes], `instruction table ${name}`);
81
+ }
82
+
83
+ hasArch(name) { return this.#tables.has(name); }
84
+
85
+ // The decoder alone (wuica_decode): the instructions of `bytes` for an XED chip ("ALL": every instruction XED knows),
86
+ // [{addr, opcode, asm, category, ...}], or throws.
87
+ decode(bytes, chip = 'ALL') {
88
+ this.#live();
89
+ const r = this.#call('wuica_decode', [bytes, enc.encode(chip)]);
90
+ if (!Array.isArray(r)) throw new Error(r?.error ?? 'the decoder failed');
91
+ return r;
92
+ }
93
+
94
+ // The size of the instance's memory in bytes (0 after a trap, until the next call).
95
+ get memoryBytes() { return this.#x?.memory.buffer.byteLength ?? 0; }
96
+
97
+ // Returns the response object; a trap becomes {error, trapped: true}.
98
+ analyze(request) {
99
+ try {
100
+ this.#live();
101
+ } catch (e) {
102
+ return { error: `the analyzer could not be restarted: ${e instanceof Error ? e.message : e}` };
103
+ }
104
+ const x = this.#x;
105
+ try {
106
+ return this.#call('wuica_analyze', [enc.encode(JSON.stringify(request))]);
107
+ } catch (e) {
108
+ // an allocation that fails ends in `unreachable` like any panic; more than 1 GiB in use: the memory ran out
109
+ let used = 0;
110
+ try { used = x.memory.buffer.byteLength; } catch { /* unknown */ }
111
+ const detail = (e instanceof Error ? e.message : String(e)) + (used >= 2 ** 30 ? `: out of memory, ${(used / 2 ** 30).toFixed(1)} GB in use; try a smaller block or fewer iterations` : '');
112
+ return {
113
+ error: `the analysis failed for this input (the WebAssembly module trapped: ${detail}); the analyzer was restarted`,
114
+ trapped: true,
115
+ };
116
+ }
117
+ }
118
+ }
119
+
120
+ // Whether bytes are the binary form of an instruction table (they start with the magic WUICATBL).
121
+ const MAGIC = [0x57, 0x55, 0x49, 0x43, 0x41, 0x54, 0x42, 0x4c];
122
+ export function isBinaryTable(bytes) {
123
+ return bytes?.length >= 8 && MAGIC.every((b, i) => bytes[i] === b);
124
+ }
125
+
126
+ // The module bytes with the maximum of every (32-bit, unshared) memory set to at most `maxPages` (64 KiB each): an
127
+ // instance of it traps where an allocation would grow the memory beyond that.
128
+ export function capMemory(bytes, maxPages) {
129
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
130
+ const readLeb = (p) => { let r = 0, s = 0, x; do { x = b[p++]; r += (x & 0x7f) * 2 ** s; s += 7; } while (x & 0x80); return [r, p]; };
131
+ const leb = (n) => { const out = []; do { let x = n % 128; n = Math.floor(n / 128); if (n) x |= 0x80; out.push(x); } while (n); return out; };
132
+ let p = 8;
133
+ while (p < b.length) {
134
+ const start = p;
135
+ const id = b[p++];
136
+ let size;
137
+ [size, p] = readLeb(p);
138
+ const end = p + size;
139
+ if (id === 5) { // the memory section
140
+ let q = p, n;
141
+ [n, q] = readLeb(q);
142
+ const body = [...leb(n)];
143
+ for (let i = 0; i < n; i++) {
144
+ const flags = b[q++];
145
+ if (flags > 1) return b; // shared or 64-bit memory: left as it is
146
+ let min, max = Infinity;
147
+ [min, q] = readLeb(q);
148
+ if (flags & 1) [max, q] = readLeb(q);
149
+ body.push(1, ...leb(min), ...leb(Math.max(min, Math.min(max, maxPages))));
150
+ }
151
+ const section = [5, ...leb(body.length), ...body];
152
+ const out = new Uint8Array(b.length - (end - start) + section.length);
153
+ out.set(b.subarray(0, start), 0);
154
+ out.set(section, start);
155
+ out.set(b.subarray(end), start + section.length);
156
+ return out;
157
+ }
158
+ p = end;
159
+ }
160
+ return b;
161
+ }
162
+
163
+ // llvm-mc's diagnostics: "<input>:LINE:COL: error: MESSAGE", followed by the source line and a caret line.
164
+ export function parseDiagnostics(text) {
165
+ const out = [];
166
+ for (const l of String(text ?? '').split('\n')) {
167
+ const m = /^[^:\n]*:(\d+):(\d+): (error|warning|note): (.*)$/.exec(l);
168
+ if (m) out.push({ line: Number(m[1]), column: Number(m[2]), severity: m[3], message: m[4].trim() });
169
+ }
170
+ const rest = String(text ?? '').trim();
171
+ if (out.length === 0 && rest !== '') out.push({ line: null, column: null, severity: 'error', message: rest.split('\n')[0] });
172
+ return out;
173
+ }
174
+
175
+ // The analyzer only models 64-bit code: a source that switches the assembler to 16- or 32-bit mode (.code16,
176
+ // .code16gcc, .code32; LLVM accepts them in lower case only) would be analyzed as 64-bit code without a word.
177
+ // Returns {line, column, message} for the first such directive (outside comments), or null.
178
+ export function codeModeError(text) {
179
+ const plain = String(text).replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')); // block comments, lines kept
180
+ const lines = plain.split('\n');
181
+ for (let i = 0; i < lines.length; i++) {
182
+ const code = lines[i].replace(/(#|\/\/).*$/, '');
183
+ let at = 0;
184
+ for (const stmt of code.split(';')) {
185
+ const m = /^(\s*(?:[\w.$@]+:\s*)*)(\.code(?:16gcc|16|32))(?=\s|$)/.exec(stmt);
186
+ if (m) return { line: i + 1, column: at + m[1].length + 1, message: `${m[2]}: only 64-bit code can be analyzed` };
187
+ at += stmt.length + 1;
188
+ }
189
+ }
190
+ return null;
191
+ }
192
+
193
+ // GNU as's {load}/{store} pseudo-prefixes at the start of a line, which LLVM's assembler rejects.
194
+ export function stripHints(text) {
195
+ return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1');
196
+ }
197
+
198
+ const OUT_CAP = 1 << 20;
199
+ const ERR_CAP = 1 << 16;
200
+
201
+ export class Assembler {
202
+ #module;
203
+ #x = null;
204
+
205
+ constructor(module) {
206
+ this.#module = module;
207
+ this.#live();
208
+ for (const n of ['memory', 'malloc', 'free', 'wuica_assemble']) {
209
+ if (!this.#x[n]) throw new Error(`not a wuica assembler module: export "${n}" is missing`);
210
+ }
211
+ }
212
+
213
+ #live() {
214
+ if (this.#x) return;
215
+ const x = new WebAssembly.Instance(this.#module, {}).exports;
216
+ x._initialize?.();
217
+ this.#x = x;
218
+ }
219
+
220
+ // syntax: 0 = Intel (noprefix), 1 = AT&T. Returns {ok: true, bytes, message} or {ok: false, status, message}.
221
+ assemble(text, syntax) {
222
+ this.#live();
223
+ const x = this.#x;
224
+ const src = enc.encode(stripHints(text) + '\0');
225
+ let textPtr = 0, outPtr = 0, errPtr = 0;
226
+ try {
227
+ textPtr = x.malloc(src.length); outPtr = x.malloc(OUT_CAP); errPtr = x.malloc(ERR_CAP);
228
+ new Uint8Array(x.memory.buffer).set(src, textPtr);
229
+ const n = x.wuica_assemble(textPtr, syntax, outPtr, OUT_CAP, errPtr, ERR_CAP);
230
+ const mem = new Uint8Array(x.memory.buffer);
231
+ const end = mem.indexOf(0, errPtr);
232
+ const message = dec.decode(mem.subarray(errPtr, end < 0 ? errPtr : end));
233
+ const r = n >= 0 ? { ok: true, bytes: mem.slice(outPtr, outPtr + n), message } : { ok: false, status: n, message };
234
+ x.free(textPtr); x.free(outPtr); x.free(errPtr);
235
+ return r;
236
+ } catch (e) {
237
+ let fatal = '';
238
+ try {
239
+ const p = x.wuica_fatal_message?.();
240
+ if (p) { const mem = new Uint8Array(x.memory.buffer); fatal = dec.decode(mem.subarray(p, mem.indexOf(0, p))); }
241
+ } catch { /* the message is optional */ }
242
+ this.#x = null;
243
+ return { ok: false, status: 'trap', message: `the assembler failed${fatal ? `: ${fatal}` : ''} (${e instanceof Error ? e.message : e}); it was restarted` };
244
+ }
245
+ }
246
+ }
@@ -0,0 +1,202 @@
1
+ // The "N accumulators" what-if: the loop unrolled N times with its loop-carried register renamed in each copy, so the
2
+ // copies form N independent chains (as N accumulators, or N CRC streams, written by hand). The register is the one of
3
+ // the critical chain (the response's criticalPath); each copy after the first gets a free register of the same kind,
4
+ // and the loop's branch (with its macro-fused compare) stays once at the end, as in the unrolled variants (whatif.js).
5
+ // No DOM and no assembling here: the variant is assembly text (.byte lines for what is not renamed, so it keeps its
6
+ // exact encoding) that the caller assembles. The npm package has a copy (packages/wuica/lib/web) for MCP what_if.
7
+
8
+ export const ACCUMULATORS = Object.freeze([2, 3, 4, 8]);
9
+
10
+ const GPR = [
11
+ ['rax', 'eax', 'ax', 'al', 'ah'], ['rbx', 'ebx', 'bx', 'bl', 'bh'], ['rcx', 'ecx', 'cx', 'cl', 'ch'], ['rdx', 'edx', 'dx', 'dl', 'dh'],
12
+ ['rsi', 'esi', 'si', 'sil'], ['rdi', 'edi', 'di', 'dil'], ['rbp', 'ebp', 'bp', 'bpl'], ['rsp', 'esp', 'sp', 'spl'],
13
+ ...Array.from({ length: 8 }, (_, k) => [`r${k + 8}`, `r${k + 8}d`, `r${k + 8}w`, `r${k + 8}b`]),
14
+ ];
15
+ const FAMILY = new Map(GPR.flatMap((names) => names.map((n, size) => [n, { kind: 'gpr', base: names[0], size }])));
16
+ // the registers a copy can get, in this order (not rsp; the ones with implicit uses last)
17
+ const GPR_FREE = ['r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15', 'rbx', 'rbp', 'rsi', 'rdi', 'rcx', 'rdx', 'rax'];
18
+ // Instructions with implicit register operands (the response has no operand sets without the details: this list is
19
+ // the x86-64 instructions that read or write a register they do not name): [test, registers]. 'vall': every vector
20
+ // register. Renaming such a register would change what they do, and none of them may get a copy's register.
21
+ const IMPLICIT = [
22
+ [/^(?:i?div|mul|cdq|cqo|cwd|rdtsc|xsave\w*|xrstor\w*|in|out)$/, ['rax', 'rdx']],
23
+ [/^(?:cbw|cwde|cdqe|lahf|sahf|cmpxchg|stos\w*|lods\w*|scas\w*)$/, ['rax']],
24
+ [/^(?:cpuid|cmpxchg8b|cmpxchg16b)$/, ['rax', 'rbx', 'rcx', 'rdx']],
25
+ [/^(?:rdtscp|xgetbv|xsetbv|rdmsr|wrmsr|rdpmc|monitor\w*)$/, ['rax', 'rcx', 'rdx']],
26
+ [/^(?:mwait\w*)$/, ['rax', 'rcx']],
27
+ [/^(?:mulx)$/, ['rdx']],
28
+ [/^(?:xlatb?)$/, ['rax', 'rbx']],
29
+ [/^(?:syscall|sysret\w*)$/, ['rax', 'rcx', 'r11']],
30
+ [/^(?:rep\w*|loop\w*|jrcxz|jecxz)$/, ['rcx']],
31
+ [/^(?:movs[bwdq]?|cmps[bwdq]?|stos\w*|lods\w*|scas\w*|ins[bwd]?|outs[bwd]?)$/, ['rsi', 'rdi', 'rcx']],
32
+ [/^(?:ins[bwd]?|outs[bwd]?)$/, ['rdx']],
33
+ [/^(?:v?maskmovq|maskmovdqu|vmaskmovdqu)$/, ['rdi']],
34
+ [/^(?:push\w*|pop\w*|call\w*|ret\w*|enter|leave)$/, ['rsp']],
35
+ [/^(?:enter|leave)$/, ['rbp']],
36
+ // the legacy (non-VEX) blends and SHA-256 rounds read xmm0; the string compares write ecx or xmm0
37
+ [/^(?:blendvps|blendvpd|pblendvb|sha256rnds2)$/, ['v0']],
38
+ [/^(?:v?pcmpestri)$/, ['rax', 'rdx', 'rcx']],
39
+ [/^(?:v?pcmpestrm)$/, ['rax', 'rdx', 'v0']],
40
+ [/^(?:v?pcmpistri)$/, ['rcx']],
41
+ [/^(?:v?pcmpistrm)$/, ['v0']],
42
+ [/^(?:vzeroupper|vzeroall)$/, ['vall']],
43
+ ];
44
+ // a one-operand imul uses rax and rdx implicitly
45
+ export const implicitUse = (mnemonic, operands) => {
46
+ const m = String(mnemonic).toLowerCase().replace(/^(?:lock|rep\w*)\s+/, '');
47
+ if (m === 'imul' && !String(operands).includes(',')) return ['rax', 'rdx'];
48
+ return IMPLICIT.filter(([re]) => re.test(m)).flatMap(([, regs]) => regs);
49
+ };
50
+
51
+ const VEC = /^([xyz]mm)(\d+)$/;
52
+
53
+ // The family of a register name: {kind: 'gpr', base: 'rax', size} or {kind: 'vec', index}; null if not renamable.
54
+ export function family(name) {
55
+ const n = String(name).toLowerCase();
56
+ const v = VEC.exec(n);
57
+ if (v) return { kind: 'vec', index: Number(v[2]), base: `v${v[2]}` };
58
+ return FAMILY.get(n) ?? null;
59
+ }
60
+
61
+ // The registers on the critical loop-carried chain: {ok, bases: ['rax' | 'v0', ...], names} or {ok: false, reason}.
62
+ export function chainRegisters(response) {
63
+ const edges = response?.criticalPath?.edges;
64
+ if (!Array.isArray(edges) || !edges.length) return { ok: false, reason: 'no loop-carried chain' };
65
+ const bases = [], names = [];
66
+ for (const e of edges) {
67
+ const op = String(e.operand ?? '');
68
+ if (/^mem$/i.test(op)) return { ok: false, reason: 'the chain goes through memory' };
69
+ if (/flags/i.test(op)) return { ok: false, reason: 'the chain goes through the flags' };
70
+ const f = family(op);
71
+ if (!f) return { ok: false, reason: `the chain's register ${op.toLowerCase()} cannot be renamed` };
72
+ if (f.kind === 'gpr' && f.size === 4) return { ok: false, reason: `the chain goes through ${op.toLowerCase()}` }; // ah, bh, ...
73
+ if (!bases.includes(f.base)) { bases.push(f.base); names.push(op.toLowerCase()); }
74
+ }
75
+ return { ok: true, bases, names };
76
+ }
77
+
78
+ const REG_TOKEN = /\b(?:[re]?[abcd]x|[abcd][lh]|[re]?(?:si|di|bp|sp)|(?:si|di|bp|sp)l|r(?:[89]|1[0-5])[dwb]?|[xyz]mm\d+)\b/gi;
79
+ const regsIn = (text) => (String(text).match(REG_TOKEN) ?? []).map((r) => r.toLowerCase());
80
+
81
+ // The text of an instruction with registers renamed: map base -> new base ('rax' -> 'r9', 'v0' -> 'v3'). null if a
82
+ // register of the map is used in a form the new one does not have (ah).
83
+ function renameText(text, map) {
84
+ let bad = false;
85
+ const out = text.replace(REG_TOKEN, (tok) => {
86
+ const f = family(tok);
87
+ if (!f || !map.has(f.base)) return tok;
88
+ const to = map.get(f.base);
89
+ if (f.kind === 'vec') return tok.slice(0, 3) + to.slice(1);
90
+ const names = GPR.find((g) => g[0] === to);
91
+ const n = names[f.size];
92
+ if (!n) { bad = true; return tok; }
93
+ return tok === tok.toUpperCase() ? n.toUpperCase() : n;
94
+ });
95
+ return bad ? null : out;
96
+ }
97
+
98
+ // Instructions whose first operand is only written (with a 32- or 64-bit general register or a whole vector register:
99
+ // a byte or word write keeps the rest of the register; a legacy movss/movsd between registers keeps the upper part).
100
+ const WRITE_ONLY = /^(?:v?mov(?:aps|apd|ups|upd|dqa\w*|dqu\w*|ss|sd|d|q)|mov|movzx|movsx\w*|lea|vbroadcast\w+|vpbroadcast\w+|v?pmov[sz]x\w+|v?cvt\w+|pop)$/;
101
+ const MERGES = /^(?:movss|movsd|cvt\w+)$/; // legacy forms that merge into the destination
102
+ // true if `label` writes register family `base` as its first operand and does not read it
103
+ export function writesOnly(label, base) {
104
+ const { mnemonic, operands } = splitInstr(label);
105
+ if (!WRITE_ONLY.test(mnemonic)) return false;
106
+ const ops = operands.split(',').map((o) => o.trim());
107
+ const f = family(ops[0]);
108
+ if (!f || f.base !== base) return false;
109
+ if (f.kind === 'gpr' && f.size > 1) return false;
110
+ if (ops.slice(1).some((o) => regsIn(o).some((r) => family(r)?.base === base))) return false;
111
+ if (MERGES.test(mnemonic) && ops.length === 2 && !/\[/.test(ops[1])) return false;
112
+ return true;
113
+ }
114
+
115
+ // XED's Intel syntax where LLVM's reads it differently (as asm-text.js's llvmSyntax).
116
+ function llvmSyntax(asm) {
117
+ return asm
118
+ .replace(/(^\S+ |, )ptr \[/, '$1[')
119
+ .replace(/^(nop \S+ ptr \[[^\]]*\]), [a-z0-9]+$/, '$1')
120
+ .replace(/^xlat$/, 'xlatb');
121
+ }
122
+
123
+ const byteLine = (op) => ` .byte ${op.match(/../g).map((b) => '0x' + b).join(', ')}`;
124
+ const splitInstr = (label) => { const t = String(label).trim().replace(/\s+/g, ' '); const i = t.indexOf(' '); return i < 0 ? { mnemonic: t.toLowerCase(), operands: '' } : { mnemonic: t.slice(0, i).toLowerCase(), operands: t.slice(i + 1) }; };
125
+
126
+ // The variant with n accumulators: {ok: true, text, per: n, renamed: [{from, to: [names]}]} or {ok: false, reason}.
127
+ // response: the analysis of hex (a loop); the rows must make up the code (as for the unrolled variants).
128
+ export function accumulatorText(response, hex, n) {
129
+ if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
130
+ const rows = Array.isArray(response.rows) ? response.rows : [];
131
+ const ins = [];
132
+ let at = 0;
133
+ rows.forEach((x, row) => {
134
+ if (x.kind !== 'instr') return;
135
+ const op = String(x.opcode ?? '').toLowerCase();
136
+ ins.push({ op, row, label: String(x.label ?? ''), fused: x.notes === 'M', start: at });
137
+ at += op.length / 2;
138
+ });
139
+ if (!ins.length || ins.map((i) => i.op).join('') !== String(hex ?? '').toLowerCase()) return { ok: false, reason: 'the code has bytes that are not instructions' };
140
+ const chain = chainRegisters(response);
141
+ if (!chain.ok) return chain;
142
+ const last = ins.length - 1;
143
+ const tailFrom = ins[last].fused && last > 0 ? last - 1 : last;
144
+ if (tailFrom === 0) return { ok: false, reason: 'nothing but the branch' };
145
+ const body = ins.slice(0, tailFrom), tail = ins.slice(tailFrom);
146
+ // registers in use (any form: al/ax/eax/rax, xmm/ymm/zmm are one register), and the implicit ones
147
+ const uses = (i) => { const s = splitInstr(i.label); return new Set([...regsIn(i.label).map((r) => family(r)?.base).filter(Boolean), ...implicitUse(s.mnemonic, s.operands)]); };
148
+ const usesOf = new Map(ins.map((i) => [i, uses(i)]));
149
+ const used = new Set(ins.flatMap((i) => [...usesOf.get(i)]));
150
+ const implicit = new Set(ins.flatMap((i) => { const s = splitInstr(i.label); return implicitUse(s.mnemonic, s.operands); }));
151
+ for (const b of chain.bases) {
152
+ if (implicit.has(b) || (b.startsWith('v') && implicit.has('vall'))) return { ok: false, reason: `${chain.names[chain.bases.indexOf(b)]} is an implicit operand` };
153
+ }
154
+ // a register used in an address is the loop's induction variable (a pointer or an index), not an accumulator
155
+ const addressed = new Set(ins.flatMap((i) => [...i.label.matchAll(/\[([^\]]*)\]/g)].flatMap((m) => regsIn(m[1]))).map((r) => family(r)?.base));
156
+ const induction = chain.bases.find((b) => addressed.has(b));
157
+ if (induction) return { ok: false, reason: `the chain is the induction variable ${chain.names[chain.bases.indexOf(induction)]} (used in an address), not an accumulator` };
158
+ // the chain's register read by an instruction off the chain (a store of a running sum): splitting the chain would
159
+ // change what it reads. Writing it off the chain is sound (clang reuses the chain's registers for loads: the copy's
160
+ // registers are renamed as a whole, the load with them).
161
+ const onChain = new Set(response.criticalPath.edges.flatMap((e) => [e.from, e.to]));
162
+ for (const i of ins) {
163
+ if (onChain.has(i.row)) continue;
164
+ const b = chain.bases.find((x) => usesOf.get(i).has(x) && !writesOnly(i.label, x));
165
+ if (b) return { ok: false, reason: `${chain.names[chain.bases.indexOf(b)]}'s running value is also read off the chain (${i.label}): it cannot be split` };
166
+ }
167
+ // free registers for the copies after the first
168
+ const freeGpr = GPR_FREE.filter((r) => !used.has(r) && !implicit.has(r));
169
+ const usesEvex = ins.some((i) => /\b[xyz]mm(?:1[6-9]|2\d|3[01])\b/i.test(i.label));
170
+ const freeVec = Array.from({ length: usesEvex ? 32 : 16 }, (_, k) => `v${k}`).filter((v) => !used.has(v) && !implicit.has(v));
171
+ const maps = Array.from({ length: n }, () => new Map());
172
+ const renamed = [];
173
+ for (const b of chain.bases) {
174
+ const pool = b.startsWith('v') ? freeVec : freeGpr;
175
+ if (pool.length < n - 1) return { ok: false, reason: `${n - 1} free registers needed for ${chain.names[chain.bases.indexOf(b)]}` };
176
+ const to = pool.splice(0, n - 1);
177
+ to.forEach((r, k) => maps[k + 1].set(b, r));
178
+ renamed.push({ from: chain.names[chain.bases.indexOf(b)], to: to.map((r) => renameText(chain.names[chain.bases.indexOf(b)], new Map([[b, r]]))) });
179
+ }
180
+ const lines = [];
181
+ for (let k = 0; k < n; k++) {
182
+ for (const i of body) {
183
+ const touches = k > 0 && regsIn(i.label).some((r) => maps[k].has(family(r)?.base));
184
+ if (!touches) { lines.push(byteLine(i.op)); continue; }
185
+ const t = renameText(llvmSyntax(i.label), maps[k]);
186
+ if (t === null) return { ok: false, reason: `${i.label}: the register has no such form in its copy` };
187
+ lines.push(` ${t}`);
188
+ }
189
+ }
190
+ for (const i of tail) lines.push(byteLine(i.op));
191
+ return { ok: true, text: lines.join('\n') + '\n', per: n, renamed };
192
+ }
193
+
194
+ // The best number of accumulators from the throughput per original iteration of each (n -> tp; 1: the loop as it is):
195
+ // the smallest n within 1% of the fastest. {n, tp} or null.
196
+ export function bestAccumulators(tps) {
197
+ const all = [...tps].filter(([, tp]) => Number.isFinite(tp) && tp > 0).sort((a, b) => a[0] - b[0]);
198
+ if (!all.length) return null;
199
+ const min = Math.min(...all.map(([, tp]) => tp));
200
+ const [n, tp] = all.find(([, t]) => t <= min * 1.01 + 0.005);
201
+ return { n, tp };
202
+ }