wuica-cli 0.1.9 → 0.1.10

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
 
@@ -32,7 +37,8 @@ Input:
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
39
  -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
40
+ "Inner Loop Header" notes count; perf annotate: the loop with the most samples of its
41
+ own), whole (all the text), a loop's index (0-based, as
36
42
  -loops lists them) or its label (-loop .LBB0_12)
37
43
  -func NAME only the loops of function NAME (with -loop: its index or label among them); in an object
38
44
  file its symbol, or a unique part of it
@@ -49,6 +55,11 @@ Output:
49
55
  -per N the loop does N elements (bytes, floats, ...) per iteration: also print cycles per element
50
56
  (what-if values too)
51
57
  -whatif the what-if variants (unrolled, N accumulators, front end, fusion) per microarchitecture
58
+ -variants LIST with -whatif (implied): these variants only, comma-separated; also align (the 64 alignment
59
+ offsets: min, median, max, best and worst offset; 64 analyses, not in the default set)
60
+ -md print GitHub-flavoured Markdown instead of the text report (for an issue, a review, a
61
+ chat): the result with its uop table, the CPU table, the what-if and loop tables; not with
62
+ -json or -TPonly
52
63
  -json print the response as JSON
53
64
  -trace with -json: include the cycle-by-cycle events (large)
54
65
  -details with -json: include the details (allowed ports, latencies, port set, issue slots)
@@ -81,7 +92,8 @@ prototype models (from the fork jtl06/uiCA), less validated than the Intel model
81
92
 
82
93
  export const MCP_USAGE = `Usage: wuica-mcp (or: wuica mcp)
83
94
 
84
- The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, compare_archs, assemble.
95
+ The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, diff_blocks, compare_archs, list_loops,
96
+ assemble.
85
97
  Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli mcp"). Options: --help, --version.
86
98
  `;
87
99
 
@@ -104,12 +116,15 @@ const FLAGS = {
104
116
  examples: ['examples'], example: ['example', 1], show: ['show'], files: ['files', 1], report: ['report'], funcs: ['funcs'],
105
117
  arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
106
118
  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'],
119
+ tponly: ['tpOnly'], json: ['json'], md: ['md'], variants: ['variants', 1], trace: ['trace'], details: ['details'],
108
120
  alignmentoffset: ['alignmentOffset', 1], initpolicy: ['initPolicy', 1], simplefrontend: ['simpleFrontEnd'],
109
121
  nomicrofusion: ['noMicroFusion'], nomacrofusion: ['noMacroFusion'], miniterations: ['minIterations', 1], mincycles: ['minCycles', 1],
110
122
  };
111
123
 
