wuica-cli 0.1.9 → 0.1.12

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/lib/cli.js CHANGED
@@ -3,17 +3,22 @@
3
3
 
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, CODES, examples, findExample, objectKind } from './index.js';
6
+ import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, WHAT_IF_OPT_IN_VARIANTS, CODES, examples, findExample, objectKind, markdown } from './index.js';
7
+ import { analyzedLines } from './web/branch-label.js';
8
+ import { whatIfPerElement, whatIfText } from './web/whatif-core.js';
9
+ import { diffAnalyses, diffMarkdown, diffText } from './web/block-diff.js';
7
10
 
8
11
  export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
9
12
 
10
13
  export const USAGE = `Usage: wuica [options] [FILE | - | HEX]
14
+ wuica diff [options] A B two blocks (files, - or hex) on one CPU: throughput, bottlenecks, ports, instructions
15
+ changed; -per N or -per A,B (per element), -md, -json, -arch NAME, -loop, the options
11
16
  wuica [options] FILE FILE... several inputs in one run: one table (-files LIST reads the names from a file)
12
17
  wuica mcp start the MCP server (stdio)
13
18
 
14
19
  Predicts the throughput of an x86-64 basic block with uiCA's pipeline model (this is wuica ${VERSION}, a WebAssembly
15
- port of uiCA). One input per run: assembly from FILE (gcc -S, clang -S, objdump -d output, or a hand-written loop),
16
- or from stdin if FILE is - or missing. A HEX argument that is not a file (e.g. 4801d84801c349ffcf75f5) is machine code.
20
+ port of uiCA). Input: assembly from FILE (gcc -S, clang -S, objdump -d or -dS, perf annotate --stdio, a hand-written
21
+ loop), or stdin if FILE is - or missing; several FILEs: one table. A HEX argument that is not a file is machine code.
17
22
  Built-in examples (no file needed): -examples lists them, -example saxpy analyzes one (every option applies),
18
23
  -example saxpy -show prints its assembly to save and edit.
19
24
 
@@ -31,9 +36,12 @@ Input:
31
36
  -raw FILE read the machine code from a binary file that contains only the code (not an object
32
37
  file: for those, objdump -d FILE | wuica)
33
38
  -loops list the loops of the assembly (index, label, function, lines, instructions, depth, auto)
34
- -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
35
- "Inner Loop Header" notes count), whole (all the text), a loop's index (0-based, as
36
- -loops lists them) or its label (-loop .LBB0_12)
39
+ -loop L what is analyzed: auto (default: of the deepest innermost loops in the function of
40
+ the first of them, the one with the widest vector registers, then the most vector
41
+ instructions, then the most instructions, then the first; clang's "Inner Loop
42
+ Header" notes count; perf annotate: the loop with the most samples of its own),
43
+ whole (all the text), a loop's index (0-based, as -loops lists them) or its label
44
+ (-loop .LBB0_12)
37
45
  -func NAME only the loops of function NAME (with -loop: its index or label among them); in an object
38
46
  file its symbol, or a unique part of it
39
47
  -funcs list the functions of an object file (name, section, address, size)
@@ -49,6 +57,11 @@ Output:
49
57
  -per N the loop does N elements (bytes, floats, ...) per iteration: also print cycles per element
50
58
  (what-if values too)
51
59
  -whatif the what-if variants (unrolled, N accumulators, front end, fusion) per microarchitecture
60
+ -variants LIST with -whatif (implied): these variants only, comma-separated; also align (the 64 alignment
61
+ offsets: min, median, max, best and worst offset; 64 analyses, not in the default set)
62
+ -md print GitHub-flavoured Markdown instead of the text report (for an issue, a review, a
63
+ chat): the result with its uop table, the CPU table, the what-if and loop tables; not with
64
+ -json or -TPonly
52
65
  -json print the response as JSON
53
66
  -trace with -json: include the cycle-by-cycle events (large)
54
67
  -details with -json: include the details (allowed ports, latencies, port set, issue slots)
@@ -81,7 +94,8 @@ prototype models (from the fork jtl06/uiCA), less validated than the Intel model
81
94
 
82
95
  export const MCP_USAGE = `Usage: wuica-mcp (or: wuica mcp)
83
96
 
84
- The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, compare_archs, assemble.
97
+ The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, diff_blocks, compare_archs, list_loops,
98
+ assemble.
85
99
  Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli mcp"). Options: --help, --version.
