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
package/lib/cli.js ADDED
@@ -0,0 +1,430 @@
1
+ // The command-line tool: `wuica [options] [FILE | - | HEX]`. Options follow uiCA's and the Rust CLI's (crates/wuica-cli);
2
+ // every flag also takes "--" and "=value" spellings, and flag names are case-insensitive.
3
+
4
+ import fs from 'node:fs';
5
+ import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, CODES } from './index.js';
6
+
7
+ export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
8
+
9
+ export const USAGE = `Usage: wuica [options] [FILE | - | HEX]
10
+ wuica mcp start the MCP server (stdio)
11
+
12
+ Predicts the throughput of an x86-64 basic block with uiCA's pipeline model (this is wuica ${VERSION}, a WebAssembly
13
+ port of uiCA). One input per run: assembly from FILE (gcc -S, clang -S, objdump -d output, or a hand-written loop),
14
+ or from stdin if FILE is - or missing. A HEX argument that is not a file (e.g. 4801d84801c349ffcf75f5) is machine code.
15
+
16
+ Input:
17
+ -att, -intel the assembly's syntax (default: detected from the text: %registers mean AT&T)
18
+ -hex the input is machine code as hex digits (spaces, commas, 0x prefixes allowed)
19
+ -raw FILE read the machine code from a binary file that contains only the code (not an object
20
+ file: for those, objdump -d FILE | wuica)
21
+ -loops list the loops of the assembly (index, label, function, lines, instructions, depth, auto)
22
+ -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
23
+ "Inner Loop Header" notes count), whole (all the text), a loop's index (0-based, as
24
+ -loops lists them) or its label (-loop .LBB0_12)
25
+ -func NAME only the loops of function NAME (with -loop: its index or label among them)
26
+
27
+ Output:
28
+ -arch NAME microarchitecture (default: SKL; case-insensitive); "all" prints a table for every one,
29
+ a comma-separated list (e.g. SKL,ICL,ZEN3) a table for those
30
+ -list list the microarchitectures (same as -arch list)
31
+ -TPonly print only the throughput (with -per: also cycles per element; with -whatif: one
32
+ "variant cycles" line per variant)
33
+ -per N the loop does N elements (bytes, floats, ...) per iteration: also print cycles per element
34
+ (what-if values too)
35
+ -whatif the what-if variants (unrolled, N accumulators, front end, fusion) per microarchitecture
36
+ -json print the response as JSON
37
+ -trace with -json: include the cycle-by-cycle events (large)
38
+ -details with -json: include the details (allowed ports, latencies, port set, issue slots)
39
+
40
+ Simulation (as in uiCA):
41
+ -alignmentOffset N alignment offset relative to a 64-byte cache line (default: 0; objdump input: from the
42
+ loop's address)
43
+ -initPolicy P initial register state: diff (default), same, stack
44
+ -simpleFrontEnd simulate a front end that is only limited by the issue width
45
+ -noMicroFusion, -noMacroFusion
46
+ -minIterations N simulate at least N iterations (default: 10)
47
+ -minCycles N simulate at least N cycles (default: 500)
48
+
49
+ Other:
50
+ -threads N with several microarchitectures: analyze them on up to N threads (default: the environment
51
+ variable WUICA_THREADS, else one thread per two microarchitectures; 1 = one after another)
52
+ -data DIR directory with uarch.json and arch/*.json (default: the tables in the package)
53
+ -h, --help this text
54
+ -v, --version the version (with -json: also the uiCA commit of the data and model)
55
+
56
+ Exit status: 0 ok, 1 bad request or usage, 2 assembler error, 3 the analysis failed for this input; with several
57
+ microarchitectures, the largest of their codes (also the JSON's "code"). A reader that closes the output early
58
+ (| head) does not change it.
59
+
60
+ Throughput is in cycles per iteration of the loop as written (a compiler's unrolled loop does several elements per
61
+ iteration: -per N). A block that ends with a branch is analyzed as a loop, otherwise as if repeated back to back.
62
+ Assumes all data in L1 and no branch mispredictions. "-" in a table means unknown. ZEN3, ADL-P and ICX are
63
+ prototype models (from the fork jtl06/uiCA), less validated than the Intel models of uiCA.`;
64
+
65
+ export const MCP_USAGE = `Usage: wuica-mcp (or: wuica mcp)
66
+
67
+ The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, compare_archs, assemble.
68
+ Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli mcp"). Options: --help, --version.
69
+ `;
70
+
71
+ class UsageError extends Error {}
72
+
73
+ // flag (lower case, without dashes) -> [canonical, takes a value]
74
+ const FLAGS = {
75
+ h: ['help'], help: ['help'], v: ['version'], version: ['version'],
76
+ arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
77
+ loop: ['loop', 1], loops: ['loops'], func: ['func', 1], per: ['per', 1], whatif: ['whatif'], threads: ['threads', 1],
78
+ tponly: ['tpOnly'], json: ['json'], trace: ['trace'], details: ['details'],
79
+ alignmentoffset: ['alignmentOffset', 1], initpolicy: ['initPolicy', 1], simplefrontend: ['simpleFrontEnd'],
80
+ nomicrofusion: ['noMicroFusion'], nomacrofusion: ['noMacroFusion'], miniterations: ['minIterations', 1], mincycles: ['minCycles', 1],
81
+ };
82
+
83
+ export function parseArgs(argv) {
84
+ const o = { arch: 'SKL', options: {}, input: null, syntax: 'auto' };
85
+ const int = (s, name) => {
86
+ if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
87
+ return Number(s);
88
+ };
89
+ for (let i = 0; i < argv.length; i++) {
90
+ const a = argv[i];
91
+ if (!a.startsWith('-') || a === '-') {
92
+ if (o.input !== null) throw new UsageError(`more than one input: ${o.input}, ${a} (one input per run)`);
93
+ o.input = a;
94
+ continue;
95
+ }
96
+ const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
97
+ const f = FLAGS[m[1].toLowerCase()];
98
+ if (!f) throw new UsageError(`unknown option ${a}`);
99
+ const [name, takes] = f;
100
+ let v = m[2];
101
+ if (takes && v === undefined) { if (i + 1 >= argv.length) throw new UsageError(`-${name} needs a value`); v = argv[++i]; }
102
+ if (!takes && v !== undefined) throw new UsageError(`-${name} takes no value`);
103
+ switch (name) {
104
+ case 'att': case 'intel': o.syntax = name; break;
105
+ case 'loop': o.loop = /^\d+$/.test(v) ? Number(v) : v; break;
106
+ case 'per': o.per = Number(v); if (!(o.per > 0)) throw new UsageError(`-per: a positive number of elements per iteration: ${v}`); break;
107
+ case 'threads': o.threads = int(v, name); if (o.threads < 1) throw new UsageError('-threads: at least 1'); break;
108
+ case 'trace': o.options.includeTrace = true; break;
109
+ case 'details': o.options.details = true; break;
110
+ case 'alignmentOffset': case 'minIterations': case 'minCycles': o.options[name] = int(v, name); break;
111
+ case 'initPolicy': o.options.initPolicy = v; break;
112
+ case 'simpleFrontEnd': case 'noMicroFusion': case 'noMacroFusion': o.options[name] = true; break;
113
+ default: o[name] = takes ? v : true;
114
+ }
115
+ }
116
+ o.arch = o.arch.trim();
117
+ if (o.arch.toLowerCase() === 'list') o.list = true;
118
+ // several microarchitectures: all, or a comma-separated list
119
+ if (o.arch.toLowerCase() === 'all') o.archs = [];
120
+ else if (o.arch.includes(',')) {
121
+ o.archs = o.arch.split(',').map((x) => x.trim()).filter((x) => x !== '');
122
+ if (o.archs.length === 0) throw new UsageError(`-arch: no microarchitecture in "${o.arch}"`);
123
+ if (o.archs.some((x) => x.toLowerCase() === 'all')) throw new UsageError('-arch: "all" cannot be part of a list');
124
+ }
125
+ return o;
126
+ }
127
+
128
+ async function readStdin(stdin) {
129
+ const chunks = [];
130
+ for await (const c of stdin) chunks.push(typeof c === 'string' ? Buffer.from(c) : c);
131
+ return Buffer.concat(chunks).toString('utf8');
132
+ }
133
+
134
+ // The format of a file that is not bare machine code, from its first bytes, or null.
135
+ export function binaryFormat(b) {
136
+ const at = (i, ...xs) => xs.every((x, k) => b[i + k] === x);
137
+ if (at(0, 0x7f, 0x45, 0x4c, 0x46)) return 'an ELF file';
138
+ if (at(0, 0xcf, 0xfa, 0xed, 0xfe) || at(0, 0xce, 0xfa, 0xed, 0xfe) || at(0, 0xfe, 0xed, 0xfa, 0xcf) || at(0, 0xfe, 0xed, 0xfa, 0xce) || at(0, 0xca, 0xfe, 0xba, 0xbe)) return 'a Mach-O file';
139
+ if (at(0, 0x21, 0x3c, 0x61, 0x72, 0x63, 0x68, 0x3e, 0x0a)) return 'an archive (.a)';
140
+ if (at(0, 0x4d, 0x5a)) return 'a PE (Windows) executable';
141
+ if (at(0, 0x64, 0x86) && b.length >= 20) return 'a COFF object file';
142
+ return null;
143
+ }
144
+ // mostly printable text
145
+ const looksText = (b) => b.length > 0 && [...b.subarray(0, 4096)].filter((x) => x === 9 || x === 10 || x === 13 || (x >= 32 && x < 127)).length >= 0.95 * Math.min(b.length, 4096);
146
+
147
+ // Reads a file for -raw or as the input: its bytes, or a UsageError that says what is wrong.
148
+ function readFile(file) {
149
+ let st;
150
+ try { st = fs.statSync(file); } catch { throw new UsageError(`no such file: ${file}`); }
151
+ if (st.isDirectory()) throw new UsageError(`${file} is a directory, not a file`);
152
+ return fs.readFileSync(file);
153
+ }
154
+
155
+ // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
156
+ async function readInput(o, io) {
157
+ const notes = [];
158
+ if (o.raw !== undefined) {
159
+ if (o.input !== null) throw new UsageError(`-raw and an input (${o.input}) cannot be combined`);
160
+ const b = readFile(o.raw);
161
+ const fmt = binaryFormat(b);
162
+ if (fmt) throw new UsageError(`${o.raw} is ${fmt}, not bare machine code: disassemble it and pipe the listing (objdump -d ${o.raw} | wuica)`);
163
+ if (looksText(b)) notes.push(`warning: ${o.raw} looks like text, not machine code (without -raw it is read as assembly)`);
164
+ return { request: { hex: b.toString('hex') }, name: o.raw, notes };
165
+ }
166
+ let text, name;
167
+ if (o.input === null || o.input === '-') {
168
+ if (o.input === null && io.stdin.isTTY) throw new UsageError('no input');
169
+ text = await readStdin(io.stdin);
170
+ name = '<stdin>';
171
+ } else if (fs.existsSync(o.input)) {
172
+ text = readFile(o.input).toString('utf8');
173
+ name = o.input;
174
+ } else if (normalizeHex(o.input) !== null) {
175
+ const n = normalizeHex(o.input).length / 2;
176
+ notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
177
+ return { request: { hex: o.input }, name: 'the argument', notes };
178
+ } else {
179
+ readFile(o.input); // the error
180
+ }
181
+ if (o.hex) return { request: { hex: text }, name, notes };
182
+ return { request: { source: text, syntax: o.syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name, notes };
183
+ }
184
+
185
+ const fmt = (x) => Number(x).toFixed(2);
186
+ // cycles per element: 3 significant digits under 0.1 (0.0625, 0.0313), else as fmt
187
+ const fmtEl = (x) => (x !== 0 && Math.abs(x) < 0.1 ? Number(x).toPrecision(3) : fmt(x));
188
+ const MAX_ERRORS = 10;
189
+
190
+ function printList(w, o, out) {
191
+ const archs = w.archs();
192
+ if (o.json) { out.write(JSON.stringify(archs, null, 1) + '\n'); return; }
193
+ const width = Math.max(...archs.map((a) => a.id.length));
194
+ for (const a of archs) out.write(`${a.id.padEnd(width)} ${a.name}${a.year ? ` (${a.year})` : ''}${a.prototype ? ' [prototype]' : ''}\n`);
195
+ }
196
+
197
+ // stderr lines with the input's name for <input>; after MAX_ERRORS errors (each with its source and caret lines), one
198
+ // line for the rest
199
+ function printStderr(r, err, name) {
200
+ let errors = 0, skipping = false;
201
+ const hints = [];
202
+ for (const l of r.stderr ?? []) {
203
+ if (/^hint: /.test(l.text)) { hints.push(l.text); continue; } // last, after the count of the errors left out
204
+ if (l.tag?.severity === 'error') { errors++; skipping = errors > MAX_ERRORS; }
205
+ else if (l.tag) skipping = false;
206
+ if (!skipping) err.write(String(l.text).replace(/^<input>:/, `${name}:`) + '\n');
207
+ }
208
+ if (errors > MAX_ERRORS) err.write(`… and ${errors - MAX_ERRORS} more error${errors - MAX_ERRORS === 1 ? '' : 's'}\n`);
209
+ for (const h of hints) err.write(`${h}\n`);
210
+ }
211
+
212
+ // What of the text was analyzed, the syntax, the other loops; the alignment offset from addresses.
213
+ function printAnalyzed(r, err, o) {
214
+ const p = r.loop;
215
+ const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
216
+ if (p && p.line) {
217
+ const others = (p.count ?? 1) - (Number.isInteger(p.index) ? 1 : 0);
218
+ err.write(`analyzed: ${p.name} (lines ${p.line}-${p.endLine}${p.function ? `, in ${p.function}` : ''}${p.address !== undefined ? `, address 0x${p.address.toString(16)}` : ''})${syn ? `, ${syn}` : ''}`
219
+ + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
220
+ } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
221
+ err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
222
+ }
223
+ if (p && p.alignmentOffset !== undefined && o.options.alignmentOffset === undefined) err.write(`alignment offset ${p.alignmentOffset} (from the addresses)\n`);
224
+ }
225
+
226
+ // The registers a loop advances by a constant and uses in an address or a compare, with what the step counts: "rcx +=
227
+ // 8 per iteration (index; ×4 bytes in [rdi+rcx*4])" (an index register: elements of that size), "r13 += 64 per iteration
228
+ // (bytes; the base of [r13+0x20])", or "(register step)" when no address says (a counter only compared).
229
+ export function inductionSteps(r) {
230
+ if (r?.mode !== 'loop') return [];
231
+ const step = new Map(), other = new Set(), used = new Set(), unit = new Map();
232
+ for (const x of r.rows ?? []) {
233
+ if (x.kind !== 'instr') continue;
234
+ const t = String(x.label).trim().toLowerCase().replace(/\s+/g, ' ');
235
+ const [mn, rest = ''] = t.split(/ (.*)/);
236
+ const ops = rest.split(',').map((s) => s.trim());
237
+ for (const m of t.matchAll(/\[([^\]]*)\]/g)) {
238
+ const regs = m[1].split(/[+-]/).map((p) => p.trim()).filter((p) => /^[a-z]\w*(?:\*\d)?$/.test(p) && !/^0x/.test(p));
239
+ regs.forEach((p, k) => {
240
+ const [reg, scale] = p.split('*');
241
+ used.add(reg);
242
+ if (unit.has(reg)) return;
243
+ // the first register without a scale is the base (bytes); a scaled one is an index (elements of that size)
244
+ if (scale && scale !== '1') unit.set(reg, `index; ×${scale} bytes in [${m[1]}]`);
245
+ else unit.set(reg, k === 0 && !scale ? `bytes; the base of [${m[1]}]` : `bytes; the index of [${m[1]}]`);
246
+ });
247
+ }
248
+ if (mn === 'cmp' || mn === 'test') for (const op of ops) used.add(op);
249
+ const reg = /^(?:r(?:[abcd]x|[sd]i|bp|[89]|1[0-5]))$/.test(ops[0]) ? ops[0] : null;
250
+ if (!reg) continue;
251
+ const imm = /^-?(?:0x[0-9a-f]+|\d+)$/.test(ops[1] ?? '') ? Number(ops[1].startsWith('-') ? -Number(ops[1].slice(1)) : Number(ops[1])) : null;
252
+ if (mn === 'add' && imm !== null) step.set(reg, (step.get(reg) ?? 0) + imm);
253
+ else if (mn === 'sub' && imm !== null) step.set(reg, (step.get(reg) ?? 0) - imm);
254
+ else if (mn === 'inc' && ops.length === 1) step.set(reg, (step.get(reg) ?? 0) + 1);
255
+ else if (mn === 'dec' && ops.length === 1) step.set(reg, (step.get(reg) ?? 0) - 1);
256
+ else if (!['cmp', 'test', 'push', 'bt'].includes(mn)) other.add(reg); // written otherwise
257
+ }
258
+ return [...step].filter(([reg, s]) => s !== 0 && !other.has(reg) && used.has(reg)).map(([reg, s]) => `${reg} ${s < 0 ? '-=' : '+='} ${Math.abs(s)} per iteration (${unit.get(reg) ?? 'register step'})`);
259
+ }
260
+ const stepLine = (steps) => `step: ${steps.join(', ')}; -per N (N elements per iteration): cycles per element\n`;
261
+
262
+ // The diagnosis after the report: the nearest limit when uiCA names no bottleneck, the next limit, the caveats.
263
+ function diagnosis(ins, r) {
264
+ const lines = [];
265
+ if (!ins) return lines;
266
+ if (ins.largest) lines.push(`Bottleneck: unknown (nearest ${ins.largest.join(', ')} ${fmt(Math.max(...r.limits.filter((l) => ins.largest.includes(l.name)).map((l) => l.tp)))}${ins.unexplained ? `; ${fmt(ins.unexplained)} cycles/iteration no single limit explains` : ''})`);
267
+ else if (ins.next && ins.binding.length) lines.push(`Next limit: ${ins.next.limit} ${fmt(ins.next.tp)} (at most ${fmt(ins.next.maxSpeedup)}x faster without ${ins.binding.join(', ')})`);
268
+ for (const c of ins.caveats ?? []) lines.push(`Not modelled: ${c.text}: ${c.title}`);
269
+ return lines;
270
+ }
271
+
272
+ // A what-if result with cycles per element (-per N): elementsPerIteration and perElement on it, perElement on each
273
+ // variant with a tp.
274
+ function whatIfPer(x, per) {
275
+ if (!per || x.code) return x;
276
+ return { ...x, elementsPerIteration: per, perElement: x.tp / per, variants: x.variants.map((v) => (v.tp !== undefined ? { ...v, perElement: v.tp / per } : v)) };
277
+ }
278
+
279
+ const VARIANT_W = 18;
280
+ function whatIfTable(x) {
281
+ const per = x.elementsPerIteration;
282
+ const f = per ? (v) => fmtEl(v / per) : fmt;
283
+ const rows = x.variants.map((v) => (v.error ? ` ${v.label.padEnd(VARIANT_W)} ${'-'.padStart(8)} ${v.error}`
284
+ : ` ${v.label.padEnd(VARIANT_W)} ${`${v.estimate ? '>=' : ''}${f(v.tp)}`.padStart(8)} ${`${v.delta > 0 ? '+' : ''}${f(v.delta)}`.padStart(8)} ${`${fmt(v.speedup ?? 0)}x`.padStart(7)}`));
285
+ return [per ? `What if (${x.arch}), cycles per element (${per} per original iteration; base ${fmtEl(x.tp / per)}):` : `What if (${x.arch}), cycles per original iteration (base ${fmt(x.tp)}):`,
286
+ ` ${'variant'.padEnd(VARIANT_W)} ${'cycles'.padStart(8)} ${'delta'.padStart(8)} ${'speedup'.padStart(7)}`, ...rows,
287
+ ...(x.accumulators ? [` best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}`] : [])].join('\n') + '\n';
288
+ }
289
+ // -TPonly -whatif: one "variant cycles [per element]" line per variant (prefix: the CPU, with several)
290
+ function whatIfTerse(x, prefix = '') {
291
+ if (x.code) return `${prefix}what-if error: ${x.error}\n`;
292
+ return x.variants.map((v) => `${prefix}${v.id} ${v.error ? 'error' : `${fmt(v.tp)}${v.perElement !== undefined ? ` ${fmtEl(v.perElement)}` : ''}`}\n`).join('');
293
+ }
294
+
295
+ // argv: the arguments after the program name. io: {stdin, stdout, stderr}. Returns the exit code: the result's
296
+ // `code` (0 ok, 1 bad request or usage, 2 assembler error, 3 analysis error).
297
+ export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
298
+ const { stdout: out, stderr: err } = io;
299
+ let o = null;
300
+ const fail = (code, msg) => {
301
+ if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
302
+ else err.write(`${msg}\n`);
303
+ return code;
304
+ };
305
+ try {
306
+ o = parseArgs(argv);
307
+ if (o.help) { out.write(USAGE + '\n'); return 0; }
308
+ if (o.version) {
309
+ // -json: with the uiCA reference whose data and model this is (dist/manifest.json, from ci/data-asset.txt)
310
+ if (o.json) {
311
+ let uiCA = null;
312
+ try { uiCA = JSON.parse(fs.readFileSync(new URL('../dist/manifest.json', import.meta.url), 'utf8')).uiCA ?? null; } catch { /* not built */ }
313
+ out.write(JSON.stringify({ wuica: VERSION, uiCA, node: process.versions.node }) + '\n');
314
+ } else out.write(`wuica ${VERSION}\n`);
315
+ return 0;
316
+ }
317
+ const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}), ...(o.threads ? { threads: o.threads } : {}) });
318
+ if (o.list) { printList(w, o, out); return 0; }
319
+ // the microarchitectures before the input (stdin is not read for a mistyped name)
320
+ const names = o.archs ?? [o.arch];
321
+ const unknown = names.filter((a) => !w.resolveArch(a));
322
+ if (unknown.length) return fail(CODES.REQUEST, `unknown microarchitecture${unknown.length > 1 ? 's' : ''}: ${unknown.join(', ')} (known: ${w.archs('id').map((a) => a.id).join(', ')})`);
323
+ if (o.options.details && (!o.json || o.archs)) err.write('-details: shown only with -json and one microarchitecture; ignored\n');
324
+ if (o.options.includeTrace && (!o.json || o.archs)) { err.write('-trace: shown only with -json and one microarchitecture; ignored\n'); delete o.options.includeTrace; }
325
+ const input = await readInput(o, io);
326
+ for (const n of input.notes) err.write(`${n}\n`);
327
+ const req = { ...input.request, options: o.options };
328
+
329
+ if (o.loops) {
330
+ if (!req.source) return fail(CODES.REQUEST, '-loops: needs assembly (not machine code)');
331
+ const ls = listLoops(req.source, { func: o.func ?? null });
332
+ if (ls.error) return fail(CODES.REQUEST, ls.error);
333
+ if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
334
+ if (!ls.length) { out.write('no loops\n'); return 0; }
335
+ const lw = Math.max(5, ...ls.map((l) => l.label.length)), fw = Math.max(8, ...ls.map((l) => String(l.function ?? '-').length));
336
+ out.write(`${'#'.padStart(3)} ${'label'.padEnd(lw)} ${'function'.padEnd(fw)} ${'lines'.padEnd(9)} instrs depth\n`);
337
+ for (const l of ls) out.write(`${String(l.index).padStart(3)} ${l.label.padEnd(lw)} ${String(l.function ?? '-').padEnd(fw)} ${`${l.line}-${l.endLine}`.padEnd(9)} ${String(l.instructions).padStart(6)} ${String(l.depth).padStart(5)}${l.auto ? ' auto' : ''}\n`);
338
+ out.write('\n-loop N (0-based) or -loop LABEL analyzes one; "auto" is what runs without -loop.\n');
339
+ return 0;
340
+ }
341
+ const per = (tp) => (o.per ? tp / o.per : undefined);
342
+ const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
343
+ const whatIfs = async (archs) => {
344
+ const res = {};
345
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
346
+ return res;
347
+ };
348
+
349
+ if (o.archs) {
350
+ const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}) });
351
+ const status = c.code || Math.max(0, ...(c.results ?? []).map((r) => r.code));
352
+ if (c.code) {
353
+ if (o.json) { out.write(JSON.stringify(c) + '\n'); return status; }
354
+ printStderr(c, err, input.name);
355
+ return status;
356
+ }
357
+ // the caveats per CPU: one analysis for the instructions, each CPU's configuration (the split-load cost)
358
+ const first = c.results.find((r) => r.code === 0);
359
+ const base = !o.tpOnly && first ? await w.analyze(first.arch, req) : null;
360
+ const insOf = (r) => (base?.code === 0 && r.code === 0 ? w.insights({ ...base, arch: r.arch, tp: r.tp, limits: r.limits, bottlenecks: r.bottlenecks }) : null);
361
+ const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
362
+ const wi = o.whatif ? await whatIfs(c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
363
+ if (o.json) {
364
+ const results = c.results.map((r, k) => ({ ...r, ...(extra[k].per !== undefined ? { perElement: extra[k].per } : {}), ...(extra[k].ins?.caveats ? { caveats: extra[k].ins.caveats } : {}) }));
365
+ out.write(JSON.stringify({ ...c, code: status, results, ...(wi ? { whatIf: wi } : {}) }) + '\n');
366
+ return status;
367
+ }
368
+ printStderr(c, err, input.name);
369
+ printAnalyzed(c, err, o);
370
+ const kw = Math.max(4, ...c.results.map((r) => r.arch.length));
371
+ const nw = Math.max(5, ...c.results.map((r) => r.name.length));
372
+ const bns = c.results.map((r, k) => (r.code ? `error: ${r.error.split('\n')[0]}` : r.bottlenecks.join(', ') || (extra[k].ins?.largest ? `- (nearest ${extra[k].ins.largest.join(', ')})` : '-')));
373
+ // the Bottlenecks column as wide as its widest entry (an error's message, the last thing on its row, not counted)
374
+ const bw = Math.max(11, ...bns.filter((b, k) => !c.results[k].code).map((b) => b.length));
375
+ if (!o.tpOnly) out.write(`${'Arch'.padEnd(kw)} ${'Model'.padEnd(nw)} Year ${'TP'.padStart(6)}${o.per ? ` ${'per el'.padStart(6)}` : ''} ${'Bottlenecks'.padEnd(bw)} Notes\n`);
376
+ c.results.forEach((r, k) => {
377
+ const { ins, per: pe } = extra[k];
378
+ if (o.tpOnly) {
379
+ out.write(`${r.arch.padEnd(kw)} ${r.code ? 'error' : fmt(r.tp)}${pe !== undefined ? ` ${fmtEl(pe)}` : ''}\n`);
380
+ if (wi?.[r.arch]) out.write(whatIfTerse(wi[r.arch], `${r.arch.padEnd(kw)} `));
381
+ return;
382
+ }
383
+ const year = String(r.year ?? '').padEnd(4);
384
+ const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors ? '*' : ''}`).padStart(6);
385
+ const notes = [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
386
+ out.write(`${r.arch.padEnd(kw)} ${r.name.padEnd(nw)} ${year} ${tp}${o.per ? ` ${(pe !== undefined ? fmtEl(pe) : '-').padStart(6)}` : ''} ${bns[k].padEnd(bw)}${notes ? ` ${notes}` : ''}`.trimEnd() + '\n');
387
+ });
388
+ if (!o.tpOnly) {
389
+ out.write(`\nTP: cycles per iteration${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown. *: some instructions could not be decoded for that CPU and are left out.\n`);
390
+ if (c.results.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
391
+ if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
392
+ for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
393
+ }
394
+ return status;
395
+ }
396
+
397
+ const r = await w.analyze(o.arch, req);
398
+ const ins = r.code === 0 ? w.insights(r) : null;
399
+ const wi = o.whatif && r.code === 0 ? await whatIfs([o.arch]) : null;
400
+ if (o.json) {
401
+ out.write(JSON.stringify(r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) }) + '\n');
402
+ return r.code;
403
+ }
404
+ printStderr(r, err, input.name);
405
+ if (r.code) return r.code;
406
+ printAnalyzed(r, err, o);
407
+ if (o.tpOnly) {
408
+ out.write(`${fmt(r.tp)}${o.per ? ` ${fmtEl(per(r.tp))}` : ''}\n`);
409
+ for (const x of Object.values(wi ?? {})) out.write(whatIfTerse(x));
410
+ return 0;
411
+ }
412
+ // uiCA's "Bottleneck: unknown" line says what is nearest (the diagnosis's first line)
413
+ const d = diagnosis(ins, r);
414
+ let text = r.text;
415
+ if (ins?.largest && /^Bottleneck: unknown$/m.test(text)) text = text.replace(/^Bottleneck: unknown$/m, d.shift());
416
+ out.write(text);
417
+ if (o.per) d.push(`Per element: ${fmtEl(per(r.tp))} cycles (${fmt(r.tp)} cycles/iteration, ${o.per} elements per iteration)`);
418
+ if (d.length) out.write(`\n${d.join('\n')}\n`);
419
+ const steps = !o.per ? inductionSteps(r) : [];
420
+ if (steps.length) err.write(stepLine(steps));
421
+ for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
422
+ return 0;
423
+ } catch (e) {
424
+ if (e instanceof UsageError) {
425
+ if (e.message === 'no input') { err.write(`${USAGE}\n`); return 1; }
426
+ return o?.json ? fail(1, `wuica: ${e.message}`) : (err.write(`wuica: ${e.message}\nRun "wuica -h" for the options.\n`), 1);
427
+ }
428
+ return fail(1, `wuica: ${e?.message ?? e}`);
429
+ }
430
+ }
package/lib/core.js ADDED
@@ -0,0 +1,36 @@
1
+ // The result shapes that the library's main thread and its worker threads (threads.js) both build, so that a compare()
2
+ // gives the same rows whichever thread analyzed a microarchitecture.
3
+
4
+ /** Result codes (`code`), like an exit status: 0 = success. */
5
+ export const CODES = Object.freeze({ OK: 0, REQUEST: 1, ASSEMBLER: 2, ANALYSIS: 3 });
6
+
7
+ // A failed call: {code, error, stderr}, stderr as in Compiler Explorer (one entry per line, `tag` on positioned ones).
8
+ export function failure(code, error, stderr = [{ text: error }], extra = {}) {
9
+ return { code, error, stderr, ...extra };
10
+ }
11
+
12
+ // The failure when a microarchitecture's instruction table cannot be loaded.
13
+ export function tableFailure(id, e) {
14
+ return failure(CODES.ANALYSIS, `could not load the instruction table for ${id}: ${e.message}`);
15
+ }
16
+
17
+ // The analyzer's response (Analyzer.analyze) as a library result: the response itself, or a failure.
18
+ export function analysisResult(r) {
19
+ if (r.error) return failure(CODES.ANALYSIS, r.error, undefined, r.trapped ? { trapped: true } : {});
20
+ return r;
21
+ }
22
+
23
+ // The fields of a compare() row taken from an analysis result (after arch, name, year, prototype).
24
+ export function compareFields(r) {
25
+ if (r.code !== undefined) return { code: r.code, error: r.error };
26
+ return { code: CODES.OK, tp: r.tp, mode: r.mode, bottlenecks: r.bottlenecks, limits: r.limits, decodeErrors: r.decodeErrors };
27
+ }
28
+
29
+ // A block for warming up the analyzer: ~500 instructions of several kinds in a loop (a 24-instruction mix, 20 times;
30
+ // ~10 ms). V8 compiles the module's functions when they are first called, with its baseline compiler, and optimizes the
31
+ // hot ones in the background later: after one analysis of this block, the first analysis of a large block runs at
32
+ // nearly full speed (docs/PORTING.md, "Speed").
33
+ const WARM_MIX = '4883c001' + '488906' + '8b06' + 'c4e2d5aaf4' + '4c03d1' + '4d0fafc0' + 'c5fc100c87' + 'c4e27da80c86' + 'c5fc110c86'
34
+ + 'f3480fb80cc7' + '4801ca' + 'f2480f38f104cf' + '660f6f0f' + '660f74c8' + '660fd7c1' + '488b00' + 'c4626db8c0' + '4839d0'
35
+ + '4883c708' + '4c8d0c49' + '48c1e005' + '4421c0' + 'c5f857c0' + '488d0c0a';
36
+ export const WARM_HEX = WARM_MIX.repeat(20) + '49ffcf' + '0f853bf8ffff'; // dec r15; jnz to the start
package/lib/details.js ADDED
@@ -0,0 +1,60 @@
1
+ // The details of an analysis ("details": true; docs/WASM-API.md) in the compact form (summarize(), the MCP `analyze`
2
+ // JSON): per instruction its allowed ports in uops.info's notation, its latencies and front-end facts; the port set behind
3
+ // the Ports limit with the instructions that load it; the issue slots per cause. As the web page shows them (web/js/
4
+ // details.js, portset.js, slots.js); tests-js/web_details.mjs checks that they agree.
5
+
6
+ // "1*p0156+1*p23"; non-Intel port names listed: "1*[ALU0 ALU1]"
7
+ export function portString(portData) {
8
+ if (!Array.isArray(portData) || !portData.length) return '';
9
+ return portData.map((p) => {
10
+ const names = p.ports ?? [];
11
+ const intel = names.every((n) => /^Port \w$/.test(n));
12
+ return `${p.uops}*${intel ? 'p' + names.map((n) => n.slice(5)).join('') : `[${names.join(' ')}]`}`;
13
+ }).join('+');
14
+ }
15
+
16
+ // the latencies per (input, output) pair, without the flag outputs of an instruction that writes a register too
17
+ export function latencyPairs(det) {
18
+ const all = Array.isArray(det?.latencies) ? det.latencies : [];
19
+ const isFlags = (x) => String(x).startsWith('flags');
20
+ const regOut = all.some((l) => !isFlags(l.to));
21
+ const out = [];
22
+ for (const l of all) {
23
+ if (regOut && isFlags(l.to)) continue;
24
+ if (!out.some((x) => x.from === l.from && x.to === l.to)) out.push(l);
25
+ }
26
+ return out;
27
+ }
28
+
29
+ const round = (x) => Math.round(x * 100) / 100;
30
+
31
+ // the fields one instruction of the compact form gets
32
+ export function instrDetails(det) {
33
+ if (!det) return null;
34
+ const out = { allowedPorts: portString(det.portData), uops: det.uops, fusedUops: det.retireSlots };
35
+ if (det.uopsMS) out.msUops = det.uopsMS;
36
+ const lat = latencyPairs(det);
37
+ if (lat.length) out.latencies = lat.map((l) => `${l.from}->${l.to}:${l.cycles}`);
38
+ const fe = { length: det.length, offset: det.offset };
39
+ if (det.crosses?.length) fe.crosses = det.crosses;
40
+ for (const k of ['lcp', 'microcoded', 'complexDecoder', 'macroFusedWithNext', 'macroFusedWithPrev']) if (det[k]) fe[k] = true;
41
+ out.frontEnd = fe;
42
+ return out;
43
+ }
44
+
45
+ // {portSet, issueSlots} for insights (either may be absent)
46
+ export function detailInsights(r) {
47
+ const d = r?.details;
48
+ if (!d) return {};
49
+ const out = {};
50
+ if (d.ports && Array.isArray(d.ports.rows)) {
51
+ const instructions = d.ports.rows.map((uops, index) => ({ index, instr: r.rows[index]?.label, uops: round(uops) })).filter((x) => x.uops > 0)
52
+ .sort((a, b) => b.uops - a.uops || a.index - b.index);
53
+ out.portSet = { ports: d.ports.ports, uops: round(d.ports.uops), cycles: round(d.ports.tp), instructions };
54
+ }
55
+ if (d.issue?.slots) {
56
+ const s = d.issue.slots;
57
+ out.issueSlots = { width: d.issue.width, perIteration: { issued: s.issued, frontEnd: s.frontEnd, rob: s.rob, rs: s.rs, other: s.other } };
58
+ }
59
+ return out;
60
+ }
package/lib/files.js ADDED
@@ -0,0 +1,18 @@
1
+ // Reading the package's files (shared by the library and its worker threads).
2
+
3
+ import fs from 'node:fs/promises';
4
+ import zlib from 'node:zlib';
5
+ import { promisify } from 'node:util';
6
+
7
+ const brotli = promisify(zlib.brotliDecompress);
8
+
9
+ // Reads a file; `.br` files are decompressed. For a path without `.br`, `<path>.br` is tried first.
10
+ export async function readMaybeCompressed(file) {
11
+ if (file.endsWith('.br')) return new Uint8Array(await brotli(await fs.readFile(file)));
12
+ try {
13
+ return new Uint8Array(await brotli(await fs.readFile(file + '.br')));
14
+ } catch (e) {
15
+ if (e.code !== 'ENOENT') throw e;
16
+ }
17
+ return new Uint8Array(await fs.readFile(file));
18
+ }