124
+ /** @typedef {Record<string, any> & {arch: string, options: Record<string, any>, input: string | null, inputs: string[], syntax: string}} CliOptions */
125
+ /** @param {string[]} argv @returns {CliOptions} */
112
126
  export function parseArgs(argv) {
127
+ /** @type {CliOptions} */
113
128
  const o = { arch: 'SKL', options: {}, input: null, inputs: [], syntax: 'auto' };
114
129
  const int = (s, name) => {
115
130
  if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
@@ -124,6 +139,7 @@ export function parseArgs(argv) {
124
139
  continue;
125
140
  }
126
141
  const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
142
+ if (!m) throw new UsageError(`unknown option ${a}`); // "-=x"
127
143
  const f = FLAGS[m[1].toLowerCase()];
128
144
  if (!f) throw new UsageError(`unknown option ${a}`);
129
145
  const [name, takes] = f;
@@ -133,6 +149,15 @@ export function parseArgs(argv) {
133
149
  switch (name) {
134
150
  case 'att': case 'intel': o.syntax = name; break;
135
151
  case 'loop': o.loop = /^\d+$/.test(v) ? Number(v) : v; break;
152
+ case 'variants': {
153
+ o.variants = v.split(',').map((x) => x.trim()).filter(Boolean);
154
+ const known = [...WHAT_IF_VARIANTS, ...WHAT_IF_OPT_IN_VARIANTS];
155
+ if (!o.variants.length) throw new UsageError(`-variants: no variant in "${v}" (known: ${known.join(', ')})`);
156
+ const unknown = o.variants.filter((x) => !known.includes(x));
157
+ if (unknown.length) throw new UsageError(`-variants: unknown variant(s): ${unknown.join(', ')} (known: ${known.join(', ')})`);
158
+ o.whatif = true;
159
+ break;
160
+ }
136
161
  case 'per': o.per = Number(v); if (!(o.per > 0)) throw new UsageError(`-per: a positive number of elements per iteration: ${v}`); break;
137
162
  case 'threads': o.threads = int(v, name); if (o.threads < 1) throw new UsageError('-threads: at least 1'); break;
138
163
  case 'trace': o.options.includeTrace = true; break;
@@ -143,6 +168,7 @@ export function parseArgs(argv) {
143
168
  default: o[name] = takes ? v : true;
144
169
  }
145
170
  }
171
+ 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
172
  o.arch = o.arch.trim();
147
173
  if (o.arch.toLowerCase() === 'list') o.list = true;
148
174
  // several microarchitectures: all, or a comma-separated list
@@ -183,6 +209,7 @@ function readFile(file) {
183
209
  }
184
210
 
185
211
  // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
212
+ /** @param {CliOptions} o @param {any} io @param {any} [w] @returns {Promise<any>} */
186
213
  async function readInput(o, io, w = null) {
187
214
  const notes = [];
188
215
  if (o.example !== undefined) {
@@ -217,7 +244,7 @@ async function readInput(o, io, w = null) {
217
244
  }
218
245
  text = b.toString('utf8');
219
246
  } else if (normalizeHex(o.input) !== null) {
220
- const n = normalizeHex(o.input).length / 2;
247
+ const n = String(normalizeHex(o.input)).length / 2;
221
248
  notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
222
249
  return { request: { hex: o.input }, name: 'the argument', notes };
223
250
  } else {
@@ -337,39 +364,47 @@ function diagnosis(ins, r) {
337
364
  return lines;
338
365
  }
339
366
 
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
- }
367
+ // what-if results per element and as text: web/js/whatif-core.js (shared with the REST API)
368
+ const whatIfPer = whatIfPerElement;
369
+ const whatIfTable = whatIfText;
357
370
  // -TPonly -whatif: one "variant cycles [per element]" line per variant (prefix: the CPU, with several)
358
371
  function whatIfTerse(x, prefix = '') {
359
372
  if (x.code) return `${prefix}what-if error: ${x.error}\n`;
373
+ if (x.unsupported) return `${prefix}what-if: not a result: ${x.unsupported}\n`; // (no variants)
360
374
  return x.variants.map((v) => `${prefix}${v.id} ${v.error ? 'error' : `${fmt(v.tp)}${v.perElement !== undefined ? ` ${fmtEl(v.perElement)}` : ''}`}\n`).join('');
361
375
  }
362
376
 
377
+ // -md: "SKL · Skylake (2015)"
378
+ function archTitle(w, id) {
379
+ const a = w.archs().find((x) => x.id === id);
380
+ return a ? `${id} · ${a.name}${a.year ? ` (${a.year})` : ''}` : id;
381
+ }
382
+ // -md: the analyzed lines of an assembly input, for the branch targets as labels (branch-label.js); null for machine code
383
+ const srcOf = (req, r) => (req.source ? analyzedLines(String(req.source).replace(/\r\n?/g, '\n'), r) : null);
384
+ // -md: the assembly that was analyzed (the loop's lines, or all of the text), for the report's code block; none for
385
+ // machine code or a text longer than MD_CODE_LINES lines
386
+ const MD_CODE_LINES = 200;
387
+ function analyzedCode(req, r) {
388
+ if (!req.source) return null;
389
+ const lines = String(req.source).replace(/\r\n?/g, '\n').split('\n');
390
+ const p = r.loop;
391
+ const part = p && p.line && p.endLine ? lines.slice(p.line - 1, p.endLine) : lines;
392
+ const text = part.join('\n').replace(/^\n+|\s+$/g, '');
393
+ return text && part.length <= MD_CODE_LINES ? text : null;
394
+ }
395
+
363
396
  // argv: the arguments after the program name. io: {stdin, stdout, stderr}. Returns the exit code: the result's
364
397
  // `code` (0 ok, 1 bad request or usage, 2 assembler error, 3 analysis error).
365
398
  export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
366
399
  const { stdout: out, stderr: err } = io;
367
- let o = null;
400
+ /** @type {CliOptions} */
401
+ let o = /** @type {any} */ (null); // set by parseArgs, first thing (fail() before that: o?.json)
368
402
  const fail = (code, msg) => {
369
403
  if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
370
404
  else err.write(`${msg}\n`);
371
405
  return code;
372
406
  };
407
+ if (argv[0] === 'diff') return diffMain(argv.slice(1), io);
373
408
  try {
374
409
  o = parseArgs(argv);
375
410
  if (o.help) { out.write(USAGE + '\n'); return 0; }
@@ -423,6 +458,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
423
458
  const ls = listLoops(req.source, { func: o.func ?? null });
424
459
  if (ls.error) return fail(CODES.REQUEST, ls.error);
425
460
  if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
461
+ if (o.md) { out.write(markdown.loops(ls)); return 0; }
426
462
  if (!ls.length) { out.write('no loops\n'); return 0; }
427
463
  printLoops(ls, out);
428
464
  return 0;
@@ -431,12 +467,12 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
431
467
  const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
432
468
  const whatIfs = async (archs) => {
433
469
  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);
470
+ 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
471
  return res;
436
472
  };
437
473
 
438
474
  if (o.archs) {
439
- const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}) });
475
+ const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}), ...(o.per ? { per: o.per } : {}) });
440
476
  const status = c.code || Math.max(0, ...(c.results ?? []).map((r) => r.code));
