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.
@@ -0,0 +1,211 @@
1
+ // The bound model of a response, without the DOM: how busy each resource is as a share of the predicted cycles, the
2
+ // binding resource, the next limit after it, which instructions use a resource (blame), and the compact form of all
3
+ // that the npm package returns as `insights` (REST, MCP, the CLI's -json). One module for the page (bound.js, icard.js,
4
+ // srcmap.js render it) and the package (its copy in packages/wuica/lib/web, web-modules.json).
5
+
6
+ import { caveats } from './caveats.js';
7
+
8
+ const EPS = 0.005; // values are shown with two decimals
9
+ const LIMIT_GROUP = { Issue: 'issue', Ports: 'ports', Dependencies: 'deps' }; // the rest: front end
10
+ const FE_COLUMN = { DSB: 'DSB', LSD: 'LSD', MS: 'MS' };
11
+ const SATURATED = 0.95; // "Ports": the ports at least this busy relative to the busiest one
12
+ const FRONT_END = ['MITE', 'MS', 'DSB', 'LSD'];
13
+ const COUNTS = ['Issued', 'Exec.'];
14
+
15
+ const sum = (a) => a.reduce((s, x) => s + x, 0);
16
+ const pct = (u) => `${Math.round(u * 100)}%`;
17
+ const f2 = (x) => Number(x).toFixed(2);
18
+ const round = (x) => Math.round(x * 100) / 100;
19
+
20
+ // The kind of a column of the uop table: 'front' (uops from the decoders, the DSB, the LSD, the MS), 'count' (issued,
21
+ // executed), 'port' ("Port 0", "ALU0", "FP2", "Div", ...: every other column is an execution resource).
22
+ export function columnKind(name) {
23
+ if (FRONT_END.includes(name)) return 'front';
24
+ if (COUNTS.includes(name)) return 'count';
25
+ return 'port';
26
+ }
27
+
28
+ // "Port 0" -> "p0"; Zen 3's names (ALU0, FP2, ...) and Div as they are
29
+ export function shortPort(name) {
30
+ const m = /^Port (\w+)$/.exec(name);
31
+ return m ? `p${m[1]}` : name === 'Div' ? 'div' : name;
32
+ }
33
+
34
+ function columnTotal(r, i) {
35
+ let t = 0;
36
+ for (const x of r.rows) t += Number(x.values?.[i]) || 0;
37
+ return t;
38
+ }
39
+
40
+ // The resources of a response:
41
+ // {tp, items: [{id, name, title, group, cycles, util, limit, bottleneck}], binding: [ids], next: {name, tp, speedup} | null,
42
+ // gap}. util = cycles / tp (1: busy every cycle; above 1: uiCA's bound is above the simulated throughput).
43
+ // binding: the bottlenecks uiCA names that are resources here (the divider: its Div column); when it names none, the
44
+ // largest limit(s), the nearest bound. A bottleneck without a limit of its own ("Scheduling") binds nothing here: no
45
+ // resource is marked and there is no next limit (until 0.1.9 the page then took the largest limits as binding and showed
46
+ // the next limit below them, which is no bound once the scheduling goes; the package's insights had it right).
47
+ // next: the largest limit below the binding one; speedup = tp / next.tp is an upper bound (the next limit is a lower
48
+ // bound of the cycles). gap: cycles that no single limit explains (interactions), 0 if none.
49
+ export function boundModel(r) {
50
+ const tp = Number(r?.tp);
51
+ if (!(tp > 0) || !Array.isArray(r.limits) || !Array.isArray(r.columns) || !Array.isArray(r.rows)) return null;
52
+ const bottlenecks = Array.isArray(r.bottlenecks) ? r.bottlenecks : [];
53
+ const items = [];
54
+ for (const l of r.limits) {
55
+ const c = Number(l.tp);
56
+ if (!Number.isFinite(c)) continue;
57
+ items.push({
58
+ id: l.name, name: l.name, group: LIMIT_GROUP[l.name] ?? 'front', cycles: c, util: c / tp, limit: true,
59
+ bottleneck: bottlenecks.includes(l.name),
60
+ title: `${l.name}: ${f2(c)} cycles/iteration if it were the only bottleneck (${pct(c / tp)} of ${f2(tp)})`,
61
+ });
62
+ }
63
+ r.columns.forEach((name, i) => {
64
+ if (columnKind(name) !== 'port') return;
65
+ const c = columnTotal(r, i);
66
+ if (c <= 0) return;
67
+ const div = name === 'Div';
68
+ items.push({
69
+ id: `col:${name}`, name: shortPort(name), group: 'ports', cycles: c, util: c / tp, limit: false, bottleneck: false,
70
+ title: div ? `divider: busy ${f2(c)} cycles/iteration (${pct(c / tp)})` : `${name}: ${f2(c)} uops/iteration, busy ${pct(c / tp)} of the cycles`,
71
+ });
72
+ });
73
+ const limits = items.filter((x) => x.limit);
74
+ const max = limits.length ? Math.max(...limits.map((x) => x.cycles)) : 0;
75
+ const gap = limits.length && tp - max > EPS ? tp - max : 0;
76
+ if (gap) {
77
+ items.push({ id: 'other', name: 'unexplained', group: 'other', cycles: gap, util: gap / tp, limit: false, bottleneck: false,
78
+ title: `${f2(gap)} cycles/iteration that no single limit explains (interactions between front end, ports and dependencies)` });
79
+ }
80
+ const binding = bottlenecks.map((b) => resourceId(r, b)).filter((b) => items.some((x) => x.id === b));
81
+ if (!bottlenecks.length) for (const x of limits) if (x.cycles >= max - EPS) binding.push(x.id);
82
+ const bindValue = Math.max(...binding.map((b) => items.find((x) => x.id === b).cycles), 0);
83
+ /** @type {{name: string, tp: number, speedup?: number} | null} */
84
+ let next = null;
85
+ for (const x of limits) if (!binding.includes(x.id) && x.cycles < bindValue - EPS && (!next || x.cycles > next.tp)) next = { name: x.name, tp: x.cycles };
86
+ if (next) next.speedup = next.tp > 0 ? tp / next.tp : Infinity;
87
+ return { tp, items, binding, next, gap };
88
+ }
89
+
90
+ // The resource of a bottleneck's name: the divider (no limit of its own) is its Div column
91
+ const resourceId = (r, name) => (name === 'Divider' && r.columns.includes('Div') ? 'col:Div' : name);
92
+
93
+ // The share of each row of the response in a resource: {weights, total, max, unit, ports, portColumns} or null (nothing
94
+ // to attribute).
95
+ // col:<name> the row's uops on that port (or cycles on the divider)
96
+ // Ports its uops on the saturated ports (at least 95 % as busy as the busiest port); ports: their short names,
97
+ // portColumns: the columns
98
+ // Issue its issued (fused) uops; DSB, LSD, MS: its uops from there
99
+ // Decoder its uops from the legacy decoders (MITE); every instruction once if none come from there
100
+ // Predecoder its bytes
101
+ // Dependencies the latency of the chain's edges that start at it
102
+ export function blame(r, id) {
103
+ const n = r.rows.length;
104
+ const w = new Float64Array(n);
105
+ const col = (name) => r.columns.indexOf(name);
106
+ const fromColumn = (i) => { for (let k = 0; k < n; k++) w[k] = Number(r.rows[k].values?.[i]) || 0; };
107
+ let unit = 'uops';
108
+ if (id.startsWith('col:')) {
109
+ const i = col(id.slice(4));
110
+ if (i < 0) return null;
111
+ fromColumn(i);
112
+ if (id === 'col:Div') unit = 'cycles';
113
+ } else if (id === 'Ports') {
114
+ const ports = r.columns.map((name, i) => ({ i, name, t: columnKind(name) === 'port' && name !== 'Div' ? columnTotal(r, i) : 0 })).filter((p) => p.t > 0);
115
+ if (!ports.length) return null;
116
+ const top = Math.max(...ports.map((p) => p.t));
117
+ const hot = ports.filter((p) => p.t >= SATURATED * top);
118
+ for (let k = 0; k < n; k++) w[k] = sum(hot.map((p) => Number(r.rows[k].values?.[p.i]) || 0));
119
+ return finish(w, unit, hot.map((p) => p.name));
120
+ } else if (id === 'Issue') {
121
+ const i = col('Issued');
122
+ if (i < 0) return null;
123
+ fromColumn(i);
124
+ } else if (FE_COLUMN[id]) {
125
+ const i = col(FE_COLUMN[id]);
126
+ if (i < 0) return null;
127
+ fromColumn(i);
128
+ } else if (id === 'Decoder') {
129
+ const i = col('MITE');
130
+ if (i >= 0 && columnTotal(r, i) > 0) fromColumn(i);
131
+ else { unit = 'instructions'; r.rows.forEach((x, k) => { w[k] = x.kind === 'instr' && x.notes !== 'M' ? 1 : 0; }); }
132
+ } else if (id === 'Predecoder') {
133
+ unit = 'bytes';
134
+ r.rows.forEach((x, k) => { w[k] = x.kind === 'instr' ? String(x.opcode ?? '').length / 2 : 0; });
135
+ } else if (id === 'Dependencies') {
136
+ const edges = r.criticalPath?.edges;
137
+ if (!Array.isArray(edges) || !edges.length) return null;
138
+ unit = 'cycles';
139
+ for (const e of edges) if (e.from >= 0 && e.from < n) w[e.from] += Number(e.latency) || 0;
140
+ } else {
141
+ return null;
142
+ }
143
+ return finish(w, unit, null);
144
+ }
145
+
146
+ function finish(w, unit, columns) {
147
+ let total = 0, max = 0;
148
+ for (const x of w) { total += x; if (x > max) max = x; }
149
+ if (!(total > 0)) return null;
150
+ return { weights: w, total, max, unit, ports: columns ? columns.map(shortPort) : null, portColumns: columns };
151
+ }
152
+
153
+ // The rows with the largest shares: [{row, share}], largest first (ties: in table order).
154
+ export function topRows(b, count = 5) {
155
+ if (!b) return [];
156
+ const out = [];
157
+ b.weights.forEach((x, row) => { if (x > 0) out.push({ row, share: x / b.total }); });
158
+ out.sort((a, c) => c.share - a.share || a.row - c.row);
159
+ return out.slice(0, count);
160
+ }
161
+
162
+ // The resource selected by default: the first bottleneck (or the largest limit).
163
+ export const defaultResource = (m) => m?.binding[0] ?? null;
164
+
165
+ // The package's insights (the bound model in its compact form):
166
+ // {utilization, binding, largest?, next?, unexplained?, chain?, hot?, caveats?} or null.
167
+ // utilization: {limit or port column: cycles / tp} (1 = busy every cycle; above 1: uiCA's bound is above the simulation)
168
+ // binding: the bottlenecks uiCA names (the response's `bottlenecks`; [] when it names none: no single limit explains
169
+ // tp, the page says "unknown")
170
+ // largest: when uiCA names none, the largest limit(s): the nearest bound, which alone does not reach tp
171
+ // next: {limit, tp, maxSpeedup}: the largest limit below the binding one; tp / next.tp is an upper bound of the speedup
172
+ // unexplained: cycles per iteration that no single limit explains
173
+ // chain: the critical loop-carried chain: [{index, instr, operand, latency, carried}] (index into `instructions`)
174
+ // hot: {resource, ports?, instructions: [{index, instr, share}]}: the largest shares of the binding resource (top 5)
175
+ // caveats: [{id, text, title, instructions: [index]}]: known blind spots the block meets (caveats.js); absent if none
176
+ // config: the CPU's configuration in uarch.json (configs[r.arch]), for the caveats; without it, split warns as on a CPU
177
+ // without a split-load cost.
178
+ // where a row's instruction came from, if the response says (the package's analyze: `line`, `loc`)
179
+ const sourceOf = (row) => ({ ...(row?.line ? { line: row.line } : {}), ...(row?.loc ? { loc: row.loc } : {}) });
180
+
181
+ /** @param {any} r @param {{splitLoadCycles?: number} | null} [config] */
182
+ export function insights(r, config = null) {
183
+ const m = boundModel(r);
184
+ if (!m) return null;
185
+ const tp = m.tp;
186
+ const utilization = {};
187
+ for (const l of r.limits) utilization[l.name] = round(l.tp / tp);
188
+ for (const x of m.items) if (x.id.startsWith('col:')) utilization[x.id.slice(4)] = round(x.util);
189
+ const binding = [...(r.bottlenecks ?? [])];
190
+ const largest = binding.length ? [] : m.binding;
191
+ /** @type {Record<string, any>} */
192
+ const out = { utilization, binding };
193
+ if (largest.length) out.largest = largest;
194
+ if (m.next) out.next = { limit: m.next.name, tp: m.next.tp, maxSpeedup: m.next.tp > 0 ? round(tp / m.next.tp) : null };
195
+ if (m.gap) out.unexplained = round(m.gap);
196
+ const edges = r.criticalPath?.edges;
197
+ if (Array.isArray(edges) && edges.length) {
198
+ out.chain = edges.map((e) => ({ index: e.from, instr: r.rows[e.from]?.label, ...sourceOf(r.rows[e.from]), operand: String(e.operand).toLowerCase(), latency: e.latency, carried: !!e.carried }));
199
+ }
200
+ const top = binding.length ? binding : largest;
201
+ if (top[0]) {
202
+ const b = blame(r, resourceId(r, top[0]));
203
+ if (b) {
204
+ const instructions = topRows(b).map((x) => ({ index: x.row, instr: r.rows[x.row].label, ...sourceOf(r.rows[x.row]), share: round(x.share) }));
205
+ out.hot = { resource: top[0], ...(b.portColumns ? { ports: b.portColumns } : {}), instructions };
206
+ }
207
+ }
208
+ const cv = caveats(r, config);
209
+ if (cv.length) out.caveats = cv.map((c) => ({ id: c.id, text: c.text, title: c.title, instructions: c.rows }));
210
+ return out;
211
+ }
@@ -0,0 +1,155 @@
1
+ // Branch targets in the uop table as labels. The analyzer disassembles every instruction at address 0, so a loop
2
+ // branch reads "jnz 0xfffffffffffffff4": its target relative to the instruction. Added to the instruction's offset in
3
+ // the block, that is the target in the block. Shown as:
4
+ // - the operand as written in the pasted assembly when it is a symbol that the analyzed code does not define (an exit
5
+ // of a picked loop, "call sink@PLT"), wherever the bytes go: an undefined symbol's displacement is a placeholder;
6
+ // - the label written in the pasted assembly, when the branch's own operand names the target (a label defined there,
7
+ // a GNU numeric "1b" / "1f" as written);
8
+ // - else a label of the pasted text defined exactly at the target; else the nearest one before it plus the offset
9
+ // ("loop+0x10");
10
+ // - else (machine code, or no label before the target) the offset in the block ("jnz 0x0");
11
+ // - a target outside the block, or a call or jump whose 32-bit displacement is 0 (the placeholder of a relocation in an
12
+ // object file), relative to the instruction (".+0xc", ".-0x10"): its address is not known. The row's own label (its
13
+ // tooltip, exports) is unchanged.
14
+ // The labels' offsets come from the text's statements matched one to one with the instruction rows; when the text
15
+ // cannot be matched that way (data or alignment directives in the code, a macro), only offsets are shown.
16
+ // No DOM (tests-js/web_branch_label.mjs).
17
+
18
+ import { statements } from './loop-find.js';
19
+
20
+ const BRANCH = /^((?:(?:bnd|notrack)\s+)?(?:j[a-z]{1,4}|loop[a-z]{0,2}|jrcxz|jecxz|xbegin|call))\s+(0x[0-9a-f]{1,16})$/i;
21
+ const LABEL_ONE = /\s*([A-Za-z_.$@][\w.$@]*|\d+)\s*:(?!:)/y;
22
+ const SYMBOL = /^[A-Za-z_.$@][\w.$@]*$/;
23
+ const NUMERIC_REF = /^\d+[bf]$/i;
24
+ const INTERNAL = /^\.Lwuica_/; // labels the page itself puts into the text (asm-regions.js, loop-find.js)
25
+ // directives that put bytes into the code (or repeat it): the statements no longer match the rows one to one
26
+ const EMITS = /^\.(?:byte|2byte|4byte|8byte|word|short|hword|int|long|quad|octa|value|ascii|asciz|string\d*|fill|skip|space|zero|align|balign[wl]?|p2align[wl]?|rept|irp|irpc|endr|macro|endm|insn|inst|org|incbin|nops?)\b/i;
27
+ const SECTION = /^\.(?:section|data|bss|rodata|pushsection|popsection|previous)\b/i;
28
+
29
+ // The code of lines from..to (1-based, inclusive) of assembly text: [{kind: 'label', name} | {kind: 'instr', operand}]
30
+ // in order, or null if the statements cannot be matched with machine code one to one.
31
+ export function codeStatements(text, from = 1, to = Infinity) {
32
+ const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
33
+ const out = [];
34
+ for (let i = Math.max(1, from); i <= Math.min(lines.length, to); i++) {
35
+ const raw = lines[i - 1];
36
+ if (/^\s*;/.test(raw)) continue; // a comment line (loop-find.js)
37
+ for (const st of statements(raw)) {
38
+ let t = st.text;
39
+ LABEL_ONE.lastIndex = 0;
40
+ let m;
41
+ while ((m = LABEL_ONE.exec(t))) { out.push({ kind: 'label', name: m[1] }); t = t.slice(LABEL_ONE.lastIndex); LABEL_ONE.lastIndex = 0; }
42
+ t = t.trim();
43
+ if (!t) continue;
44
+ if (t[0] === '.') {
45
+ if (EMITS.test(t) || SECTION.test(t)) return null;
46
+ continue; // .loc, .cfi_*, .type, ...: no code
47
+ }
48
+ if (/^[\w.$@]+\s*=/.test(t)) continue; // a symbol assignment
49
+ const op = /^\S+\s+(.*)$/.exec(t.replace(/^(?:(?:lock|rep\w*|bnd|notrack|data16|data32|addr32|[cdefgs]s)\s+)+/i, ''));
50
+ out.push({ kind: 'instr', operand: op ? op[1].trim() : '' });
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // A target relative to the instruction's start, as an assembler reads it: ".+0xc", ".-0x10"
57
+ /** @param {number} rel */
58
+ export const relativeTarget = (rel) => (rel < 0 ? `.-0x${(-rel).toString(16)}` : `.+0x${rel.toString(16)}`);
59
+
60
+ // The direct branches and calls of the rows: per row null, or {mnemonic, rel (the target relative to the instruction's
61
+ // start: what the analyzer prints), offset (the instruction's in the block), target (offset + rel), inside (0 <= target
62
+ // <= the block's size), external (a call or jump with a 32-bit displacement of 0: a relocation's placeholder, as
63
+ // asm-text.js itemsOf)}. Also {size, starts, instrRows}.
64
+ export function branchTargets(rows) {
65
+ const list = Array.isArray(rows) ? rows : [];
66
+ const starts = [], instrRows = [];
67
+ let offset = 0;
68
+ list.forEach((r, i) => {
69
+ starts.push(offset);
70
+ if (r?.kind === 'instr' && typeof r.opcode === 'string') { instrRows.push(i); offset += r.opcode.length >> 1; }
71
+ });
72
+ const size = offset;
73
+ const targets = list.map((r, i) => {
74
+ if (r?.kind !== 'instr' || typeof r.opcode !== 'string') return null;
75
+ const m = BRANCH.exec(String(r.label ?? '').trim());
76
+ if (!m) return null;
77
+ let t = BigInt(m[2]);
78
+ if (t >= 1n << 63n) t -= 1n << 64n;
79
+ const rel = Number(t);
80
+ if (!Number.isSafeInteger(rel)) return null;
81
+ const target = starts[i] + rel;
82
+ const b = (r.opcode.match(/[0-9a-f]{2}/gi) ?? []).map((x) => parseInt(x, 16)), n = b.length;
83
+ const external = n >= 5 && b.slice(n - 4).every((x) => x === 0)
84
+ && (b[n - 5] === 0xe8 || b[n - 5] === 0xe9 || (n >= 6 && b[n - 6] === 0x0f && (b[n - 5] & 0xf0) === 0x80));
85
+ return { mnemonic: m[1], rel, offset: starts[i], target, inside: target >= 0 && target <= size, external };
86
+ });
87
+ return { targets, size, starts, instrRows };
88
+ }
89
+
90
+ // The shown label of each row (an array as long as rows): a branch with its target shown as above, else null (the row's
91
+ // own label). src: {text, from, to} (assembly; the lines of the analyzed code) or null (machine code).
92
+ /** @param {{text: string, from?: number, to?: number} | null} [src] */
93
+ export function branchLabels(rows, src = null) {
94
+ const list = Array.isArray(rows) ? rows : [];
95
+ const out = new Array(list.length).fill(null);
96
+ const { targets, size, starts, instrRows } = branchTargets(list);
97
+ // the text's labels at their offsets, and each instruction row's operand as written
98
+ const at = new Map(); // offset -> [label] (in the order of the text)
99
+ const placed = []; // [{name, off}] in order
100
+ const written = new Map(); // row index -> operand
101
+ const inside = new Set(); // labels defined in the analyzed code
102
+ const code = src ? codeStatements(src.text, src.from ?? 1, src.to ?? Infinity) : null;
103
+ if (code && code.filter((x) => x.kind === 'instr').length === instrRows.length) {
104
+ let k = 0, pending = [];
105
+ for (const x of code) {
106
+ if (x.kind === 'label') { pending.push(x.name); inside.add(x.name); continue; }
107
+ const off = starts[instrRows[k]];
108
+ written.set(instrRows[k], x.operand);
109
+ for (const n of pending) { (at.get(off) ?? at.set(off, []).get(off)).push(n); placed.push({ name: n, off }); }
110
+ pending = [];
111
+ k++;
112
+ }
113
+ for (const n of pending) { (at.get(size) ?? at.set(size, []).get(size)).push(n); placed.push({ name: n, off: size }); }
114
+ }
115
+ const real = (n) => !INTERNAL.test(n) && !/^\d+$/.test(n);
116
+ targets.forEach((b, i) => {
117
+ if (!b) return;
118
+ const { target } = b;
119
+ const show = (s) => { out[i] = `${b.mnemonic} ${s}`; };
120
+ const w = written.get(i);
121
+ const here = (at.get(target) ?? []);
122
+ if (w && NUMERIC_REF.test(w)) return show(w);
123
+ // a symbol the analyzed code does not define: as written (its displacement may be a placeholder)
124
+ if (w && SYMBOL.test(w) && !INTERNAL.test(w) && !inside.has(w)) return show(w);
125
+ if (!b.inside || b.external) return show(relativeTarget(b.rel));
126
+ if (w && SYMBOL.test(w) && !INTERNAL.test(w) && here.includes(w)) return show(w);
127
+ const exact = here.find(real);
128
+ if (exact) return show(exact);
129
+ const before = placed.filter((p) => real(p.name) && p.off < target).pop();
130
+ if (before) return show(`${before.name}+0x${(target - before.off).toString(16)}`);
131
+ show(`0x${target.toString(16)}`);
132
+ });
133
+ return out;
134
+ }
135
+
136
+ // The lines of the analyzed code of an assembly result (asm-regions.js): the picked loop or body, a marked region, or
137
+ // the whole text. {text, from, to, lines?: the line of each instruction of a picked loop or body}.
138
+ export function analyzedLines(text, r) {
139
+ const t = String(text ?? '');
140
+ if (r?.loop?.line) return { text: t, from: r.loop.line, to: r.loop.endLine ?? r.loop.line, ...(r.loop.lines ? { lines: r.loop.lines } : {}) };
141
+ if (r?.region?.line) {
142
+ const lines = t.split('\n');
143
+ let to = lines.length;
144
+ for (let i = r.region.line; i < lines.length; i++) if (/(?:LLVM-MCA-END|wuica-end)/i.test(lines[i])) { to = i; break; }
145
+ return { text: t, from: r.region.line + 1, to };
146
+ }
147
+ return { text: t, from: 1, to: Infinity };
148
+ }
149
+ // The text of those lines (the analyzed assembly), or null for none: caveats.js cannotRun names the extension a CPU lacks
150
+ // from it
151
+ export function analyzedText(src) {
152
+ if (!src) return null;
153
+ const lines = String(src.text).split('\n');
154
+ return lines.slice(Math.max(0, src.from - 1), Number.isFinite(src.to) ? src.to : lines.length).join('\n');
155
+ }
@@ -44,6 +44,7 @@ const COND_BRANCH = /^(?:j(?!mp)[a-z]+|loop\w*)$/;
44
44
  // Without a register destination (cmp, test, bt, push, branches) the first operand is only read.
45
45
  const READS_FIRST = /^(?:cmp|test|bt|push\w*|call\w*|jmp|j[a-z]+|loop\w*|out\w*|v?u?comis[sd]|v?ptest|kortest\w|ktest\w|nop\w*|prefetch\w*|clflush\w*|clwb|cldemote)$/;
46
46
  const BOTH_WRITTEN = /^(?:xchg|xadd|mulx)$/; // the second register operand is written too
47
+ /** @type {[RegExp, string[]][]} */
47
48
  const IMPLICIT_WRITES = [
48
49
  [/^(?:i?div|mul|cdq|cqo|cwd|rdtsc)$/, ['rax', 'rdx']],
49
50
  [/^(?:cbw|cwde|cdqe|lahf|cmpxchg|lods\w*)$/, ['rax']],
@@ -99,7 +100,11 @@ export function memOperand(label) {
99
100
  if (!m) return null;
100
101
  const inner = m[2].replace(/\s/g, '').toLowerCase();
101
102
  const parts = inner.split(/(?=[+-])/);
102
- let base = null, index = null, disp = 0;
103
+ /** @type {string | null} */
104
+ let base = null;
105
+ /** @type {string | null} */
106
+ let index = null;
107
+ let disp = 0;
103
108
  for (const p of parts) {
104
109
  const v = p.replace(/^\+/, '');
105
110
  if (/\*/.test(v)) index = v.split('*')[0];
@@ -116,6 +121,7 @@ export function memOperand(label) {
116
121
  // change of its own controls).
117
122
  const memo = new WeakMap();
118
123
  const some = (rows, ks) => `${ks.slice(0, 4).map((k) => rows[k].label).join('; ')}${ks.length > 4 ? '; …' : ''}`;
124
+ /** @param {{splitLoadCycles?: number} | null} [config] */
119
125
  export function caveats(response, config = null) {
120
126
  const splitCost = Number(config?.splitLoadCycles) > 0;
121
127
  const kept = response && typeof response === 'object' ? memo.get(response) : undefined;
@@ -162,7 +168,7 @@ export function caveats(response, config = null) {
162
168
  for (const [addr, st] of stores) if (loads.has(addr)) rmw.push(...loads.get(addr), ...st);
163
169
  // only where the address can repeat with the data: a register of it written other than by advancing it by a constant
164
170
  const dynamic = rmw.length ? untrackedWrites(rows, { lea: true }) : null;
165
- const hit = rmw.filter((row) => { const m = memOperand(rows[row].label); return [m.base, m.index].some((r) => dynamic.has(family(r)?.base)); });
171
+ const hit = rmw.filter((row) => { const m = memOperand(rows[row].label); return [m?.base, m?.index].some((r) => dynamic?.has(family(r)?.base)); });
166
172
  if (hit.length) {
167
173
  const r = [...new Set(hit)].sort((a, b) => a - b);
168
174
  out.push({ id: 'rmw-index', text: 'store forwarding', rows: r,
@@ -200,7 +206,7 @@ export function caveats(response, config = null) {
200
206
  } else if (split.length) {
201
207
  // this CPU's model charges the crossings of loads whose address advances by a constant: only the others warn
202
208
  const writes = untrackedWrites(rows);
203
- const regsOf = (row) => { const m = memOperand(rows[row].label); return [m.base, m.index].map((r) => family(r)?.base).filter((r) => r && writes.has(r)); };
209
+ const regsOf = (row) => { const m = memOperand(rows[row].label); return [m?.base, m?.index].map((r) => family(r)?.base).filter((r) => r && writes.has(r)); };
204
210
  const untracked = split.filter((row) => regsOf(row).length);
205
211
  if (untracked.length) {
206
212
  const regs = [...new Set(untracked.flatMap(regsOf))];
@@ -212,3 +218,101 @@ export function caveats(response, config = null) {
212
218
  if (response && typeof response === 'object') (kept ?? memo.set(response, new Map()).get(response)).set(splitCost, out);
213
219
  return out;
214
220
  }
221
+
222
+ // ---- code a CPU cannot run ------------------------------------------------------------------------------------------
223
+ // A block with positions the CPU's decoder skipped (decodeErrors: instructions its XED chip does not have, e.g. AVX-512
224
+ // on SKL, whose bytes it then decodes as other instructions) still gets the reference's throughput, which leaves them out:
225
+ // a number, but not a result for that CPU. So does a block with an instruction the decoder accepts but that is of an
226
+ // extension the CPU lacks (ZEN3's model decodes with XED's chip ALL, which accepts everything: its AVX-512 instructions
227
+ // get the note X and no data). The page (headline, the table of CPUs, A–B), the Markdown and the CLI's text say so with
228
+ // cannotRun's reason, keep the number reachable, and leave such a CPU out of any "fastest". The engine's numbers do not
229
+ // change.
230
+ // Any other instruction with the note X (accepted by the CPU's decoder, of no extension it lacks: x87 tbyte loads,
231
+ // syscall, endbr64, CLWB on ICX, TSX on HSW, ...) is a gap in the instruction tables: the result stands, with a note
232
+ // (noData: "N instructions without data", whose cost the throughput leaves out).
233
+ //
234
+ // Which extension an instruction with the note X is of comes from its encoding (the row's opcode bytes), as XED's ISA
235
+ // set says (tests-js/web_cannot_run.mjs checks the two agree on the fixtures): extensionOf. The reason names the
236
+ // extension: of such an instruction, or, for the positions the decoder skipped (whose rows are other instructions), from
237
+ // the analyzed assembly text (`code`, comments and strings left out), only an extension the CPU lacks; machine code
238
+ // without text: the count ("12 undecodable").
239
+ const EXTENSIONS = /** @type {[string, RegExp][]} */ ([
240
+ ['AMX', /\btmm\d|\b(?:tdp\w+|tileloadd\w*|tilestored|ldtilecfg|sttilecfg|tilezero|tilerelease)\b/i],
241
+ ['AVX-512', /\bzmm\d|%?\bk[1-7]\b|\{1to\d+\}|\b(?:kmov|kand|kor|kxor|knot|kshift|kunpck|kortest|ktest|kadd)\w*|\bv(?:pternlog|pcompress|pexpand|compress|expand|permt2|permi2|pmov[a-z]*2m|pmovm2|range|reduce|getexp|getmant|scalef|fixupimm|rcp14|rsqrt14|pconflict|plzcnt|dbpsadbw|align[dq]|pror|prol|psrav[wq]|psllv[w]|psrlvw|cvtt?p[sd]2u|cvtu)\w*/i],
242
+ ['AVX-VNNI', /\bvpdp(?:bus|ws)ds?\b/i],
243
+ ['SHA', /\bsha(?:1|256)\w+/i],
244
+ ['FMA', /\bvf(?:n?m(?:add|sub)|maddsub|msubadd)\w*/i],
245
+ ['AVX2', /\bv(?:pbroadcast[bwdq]|broadcasti128|perm[dq]\b|permp[sd]|perm2i128|inserti128|extracti128|p?gather\w+|ps[lr]lv[dq]|psravd|pmaskmov[dq]|pblendd)\b|\bvp(?!(?:extr|insr|cmp[ei]str|clmul|ermilp|erm2f128|test|dp(?:bus|ws)))\w+\s[^\n]*\bymm/i],
246
+ ['BMI2', /\b(?:bzhi|mulx|pdep|pext|rorx|sarx|shlx|shrx)[lq]?\b/i],
247
+ ['BMI1', /\b(?:andn|bextr|blsi|blsmsk|blsr)[lq]?\b/i],
248
+ ['ADX', /\b(?:adcx|adox)[lq]?\b/i],
249
+ ['TSX', /\b(?:xbegin|xend|xabort|xtest)\b/i],
250
+ ]);
251
+ const SNB_LACKS = ['AMX', 'AVX-512', 'AVX-VNNI', 'SHA', 'FMA', 'AVX2', 'BMI2', 'BMI1', 'ADX'];
252
+ const SKL_LACKS = ['AMX', 'AVX-512', 'AVX-VNNI', 'SHA'];
253
+ const AVX512_LACKS = ['AMX', 'AVX-VNNI', 'SHA'];
254
+ const ICL_LACKS = ['AMX', 'AVX-VNNI'];
255
+ // the extensions of the list each CPU (the keys of archs.js) does not have (TSX: only where no model of it had it)
256
+ export const LACKS = Object.freeze({
257
+ SNB: SNB_LACKS, IVB: SNB_LACKS, HSW: ['AMX', 'AVX-512', 'AVX-VNNI', 'SHA', 'ADX'], BDW: SKL_LACKS, SKL: SKL_LACKS, KBL: SKL_LACKS, CFL: SKL_LACKS,
258
+ SKX: AVX512_LACKS, CLX: AVX512_LACKS, ICL: ICL_LACKS, TGL: ICL_LACKS, RKL: ICL_LACKS, ICX: ICL_LACKS, ZEN3: ['AMX', 'AVX-512', 'AVX-VNNI', 'TSX'], 'ADL-P': ['AMX', 'AVX-512', 'TSX'],
259
+ });
260
+
261
+ const LEGACY = new Set([0x66, 0x67, 0xf0, 0xf2, 0xf3, 0x2e, 0x36, 0x3e, 0x26, 0x64, 0x65]);
262
+ // The extension of an instruction of the list above that an encoding is of (hex of its bytes), or null: EVEX (AVX-512),
263
+ // VEX map 0F38 0x49/0x4B/0x5C/0x5E (AMX), VEX.66 map 0F38 0x50-0x53 (AVX-VNNI), XBEGIN/XABORT/XEND/XTEST (TSX). The
264
+ // extensions whose instructions any CPU's decoder rejects that lacks them (FMA, AVX2, BMI, SHA, ADX) never get here.
265
+ export function extensionOf(opcode) {
266
+ const b = String(opcode ?? '').match(/[0-9a-f]{2}/gi)?.map((x) => parseInt(x, 16)) ?? [];
267
+ let i = 0;
268
+ while (i < b.length && (LEGACY.has(b[i]) || (b[i] & 0xf0) === 0x40)) i++;
269
+ const [o, p0, p1, p2] = b.slice(i);
270
+ if (o === 0x62) return 'AVX-512';
271
+ if (o === 0xc4 && p0 !== undefined && p1 !== undefined && (p0 & 0x1f) === 2) {
272
+ if ([0x49, 0x4b, 0x5c, 0x5e].includes(p2)) return 'AMX';
273
+ if ((p1 & 3) === 1 && p2 >= 0x50 && p2 <= 0x53) return 'AVX-VNNI';
274
+ }
275
+ if (o === 0x0f && p0 === 0x01 && (p1 === 0xd5 || p1 === 0xd6)) return 'TSX';
276
+ if ((o === 0xc7 || o === 0xc6) && p0 === 0xf8) return 'TSX';
277
+ return null;
278
+ }
279
+
280
+ // the analyzed text without comments and strings (a "zmm" in a comment names nothing)
281
+ // (a ';' only at the start of a line: elsewhere it can separate statements)
282
+ const codeOnly = (code) => String(code).replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/"(?:[^"\\\n]|\\.)*"/g, '""').replace(/(?:#|\/\/)[^\n]*|^\s*;[^\n]*/gm, ' ');
283
+ // the opcodes of a response's rows with the note X, or of a summary's (xOps)
284
+ const xOpsOf = (r) => (Array.isArray(r.rows) ? r.rows.filter((x) => x?.kind === 'instr' && x.notes === 'X').map((x) => String(x.opcode ?? ''))
285
+ : Array.isArray(r.xOps) ? r.xOps.map(String) : []);
286
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
287
+
288
+ /**
289
+ * @param {any} r a response (rows: notes X, opcode), or a summary with decodeErrors and the X rows' opcodes (xOps)
290
+ * @param {{arch?: string | null, code?: string | null}} [opts] the CPU's key; the analyzed assembly text, if any
291
+ * @returns {{reason: string, title: string, decodeErrors: number, unsupported: number, needs: string[]} | null}
292
+ */
293
+ export function cannotRun(r, { arch = null, code = null } = {}) {
294
+ if (!r || typeof r !== 'object' || 'error' in r) return null;
295
+ const decodeErrors = Number(r.decodeErrors) || 0;
296
+ const lacks = arch ? LACKS[arch] ?? [] : [];
297
+ // (with skipped positions, the X rows are other instructions than the code's: not counted)
298
+ const lacked = decodeErrors ? [] : xOpsOf(r).map(extensionOf).filter((x) => x && lacks.includes(x));
299
+ if (!decodeErrors && !lacked.length) return null;
300
+ const text = decodeErrors && code ? codeOnly(code) : '';
301
+ const needs = decodeErrors ? EXTENSIONS.filter(([name, re]) => lacks.includes(name) && re.test(text)).map(([name]) => name)
302
+ : EXTENSIONS.map(([name]) => name).filter((name) => lacked.includes(name));
303
+ const unsupported = lacked.length;
304
+ const reason = needs.length ? `needs ${needs.join(', ')}` : `${decodeErrors} undecodable`;
305
+ const what = decodeErrors ? plural(decodeErrors, 'position its decoder skipped', 'positions its decoder skipped') : plural(unsupported, 'instruction of an extension it lacks', 'instructions of an extension it lacks');
306
+ const title = `${arch ? `${arch} cannot run this code` : 'code this CPU cannot run'}${needs.length ? ` (it needs ${needs.join(', ')})` : ''}: ${what}. The throughput leaves them out, so it is not a result for this CPU`;
307
+ return { reason, title, decodeErrors, unsupported, needs };
308
+ }
309
+
310
+ // The instructions with the note X of a block the CPU can run (cannotRun null): gaps in its instruction tables, whose
311
+ // cost the throughput leaves out; 0 if none (or if the CPU cannot run the block: its reason says it).
312
+ /** @param {any} r @param {{arch?: string | null}} [opts] @returns {number} */
313
+ export function noData(r, { arch = null } = {}) {
314
+ if (!r || typeof r !== 'object' || 'error' in r || cannotRun(r, { arch })) return 0;
315
+ return xOpsOf(r).length;
316
+ }
317
+ export const noDataText = (n) => plural(n, 'instruction without data', 'instructions without data');
318
+ export const NO_DATA_TITLE = 'not in the instruction tables of this CPU (uops.info has no data for them): the throughput leaves their cost out';
@@ -0,0 +1,91 @@
1
+ // The details of a result (docs/WASM-API.md, "details": per instruction its allowed ports, latencies and front-end facts;
2
+ // the port set behind the Ports limit; the issue slots per cause), fetched only when a view asks for them: one more
3
+ // analysis of the same request with `details: true`, once per result. Shared by the instruction card (icard.js) and the
4
+ // port-set drill-down of the bound view (portset.js). A response without details (the mock engine, an old module) gives
5
+ // null: the views then show what the response has.
6
+ //
7
+ // The first half has no DOM (tests-js/web_details.mjs runs it under Node).
8
+
9
+ // The details belong to the response if they have one entry per row and the same throughput was predicted.
10
+ export function detailsFit(response, res) {
11
+ const d = res?.details;
12
+ return !!d && Array.isArray(d.rows) && Array.isArray(response?.rows) && d.rows.length === response.rows.length && res.tp === response.tp;
13
+ }
14
+
15
+ // "1*p0156+1*p23" (uops.info's notation) from portData; non-Intel names (ALU0, FP2, ...) are listed: 1*[ALU0 ALU1]
16
+ export function portString(portData) {
17
+ if (!Array.isArray(portData) || !portData.length) return '';
18
+ return portData.map((p) => {
19
+ const names = p.ports ?? [];
20
+ const intel = names.every((n) => /^Port \w$/.test(n));
21
+ return `${p.uops}*${intel ? 'p' + names.map((n) => n.slice(5)).join('') : `[${names.join(' ')}]`}`;
22
+ }).join('+');
23
+ }
24
+
25
+ // The instruction's reciprocal throughput from its ports alone (the most uops per port over the unions of two of its port
26
+ // sets, as Facile's port model computes it for the block), and from the table's limit; cycles per instruction.
27
+ export function portThroughput(det) {
28
+ const sets = (det?.portData ?? []).map((p) => ({ set: new Set(p.ports), uops: Number(p.uops) || 0 })).filter((p) => p.set.size);
29
+ let best = 0;
30
+ for (const a of sets) {
31
+ for (const b of sets) {
32
+ const u = new Set([...a.set, ...b.set]);
33
+ const uops = sets.filter((s) => [...s.set].every((x) => u.has(x))).reduce((n, s) => n + s.uops, 0);
34
+ best = Math.max(best, uops / u.size);
35
+ }
36
+ }
37
+ return Math.max(best, Number(det?.tpTable) || 0);
38
+ }
39
+
40
+ // Latencies to show: per (input, output) pair, without the flag outputs of an instruction that writes a register too.
41
+ export function latencyPairs(det) {
42
+ const all = Array.isArray(det?.latencies) ? det.latencies : [];
43
+ const isFlags = (x) => String(x).startsWith('flags');
44
+ const regOut = all.some((l) => !isFlags(l.to));
45
+ const out = [];
46
+ for (const l of all) {
47
+ if (regOut && isFlags(l.to)) continue;
48
+ if (!out.some((x) => x.from === l.from && x.to === l.to)) out.push(l);
49
+ }
50
+ return out;
51
+ }
52
+
53
+ // ---- the fetcher -----------------------------------------------------------------------------------------------------
54
+
55
+ const isCancel = (e) => e?.name === 'CancelledError';
56
+
57
+ // env: { engine() }. get(view) resolves to the details of view.response, or null; one analysis per view (a cancelled one
58
+ // is tried again on the next get).
59
+ export function createDetails(env) {
60
+ const done = new WeakMap(); // view -> details | null
61
+ const pending = new WeakMap(); // view -> promise
62
+ const listeners = []; // (view, details): details arrived (for any of the views that asked)
63
+ return {
64
+ onLoad(f) { listeners.push(f); },
65
+ peek(view) { return done.get(view); }, // undefined: not fetched
66
+ get(view) {
67
+ if (!view) return Promise.resolve(null);
68
+ if (done.has(view)) return Promise.resolve(done.get(view));
69
+ let p = pending.get(view);
70
+ if (p) return p;
71
+ const r = view.response;
72
+ if (!r || r.error || r.mock || !view.request || !env.engine?.()) { done.set(view, null); return Promise.resolve(null); }
73
+ p = (async () => {
74
+ try {
75
+ const res = await env.engine().analyze({ ...view.request, details: true });
76
+ const d = detailsFit(r, res) ? res.details : null;
77
+ done.set(view, d);
78
+ if (d) for (const f of listeners) { try { f(view, d); } catch { /* a view's problem */ } }
79
+ return d;
80
+ } catch (e) {
81
+ if (!isCancel(e)) done.set(view, null);
82
+ return null;
83
+ } finally {
84
+ pending.delete(view);
85
+ }
86
+ })();
87
+ pending.set(view, p);
88
+ return p;
89
+ },
90
+ };
91
+ }
@@ -2,6 +2,9 @@
2
2
  // parser reads, so the examples also show that disassembly output can be pasted). The four blocks are in the
3
3
  // corpus of the Python reference, so the mock engine has the reference's result for them
4
4
  // (see mock-data.js; `arch` is the microarchitecture that result was recorded for). Menu group "basics".
5
+ // An example's machine code is what the assembler makes of its text (tests-js/web_qa.mjs, web_asm_shipped.mjs), so that
6
+ // its result can be shown before the assembler has loaded (asm-shipped.js): 'avx' has `49 01 ca` for `add r10, rcx`,
7
+ // where the corpus has `4c 03 d1` (the mock engine takes it for the recorded block: engine-mock.js SAME_AS).
5
8
 
6
9
  import { SHA256_BLOCK_HEX } from './showcase.js';
7
10
 
@@ -30,7 +33,7 @@ export const EXAMPLES = [
30
33
  ex('avx', 'AVX: FMA, add and multiply', 'ADL-P',
31
34
  ['loop:', ' vfmsub213pd ymm6, ymm5, ymm4', ' add r10, rcx', ' imul r8, r8', ' dec r15', ' jnz loop'],
32
35
  ['loop:', ' vfmsub213pd %ymm4, %ymm5, %ymm6', ' addq %rcx, %r10', ' imulq %r8, %r8', ' decq %r15', ' jnz loop'],
33
- [['c4 e2 d5 aa f4', 'vfmsub213pd ymm6, ymm5, ymm4'], ['4c 03 d1', 'add r10, rcx'], ['4d 0f af c0', 'imul r8, r8'],
36
+ [['c4 e2 d5 aa f4', 'vfmsub213pd ymm6, ymm5, ymm4'], ['49 01 ca', 'add r10, rcx'], ['4d 0f af c0', 'imul r8, r8'],
34
37
  ['49 ff cf', 'dec r15'], ['75 ef', 'jnz 0x0']]),
35
38
  ex('stack', 'Stack: pops after an add to rsp', 'SKL',
36
39
  ['loop:', ' add rsp, 8', ' mov rsi, rbx', ' mov rdx, rbp', ' pop rbx', ' pop rbp', ' mov edi, eax', ' dec r15', ' jnz loop'],
@@ -85,6 +88,7 @@ export const CLASSIC_EXAMPLES = [
85
88
  export const SHOWCASE_EXAMPLES = [
86
89
  { id: 'sha256', title: 'SHA-256 block (2,949 instr)', arch: 'SKL', hex: SHA256_BLOCK_HEX.replace(/\s+/g, ''), text: { hex: SHA256_BLOCK_HEX },
87
90
  // Intel assembly, loaded when picked (showcase-asm.js, about 60 KB); the example opens in asm mode, hex if it cannot load
91
+ // @ts-ignore: the page's module (the npm package's copy of this file has no showcase-asm.js and never calls asm())
88
92
  asm: () => import('./showcase-asm.js').then((m) => m.SHA256_BLOCK_ASM) },
89
93
  ];
90
94