wuica-cli 0.1.7 → 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.
Files changed (64) hide show
  1. package/README.md +233 -57
  2. package/dist/data/arch/ADL-P.bin.br +0 -0
  3. package/dist/data/arch/BDW.bin.br +0 -0
  4. package/dist/data/arch/CFL.bin.br +0 -0
  5. package/dist/data/arch/CLX.bin.br +0 -0
  6. package/dist/data/arch/HSW.bin.br +0 -0
  7. package/dist/data/arch/ICL.bin.br +0 -0
  8. package/dist/data/arch/ICX.bin.br +0 -0
  9. package/dist/data/arch/IVB.bin.br +0 -0
  10. package/dist/data/arch/KBL.bin.br +0 -0
  11. package/dist/data/arch/RKL.bin.br +0 -0
  12. package/dist/data/arch/SKL.bin.br +0 -0
  13. package/dist/data/arch/SKX.bin.br +0 -0
  14. package/dist/data/arch/SNB.bin.br +0 -0
  15. package/dist/data/arch/TGL.bin.br +0 -0
  16. package/dist/data/arch/ZEN3.bin.br +0 -0
  17. package/dist/data/uarch.json.br +0 -0
  18. package/dist/manifest.json +145 -66
  19. package/dist/wuica_wasm.wasm.br +0 -0
  20. package/index.d.ts +205 -13
  21. package/lib/cli.js +467 -49
  22. package/lib/core.js +9 -1
  23. package/lib/details.js +4 -23
  24. package/lib/examples.js +27 -0
  25. package/lib/files.js +26 -3
  26. package/lib/index.js +228 -42
  27. package/lib/mcp.js +107 -84
  28. package/lib/objfile.js +218 -0
  29. package/lib/thread-worker.js +15 -9
  30. package/lib/threads.js +40 -23
  31. package/lib/wasm.js +42 -11
  32. package/lib/web/ab-diff.js +217 -0
  33. package/lib/web/accum.js +10 -2
  34. package/lib/web/asm-regions.js +24 -17
  35. package/lib/web/asm-tokens.js +357 -0
  36. package/lib/web/assembler.js +36 -6
  37. package/lib/web/block-diff.js +165 -0
  38. package/lib/web/bound-core.js +211 -0
  39. package/lib/web/branch-label.js +155 -0
  40. package/lib/web/caveats.js +115 -3
  41. package/lib/web/details.js +91 -0
  42. package/lib/web/examples.js +103 -0
  43. package/lib/web/loop-find.js +139 -16
  44. package/lib/web/markdown.js +437 -0
  45. package/lib/web/showcase.js +368 -0
  46. package/lib/web/whatif-core.js +339 -0
  47. package/package.json +3 -1
  48. package/dist/data/arch/ADL-P.json.br +0 -0
  49. package/dist/data/arch/BDW.json.br +0 -0
  50. package/dist/data/arch/CFL.json.br +0 -0
  51. package/dist/data/arch/CLX.json.br +0 -0
  52. package/dist/data/arch/HSW.json.br +0 -0
  53. package/dist/data/arch/ICL.json.br +0 -0
  54. package/dist/data/arch/ICX.json.br +0 -0
  55. package/dist/data/arch/IVB.json.br +0 -0
  56. package/dist/data/arch/KBL.json.br +0 -0
  57. package/dist/data/arch/RKL.json.br +0 -0
  58. package/dist/data/arch/SKL.json.br +0 -0
  59. package/dist/data/arch/SKX.json.br +0 -0
  60. package/dist/data/arch/SNB.json.br +0 -0
  61. package/dist/data/arch/TGL.json.br +0 -0
  62. package/dist/data/arch/ZEN3.json.br +0 -0
  63. package/lib/insights.js +0 -100
  64. package/lib/whatif.js +0 -136
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
 
@@ -0,0 +1,27 @@
1
+ // The built-in examples: the web page's set (web/js/examples.js, copied to lib/web with the other shared files, so the
2
+ // page and the package cannot drift): the basics, the classic loops and the SHA-256 showcase (machine code only: its
3
+ // assembly, about 60 KB, stays on the page). Not the mock engine's entries.
4
+
5
+ import { EXAMPLES, CLASSIC_EXAMPLES, SHOWCASE_EXAMPLES } from './web/examples.js';
6
+
7
+ /** @type {['basics' | 'classic' | 'showcase', any[]][]} */
8
+ const GROUPS = [['basics', EXAMPLES], ['classic', CLASSIC_EXAMPLES], ['showcase', SHOWCASE_EXAMPLES]];
9
+
10
+ // [{name, title, group, arch, instructions, hex, intel?, att?}]: arch is the CPU the page shows it on first; intel and
11
+ // att the assembly (absent for the showcase, which is machine code only).
12
+ const LIST = Object.freeze(GROUPS.flatMap(([group, list]) => list.map((e) => {
13
+ const asm = typeof e.text.intel === 'string';
14
+ // the instructions: the lines of the listing (32-byte lines for the showcase: its title says how many)
15
+ const instructions = asm ? e.text.hex.trim().split('\n').length : Number(/([\d,]+) instr/.exec(e.title)?.[1].replace(/,/g, '') ?? 0);
16
+ return Object.freeze({ name: e.id, title: e.title, group, arch: e.arch, instructions, hex: e.hex, ...(asm ? { intel: e.text.intel, att: e.text.att } : {}) });
17
+ })));
18
+
19
+ export function examples() {
20
+ return LIST;
21
+ }
22
+
23
+ // The example called `name` (case-insensitive), or null.
24
+ export function findExample(name) {
25
+ const n = String(name ?? '').toLowerCase();
26
+ return LIST.find((e) => e.name.toLowerCase() === n) ?? null;
27
+ }
package/lib/files.js CHANGED
@@ -1,18 +1,41 @@
1
1
  // Reading the package's files (shared by the library and its worker threads).