441
477
  if (c.code) {
442
478
  if (o.json) { out.write(JSON.stringify(c) + '\n'); return status; }
@@ -446,7 +482,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
446
482
  // the caveats per CPU: one analysis for the instructions, each CPU's configuration (the split-load cost)
447
483
  const first = c.results.find((r) => r.code === 0);
448
484
  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);
485
+ 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
486
  const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
451
487
  const wi = o.whatif ? await whatIfs(c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
452
488
  if (o.json) {
@@ -456,9 +492,16 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
456
492
  }
457
493
  printStderr(c, err, input.name);
458
494
  printAnalyzed(c, err, o);
495
+ if (o.md) {
496
+ const results = c.results.map((r, k) => ({ ...r, ...(extra[k].ins?.caveats ? { caveats: extra[k].ins.caveats } : {}) }));
497
+ out.write(markdown.cpuTable({ ...c, results }, { per: o.per }));
498
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
499
+ if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
500
+ return status;
501
+ }
459
502
  const kw = Math.max(4, ...c.results.map((r) => r.arch.length));
460
503
  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(', ')})` : '-')));
504
+ 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
505
  // the Bottlenecks column as wide as its widest entry (an error's message, the last thing on its row, not counted)
463
506
  const bw = Math.max(11, ...bns.filter((b, k) => !c.results[k].code).map((b) => b.length));
464
507
  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 +513,12 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
470
513
  return;
471
514
  }
472
515
  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('; ');
516
+ const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors || r.unsupported ? '*' : ''}`).padStart(6);
517
+ 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
518
  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
519
  });
