wuica-cli 0.0.0-stage → 0.1.7

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 (44) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +436 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.json.br +0 -0
  6. package/dist/data/arch/BDW.json.br +0 -0
  7. package/dist/data/arch/CFL.json.br +0 -0
  8. package/dist/data/arch/CLX.json.br +0 -0
  9. package/dist/data/arch/HSW.json.br +0 -0
  10. package/dist/data/arch/ICL.json.br +0 -0
  11. package/dist/data/arch/ICX.json.br +0 -0
  12. package/dist/data/arch/IVB.json.br +0 -0
  13. package/dist/data/arch/KBL.json.br +0 -0
  14. package/dist/data/arch/RKL.json.br +0 -0
  15. package/dist/data/arch/SKL.json.br +0 -0
  16. package/dist/data/arch/SKX.json.br +0 -0
  17. package/dist/data/arch/SNB.json.br +0 -0
  18. package/dist/data/arch/TGL.json.br +0 -0
  19. package/dist/data/arch/ZEN3.json.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +81 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +372 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +430 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/files.js +18 -0
  30. package/lib/index.js +474 -0
  31. package/lib/insights.js +100 -0
  32. package/lib/mcp.js +366 -0
  33. package/lib/thread-worker.js +46 -0
  34. package/lib/threads.js +224 -0
  35. package/lib/wasm.js +221 -0
  36. package/lib/web/accum.js +202 -0
  37. package/lib/web/asm-regions.js +415 -0
  38. package/lib/web/assembler.js +188 -0
  39. package/lib/web/caveats.js +206 -0
  40. package/lib/web/loop-find.js +492 -0
  41. package/lib/whatif.js +136 -0
  42. package/licenses/LICENSE-LLVM.txt +279 -0
  43. package/licenses/LICENSE-XED.txt +178 -0
  44. package/package.json +58 -4