2
2
 
3
3
  import fs from 'node:fs/promises';
4
+ import { readFileSync, existsSync } from 'node:fs';
5
+ import path from 'node:path';
4
6
  import zlib from 'node:zlib';
5
7
  import { promisify } from 'node:util';
6
8
 
7
9
  const brotli = promisify(zlib.brotliDecompress);
10
+ // a Uint8Array view of a Buffer (new Uint8Array(buffer) would copy it)
11
+ const view = (b) => new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
8
12
 
9
13
  // Reads a file; `.br` files are decompressed. For a path without `.br`, `<path>.br` is tried first.
10
14
  export async function readMaybeCompressed(file) {
11
- if (file.endsWith('.br')) return new Uint8Array(await brotli(await fs.readFile(file)));
15
+ if (file.endsWith('.br')) return view(await brotli(await fs.readFile(file)));
12
16
  try {
13
- return new Uint8Array(await brotli(await fs.readFile(file + '.br')));
17
+ return view(await brotli(await fs.readFile(file + '.br')));
14
18
  } catch (e) {
15
19
  if (e.code !== 'ENOENT') throw e;
16
20
  }
17
- return new Uint8Array(await fs.readFile(file));
21
+ return view(await fs.readFile(file));
22
+ }
23
+
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: the analyzer that ships reads no JSON tables and says so), each plain
26
+ // or .br.
27
+ export function tableFile(dataDir, name) {
28
+ const bin = path.join(dataDir, 'arch', `${name}.bin`);
29
+ return existsSync(bin) || existsSync(bin + '.br') ? bin : path.join(dataDir, 'arch', `${name}.json`);
30
+ }
31
+
32
+ // The same, synchronously (an analyzer reloads its tables this way after a trap, instead of keeping their bytes).
33
+ export function readMaybeCompressedSync(file) {
34
+ if (file.endsWith('.br')) return view(zlib.brotliDecompressSync(readFileSync(file)));
35
+ try {
36
+ return view(zlib.brotliDecompressSync(readFileSync(file + '.br')));
37
+ } catch (e) {
38
+ if (e.code !== 'ENOENT') throw e;
39
+ }
40
+ return view(readFileSync(file));
18
41
  }
package/lib/index.js CHANGED
@@ -12,28 +12,45 @@ import path from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { Analyzer, Assembler, parseDiagnostics, codeModeError } from './wasm.js';
14
14
  import { archList, DEFAULT_ARCH, ARCH_INFO, ARCH_ORDER } from './archs.js';
15
- import { insights } from './insights.js';
15
+ import { insights } from './web/bound-core.js';
16
+ import { cannotRun, noData } from './web/caveats.js';
17
+ import { analyzedLines, analyzedText } from './web/branch-label.js';
16
18
  import { instrDetails, detailInsights } from './details.js';
17
19
  export { detailInsights };
18
- import { readMaybeCompressed } from './files.js';
20
+ import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
21
+ import { readObject, objdumpText, resolveFunction, objectKind } from './objfile.js';
19
22
  import { CODES, WARM_HEX, failure, tableFailure, analysisResult, compareFields } from './core.js';
20
- import { ThreadPool, threadLimit, threadOption, threadsFor } from './threads.js';
23
+ import { ThreadPool, threadLimit, threadOption, threadsForWork } from './threads.js';
21
24
  // the web page's reading of pasted assembly (copies of web/js in lib/web: tests-js/web_pkg_copies.mjs): the loop of a whole function, objdump lines,
22
25
  // exits as not taken, ';' comments, region markers
23
- import { assembleMarked, commentFixes, separatorNotes } from './web/asm-regions.js';
26
+ import { assembleMarked, commentFixes, separatorNotes, spanLines } from './web/asm-regions.js';
24
27
  import { normalizeText, detectSyntax, preparePaste, syntaxSigns } from './web/loop-find.js';
25
28
  export { detectSyntax };
26
29
 
27
30
  // The loops of assembly text, as `loop` and `func` choose among them: [{index, label, function, line, endLine,
28
31
  // instructions, depth, auto}] (auto: the one "auto" analyzes) or {error}. No assembling.