477
520
  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`);
521
+ 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
522
  if (c.results.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
480
523
  if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
481
524
  for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
@@ -484,7 +527,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
484
527
  }
485
528
 
486
529
  const r = await w.analyze(o.arch, req);
487
- const ins = r.code === 0 ? w.insights(r) : null;
530
+ const ins = r.code === 0 && !r.unsupported ? w.insights(r) : null; // (none for a result its CPU cannot run)
488
531
  const wi = o.whatif && r.code === 0 ? await whatIfs([o.arch]) : null;
489
532
  if (o.json) {
490
533
  out.write(JSON.stringify(r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) }) + '\n');
@@ -493,6 +536,13 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
493
536
  printStderr(r, err, input.name);
494
537
  if (r.code) return r.code;
495
538
  printAnalyzed(r, err, o);
539
+ if (o.md) {
540
+ out.write(markdown.report(r, { arch: archTitle(w, r.arch), per: o.per, insights: ins, src: srcOf(req, r), code: analyzedCode(req, r) }));
541
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
542
+ const steps = !o.per ? inductionSteps(r) : [];
543
+ if (steps.length) err.write(stepLine(steps));
544
+ return 0;
545
+ }
496
546
  if (o.tpOnly) {
497
547
  out.write(`${fmt(r.tp)}${o.per ? ` ${fmtEl(per(r.tp))}` : ''}\n`);
498
548
  for (const x of Object.values(wi ?? {})) out.write(whatIfTerse(x));
@@ -503,6 +553,8 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
503
553
  let text = r.text;
504
554
  if (ins?.largest && /^Bottleneck: unknown$/m.test(text)) text = text.replace(/^Bottleneck: unknown$/m, d.shift());
505
555
  out.write(text);
556
+ if (r.unsupported) d.unshift(`Not a result for ${r.arch}: ${r.unsupported} (the throughput leaves out what it cannot run)`);
557
+ 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
558
  if (o.per) d.push(`Per element: ${fmtEl(per(r.tp))} cycles (${fmt(r.tp)} cycles/iteration, ${o.per} elements per iteration)`);
507
559
  if (d.length) out.write(`\n${d.join('\n')}\n`);
508
560
  const steps = !o.per ? inductionSteps(r) : [];
@@ -518,6 +570,70 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
518
570
  }
519
571
  }
520
572
 
573
+ // ---- wuica diff A B ---------------------------------------------------------------------------------------------------
574
+ // Two blocks (each a file, - for stdin, or hex; object files as for one input) on one microarchitecture (-arch, default
575
+ // 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;
576
+ // -json: the result object. The other options as for one input (applied to both). Exit status: 0, or the failing side's.
577
+ async function diffMain(argv, io) {
578
+ const { stdout: out, stderr: err } = io;
579
+ /** @type {CliOptions} */
580
+ let o = /** @type {any} */ (null);
581
+ try {
582
+ // -per N or -per A,B (parseArgs takes one number)
583
+ /** @type {number[] | null} */
584
+ let per = null;
585
+ const rest = [];
586
+ for (let i = 0; i < argv.length; i++) {
587
+ const m = /^--?per(?:=(.*))?$/i.exec(argv[i]);
588
+ if (!m) { rest.push(argv[i]); continue; }
589
+ const v = m[1] ?? argv[++i];
590
+ if (v === undefined) throw new UsageError('-per needs a value');
591
+ per = String(v).split(',').map(Number);
592
+ if (per.length === 1) per = [per[0], per[0]];
593
+ if (per.length !== 2 || !per.every((n) => Number.isFinite(n) && n > 0)) throw new UsageError(`-per: elements per iteration, N or A,B: ${v}`);
594
+ }
595
+ o = parseArgs(rest);
596
+ if (o.help) { out.write(USAGE + '\n'); return 0; }
597
+ 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)'}`);
598
+ if (o.inputs.length !== 2) throw new UsageError(`two inputs, A and B (got ${o.inputs.length})`);
599
+ if (o.archs) throw new UsageError('one microarchitecture (-arch NAME)');
600
+ const NOT = { whatif: '-whatif', variants: '-variants', loops: '-loops', funcs: '-funcs', example: '-example', files: '-files', raw: '-raw', tpOnly: '-TPonly', report: '-report' };
601
+ for (const [f, flag] of Object.entries(NOT)) if (o[f] !== undefined && o[f] !== false) throw new UsageError(`${flag} is not available here`);
602
+ if (o.inputs.filter((n) => n === '-').length > 1) throw new UsageError('stdin (-) can be read only once');
603
+ const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}) });
604
+ if (!w.resolveArch(o.arch)) return failWith(CODES.REQUEST, `unknown microarchitecture: ${o.arch} (known: ${w.archs('id').map((a) => a.id).join(', ')})`);
605
+ const sides = [];
606
+ for (const name of o.inputs) {
607
+ const input = await readInput({ ...o, input: name }, io, w);
608
+ for (const n of input.notes) err.write(`${name}: ${n}\n`);
609
+ sides.push(input);
610
+ }
611
+ const x = await diffAnalyses(w, o.arch, { a: sides[0].request, b: sides[1].request, options: o.options, ...(per ? { per } : {}) });
612
+ if (x.failure) {
613
+ if (o.json) { out.write(JSON.stringify(x.failure) + '\n'); return x.failure.code; }
614
+ // one message: the assembler's positioned lines with the side's file name, else the error (with the side's name
615
+ // when it is one side's)
616
+ const k = /^A: /.test(x.failure.error) ? 0 : /^B: /.test(x.failure.error) ? 1 : -1;
617
+ const tagged = (x.failure.stderr ?? []).some((l) => l.tag);
618
+ if (k >= 0 && tagged) printStderr(x.failure, err, o.inputs[k]);
619
+ else err.write(`${k >= 0 ? o.inputs[k] : 'wuica diff'}: ${String(x.failure.error).replace(/^[AB]: /, '')}\n`);
620
+ return x.failure.code;
621
+ }
622
+ for (const [k, r] of [x.a, x.b].entries()) printStderr(prefixed(r, o.inputs[k]), err, o.inputs[k]);
623
+ if (o.json) { out.write(JSON.stringify(x.result) + '\n'); return 0; }
624
+ out.write(o.md ? diffMarkdown(x, { archTitle: archTitle(w, x.result.arch) }) : `A: ${o.inputs[0]}\nB: ${o.inputs[1]}\n${diffText(x.result)}`);
625
+ return 0;
626
+ } catch (e) {
627
+ if (e instanceof UsageError) return failWith(1, `wuica diff: ${e.message}`);
628
+ return failWith(1, `wuica diff: ${e?.message ?? e}`);
629
+ }
630
+ function failWith(code, msg) {
631
+ if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
632
+ else err.write(`${msg}\n`);
633
+ return code;
634
+ }
635
+ }
636
+
521
637
  // ---- several inputs in one run ---------------------------------------------------------------------------------------