@@ -0,0 +1,206 @@
1
+ // Known blind spots of the model, found in a response's instructions (no analysis): what uiCA does not simulate and
2
+ // that the block is likely to meet. Shown as one small line under the throughput (render.js) and as insights.caveats in
3
+ // the API (the npm package has a copy: packages/wuica/lib/web). No DOM.
4
+ // rmw-index a read-modify-write to an indexed address (inc dword ptr [rsp+rdx*4]), or a load and a store to the same
5
+ // indexed address, where a register of the address is written in the loop other than by advancing it by a
6
+ // constant (rdx loaded from the data): whether an iteration's load waits for an earlier store (store
7
+ // forwarding) depends on the data (a histogram of repeated bytes); uiCA assumes it does not. Not for an
8
+ // address of induction registers only (saxpy's [rsi+rax*4], rax advanced by add rax, 8: never the same
9
+ // location twice) nor for a loop-invariant one (the same location every iteration: the model has that
10
+ // chain through memory, criticalPath operand "mem").
11
+ // exit a loop with an exit before its branch (a search; a forward branch within the loop, an if, is not an
12
+ // exit): the exit's mispredict, once per call, is not modelled;
13
+ // with short trip counts it can cost more than the loop.
14
+ // paths a conditional branch before the last instruction whose target is inside the block (an if/else, or a
15
+ // second back edge: clang's remainder loop of sum_mod, `jne .LBB0_9` back to the top and the latch to the
16
+ // middle): uiCA runs the block straight through, so both sides of the branch are simulated one after the
17
+ // other, while a real iteration takes one. Not an inner loop's back edge (backward, to after the target
18
+ // of the block's own branch: the outer loop of count_u8). Named by source line when the response has the
19
+ // lines of the picked span (response.loop.lines, the package's analyze; alignment padding, nops the
20
+ // source does not have, left out), else by instruction. Region markers around one side analyze that side.
21
+ // split loads at an offset that is not a multiple of their width (ymmword ptr [rdi+rax*4+0x4]): with a base
22
+ // aligned to the width, some of them cross a 64-byte line (split loads cost extra). Per CPU (`config`, its
23
+ // configuration in uarch.json): where splitLoadCycles is 0 (the stock Intel models) no crossing is charged,
24
+ // so every such load warns. Where it is > 0 (ZEN3, ADL-P, ICX) the model charges the crossings of a load
25
+ // whose address registers change only by adding an immediate (add, sub, inc, dec; instr_builder.rs,
26
+ // split_load_patterns), assuming the start alignment with the fewest crossings; only loads with an
27
+ // address register written otherwise (mov, lea, a load, ...) warn, worded for that.
28
+
29
+ import { family } from './accum.js';
30
+
31
+ const SIZE = { byte: 1, word: 2, dword: 4, qword: 8, xmmword: 16, ymmword: 32, zmmword: 64, tbyte: 10 };
32
+ const RMW = /^(?:add|adc|sub|sbb|and|or|xor|inc|dec|neg|not|shl|shr|sar|sal|rol|ror|rcl|rcr|xadd|btc|btr|bts|cmpxchg\w*)$/;
33
+ // a memory operand in any position is read and written (xchg [mem], reg or xchg reg, [mem])
34
+ const RMW_ANY = /^xchg$/;
35
+ // an address that is not an access (lea), or hints that move no data the loop uses
36
+ const NO_ACCESS = /^(?:lea|nop\w*|prefetch\w*|clflush\w*|clwb|cldemote)$/;
37
+ // instructions whose memory destination is only written (a store, not a read)
38
+ const STORE_ONLY = /^(?:v?mov\w*|movnt\w*|stos\w*|set\w+|v?pextr\w+|v?extract\w*|vextract\w+|v?pmovm\w*|vp?scatter\w+|vmaskmov\w*|vpmaskmov\w*|v?cvt\w*|push\w*|pop\w*|fstp?\w*|fistp?\w*)$/;
39
+ const COND_BRANCH = /^(?:j(?!mp)[a-z]+|loop\w*)$/;
40
+ // Splits with a split-load cost: what writes a general-purpose register. An add or sub of an immediate, inc or dec, to a
41
+ // 32- or 64-bit register keeps it advancing by a constant (instr_builder.rs, affine_delta); any other write does not.
42
+ // Without a register destination (cmp, test, bt, push, branches) the first operand is only read.
43
+ const READS_FIRST = /^(?:cmp|test|bt|push\w*|call\w*|jmp|j[a-z]+|loop\w*|out\w*|v?u?comis[sd]|v?ptest|kortest\w|ktest\w|nop\w*|prefetch\w*|clflush\w*|clwb|cldemote)$/;
44
+ const BOTH_WRITTEN = /^(?:xchg|xadd|mulx)$/; // the second register operand is written too
45
+ const IMPLICIT_WRITES = [
46
+ [/^(?:i?div|mul|cdq|cqo|cwd|rdtsc)$/, ['rax', 'rdx']],
47
+ [/^(?:cbw|cwde|cdqe|lahf|cmpxchg|lods\w*)$/, ['rax']],
48
+ [/^(?:cpuid|cmpxchg8b|cmpxchg16b)$/, ['rax', 'rbx', 'rcx', 'rdx']],
49
+ [/^(?:rdtscp|rdmsr|rdpmc|xgetbv)$/, ['rax', 'rcx', 'rdx']],
50
+ [/^(?:syscall)$/, ['rcx', 'r11']],
51
+ [/^(?:loop\w*)$/, ['rcx']],
52
+ [/^(?:movs[bwdq]?|cmps[bwdq]?)$/, ['rsi', 'rdi']],
53
+ [/^(?:stos\w*|scas\w*|ins[bwd]?)$/, ['rdi']],
54
+ [/^(?:lods\w*|outs[bwd]?)$/, ['rsi']],
55
+ [/^(?:v?pcmpestri|v?pcmpistri)$/, ['rcx']],
56
+ [/^(?:push\w*|pop\w*|call\w*|ret\w*|enter|leave)$/, ['rsp']],
57
+ [/^(?:leave)$/, ['rbp']],
58
+ ];
59
+ const IMM = /^-?(?:0x[0-9a-f]+|\d+)$/i;
60
+ // {register family: [rows]} of the writes that do not advance a register by a constant. lea: lea r, [r+imm] advances it
61
+ // too (for rmw-index; the split-load model, affine_delta, does not count it)
62
+ function untrackedWrites(rows, { lea = false } = {}) {
63
+ const out = new Map();
64
+ const add = (reg, row) => { const f = family(reg); if (f?.kind === 'gpr') (out.get(f.base) ?? out.set(f.base, []).get(f.base)).push(row); };
65
+ rows.forEach((x, row) => {
66
+ if (x?.kind !== 'instr') return;
67
+ const t = String(x.label).trim().replace(/\s+/g, ' ').toLowerCase();
68
+ const rep = /^rep\w* /.test(t);
69
+ const u = t.replace(/^(?:lock|rep[a-z]*|notrack|bnd) /, '');
70
+ const sp = u.indexOf(' ');
71
+ const mn = sp < 0 ? u : u.slice(0, sp);
72
+ const ops = sp < 0 ? [] : u.slice(sp + 1).split(',').map((o) => o.trim());
73
+ if (rep) add('rcx', row);
74
+ for (const [re, regs] of IMPLICIT_WRITES) if (re.test(mn)) for (const r of regs) add(r, row);
75
+ if (mn === 'imul' && ops.length === 1) { add('rax', row); add('rdx', row); }
76
+ if (!ops.length || READS_FIRST.test(mn)) return;
77
+ const f = family(ops[0]);
78
+ if (f?.kind === 'gpr') {
79
+ const self = lea && mn === 'lea' && ops.length === 2 && new RegExp(`^(?:(?:\\w+ )?ptr )?\\[${ops[0]}(?:[+-](?:0x[0-9a-f]+|\\d+))?\\]$`).test(ops[1]);
80
+ const affine = f.size <= 1 && (((mn === 'add' || mn === 'sub') && ops.length === 2 && IMM.test(ops[1])) || ((mn === 'inc' || mn === 'dec') && ops.length === 1) || self);
81
+ if (!affine) add(ops[0], row);
82
+ }
83
+ if (BOTH_WRITTEN.test(mn) && ops[1]) add(ops[1], row);
84
+ });
85
+ return out;
86
+ }
87
+
88
+ // The memory operand of an instruction label (XED's Intel syntax): {first, size, base, index, disp, text} or null.
89
+ export function memOperand(label) {
90
+ const t = String(label).trim().replace(/\s+/g, ' ').replace(/^(?:lock|rep[a-z]*|notrack|bnd) /i, '');
91
+ const sp = t.indexOf(' ');
92
+ if (sp < 0) return null;
93
+ const mnemonic = t.slice(0, sp).toLowerCase();
94
+ if (NO_ACCESS.test(mnemonic)) return null;
95
+ const ops = t.slice(sp + 1);
96
+ const m = /(?:(\w+) ptr )?\[([^\]]*)\]/.exec(ops);
97
+ if (!m) return null;
98
+ const inner = m[2].replace(/\s/g, '').toLowerCase();
99
+ const parts = inner.split(/(?=[+-])/);
100
+ let base = null, index = null, disp = 0;
101
+ for (const p of parts) {
102
+ const v = p.replace(/^\+/, '');
103
+ if (/\*/.test(v)) index = v.split('*')[0];
104
+ else if (/^-?(?:0x[0-9a-f]+|\d+)$/.test(v)) disp += Number(v.startsWith('-') ? -Number(v.slice(1)) : Number(v));
105
+ else if (/^[a-z]\w*$/.test(v)) { if (base === null) base = v; else index = v; }
106
+ }
107
+ if (base === 'rip') return null;
108
+ return { mnemonic, first: ops.indexOf('[') <= (ops.indexOf(',') < 0 ? ops.length : ops.indexOf(',')), size: SIZE[String(m[1] ?? '').toLowerCase()] ?? null, base, index, disp, text: m[0].replace(/^\w+ ptr /, '') };
109
+ }
110
+
111
+ // [{id, text, title, rows}] (rows: indices into response.rows), in the order rmw-index, paths, exit, split; [] if none.
112
+ // config: the CPU's configuration in uarch.json (configs[response.arch]); only splitLoadCycles is read. Without it, as on
113
+ // a CPU without a split-load cost. Kept per response and split-load cost (the result view is drawn again on every
114
+ // change of its own controls).
115
+ const memo = new WeakMap();
116
+ const some = (rows, ks) => `${ks.slice(0, 4).map((k) => rows[k].label).join('; ')}${ks.length > 4 ? '; …' : ''}`;
117
+ export function caveats(response, config = null) {
118
+ const splitCost = Number(config?.splitLoadCycles) > 0;
119
+ const kept = response && typeof response === 'object' ? memo.get(response) : undefined;
120
+ if (kept?.has(splitCost)) return kept.get(splitCost);
121
+ const rows = Array.isArray(response?.rows) ? response.rows : [];
122
+ const out = [];
123
+ const rmw = [], split = [], early = [], inside = [];
124
+ const target = (row, op) => {
125
+ const v = /^0x[0-9a-f]+$/i.test(op ?? '') ? Number(BigInt.asIntN(64, BigInt(op))) : null;
126
+ return v === null ? null : offset.get(row) + v;
127
+ };
128
+ const loads = new Map(), stores = new Map();
129
+ let last = -1, total = 0;
130
+ const offset = new Map();
131
+ rows.forEach((x, row) => { if (x?.kind === 'instr') { last = row; offset.set(row, total); total += String(x.opcode ?? '').length / 2; } });
132
+ // where the block's own branch goes (the loop's header; not always the top: a rotated loop)
133
+ const [lastMn, lastOp] = last >= 0 ? String(rows[last].label).trim().split(/\s+/) : [];
134
+ const latch = last >= 0 && /^(?:j[a-z]+|loop\w*)$/.test(String(lastMn).toLowerCase()) ? target(last, lastOp) : null;
135
+ const head = latch !== null && latch >= 0 && latch < total ? latch : 0;
136
+ rows.forEach((x, row) => {
137
+ if (x?.kind !== 'instr') return;
138
+ const [mn, op] = String(x.label).trim().split(/\s+/);
139
+ if (row !== last && COND_BRANCH.test(mn.toLowerCase())) {
140
+ // the label's target is relative to the branch (XED, as if it were at address 0): inside the loop's code (an
141
+ // if) it is not an exit
142
+ const to = target(row, op);
143
+ if (to === null || to < 0 || to >= total) early.push(row);
144
+ // forward (an if/else), or back to the header or before it (a second back edge, a rotated if/else); backward to
145
+ // after the header is an inner loop's back edge
146
+ else if (to > offset.get(row) || to <= head) inside.push(row);
147
+ }
148
+ const m = memOperand(x.label);
149
+ if (!m) return;
150
+ const storeOnly = m.first && STORE_ONLY.test(m.mnemonic);
151
+ // read-modify-write, or a load and a store, to the same indexed address
152
+ if (m.index) {
153
+ if ((m.first && RMW.test(m.mnemonic)) || RMW_ANY.test(m.mnemonic)) rmw.push(row);
154
+ else if (storeOnly) (stores.get(m.text) ?? stores.set(m.text, []).get(m.text)).push(row);
155
+ else if (!m.first) (loads.get(m.text) ?? loads.set(m.text, []).get(m.text)).push(row);
156
+ }
157
+ // a load that may split a cache line
158
+ if (!storeOnly && m.size && m.size >= 2 && m.size <= 64 && ((m.disp % m.size) + m.size) % m.size !== 0) split.push(row);
159
+ });
160
+ for (const [addr, st] of stores) if (loads.has(addr)) rmw.push(...loads.get(addr), ...st);
161
+ // only where the address can repeat with the data: a register of it written other than by advancing it by a constant
162
+ const dynamic = rmw.length ? untrackedWrites(rows, { lea: true }) : null;
163
+ const hit = rmw.filter((row) => { const m = memOperand(rows[row].label); return [m.base, m.index].some((r) => dynamic.has(family(r)?.base)); });
164
+ if (hit.length) {
165
+ const r = [...new Set(hit)].sort((a, b) => a - b);
166
+ out.push({ id: 'rmw-index', text: 'store forwarding', rows: r,
167
+ title: `a read-modify-write to an indexed address (${some(rows, r)}): when iterations hit the same address (repeated data), each waits for the previous store; not modelled` });
168
+ }
169
+ // a branch within the block: both sides are simulated
170
+ if (inside.length) {
171
+ const instrRows = rows.flatMap((x, row) => (x?.kind === 'instr' ? [row] : []));
172
+ // the source line of each row: as many lines as instructions, or as many once the padding (nops of .p2align) is out
173
+ const given = Array.isArray(response?.loop?.lines) ? response.loop.lines : null;
174
+ const real = instrRows.filter((row) => !/^(?:nop|data16|cs nop|xchg ax, ax)\b/i.test(String(rows[row].label).trim()));
175
+ const mapped = given?.length === instrRows.length ? instrRows : given?.length === real.length ? real : null;
176
+ const where = inside.map((row) => (mapped && mapped.includes(row) ? given[mapped.indexOf(row)] : null));
177
+ const lines = where.every((x) => x !== null) ? where : null;
178
+ if (!lines) where.splice(0, where.length, ...inside.map((row) => instrRows.indexOf(row) + 1));
179
+ const at = `${lines ? 'line' : 'instruction'}${where.length > 1 ? 's' : ''} ${where.join(', ')}`;
180
+ const one = inside.length === 1;
181
+ out.push({ id: 'paths', text: 'both paths', rows: inside,
182
+ title: `both sides of the branch${one ? '' : 'es'} at ${at} (${[...new Set(inside.map((row) => String(rows[row].label).trim().split(/\s+/)[0]))].join(', ')}) are simulated, one after the other; a real iteration takes one, so the cycles per iteration (and the step) count both. To analyze one side, put # wuica-begin and # wuica-end around it` });
183
+ }
184
+ // an exit before the loop's branch
185
+ if (response?.mode === 'loop' && early.length) {
186
+ out.push({ id: 'exit', text: 'exit mispredict', rows: early,
187
+ title: 'the loop has an exit before its branch: its mispredict when the loop ends (once per call) is not modelled; with short trip counts it can cost more than the loop' });
188
+ }
189
+ if (split.length && !splitCost) {
190
+ out.push({ id: 'split', text: `split loads? (${split.length})`, rows: split,
191
+ title: `${split.length} load${split.length === 1 ? '' : 's'} at an offset that is not a multiple of the width (${some(rows, split)}): some cross a 64-byte line, which costs extra; not modelled` });
192
+ } else if (split.length) {
193
+ // this CPU's model charges the crossings of loads whose address advances by a constant: only the others warn
194
+ const writes = untrackedWrites(rows);
195
+ const regsOf = (row) => { const m = memOperand(rows[row].label); return [m.base, m.index].map((r) => family(r)?.base).filter((r) => r && writes.has(r)); };
196
+ const untracked = split.filter((row) => regsOf(row).length);
197
+ if (untracked.length) {
198
+ const regs = [...new Set(untracked.flatMap(regsOf))];
199
+ const by = [...new Set(regs.flatMap((r) => writes.get(r)))].sort((a, b) => a - b);
200
+ out.push({ id: 'split', text: `split loads? (${untracked.length})`, rows: untracked,
201
+ title: `${untracked.length} load${untracked.length === 1 ? '' : 's'} at an offset that is not a multiple of the width (${some(rows, untracked)}): some may cross a 64-byte line. This CPU's model charges a crossing only for a load whose address advances by a constant each iteration (its registers changed only by add, sub, inc or dec of an immediate); ${regs.join(', ')} ${regs.length === 1 ? 'is' : 'are'} written otherwise here (${some(rows, by)}), so these crossings are not modelled` });
202
+ }
203
+ }
204
+ if (response && typeof response === 'object') (kept ?? memo.set(response, new Map()).get(response)).set(splitCost, out);
205
+ return out;
206
+ }