86
100
  `;
87
101
 
@@ -104,12 +118,15 @@ const FLAGS = {
104
118
  examples: ['examples'], example: ['example', 1], show: ['show'], files: ['files', 1], report: ['report'], funcs: ['funcs'],
105
119
  arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
106
120
  loop: ['loop', 1], loops: ['loops'], func: ['func', 1], per: ['per', 1], whatif: ['whatif'], threads: ['threads', 1],
107
- tponly: ['tpOnly'], json: ['json'], trace: ['trace'], details: ['details'],
121
+ tponly: ['tpOnly'], json: ['json'], md: ['md'], variants: ['variants', 1], trace: ['trace'], details: ['details'],
108
122
  alignmentoffset: ['alignmentOffset', 1], initpolicy: ['initPolicy', 1], simplefrontend: ['simpleFrontEnd'],
109
123
  nomicrofusion: ['noMicroFusion'], nomacrofusion: ['noMacroFusion'], miniterations: ['minIterations', 1], mincycles: ['minCycles', 1],
110
124
  };
111
125
 
126
+ /** @typedef {Record<string, any> & {arch: string, options: Record<string, any>, input: string | null, inputs: string[], syntax: string}} CliOptions */
127
+ /** @param {string[]} argv @returns {CliOptions} */
112
128
  export function parseArgs(argv) {
129
+ /** @type {CliOptions} */
113
130
  const o = { arch: 'SKL', options: {}, input: null, inputs: [], syntax: 'auto' };
114
131
  const int = (s, name) => {
115
132
  if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
@@ -124,6 +141,7 @@ export function parseArgs(argv) {
124
141
  continue;
125
142
  }
126
143
  const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
144
+ if (!m) throw new UsageError(`unknown option ${a}`); // "-=x"
127
145
  const f = FLAGS[m[1].toLowerCase()];
128
146
  if (!f) throw new UsageError(`unknown option ${a}`);
129
147
  const [name, takes] = f;
@@ -133,6 +151,15 @@ export function parseArgs(argv) {
133
151
  switch (name) {
134
152
  case 'att': case 'intel': o.syntax = name; break;
135
153
  case 'loop': o.loop = /^\d+$/.test(v) ? Number(v) : v; break;
154
+ case 'variants': {
155
+ o.variants = v.split(',').map((x) => x.trim()).filter(Boolean);
156
+ const known = [...WHAT_IF_VARIANTS, ...WHAT_IF_OPT_IN_VARIANTS];
157
+ if (!o.variants.length) throw new UsageError(`-variants: no variant in "${v}" (known: ${known.join(', ')})`);
158
+ const unknown = o.variants.filter((x) => !known.includes(x));
159
+ if (unknown.length) throw new UsageError(`-variants: unknown variant(s): ${unknown.join(', ')} (known: ${known.join(', ')})`);
160
+ o.whatif = true;
161
+ break;
162
+ }
136
163
  case 'per': o.per = Number(v); if (!(o.per > 0)) throw new UsageError(`-per: a positive number of elements per iteration: ${v}`); break;
137
164
  case 'threads': o.threads = int(v, name); if (o.threads < 1) throw new UsageError('-threads: at least 1'); break;
138
165
  case 'trace': o.options.includeTrace = true; break;
@@ -143,6 +170,7 @@ export function parseArgs(argv) {
143
170
  default: o[name] = takes ? v : true;
144
171
  }
145
172
  }
173
+ if (o.md && (o.json || o.tpOnly)) throw new UsageError(`-md: Markdown instead of the text report; not with ${o.json ? '-json (JSON is its own format)' : '-TPonly (one number per line)'}`);
146
174
  o.arch = o.arch.trim();
147
175
  if (o.arch.toLowerCase() === 'list') o.list = true;
148
176
  // several microarchitectures: all, or a comma-separated list
@@ -183,6 +211,7 @@ function readFile(file) {
183
211
  }
184
212
 
185
213
  // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
214
+ /** @param {CliOptions} o @param {any} io @param {any} [w] @returns {Promise<any>} */
186
215
  async function readInput(o, io, w = null) {
187
216
  const notes = [];
188
217
  if (o.example !== undefined) {
@@ -217,7 +246,7 @@ async function readInput(o, io, w = null) {
217
246
  }
218
247
  text = b.toString('utf8');
219
248
  } else if (normalizeHex(o.input) !== null) {
220
- const n = normalizeHex(o.input).length / 2;
249
+ const n = String(normalizeHex(o.input)).length / 2;
221
250
  notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
222
251
  return { request: { hex: o.input }, name: 'the argument', notes };
223
252
  } else {
@@ -283,7 +312,10 @@ function printAnalyzed(r, err, o) {
283
312
  const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
284
313
  if (p && p.line) {
285
314
  const others = (p.count ?? 1) - (Number.isInteger(p.index) ? 1 : 0);
286
- err.write(`analyzed: ${p.name} (${o.objectInput ? '' : `lines ${p.line}-${p.endLine}`}${p.function ? `${o.objectInput ? '' : ', '}in ${p.function}` : ''}${p.address !== undefined ? `, address 0x${p.address.toString(16)}` : ''})${syn ? `, ${syn}` : ''}`
315
+ // (an object file's function: the loop's, or for a body the -func it was given)
316
+ const fn = p.function ?? (o.objectInput ? o.objectFunc : null);
317
+ const where = [o.objectInput ? null : `lines ${p.line}-${p.endLine}`, fn ? `in ${fn}` : null, p.address !== undefined ? `address 0x${p.address.toString(16)}` : null].filter(Boolean);
318
+ err.write(`analyzed: ${p.name} (${where.join(', ')})${syn ? `, ${syn}` : ''}`
287
319
  + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
288
320
  } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
289
321
  err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
@@ -337,39 +369,47 @@ function diagnosis(ins, r) {
337
369
  return lines;
338
370
  }
339
371
 
340
- // A what-if result with cycles per element (-per N): elementsPerIteration and perElement on it, perElement on each
341
- // variant with a tp.
342
- function whatIfPer(x, per) {
343
- if (!per || x.code) return x;
344
- return { ...x, elementsPerIteration: per, perElement: x.tp / per, variants: x.variants.map((v) => (v.tp !== undefined ? { ...v, perElement: v.tp / per } : v)) };
345
- }
346
-
347
- const VARIANT_W = 18;
348
- function whatIfTable(x) {
349
- const per = x.elementsPerIteration;
350
- const f = per ? (v) => fmtEl(v / per) : fmt;
351
- const rows = x.variants.map((v) => (v.error ? ` ${v.label.padEnd(VARIANT_W)} ${'-'.padStart(8)} ${v.error}`
352
- : ` ${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)}`));
353
- 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)}):`,
354
- ` ${'variant'.padEnd(VARIANT_W)} ${'cycles'.padStart(8)} ${'delta'.padStart(8)} ${'speedup'.padStart(7)}`, ...rows,
355
- ...(x.accumulators ? [` best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}`] : [])].join('\n') + '\n';
356
- }
372
+ // what-if results per element and as text: web/js/whatif-core.js (shared with the REST API)
373
+ const whatIfPer = whatIfPerElement;
374
+ const whatIfTable = whatIfText;
357
375
  // -TPonly -whatif: one "variant cycles [per element]" line per variant (prefix: the CPU, with several)