522
638
  // wuica a.s b.s ... / -files LIST (one path per line; - for stdin): each input as a single run would read it, the
523
639
  // analyses of all of them (x the CPUs) as one set of jobs for the threads, the output in input order:
@@ -568,6 +684,12 @@ async function batch(w, o, io) {
568
684
  const code = ls.error ? CODES.REQUEST : 0;
569
685
  worst = Math.max(worst, code);
570
686
  if (o.json) { docs.push({ file: it.name, ...(ls.error ? { code, error: ls.error, stderr: [{ text: ls.error }] } : { code: 0, loops: ls }) }); continue; }
687
+ if (o.md) {
688
+ out.write(`${it === items[0] ? '' : '\n'}### ${markdown.text(it.name)}\n\n`);
689
+ if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
690
+ out.write(ls.error ? `error: ${markdown.text(ls.error)}\n` : markdown.loops(ls));
691
+ continue;
692
+ }
571
693
  out.write(`==> ${it.name} <==\n`);
572
694
  if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
573
695
  else if (!ls.length) out.write('no loops\n');
@@ -581,7 +703,7 @@ async function batch(w, o, io) {
581
703
  const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
582
704
  const whatIfs = async (req, archs) => {
583
705
  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);
706
+ 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
707
  return res;
586
708
  };
587
709
  const docs = new Map(); // item -> {doc (as a single run's JSON), status, rows: [{cpu, tp, pe, bn, notes, code}], report, wi}
@@ -613,7 +735,7 @@ async function batch(w, o, io) {
613
735
  const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
614
736
  const wi = o.whatif ? await whatIfs(it.req, c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
615
737
  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 } : {}) };