32
+ /** @param {string} source @param {{func?: string | null}} [opts] @returns {any} (index.d.ts: LoopListing[] | {error}) */
29
33
  export function listLoops(source, { func = null } = {}) {
34
+ if (typeof source !== 'string') return { error: '`source` must be assembly text' };
30
35
  const p = preparePaste(normalizeText(source), { loop: 'auto', func });
31
36
  if (p.error) return { error: p.error };
32
- return p.loops.map((l, index) => ({ index, label: l.label, function: l.function, line: l.begin, endLine: l.end, instructions: l.instructions, depth: l.depth, auto: p.choice === index }));
37
+ return loopListing(p.loops, p.choice);
38
+ }
39
+
40
+ // The loops of a text (loop-find.js preparePaste's, or what an assembly of it found) as listLoops gives them; the one
41
+ // implementation behind -loops, the MCP tool list_loops and the analyze response's otherLoops.
42
+ function loopListing(loops, choice) {
43
+ return loops.map((l, index) => ({ index, label: l.label, function: l.function, line: l.begin, endLine: l.end, instructions: l.instructions, depth: l.depth, auto: choice === index }));
33
44
  }
34
45
 
35
46
  export { ARCH_INFO, ARCH_ORDER, DEFAULT_ARCH, CODES, WARM_HEX, parseDiagnostics, insights };
36
- export { whatIf, VARIANTS as WHAT_IF_VARIANTS } from './whatif.js';
47
+ export { whatIf, VARIANTS as WHAT_IF_VARIANTS, OPT_IN_VARIANTS as WHAT_IF_OPT_IN_VARIANTS, whatIfPerElement, whatIfText, whatIfRequest } from './web/whatif-core.js';
48
+ export { diffResult, diffAnalyses, diffRequest, diffMarkdown, diffText } from './web/block-diff.js';
49
+ import { diffRequest } from './web/block-diff.js';
50
+ import { whatIfRequest } from './web/whatif-core.js';
51
+ export { examples, findExample } from './examples.js';
52
+ export * as markdown from './web/markdown.js';
53
+ export { objectKind } from './objfile.js';
37
54
 
38
55
  const DIST = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
39
56
 