358
376
  function whatIfTerse(x, prefix = '') {
359
377
  if (x.code) return `${prefix}what-if error: ${x.error}\n`;
378
+ if (x.unsupported) return `${prefix}what-if: not a result: ${x.unsupported}\n`; // (no variants)
360
379
  return x.variants.map((v) => `${prefix}${v.id} ${v.error ? 'error' : `${fmt(v.tp)}${v.perElement !== undefined ? ` ${fmtEl(v.perElement)}` : ''}`}\n`).join('');
361
380
  }
362
381
 
382
+ // -md: "SKL · Skylake (2015)"
383
+ function archTitle(w, id) {
384
+ const a = w.archs().find((x) => x.id === id);
385
+ return a ? `${id} · ${a.name}${a.year ? ` (${a.year})` : ''}` : id;
386
+ }
387
+ // -md: the analyzed lines of an assembly input, for the branch targets as labels (branch-label.js); null for machine code
388
+ const srcOf = (req, r) => (req.source ? analyzedLines(String(req.source).replace(/\r\n?/g, '\n'), r) : null);
389
+ // -md: the assembly that was analyzed (the loop's lines, or all of the text), for the report's code block; none for
390
+ // machine code or a text longer than MD_CODE_LINES lines
391
+ const MD_CODE_LINES = 200;
392
+ function analyzedCode(req, r) {
393
+ if (!req.source) return null;
394
+ const lines = String(req.source).replace(/\r\n?/g, '\n').split('\n');
395
+ const p = r.loop;
396
+ const part = p && p.line && p.endLine ? lines.slice(p.line - 1, p.endLine) : lines;
397
+ const text = part.join('\n').replace(/^\n+|\s+$/g, '');
398
+ return text && part.length <= MD_CODE_LINES ? text : null;
399
+ }
400
+
363
401
  // argv: the arguments after the program name. io: {stdin, stdout, stderr}. Returns the exit code: the result's
364
402
  // `code` (0 ok, 1 bad request or usage, 2 assembler error, 3 analysis error).
365
403
  export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
366
404
  const { stdout: out, stderr: err } = io;
367
- let o = null;
405
+ /** @type {CliOptions} */
406
+ let o = /** @type {any} */ (null); // set by parseArgs, first thing (fail() before that: o?.json)
368
407
  const fail = (code, msg) => {
369
408
  if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
370
409
  else err.write(`${msg}\n`);
371
410
  return code;
372
411
  };