738
+ const doc = { ...c, code: status, ...(o.per ? { elementsPerIteration: o.per } : {}), results, ...(wi ? { whatIf: wi } : {}) };
617
739
  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
740
  }
619
741
  }
@@ -639,6 +761,8 @@ async function batch(w, o, io) {
639
761
  return worst;
640
762
  }
641
763
 
764
+ if (o.md) return batchMarkdown(w, o, out, items, docs, worst);
765
+
642
766
  // the table
643
767
  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
768
  const fw = Math.max(4, ...items.map((it) => it.name.length)), lw = Math.max(4, ...items.map((it) => loopOf(it).length));
@@ -648,13 +772,13 @@ async function batch(w, o, io) {
648
772
  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
773
  for (const it of items) {
650
774
  docs.get(it).rows.forEach((row, j) => {
651
- const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors ? '*' : ''}`).padStart(6);
775
+ const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors || row.unsupported ? '*' : ''}`).padStart(6);
652
776
  const notes = [...row.notes, row.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
653
777
  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
778
  });
655
779
  }
656
780
  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');
781
+ + 'Loop: what was analyzed ("as is": all of it). *: not a result (code left out).\n');
658
782
  if (all.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
659
783
  if (o.report) {
660
784
  for (const it of items) {
@@ -675,13 +799,44 @@ async function batch(w, o, io) {
675
799
  return worst;
676
800
  }
677
801
 
802
+ // -md with several inputs: the files x CPUs table (a CPU column also with one CPU), then with -report each file's
803
+ // report, then each file's what-if tables, under a heading per file
804
+ async function batchMarkdown(w, o, out, items, docs, worst) {
805
+ const info = new Map(w.archs().map((a) => [a.id, a]));
806
+ 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 });
807
+ const rows = items.map((it) => {
808
+ const d = docs.get(it).doc;
809
+ if (d.results) return { file: it.name, result: { ...d, results: d.results.map(named) } };
810
+ if (d.code) return { file: it.name, result: d };
811
+ return { file: it.name, result: { ...named(d), caveats: d.insights?.caveats ?? [] } };
812
+ });
813
+ out.write(markdown.cpuTable(rows, { per: o.per }));
814
+ if (o.report) {
815
+ for (const it of items) {
816
+ const d = docs.get(it);
817
+ 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; }
818
+ if (d.c) for (const r of d.c.results.filter((x) => x.code === 0)) {
819
+ const full = await w.analyze(r.arch, it.req);
820
+ 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) }));
821
+ }
822
+ }
823
+ }
824
+ for (const it of items) {
825
+ const wi = docs.get(it).wi;
826
+ if (!wi) continue;
827
+ out.write(`\n### ${markdown.text(it.name)}\n`);
828
+ for (const x of Object.values(wi)) out.write('\n' + markdown.whatIfAlignment(x));
829
+ }
830
+ return worst;
831
+ }
832
+
678
833
  // A table row of a result (analyze, a compare() row, or a failure): tp, per element, bottlenecks, notes
679
834
  function rowOf(r, ins, per) {
680
835
  if (r.code) return { code: r.code, bn: `error: ${String(r.error).split('\n')[0]}`, notes: [] };
681
836
  return {
682
- code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors,
837
+ code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors, unsupported: r.unsupported ?? null,
683
838
  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),
839
+ 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
840
  };
686
841
  }
687
842
 
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`);