@@ -118,7 +135,7 @@ export function stderrLines(message) {
118
135
  const REQUEST_KEYS = ['source', 'asm', 'hex', 'syntax', 'loop', 'func', 'options'];
119
136
 
120
137
  // `loop` of a request: what of the source is analyzed (web/js/loop-find.js). null if it is not one of these.
121
- export const LOOP_CHOICES = Object.freeze(['auto', 'whole']);
138
+ export const LOOP_CHOICES = /** @type {readonly ['auto', 'whole']} */ (Object.freeze(['auto', 'whole']));
122
139
  // (a string other than these is a loop's label: ".LBB0_12", "0x10")
123
140
  const loopChoice = (v) => (v === undefined || v === null ? 'auto' : LOOP_CHOICES.includes(v) || (Number.isSafeInteger(v) && v >= 0) || (typeof v === 'string' && v.trim() !== '') ? v : null);
124
141
  const LOOP_ERROR = '`loop` must be "auto", "whole", the index of a loop (0-based) or its label';
@@ -147,6 +164,7 @@ function pickOptions(req, extraKeys) {
147
164
  // a value of the wrong kind is a bad request (code 1), like an unknown option, not a failed analysis
148
165
  const bad = typeof d === 'number' ? !Number.isSafeInteger(v) : typeof d === 'boolean' ? typeof v !== 'boolean'
149
166
  : k === 'initPolicy' && !['diff', 'same', 'stack'].includes(v);
167
+ if (bad && typeof d === 'number' && Number.isInteger(v)) return { error: `option ${k}: ${v} is out of range (at most 2^53 - 1 in magnitude)` };
150
168
  if (bad) return { error: `option ${k}: ${JSON.stringify(v)} is not ${typeof d === 'number' ? 'an integer' : typeof d === 'boolean' ? 'true or false' : 'one of "diff", "same", "stack"'}` };
151
169
  out[k] = v;
152
170
  }
@@ -154,6 +172,33 @@ function pickOptions(req, extraKeys) {
154
172
  }
155
173
 
156
174
 
175
+ // A compare() result with cycles per element (`per` elements per iteration, as the CLI's -arch with -per):
176
+ // elementsPerIteration on it and perElement (tp / per) on each row that has a tp. Unchanged without `per`.
177
+ export function comparePerElement(c, per) {
178
+ if (!per || c.code) return c;
179
+ return { ...c, elementsPerIteration: per, results: c.results.map((r) => (r.code === CODES.OK ? { ...r, perElement: r.tp / per } : r)) };
180
+ }
181
+
182
+ // The rows of an analysis with where each instruction came from (assembly input): `line` (1-based, of the text as given)
183
+ // and `loc` ("file.c:12", from .loc/.file directives). Only when the counts fit the instruction rows exactly (from the
184
+ // loop finder and the assembler, never by matching text); unchanged otherwise.
185
+ function withSourceLines(r, src) {
186
+ if (!src || !Array.isArray(r.rows)) return r;
187
+ const instr = r.rows.filter((x) => x.kind === 'instr');
188
+ const lines = Array.isArray(src.lines) && src.lines.length === instr.length ? src.lines : null;
189
+ const locs = src.loc?.spans?.length ? spanLines(r.rows, src.loc.spans) : null;
190
+ const file = src.loc?.file ?? null;
191
+ if (!lines && !(locs && file)) return r;
192
+ let k = 0;
193
+ const rows = r.rows.map((x) => {
194
+ if (x.kind !== 'instr') return x;
195
+ const i = k++;
196
+ const info = lines && src.info ? src.info.get(lines[i]) : undefined; // objdump -S, perf annotate: source, samples
197
+ return { ...x, ...(lines ? { line: lines[i] } : {}), ...(locs && file && locs[i] ? { loc: `${file}:${locs[i]}` } : {}), ...(info ?? {}) };
198
+ });
199
+ return { ...r, rows };
200
+ }
201
+
157
202
  // A list of arch names without repeats (the same id, or the same unknown name), in the order of their first appearance.
158
203
  function uniqueArchs(list, resolve) {
159
204
  const seen = new Set();
@@ -170,12 +215,14 @@ class Wuica {
170
215
  #archs;
171
216
  #dataDir;
172
217
  #asmWasm;
218
+ /** @type {Promise<any> | null} */
173
219
  #assembler = null; // promise of an Assembler
174
220
  #loading = new Map(); // table name -> promise
175
221
  #wasm; // bytes of the analyzer module (the threads compile it with a memory limit of their own)
176
222
  #uarch; // bytes of uarch.json
177
223
  #threads; // the most threads compare() uses (1: none)
178
224
  #threadsAuto; // no number given: at most one thread per two microarchitectures (threads.js, threadsFor)
225
+ /** @type {import('./threads.js').ThreadPool | null} */
179
226
  #pool = null; // ThreadPool, started by the first compare() that uses threads
180
227
 
181
228
  constructor(analyzer, configs, dataDir, asmWasm, { wasm, uarch, threads, threadsAuto }) {
@@ -216,8 +263,9 @@ class Wuica {
216
263
  let p = this.#loading.get(name);
217
264
  if (!p) {
218
265
  p = (async () => {
219
- const bytes = await readMaybeCompressed(path.join(this.#dataDir, 'arch', `${name}.json`));
220
- if (!this.#analyzer.hasArch(name)) this.#analyzer.loadArch(name, bytes);
266
+ const file = tableFile(this.#dataDir, name);
267
+ const bytes = await readMaybeCompressed(file);
268
+ if (!this.#analyzer.hasArch(name)) this.#analyzer.loadArch(name, bytes, () => readMaybeCompressedSync(file));
221
269
  })();
222
270
  this.#loading.set(name, p);
223
271
  p.finally(() => this.#loading.delete(name)).catch(() => {});
@@ -236,6 +284,7 @@ class Wuica {
236
284
  }
237
285
 
238
286
  // POST /api/assemble {source, syntax}
287
+ /** @param {string} source @param {string} [syntax] @returns {Promise<any>} */
239
288
  async assemble(source, syntax = 'auto') {
240
289
  if (typeof source !== 'string') return failure(CODES.REQUEST, '`source` must be a string');
241
290
  if (syntaxCode(syntax) < 0) return failure(CODES.REQUEST, SYNTAX_ERROR(syntax));
@@ -270,6 +319,7 @@ class Wuica {
270
319
  // lines, exits as not taken, ';' comments, a marked region (web/js/loop-find.js, asm-regions.js). loop: 'auto',
271
320
  // 'whole', a loop's index or its label; func: the function whose loops count (or null).
272
321
  // -> {code: 0, hex, bytes, stderr, loop, syntax} (loop: what was picked, or null; syntax: {name, detected}) or a failure.
322
+ /** @param {string} source @param {string} [syntax] @param {string | number} [loop] @param {string | null} [func] @returns {Promise<any>} */
273
323
  async machineCode(source, syntax = 'auto', loop = 'auto', func = null) {
274
324
  if (typeof source !== 'string') return failure(CODES.REQUEST, '`source` must be a string');
275
325
  if (syntaxCode(syntax) < 0) return failure(CODES.REQUEST, SYNTAX_ERROR(syntax));
@@ -288,7 +338,7 @@ class Wuica {
288
338
  const r = await assembleMarked(assemble, text, { loop: loopChoice(loop), func });
289
339
  if (trap) return failure(CODES.ASSEMBLER, trap, undefined, { trapped: true });
290
340
  if (!r.ok) {
291
- const bad = r.diagnostics.find((d) => /^(?:loop|func): /.test(d.message));
341
+ const bad = r.diagnostics.find((d) => /^(?:loop|func|input): /.test(d.message));
292
342
  if (bad) return failure(CODES.REQUEST, bad.message);
293
343
  if (looksAArch64(text)) return failure(CODES.ASSEMBLER, 'this looks like AArch64 assembly; wuica analyzes x86-64 (compile with --target=x86_64-linux-gnu)');
294
344
  const first = r.diagnostics.find((d) => d.severity === 'error');
@@ -305,7 +355,12 @@ class Wuica {
305
355
  const loopInfo = picked && { index: picked.index, count: picked.count, name: picked.name, line: picked.line, endLine: picked.endLine, ...(picked.lines ? { lines: picked.lines } : {}),
306
356
  ...(info ? { function: info.function, depth: info.depth, instructions: info.instructions } : {}),
307
357
  ...(picked.address !== null && picked.address !== undefined ? { address: picked.address } : {}), ...(r.alignment !== null ? { alignmentOffset: r.alignment } : {}) };
308
- return { code: CODES.OK, hex: Buffer.from(r.bytes).toString('hex'), bytes: r.bytes, stderr: diagnosticLines(r.diagnostics), loop: loopInfo, syntax: { name: syn.name, detected: syn.detected } };
358
+ // the other loops of the text, when it has more than one and one of them was analyzed (with -loop whole every loop
359
+ // is in the analyzed code; a marked region has none)
360
+ const otherLoops = r.loops.length > 1 && Number.isInteger(picked?.index) ? loopListing(r.loops, null).filter((l) => l.index !== picked?.index).map(({ auto, ...l }) => l) : null;
361
+ // where each instruction came from: its line of the text (the loop finder's), and its .loc line (the assembler's)
362
+ const sourceLines = { lines: r.lines ?? null, loc: r.source ?? null, info: r.lineInfo ?? null };
363
+ return { code: CODES.OK, hex: Buffer.from(r.bytes).toString('hex'), bytes: r.bytes, stderr: diagnosticLines(r.diagnostics), loop: loopInfo, syntax: { name: syn.name, detected: syn.detected }, ...(otherLoops ? { otherLoops } : {}), sourceLines };
309
364
  }
310
365
 
311
366
  // {source | asm | hex, syntax, loop} -> {hex, assembled, stderr, loop} or a failure.
@@ -328,7 +383,9 @@ class Wuica {
328
383
  const a = await this.machineCode(source, req.syntax ?? 'auto', loopChoice(req.loop), req.func ?? null);
329
384
  if (a.code !== CODES.OK) return a;
330
385
  if (a.bytes.length === 0) return failure(CODES.REQUEST, 'the source contains no instructions');
331
- return { hex: a.hex, assembled: true, stderr: a.stderr, loop: a.loop, syntax: a.syntax.name };
386
+ // (analyzed: the text of what was analyzed, which names an extension a CPU lacks: web/caveats.js cannotRun)
387
+ const analyzed = typeof source === 'string' ? analyzedText(analyzedLines(normalizeText(source).replace(/^\uFEFF/, ''), { loop: a.loop })) : null;
388
+ return { hex: a.hex, assembled: true, stderr: a.stderr, loop: a.loop, syntax: a.syntax.name, ...(a.otherLoops ? { otherLoops: a.otherLoops } : {}), sourceLines: a.sourceLines, analyzed };
332
389
  }
333
390
 
334
391
  // The options of a request with the alignment offset of the code's addresses (objdump input), unless it was given.
@@ -358,46 +415,135 @@ class Wuica {
358
415
  if (opts.error) return failure(CODES.REQUEST, opts.error);
359
416
  const code = await this.#code(req);
360
417
  if (code.code !== undefined) return code;
361
- const r = await this.#run(code.hex, arch, Wuica.#withAlignment(req, opts.options, code));
418
+ return Wuica.#analyzeResult(code, await this.#run(code.hex, arch, Wuica.#withAlignment(req, opts.options, code)));
419
+ }
420
+
421
+ // analyze()'s result from the code (#code) and the analysis (#run)
422
+ static #analyzeResult(code, r) {
362
423
  if (r.code !== undefined) return r;
424
+ r = withSourceLines(r, code.sourceLines);
363
425
  const stderr = [...code.stderr];
364
426
  if (r.decodeErrors > 0) stderr.push({ text: `Warning: ${r.decodeErrors} position(s) could not be decoded` });
365
- return { code: CODES.OK, ...r, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr };
427
+ // code this CPU cannot run (web/caveats.js cannotRun): the number is the reference's, but not a result for it
428
+ const bad = cannotRun(r, { arch: r.arch, code: code.analyzed ?? null }), gaps = noData(r, { arch: r.arch });
429
+ return { code: CODES.OK, ...r, ...(bad ? { unsupported: bad.reason } : {}), ...(gaps ? { noData: gaps } : {}), ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), ...(code.otherLoops ? { otherLoops: code.otherLoops } : {}), stderr };
366
430
  }
367
431
 
368
- // POST /api/compare {source | hex, syntax, archs?, options}: one block on several microarchitectures (default: all).
369
- async compare(request = {}) {
370
- const opts = pickOptions(request, ['archs']);
371
- if (opts.error) return failure(CODES.REQUEST, opts.error);
372
- const code = await this.#code(request);
373
- if (code.code !== undefined) return code;
374
- if (request.archs !== undefined && !Array.isArray(request.archs)) return failure(CODES.REQUEST, '`archs` must be an array of ids');
375
- const ids = request.archs?.length ? uniqueArchs(request.archs, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
376
- const options = { ...Wuica.#withAlignment(request, opts.options, code), includeTrace: false, details: false };
377
- const resolved = ids.map((arch) => this.resolveArch(arch));
378
- // the microarchitectures in threads (if that means at least two threads), each as #run() would on this thread;
379
- // whatever the threads do not do (unknown ids, a thread that failed) is done here, one after another
380
- const fields = new Array(ids.length).fill(null);
381
- const known = resolved.flatMap((id, i) => (id ? [{ i, table: this.#configs[id].name, request: { hex: code.hex, arch: id, ...options } }] : []));
382
- const threads = threadsFor(new Set(known.map((j) => j.table)).size, this.#threads, this.#threadsAuto);
432
+ // Several blocks on one microarchitecture: [request] -> [analyze() result] in the same order (each exactly what
433
+ // analyze(arch, request) returns). The code is assembled here; the analyses run on the threads when the work is worth
434
+ // it (threads.js, threadsForWork).
435
+ async analyzeMany(arch, requests) {
436
+ if (!Array.isArray(requests)) return failure(CODES.REQUEST, '`requests` must be an array');
437
+ const prepared = await this.#prepare(requests, ['arch']);
438
+ const jobs = prepared.flatMap((p, i) => (p.failure ? [] : [{ i, hex: p.code.hex, arch, options: Wuica.#withAlignment(p.request, p.options, p.code), full: true }]));
439
+ const done = await this.#runJobs(jobs);
440
+ const out = prepared.map((p) => p.failure);
441
+ jobs.forEach((j, k) => { out[j.i] = Wuica.#analyzeResult(prepared[j.i].code, done[k]); });
442
+ return out;
443
+ }
444
+
445
+ // Several blocks on several microarchitectures: [request] -> [compare() result] in the same order (each exactly what
446
+ // compare(request) returns; `archs` is that of each request, else of the call, else all). Every block x CPU is one
447
+ // job for the threads.
448
+ /** @param {any[]} requests @param {{archs?: string[]}} [opts] */
449
+ async compareMany(requests, { archs } = {}) {
450
+ if (!Array.isArray(requests)) return failure(CODES.REQUEST, '`requests` must be an array');
451
+ const prepared = await this.#prepare(requests, ['archs']);
452
+ const jobs = [], rows = [];
453
+ prepared.forEach((p, i) => {
454
+ if (p.failure) return;
455
+ const list = p.request.archs ?? archs;
456
+ if (list !== undefined && !Array.isArray(list)) { p.failure = failure(CODES.REQUEST, '`archs` must be an array of ids'); return; }
457
+ const ids = list?.length ? uniqueArchs(list, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
458
+ const options = { ...Wuica.#withAlignment(p.request, p.options, p.code), includeTrace: false, details: false };
459
+ rows[i] = ids.map((a) => { jobs.push({ i, hex: p.code.hex, arch: a, options }); return a; });
460
+ });
461
+ const done = await this.#runJobs(jobs);
462
+ let k = 0;
463
+ return prepared.map((p, i) => {
464
+ if (p.failure) return p.failure;
465
+ const fields = rows[i].map(() => done[k++]);
466
+ return this.#compareResult(p.code, rows[i], fields);
467
+ });
468
+ }
469
+
470
+ // The requests checked and their code assembled, one after another: [{request, options, code} | {failure}]
471
+ async #prepare(requests, extra) {
472
+ const out = [];
473
+ for (const req of requests) {
474
+ if (typeof req !== 'object' || req === null) { out.push({ failure: failure(CODES.REQUEST, 'the request must be an object') }); continue; }
475
+ const opts = pickOptions(req, extra);
476
+ if (opts.error) { out.push({ failure: failure(CODES.REQUEST, opts.error) }); continue; }
477
+ const code = await this.#code(req);
478
+ if (code.code !== undefined) { out.push({ failure: code }); continue; }
479
+ out.push({ request: req, options: opts.options, code });
480
+ }
481
+ return out;
482
+ }
483
+
484
+ // [{hex, arch, options, full}] -> the analyses in the same order: analyze results (full) or compare() row fields. On
485
+ // the threads when the work is worth it (threadsForWork) or -threads asks; what they do not do (an unknown arch, a
486
+ // thread that failed) is done here, one after another.
487
+ async #runJobs(list) {
488
+ const out = new Array(list.length).fill(null);
489
+ const known = list.flatMap((j, i) => {
490
+ const id = this.resolveArch(j.arch);
491
+ return id ? [{ i, table: this.#configs[id].name, request: { hex: j.hex, arch: id, ...j.options }, full: !!j.full }] : [];
492
+ });
493
+ const threads = this.#threadsAuto ? threadsForWork(known, this.#threads) : Math.min(this.#threads, known.length);
383
494
  if (threads > 1) {
384
- this.#pool ??= new ThreadPool({ wasm: this.#wasm, uarch: this.#uarch, dataDir: this.#dataDir, limit: this.#threads });
495
+ if (!this.#pool) {
496
+ // the pool compiles the module for its threads once; its bytes are dropped after that
497
+ this.#pool = new ThreadPool({ wasm: this.#wasm, uarch: this.#uarch, dataDir: this.#dataDir, limit: this.#threads });
498
+ this.#wasm = null;
499
+ }
385
500
  if (!this.#pool.broken) {
386
501
  const done = await this.#pool.run(known, threads);
387
- known.forEach((j, k) => { fields[j.i] = done[k]; });
502
+ known.forEach((j, k) => { out[j.i] = done[k]; });
388
503
  }
389
504
  }
390
- const results = [];
391
- for (const [i, arch] of ids.entries()) {
392
- const id = resolved[i];
393
- const { name, year, prototype } = id ? this.#info(id) : { name: String(arch), year: null, prototype: false };
394
- const row = { arch: id ?? String(arch), name, year, prototype };
395
- results.push({ ...row, ...(fields[i] ?? compareFields(await this.#run(code.hex, arch, options))) });
505
+ for (const [i, j] of list.entries()) {
506
+ if (out[i] !== null) continue;
507
+ const r = await this.#run(j.hex, j.arch, j.options);
508
+ out[i] = j.full ? r : compareFields(r);
396
509
  }
510
+ return out;
511
+ }
512
+
513
+ // compare()'s result from the code, the microarchitectures asked for and their fields (#runJobs)
514
+ #compareResult(code, ids, fields) {
515
+ const results = ids.map((arch, i) => {
516
+ const id = this.resolveArch(arch);
517
+ const { name, year, prototype } = id ? this.#info(id) : { name: String(arch), year: null, prototype: false };
518
+ const { xOps, ...f } = fields[i];
519
+ // code this CPU cannot run (web/caveats.js cannotRun): `unsupported`, the reason; else instructions without data
520
+ // (gaps in its tables): `noData`, their count
521
+ const s = { decodeErrors: f.decodeErrors, xOps: xOps ?? [] };
522
+ const bad = f.code === CODES.OK ? cannotRun(s, { arch: id, code: code.analyzed ?? null }) : null;
523
+ const gaps = f.code === CODES.OK ? noData(s, { arch: id }) : 0;
524
+ return { arch: id ?? String(arch), name, year, prototype, ...f, ...(bad ? { unsupported: bad.reason } : {}), ...(gaps ? { noData: gaps } : {}) };
525
+ });
397
526
  // a CPU that could not decode some instructions (FMA on SNB): its throughput leaves them out
398
527
  const decode = results.filter((r) => r.code === CODES.OK && r.decodeErrors > 0)
399
528
  .map((r) => ({ text: `Warning: ${r.arch}: ${r.decodeErrors} position(s) could not be decoded (instructions it does not have): its throughput leaves them out` }));
400
- return { code: CODES.OK, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr: [...code.stderr, ...decode], results };
529
+ return { code: CODES.OK, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), ...(code.otherLoops ? { otherLoops: code.otherLoops } : {}), stderr: [...code.stderr, ...decode], results };
530
+ }
531
+
532
+ // POST /api/compare {source | hex, syntax, archs?, options}: one block on several microarchitectures (default: all).
533
+ /** @param {any} [request] @returns {Promise<any>} */
534
+ async compare(request = {}) {
535
+ const opts = pickOptions(request, ['archs', 'per']);
536
+ if (opts.error) return failure(CODES.REQUEST, opts.error);
537
+ const code = await this.#code(request);
538
+ if (code.code !== undefined) return code;
539
+ if (request.archs !== undefined && !Array.isArray(request.archs)) return failure(CODES.REQUEST, '`archs` must be an array of ids');
540
+ const ids = request.archs?.length ? uniqueArchs(request.archs, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
541
+ const options = { ...Wuica.#withAlignment(request, opts.options, code), includeTrace: false, details: false };
542
+ // each microarchitecture as #run() would do it here, on the threads when the work is worth it (#runJobs)
543
+ const per = request.per;
544
+ if (per !== undefined && !(typeof per === 'number' && Number.isFinite(per) && per > 0)) return failure(CODES.REQUEST, '`per` must be a positive number (elements per iteration)');
545
+ const fields = await this.#runJobs(ids.map((arch) => ({ hex: code.hex, arch, options })));
546
+ return comparePerElement(this.#compareResult(code, ids, fields), per);
401
547
  }
402
548
 
403
549
  // Stops compare()'s threads, if any (they also stop by themselves when idle, and never keep the process alive while
@@ -409,21 +555,36 @@ class Wuica {
409
555
  // The number of threads compare() has running now (0 if none).
410
556
  get threads() { return this.#pool?.threads ?? 0; }
411
557
 
412
- // The derived diagnosis of an analyze() response (insights.js) with this CPU's configuration (the split-load caveat
558
+ // The derived diagnosis of an analyze() response (web/bound-core.js) with this CPU's configuration (the split-load caveat
413
559
  // depends on it); null for a failure.
560
+ // The what-if experiments of a block (web/js/whatif-core.js whatIfRequest): request as analyze's, with `variants` and
561
+ // `per`. The MCP tool what_if and POST /api/what-if/<arch> give the same.
562
+ /** @param {string} arch @param {any} [request] @returns {Promise<any>} */
563
+ async whatIf(arch, request = {}) {
564
+ return whatIfRequest(this, arch, request);
565
+ }
566
+
567
+ // Two blocks on one microarchitecture (web/js/block-diff.js): {a: block, b: block, options?, per?} -> the change of
568
+ // throughput, bottlenecks, limits, ports and instructions. wuica diff, the MCP tool diff_blocks and POST /api/diff/<arch>.
569
+ /** @param {string} arch @param {any} request @returns {Promise<any>} */
570
+ async diff(arch, request) {
571
+ return diffRequest(this, arch, request);
572
+ }
573
+
414
574
  insights(r) {
415
575
  return r?.code === CODES.OK ? insights(r, this.#configs[r.arch] ?? null) : null;
416
576
  }
417
577
 
418
578
  // The compact form of an analyze() response (used by the MCP server): uop table reduced to non-zero values, plus the
419
- // derived diagnosis of the web page's bound view (insights.js).
579
+ // derived diagnosis of the web page's bound view (web/bound-core.js).
420
580
  summarize(r) {
421
581
  if (r.code !== CODES.OK) return r;
422
582
  const { name, year, prototype } = this.#info(r.arch);
423
583
  const round = (x) => Math.round(x * 100) / 100;
424
584
  const sources = new Set(['MITE', 'MS', 'DSB', 'LSD']);
425
585
  const instructions = r.rows.map((row, k) => {
426
- const e = { instr: row.label };
586
+ /** @type {Record<string, any>} */
587
+ const e = { instr: row.label, ...(row.line ? { line: row.line } : {}), ...(row.loc ? { loc: row.loc } : {}), ...(row.source !== undefined ? { source: row.source } : {}), ...(row.samples !== undefined ? { samples: row.samples } : {}) };
427
588
  if (row.opcode) e.bytes = row.opcode.toLowerCase();
428
589
  if (row.kind !== 'instr') e.kind = row.kind;
429
590
  const uopSource = {}, ports = {};
@@ -447,11 +608,35 @@ class Wuica {
447
608
  const ins = base ? { ...base, ...detailInsights(r) } : null;
448
609
  return {
449
610
  code: r.code, arch: r.arch, name, year, prototype, tp: r.tp, unit: 'cycles per iteration', mode: r.mode,
450
- bottlenecks: r.bottlenecks, limits: r.limits, decodeErrors: r.decodeErrors, ...(r.hex ? { hex: r.hex } : {}), ...(r.loop ? { loop: r.loop } : {}),
611
+ bottlenecks: r.bottlenecks, limits: r.limits, decodeErrors: r.decodeErrors, ...(r.unsupported ? { unsupported: r.unsupported } : {}), ...(r.noData ? { noData: r.noData } : {}), ...(r.hex ? { hex: r.hex } : {}), ...(r.loop ? { loop: r.loop } : {}), ...(r.otherLoops ? { otherLoops: r.otherLoops } : {}),
451
612
  stderr: r.stderr, instructions, ...(ins ? { insights: ins } : {}),
452
613
  };
453
614
  }
454
615
 
616
+ // An object file (ELF or Mach-O, x86-64; objfile.js) as llvm-objdump -d's text of its code, which analyze() and
617
+ // compare() read as `source` (the objdump path: the loop at its address, exits stubbed, the alignment from it).
618
+ // -> {code: 0, text, format, functions: [{name, section, address, size}]} or a failure (another architecture says how
619
+ // to compile for x86-64). `func`: also resolves a -func name (exact, without Mach-O's "_", or a unique part): `func`.
620
+ /** @param {Uint8Array} bytes @param {{name?: string, func?: string | null}} [opts] @returns {any} */
621
+ disassemble(bytes, { name = 'input', func = null } = {}) {
622
+ const obj = readObject(bytes);
623
+ if (obj.error) return failure(CODES.REQUEST, obj.error);
624
+ if (!obj.functions.length) return failure(CODES.REQUEST, 'no functions in the code sections');
625
+ let resolved = null;
626
+ if (func !== null && func !== undefined) {
627
+ const r = resolveFunction(obj.functions, func);
628
+ if (r.error) return failure(CODES.REQUEST, r.error);
629
+ resolved = r.name;
630
+ }
631
+ let text;
632
+ try {
633
+ text = objdumpText(obj, (b) => this.#analyzer.decode(b, 'ALL'), name);
634
+ } catch (e) {
635
+ return failure(CODES.ANALYSIS, `the decoder failed (${e.message})`);
636
+ }
637
+ return { code: CODES.OK, text, format: obj.format, functions: obj.functions.map(({ name: n, section, address, size }) => ({ name: n, section, address, size })), ...(resolved !== null ? { func: resolved } : {}) };
638
+ }
639
+
455
640
  get restarts() { return this.#analyzer.restarts; }
456
641
  }
457
642
 
@@ -460,6 +645,7 @@ class Wuica {
460
645
  // options.threads: the most worker threads compare() uses, one per microarchitecture (default: the environment variable
461
646
  // WUICA_THREADS, else "auto": os.availableParallelism(), and one thread per two microarchitectures; 1 = none, every
462
647
  // microarchitecture one after another on this thread).
648
+ /** @param {import('../index.d.ts').CreateOptions} [options] */
463
649
  export async function createWuica(options = {}) {
464
650
  const threads = threadLimit(options.threads);
465
651
  const threadsAuto = threadOption(options.threads) === 'auto';