412
+ if (argv[0] === 'diff') return diffMain(argv.slice(1), io);
373
413
  try {
374
414
  o = parseArgs(argv);
375
415
  if (o.help) { out.write(USAGE + '\n'); return 0; }
@@ -406,7 +446,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
406
446
  if (o.report) err.write('-report: with several inputs (one input prints its report anyway); ignored\n');
407
447
  const input = await readInput(o, io, w);
408
448
  for (const n of input.notes) err.write(`${n}\n`);
409
- if (input.object) o.objectInput = true;
449
+ if (input.object) { o.objectInput = true; o.objectFunc = input.request.func ?? null; }
410
450
  if (o.funcs) {
411
451
  if (!input.object) return fail(CODES.REQUEST, '-funcs: lists the functions of an object file (for assembly, -loops lists the loops with their functions)');
412
452
  const fs_ = input.object.functions;
@@ -420,9 +460,11 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
420
460
 
421
461
  if (o.loops) {
422
462
  if (!req.source) return fail(CODES.REQUEST, '-loops: needs assembly (not machine code)');
423
- const ls = listLoops(req.source, { func: o.func ?? null });
463
+ // (an object file's -func as disassemble() resolved it: a part of a name, Mach-O's "_", NAME.0xADDR)
464
+ const ls = listLoops(req.source, { func: req.func ?? o.func ?? null });
424
465
  if (ls.error) return fail(CODES.REQUEST, ls.error);
425
466
  if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
467
+ if (o.md) { out.write(markdown.loops(ls)); return 0; }
426
468
  if (!ls.length) { out.write('no loops\n'); return 0; }
427
469
  printLoops(ls, out);
428
470
  return 0;
@@ -431,12 +473,12 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
431
473
  const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
432
474
  const whatIfs = async (archs) => {
433
475
  const res = {};
434
- for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
476
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, o.variants ?? WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
435
477
  return res;
436
478
  };
437
479
 
438
480
  if (o.archs) {
439
- const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}) });
481
+ const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}), ...(o.per ? { per: o.per } : {}) });
440
482
  const status = c.code || Math.max(0, ...(c.results ?? []).map((r) => r.code));
441
483
  if (c.code) {
442
484
  if (o.json) { out.write(JSON.stringify(c) + '\n'); return status; }
@@ -446,7 +488,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
446
488
  // the caveats per CPU: one analysis for the instructions, each CPU's configuration (the split-load cost)
447
489
  const first = c.results.find((r) => r.code === 0);
448
490
  const base = !o.tpOnly && first ? await w.analyze(first.arch, req) : null;
449
- 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);
491
+ const insOf = (r) => (base?.code === 0 && r.code === 0 && !r.unsupported ? w.insights({ ...base, arch: r.arch, tp: r.tp, limits: r.limits, bottlenecks: r.bottlenecks }) : null);
450
492
  const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
451
493
  const wi = o.whatif ? await whatIfs(c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
452
494
  if (o.json) {
@@ -456,9 +498,16 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
456
498
  }
457
499
  printStderr(c, err, input.name);
458
500
  printAnalyzed(c, err, o);
501
+ if (o.md) {
502
+ const results = c.results.map((r, k) => ({ ...r, ...(extra[k].ins?.caveats ? { caveats: extra[k].ins.caveats } : {}) }));
503
+ out.write(markdown.cpuTable({ ...c, results }, { per: o.per }));
504
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
505
+ if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
506
+ return status;
507
+ }
459
508
  const kw = Math.max(4, ...c.results.map((r) => r.arch.length));
460
509
  const nw = Math.max(5, ...c.results.map((r) => r.name.length));
461
- 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(', ')})` : '-')));
510
+ const bns = c.results.map((r, k) => (r.code ? `error: ${r.error.split('\n')[0]}` : r.unsupported ? '-' : r.bottlenecks.join(', ') || (extra[k].ins?.largest ? `- (nearest ${extra[k].ins.largest.join(', ')})` : '-')));
462
511
  // the Bottlenecks column as wide as its widest entry (an error's message, the last thing on its row, not counted)
463
512
  const bw = Math.max(11, ...bns.filter((b, k) => !c.results[k].code).map((b) => b.length));
464
513
  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`);
@@ -470,12 +519,12 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
470
519
  return;
471
520
  }
472
521
  const year = String(r.year ?? '').padEnd(4);
473
- const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors ? '*' : ''}`).padStart(6);
474
- const notes = [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
522
+ const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors || r.unsupported ? '*' : ''}`).padStart(6);
523
+ const notes = [r.unsupported ? `not a result: ${r.unsupported}` : null, r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, r.noData ? `${r.noData} without data (cost left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
475
524
  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');
476
525
  });
477
526
  if (!o.tpOnly) {
478
- 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`);
527
+ out.write(`\nTP: cycles per iteration${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown. *: not a result: that CPU cannot run some of the code, which its number leaves out.\n`);
479
528
  if (c.results.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
480
529
  if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
481
530
  for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
@@ -484,7 +533,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
484
533
  }
485
534
 
486
535
  const r = await w.analyze(o.arch, req);
487
- const ins = r.code === 0 ? w.insights(r) : null;
536
+ const ins = r.code === 0 && !r.unsupported ? w.insights(r) : null; // (none for a result its CPU cannot run)
488
537
  const wi = o.whatif && r.code === 0 ? await whatIfs([o.arch]) : null;
489
538
  if (o.json) {
490
539
  out.write(JSON.stringify(r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) }) + '\n');
@@ -493,6 +542,13 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
493
542
  printStderr(r, err, input.name);
494
543
  if (r.code) return r.code;
495
544
  printAnalyzed(r, err, o);
545
+ if (o.md) {
546
+ out.write(markdown.report(r, { arch: archTitle(w, r.arch), per: o.per, insights: ins, src: srcOf(req, r), code: analyzedCode(req, r) }));
547
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
548
+ const steps = !o.per ? inductionSteps(r) : [];
549
+ if (steps.length) err.write(stepLine(steps));
550
+ return 0;
551
+ }
496
552
  if (o.tpOnly) {
497
553
  out.write(`${fmt(r.tp)}${o.per ? ` ${fmtEl(per(r.tp))}` : ''}\n`);
498
554
  for (const x of Object.values(wi ?? {})) out.write(whatIfTerse(x));
@@ -503,6 +559,8 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
503
559
  let text = r.text;
504
560
  if (ins?.largest && /^Bottleneck: unknown$/m.test(text)) text = text.replace(/^Bottleneck: unknown$/m, d.shift());
505
561
  out.write(text);
562
+ if (r.unsupported) d.unshift(`Not a result for ${r.arch}: ${r.unsupported} (the throughput leaves out what it cannot run)`);
563
+ else if (r.noData) d.push(`${r.noData} instruction${r.noData === 1 ? '' : 's'} without data (not in the instruction tables): the throughput leaves their cost out`);
506
564
  if (o.per) d.push(`Per element: ${fmtEl(per(r.tp))} cycles (${fmt(r.tp)} cycles/iteration, ${o.per} elements per iteration)`);
507
565
  if (d.length) out.write(`\n${d.join('\n')}\n`);
508
566
  const steps = !o.per ? inductionSteps(r) : [];
@@ -518,6 +576,70 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
518
576
  }
519
577
  }
520
578
 
579
+ // ---- wuica diff A B ---------------------------------------------------------------------------------------------------
580
+ // Two blocks (each a file, - for stdin, or hex; object files as for one input) on one microarchitecture (-arch, default
581
+ // SKL): web/js/block-diff.js. -per N (both) or -per A,B: also per element. -md: the Markdown of the page's A–B view;
582
+ // -json: the result object. The other options as for one input (applied to both). Exit status: 0, or the failing side's.
583
+ async function diffMain(argv, io) {
584
+ const { stdout: out, stderr: err } = io;
585
+ /** @type {CliOptions} */
586
+ let o = /** @type {any} */ (null);
587
+ try {
588
+ // -per N or -per A,B (parseArgs takes one number)
589
+ /** @type {number[] | null} */
590
+ let per = null;
591
+ const rest = [];
592
+ for (let i = 0; i < argv.length; i++) {
593
+ const m = /^--?per(?:=(.*))?$/i.exec(argv[i]);
594
+ if (!m) { rest.push(argv[i]); continue; }
595
+ const v = m[1] ?? argv[++i];
596
+ if (v === undefined) throw new UsageError('-per needs a value');
597
+ per = String(v).split(',').map(Number);
598
+ if (per.length === 1) per = [per[0], per[0]];
599
+ if (per.length !== 2 || !per.every((n) => Number.isFinite(n) && n > 0)) throw new UsageError(`-per: elements per iteration, N or A,B: ${v}`);
600
+ }
601
+ o = parseArgs(rest);
602
+ if (o.help) { out.write(USAGE + '\n'); return 0; }
603
+ if (o.md && (o.json || o.tpOnly)) throw new UsageError(`-md: Markdown instead of the text report; not with ${o.json ? '-json (JSON is its own format)' : '-TPonly (one number per line)'}`);
604
+ if (o.inputs.length !== 2) throw new UsageError(`two inputs, A and B (got ${o.inputs.length})`);
605
+ if (o.archs) throw new UsageError('one microarchitecture (-arch NAME)');
606
+ const NOT = { whatif: '-whatif', variants: '-variants', loops: '-loops', funcs: '-funcs', example: '-example', files: '-files', raw: '-raw', tpOnly: '-TPonly', report: '-report' };
607
+ for (const [f, flag] of Object.entries(NOT)) if (o[f] !== undefined && o[f] !== false) throw new UsageError(`${flag} is not available here`);
608
+ if (o.inputs.filter((n) => n === '-').length > 1) throw new UsageError('stdin (-) can be read only once');
609
+ const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}) });
610
+ if (!w.resolveArch(o.arch)) return failWith(CODES.REQUEST, `unknown microarchitecture: ${o.arch} (known: ${w.archs('id').map((a) => a.id).join(', ')})`);
611
+ const sides = [];
612
+ for (const name of o.inputs) {
613
+ const input = await readInput({ ...o, input: name }, io, w);
614
+ for (const n of input.notes) err.write(`${name}: ${n}\n`);
615
+ sides.push(input);
616
+ }
617
+ const x = await diffAnalyses(w, o.arch, { a: sides[0].request, b: sides[1].request, options: o.options, ...(per ? { per } : {}) });
618
+ if (x.failure) {
619
+ if (o.json) { out.write(JSON.stringify(x.failure) + '\n'); return x.failure.code; }
620
+ // one message: the assembler's positioned lines with the side's file name, else the error (with the side's name
621
+ // when it is one side's)
622
+ const k = /^A: /.test(x.failure.error) ? 0 : /^B: /.test(x.failure.error) ? 1 : -1;
623
+ const tagged = (x.failure.stderr ?? []).some((l) => l.tag);
624
+ if (k >= 0 && tagged) printStderr(x.failure, err, o.inputs[k]);
625
+ else err.write(`${k >= 0 ? o.inputs[k] : 'wuica diff'}: ${String(x.failure.error).replace(/^[AB]: /, '')}\n`);
626
+ return x.failure.code;
627
+ }
628
+ for (const [k, r] of [x.a, x.b].entries()) printStderr(prefixed(r, o.inputs[k]), err, o.inputs[k]);
629
+ if (o.json) { out.write(JSON.stringify(x.result) + '\n'); return 0; }
630
+ out.write(o.md ? diffMarkdown(x, { archTitle: archTitle(w, x.result.arch) }) : `A: ${o.inputs[0]}\nB: ${o.inputs[1]}\n${diffText(x.result)}`);
631
+ return 0;
632
+ } catch (e) {
633
+ if (e instanceof UsageError) return failWith(1, `wuica diff: ${e.message}`);
634
+ return failWith(1, `wuica diff: ${e?.message ?? e}`);
635
+ }
636
+ function failWith(code, msg) {
637
+ if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
638
+ else err.write(`${msg}\n`);
639
+ return code;
640
+ }
641
+ }
642
+
521
643
  // ---- several inputs in one run ---------------------------------------------------------------------------------------
522
644
  // wuica a.s b.s ... / -files LIST (one path per line; - for stdin): each input as a single run would read it, the
523
645
  // analyses of all of them (x the CPUs) as one set of jobs for the threads, the output in input order:
@@ -568,6 +690,12 @@ async function batch(w, o, io) {
568
690
  const code = ls.error ? CODES.REQUEST : 0;
569
691
  worst = Math.max(worst, code);
570
692
  if (o.json) { docs.push({ file: it.name, ...(ls.error ? { code, error: ls.error, stderr: [{ text: ls.error }] } : { code: 0, loops: ls }) }); continue; }
693
+ if (o.md) {
694
+ out.write(`${it === items[0] ? '' : '\n'}### ${markdown.text(it.name)}\n\n`);
695
+ if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
696
+ out.write(ls.error ? `error: ${markdown.text(ls.error)}\n` : markdown.loops(ls));
697
+ continue;
698
+ }
571
699
  out.write(`==> ${it.name} <==\n`);
572
700
  if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
573
701
  else if (!ls.length) out.write('no loops\n');
@@ -581,7 +709,7 @@ async function batch(w, o, io) {
581
709
  const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
582
710
  const whatIfs = async (req, archs) => {
583
711
  const res = {};
584
- for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
712
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, o.variants ?? WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
585
713
  return res;
586
714
  };
587
715
  const docs = new Map(); // item -> {doc (as a single run's JSON), status, rows: [{cpu, tp, pe, bn, notes, code}], report, wi}
@@ -613,7 +741,7 @@ async function batch(w, o, io) {
613
741
  const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
614
742
  const wi = o.whatif ? await whatIfs(it.req, c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
615
743
  const results = c.results.map((r, j) => ({ ...r, ...(extra[j].per !== undefined ? { perElement: extra[j].per } : {}), ...(extra[j].ins?.caveats ? { caveats: extra[j].ins.caveats } : {}) }));
616
- const doc = { ...c, code: status, results, ...(wi ? { whatIf: wi } : {}) };
744
+ const doc = { ...c, code: status, ...(o.per ? { elementsPerIteration: o.per } : {}), results, ...(wi ? { whatIf: wi } : {}) };
617
745
  docs.set(it, { doc, status, c, wi, rows: c.results.map((r, j) => ({ ...rowOf(r, extra[j].ins, per), cpu: r.arch, prototype: r.prototype })) });
618
746
  }
619
747
  }
@@ -639,6 +767,8 @@ async function batch(w, o, io) {
639
767
  return worst;
640
768
  }
641
769
 
770
+ if (o.md) return batchMarkdown(w, o, out, items, docs, worst);
771
+
642
772
  // the table
643
773
  const loopOf = (it) => { const d = docs.get(it).doc; return d.code && !d.results ? '-' : d.loop ? (d.loop.name.replace(/^loop /, '') + (d.loop.function ? ` (${d.loop.function})` : '')) : 'as is'; };
644
774
  const fw = Math.max(4, ...items.map((it) => it.name.length)), lw = Math.max(4, ...items.map((it) => loopOf(it).length));
@@ -648,13 +778,13 @@ async function batch(w, o, io) {
648
778
  out.write(`${'File'.padEnd(fw)} ${'Loop'.padEnd(lw)} ${o.archs ? `${'CPU'.padEnd(cw)} ` : ''}${'TP'.padStart(6)}${o.per ? ` ${'per el'.padStart(6)}` : ''} ${'Bottlenecks'.padEnd(bw)} Notes`.trimEnd() + '\n');
649
779
  for (const it of items) {
650
780
  docs.get(it).rows.forEach((row, j) => {
651
- const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors ? '*' : ''}`).padStart(6);
781
+ const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors || row.unsupported ? '*' : ''}`).padStart(6);
652
782
  const notes = [...row.notes, row.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
653
783
  out.write(`${(j ? '' : it.name).padEnd(fw)} ${(j ? '' : loopOf(it)).padEnd(lw)} ${o.archs ? `${String(row.cpu ?? '-').padEnd(cw)} ` : ''}${tp}${o.per ? ` ${(row.pe !== undefined ? fmtEl(row.pe) : '-').padStart(6)}` : ''} ${row.bn.padEnd(bw)}${notes ? ` ${notes}` : ''}`.trimEnd() + '\n');
654
784
  });
655
785
  }
656
786
  out.write(`\nTP: cycles per iteration${o.archs ? '' : ` on ${w.resolveArch(o.arch)}`}${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown or failed.\n`
657
- + 'Loop: what was analyzed ("as is": all of it). *: undecodable code left out.\n');
787
+ + 'Loop: what was analyzed ("as is": all of it). *: not a result (code left out).\n');
658
788
  if (all.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
659
789
  if (o.report) {
660
790
  for (const it of items) {
@@ -675,13 +805,44 @@ async function batch(w, o, io) {
675
805
  return worst;
676
806
  }
677
807
 
808
+ // -md with several inputs: the files x CPUs table (a CPU column also with one CPU), then with -report each file's
809
+ // report, then each file's what-if tables, under a heading per file
810
+ async function batchMarkdown(w, o, out, items, docs, worst) {
811
+ const info = new Map(w.archs().map((a) => [a.id, a]));
812
+ const named = (r) => (r.code || r.name ? r : { ...r, name: info.get(r.arch)?.name ?? '', year: info.get(r.arch)?.year ?? null, prototype: !!info.get(r.arch)?.prototype });
813
+ const rows = items.map((it) => {
814
+ const d = docs.get(it).doc;
815
+ if (d.results) return { file: it.name, result: { ...d, results: d.results.map(named) } };
816
+ if (d.code) return { file: it.name, result: d };
817
+ return { file: it.name, result: { ...named(d), caveats: d.insights?.caveats ?? [] } };
818
+ });
819
+ out.write(markdown.cpuTable(rows, { per: o.per }));
820
+ if (o.report) {
821
+ for (const it of items) {
822
+ const d = docs.get(it);
823
+ if (d.r?.code === 0) { out.write('\n' + markdown.report(d.r, { title: it.name, arch: archTitle(w, d.r.arch), per: o.per, insights: d.ins, src: srcOf(it.req, d.r) })); continue; }
824
+ if (d.c) for (const r of d.c.results.filter((x) => x.code === 0)) {
825
+ const full = await w.analyze(r.arch, it.req);
826
+ if (full.code === 0) out.write('\n' + markdown.report(full, { title: `${it.name} (${r.arch})`, arch: archTitle(w, r.arch), per: o.per, insights: w.insights(full), src: srcOf(it.req, full) }));
827
+ }
828
+ }
829
+ }
830
+ for (const it of items) {
831
+ const wi = docs.get(it).wi;
832
+ if (!wi) continue;
833
+ out.write(`\n### ${markdown.text(it.name)}\n`);
834
+ for (const x of Object.values(wi)) out.write('\n' + markdown.whatIfAlignment(x));
835
+ }
836
+ return worst;
837
+ }
838
+
678
839
  // A table row of a result (analyze, a compare() row, or a failure): tp, per element, bottlenecks, notes
679
840
  function rowOf(r, ins, per) {
680
841
  if (r.code) return { code: r.code, bn: `error: ${String(r.error).split('\n')[0]}`, notes: [] };
681
842
  return {
682
- code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors,
843
+ code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors, unsupported: r.unsupported ?? null,
683
844
  bn: r.bottlenecks.join(', ') || (ins?.largest ? `- (nearest ${ins.largest.join(', ')})` : '-'),
684
- notes: [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text)].filter(Boolean),
845
+ notes: [r.unsupported ? `not a result: ${r.unsupported}` : null, r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, r.noData ? `${r.noData} without data (cost left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text)].filter(Boolean),
685
846
  };
686
847
  }
687
848
 
package/lib/core.js CHANGED
@@ -5,6 +5,11 @@
5
5
  export const CODES = Object.freeze({ OK: 0, REQUEST: 1, ASSEMBLER: 2, ANALYSIS: 3 });
6
6
 
7
7
  // A failed call: {code, error, stderr}, stderr as in Compiler Explorer (one entry per line, `tag` on positioned ones).
8
+ /**
9
+ * A failure of the contract ({code, error, stderr}: index.d.ts Failure), typed loosely so that a result-or-failure
10
+ * union narrows by its `code` at the call sites.
11
+ * @returns {any}
12
+ */
8
13
  export function failure(code, error, stderr = [{ text: error }], extra = {}) {
9
14
  return { code, error, stderr, ...extra };
10
15
  }
@@ -21,9 +26,12 @@ export function analysisResult(r) {
21
26
  }
22
27
 
23
28
  // The fields of a compare() row taken from an analysis result (after arch, name, year, prototype).
29
+ // xOps: the encodings of the instructions without data (notes X), for compare()'s `unsupported` and `noData`
30
+ // (web/caveats.js cannotRun, noData; index.js); it removes them.
24
31
  export function compareFields(r) {
25
32
  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 };
33
+ const x = Array.isArray(r.rows) ? r.rows.filter((row) => row?.kind === 'instr' && row.notes === 'X').map((row) => String(row.opcode ?? '')) : [];
34
+ return { code: CODES.OK, tp: r.tp, mode: r.mode, bottlenecks: r.bottlenecks, limits: r.limits, decodeErrors: r.decodeErrors, ...(x.length ? { xOps: x } : {}) };
27
35
  }
28
36
 
29
37
  // A block for warming up the analyzer: ~500 instructions of several kinds in a loop (a 24-instruction mix, 20 times;
package/lib/details.js CHANGED
@@ -1,30 +1,11 @@
1
1
  // The details of an analysis ("details": true; docs/WASM-API.md) in the compact form (summarize(), the MCP `analyze`
2
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.
3
+ // the Ports limit with the instructions that load it; the issue slots per cause. The notation and the latencies shown are
4
+ // the page's (web/details.js, shared).
5
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
- }
6
+ import { portString, latencyPairs } from './web/details.js';
15
7
 
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
- }
8
+ export { portString, latencyPairs };
28
9
 
29
10
  const round = (x) => Math.round(x * 100) / 100;
30
11
 
package/lib/examples.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { EXAMPLES, CLASSIC_EXAMPLES, SHOWCASE_EXAMPLES } from './web/examples.js';
6
6
 
7
+ /** @type {['basics' | 'classic' | 'showcase', any[]][]} */
7
8
  const GROUPS = [['basics', EXAMPLES], ['classic', CLASSIC_EXAMPLES], ['showcase', SHOWCASE_EXAMPLES]];
8
9
 
9
10
  // [{name, title, group, arch, instructions, hex, intel?, att?}]: arch is the CPU the page shows it on first; intel and
package/lib/files.js CHANGED
@@ -22,7 +22,8 @@ export async function readMaybeCompressed(file) {
22
22
  }
23
23
 
24
24
  // The file of an instruction table in a data directory: the binary form (<name>.bin, the package's), else the JSON
25
- // (<name>.json, as tools/export_data.py writes it), each plain or .br.
25
+ // (<name>.json, as tools/export_data.py writes it: the analyzer that ships reads no JSON tables and says so), each plain
26
+ // or .br.
26
27
  export function tableFile(dataDir, name) {
27
28
  const bin = path.join(dataDir, 'arch', `${name}.bin`);
28
29
  return existsSync(bin) || existsSync(bin + '.br') ? bin : path.join(dataDir, 'arch', `${name}.json`);