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.
- package/README.md +233 -57
- package/dist/data/arch/ADL-P.bin.br +0 -0
- package/dist/data/arch/BDW.bin.br +0 -0
- package/dist/data/arch/CFL.bin.br +0 -0
- package/dist/data/arch/CLX.bin.br +0 -0
- package/dist/data/arch/HSW.bin.br +0 -0
- package/dist/data/arch/ICL.bin.br +0 -0
- package/dist/data/arch/ICX.bin.br +0 -0
- package/dist/data/arch/IVB.bin.br +0 -0
- package/dist/data/arch/KBL.bin.br +0 -0
- package/dist/data/arch/RKL.bin.br +0 -0
- package/dist/data/arch/SKL.bin.br +0 -0
- package/dist/data/arch/SKX.bin.br +0 -0
- package/dist/data/arch/SNB.bin.br +0 -0
- package/dist/data/arch/TGL.bin.br +0 -0
- package/dist/data/arch/ZEN3.bin.br +0 -0
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +145 -66
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +205 -13
- package/lib/cli.js +467 -49
- package/lib/core.js +9 -1
- package/lib/details.js +4 -23
- package/lib/examples.js +27 -0
- package/lib/files.js +26 -3
- package/lib/index.js +228 -42
- package/lib/mcp.js +107 -84
- package/lib/objfile.js +218 -0
- package/lib/thread-worker.js +15 -9
- package/lib/threads.js +40 -23
- package/lib/wasm.js +42 -11
- package/lib/web/ab-diff.js +217 -0
- package/lib/web/accum.js +10 -2
- package/lib/web/asm-regions.js +24 -17
- package/lib/web/asm-tokens.js +357 -0
- package/lib/web/assembler.js +36 -6
- package/lib/web/block-diff.js +165 -0
- package/lib/web/bound-core.js +211 -0
- package/lib/web/branch-label.js +155 -0
- package/lib/web/caveats.js +115 -3
- package/lib/web/details.js +91 -0
- package/lib/web/examples.js +103 -0
- package/lib/web/loop-find.js +139 -16
- package/lib/web/markdown.js +437 -0
- package/lib/web/showcase.js +368 -0
- package/lib/web/whatif-core.js +339 -0
- package/package.json +3 -1
- package/dist/data/arch/ADL-P.json.br +0 -0
- package/dist/data/arch/BDW.json.br +0 -0
- package/dist/data/arch/CFL.json.br +0 -0
- package/dist/data/arch/CLX.json.br +0 -0
- package/dist/data/arch/HSW.json.br +0 -0
- package/dist/data/arch/ICL.json.br +0 -0
- package/dist/data/arch/ICX.json.br +0 -0
- package/dist/data/arch/IVB.json.br +0 -0
- package/dist/data/arch/KBL.json.br +0 -0
- package/dist/data/arch/RKL.json.br +0 -0
- package/dist/data/arch/SKL.json.br +0 -0
- package/dist/data/arch/SKX.json.br +0 -0
- package/dist/data/arch/SNB.json.br +0 -0
- package/dist/data/arch/TGL.json.br +0 -0
- package/dist/data/arch/ZEN3.json.br +0 -0
- package/lib/insights.js +0 -100
- package/lib/whatif.js +0 -136
package/lib/threads.js
CHANGED
|
@@ -25,7 +25,7 @@ import os from 'node:os';
|
|
|
25
25
|
import path from 'node:path';
|
|
26
26
|
import { Worker, isMainThread } from 'node:worker_threads';
|
|
27
27
|
import { Analyzer, capMemory } from './wasm.js';
|
|
28
|
-
import { readMaybeCompressed } from './files.js';
|
|
28
|
+
import { readMaybeCompressed, tableFile } from './files.js';
|
|
29
29
|
import { WARM_HEX } from './core.js';
|
|
30
30
|
|
|
31
31
|
const WORKER = new URL('./thread-worker.js', import.meta.url);
|
|
@@ -56,26 +56,38 @@ export function threadOption(option, env = process.env) {
|
|
|
56
56
|
return raw === 0 || raw === '0' ? 'auto' : raw;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
// The threads for a
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
export function
|
|
66
|
-
|
|
59
|
+
// The default number of threads for a set of jobs ([{table, request: {hex}}]: blocks x microarchitectures), from the
|
|
60
|
+
// work they are: the estimated time on this thread (each table loaded once, each analysis a fixed cost plus a cost per
|
|
61
|
+
// instruction). Below WORK.minMs no threads (a thread's start, its table and its first, unoptimized analysis cost more
|
|
62
|
+
// than they save); else one thread per WORK.perThreadMs, from 2 to WORK.max, at most the cores but one (and `limit`),
|
|
63
|
+
// and at most one per job. Measurements: docs/PORTING.md, "Threads".
|
|
64
|
+
export const WORK = Object.freeze({ tableMs: 8, jobMs: 1.2, instrMs: 0.009, minMs: 300, perThreadMs: 150, max: 8 });
|
|
65
|
+
export function workMs(jobs) {
|
|
66
|
+
const tables = new Set(jobs.map((j) => j.table)).size;
|
|
67
|
+
// ~4 bytes (8 hex digits) per instruction
|
|
68
|
+
return tables * WORK.tableMs + jobs.reduce((s, j) => s + WORK.jobMs + (j.request.hex.length / 8) * WORK.instrMs, 0);
|
|
69
|
+
}
|
|
70
|
+
export function threadsForWork(jobs, limit, cores = os.availableParallelism()) {
|
|
71
|
+
const ms = workMs(jobs);
|
|
72
|
+
if (ms < WORK.minMs || jobs.length < 2) return 1;
|
|
73
|
+
return Math.max(1, Math.min(limit, cores - 1, jobs.length, Math.max(2, Math.min(WORK.max, Math.ceil(ms / WORK.perThreadMs)))));
|
|
67
74
|
}
|
|
68
75
|
|
|
69
76
|
export class ThreadPool {
|
|
77
|
+
/** @type {any} */
|
|
70
78
|
#workerData = null;
|
|
71
79
|
#wasm; #uarch; #dataDir;
|
|
80
|
+
/** @type {Promise<WebAssembly.Module> | null} */
|
|
72
81
|
#compiled = null; // promise of the module with the threads' memory limit
|
|
73
82
|
#limit;
|
|
83
|
+
/** @type {any[]} */
|
|
74
84
|
#slots = []; // {worker, ready, job, tables: Set}
|
|
75
85
|
#warmed = false;
|
|
76
86
|
#want; // the threads the latest run() may start
|
|
87
|
+
/** @type {any[]} */
|
|
77
88
|
#queue = []; // {id, table, request, resolve}
|
|
78
89
|
#nextId = 1;
|
|
90
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
79
91
|
#idleTimer = null;
|
|
80
92
|
broken = false;
|
|
81
93
|
|
|
@@ -88,15 +100,18 @@ export class ThreadPool {
|
|
|
88
100
|
|
|
89
101
|
get threads() { return this.#slots.length; }
|
|
90
102
|
|
|
91
|
-
// jobs: [{table, request}] -> a promise of [fields | null] in the same order (null: not done, run it elsewhere
|
|
92
|
-
//
|
|
103
|
+
// jobs: [{table, request, full}] -> a promise of [fields | null] in the same order (null: not done, run it elsewhere;
|
|
104
|
+
// full: the whole analysis result instead of a compare() row's fields). Threads are started while there are fewer
|
|
105
|
+
// than `threads` (and `limit`) and jobs wait.
|
|
93
106
|
async run(jobs, threads = this.#limit) {
|
|
94
107
|
this.#want = Math.min(this.#limit, threads);
|
|
95
|
-
clearTimeout(this.#idleTimer);
|
|
108
|
+
clearTimeout(this.#idleTimer ?? undefined);
|
|
96
109
|
this.#idleTimer = null;
|
|
97
110
|
if (!this.#workerData) {
|
|
98
111
|
const maxBytes = maxMemoryBytes(this.#limit);
|
|
112
|
+
// (the module's bytes are not needed after this: the threads get the compiled module)
|
|
99
113
|
this.#compiled ??= WebAssembly.compile(capMemory(this.#wasm, maxBytes / (64 * 1024)));
|
|
114
|
+
this.#wasm = null;
|
|
100
115
|
try {
|
|
101
116
|
const module = await this.#compiled;
|
|
102
117
|
this.#workerData ??= { module, uarch: this.#uarch, dataDir: this.#dataDir, recycleBytes: maxBytes / 2 };
|
|
@@ -104,9 +119,9 @@ export class ThreadPool {
|
|
|
104
119
|
this.broken = true;
|
|
105
120
|
}
|
|
106
121
|
}
|
|
107
|
-
const out = Promise.all(jobs.map(({ table, request }) => new Promise((resolve) => {
|
|
122
|
+
const out = Promise.all(jobs.map(({ table, request, full = false }) => new Promise((resolve) => {
|
|
108
123
|
if (this.broken) { resolve(null); return; }
|
|
109
|
-
this.#queue.push({ id: this.#nextId++, table, request, resolve });
|
|
124
|
+
this.#queue.push({ id: this.#nextId++, table, request, full, resolve });
|
|
110
125
|
})));
|
|
111
126
|
// (not for a small block: its analyses are short, and the warm-up would compete with them for the CPU)
|
|
112
127
|
if (this.#pump() && !this.#warmed && jobs[0]?.request.hex.length >= WARM_MIN_HEX) {
|
|
@@ -118,7 +133,7 @@ export class ThreadPool {
|
|
|
118
133
|
|
|
119
134
|
// One analysis of WARM_HEX on an instance of the threads' module (see the top); the instance is dropped afterwards.
|
|
120
135
|
async #warmUp({ table, request }) {
|
|
121
|
-
const bytes = await readMaybeCompressed(
|
|
136
|
+
const bytes = await readMaybeCompressed(tableFile(this.#dataDir, table));
|
|
122
137
|
const a = new Analyzer(this.#workerData.module);
|
|
123
138
|
a.loadUarch(this.#uarch);
|
|
124
139
|
a.loadArch(table, bytes);
|
|
@@ -127,15 +142,17 @@ export class ThreadPool {
|
|
|
127
142
|
|
|
128
143
|
#owner(table) { return this.#slots.find((s) => s.tables.has(table)); }
|
|
129
144
|
|
|
130
|
-
// The job for a free thread: one of its tables, else one of a table no thread has
|
|
145
|
+
// The job for a free thread: one of its tables, else one of a table no thread has, else any (its table is loaded
|
|
146
|
+
// here too: many blocks on one microarchitecture).
|
|
131
147
|
#pick(slot) {
|
|
132
148
|
let i = this.#queue.findIndex((j) => slot.tables.has(j.table));
|
|
133
149
|
if (i < 0) i = this.#queue.findIndex((j) => !this.#owner(j.table));
|
|
150
|
+
if (i < 0) i = this.#queue.length ? 0 : -1;
|
|
134
151
|
return i < 0 ? null : this.#queue.splice(i, 1)[0];
|
|
135
152
|
}
|
|
136
153
|
|
|
137
|
-
// Gives the waiting jobs to free threads, and starts
|
|
138
|
-
//
|
|
154
|
+
// Gives the waiting jobs to free threads, and starts threads for the jobs left (up to the threads wanted): first
|
|
155
|
+
// for tables no thread has. Returns the number of threads started.
|
|
139
156
|
#pump() {
|
|
140
157
|
for (const s of this.#slots) {
|
|
141
158
|
if (s.job || !this.#queue.length) continue;
|
|
@@ -143,9 +160,8 @@ export class ThreadPool {
|
|
|
143
160
|
if (j) this.#start(s, j);
|
|
144
161
|
}
|
|
145
162
|
let started = 0;
|
|
146
|
-
while (this.#slots.length < this.#want) {
|
|
147
|
-
const i = this.#queue.findIndex((j) => !this.#owner(j.table));
|
|
148
|
-
if (i < 0) break;
|
|
163
|
+
while (this.#slots.length < this.#want && this.#queue.length) {
|
|
164
|
+
const i = Math.max(0, this.#queue.findIndex((j) => !this.#owner(j.table)));
|
|
149
165
|
this.#spawn(this.#queue.splice(i, 1)[0]);
|
|
150
166
|
started++;
|
|
151
167
|
}
|
|
@@ -157,11 +173,12 @@ export class ThreadPool {
|
|
|
157
173
|
slot.job = job;
|
|
158
174
|
slot.tables.add(job.table);
|
|
159
175
|
slot.worker.ref();
|
|
160
|
-
slot.worker.postMessage({ id: job.id, table: job.table, request: job.request });
|
|
176
|
+
slot.worker.postMessage({ id: job.id, table: job.table, request: job.request, full: job.full });
|
|
161
177
|
}
|
|
162
178
|
|
|
163
179
|
#spawn(job) {
|
|
164
180
|
const worker = new Worker(WORKER, { workerData: this.#workerData, stdout: true, stderr: true });
|
|
181
|
+
/** @type {{worker: Worker, ready: boolean, job: any, tables: Set<string>}} */
|
|
165
182
|
const slot = { worker, ready: false, job: null, tables: new Set() };
|
|
166
183
|
this.#slots.push(slot);
|
|
167
184
|
this.#start(slot, job);
|
|
@@ -211,7 +228,7 @@ export class ThreadPool {
|
|
|
211
228
|
|
|
212
229
|
// Stops the threads; waiting and running jobs resolve to null. The next run() starts new ones.
|
|
213
230
|
async close() {
|
|
214
|
-
clearTimeout(this.#idleTimer);
|
|
231
|
+
clearTimeout(this.#idleTimer ?? undefined);
|
|
215
232
|
this.#idleTimer = null;
|
|
216
233
|
const slots = this.#slots.splice(0);
|
|
217
234
|
for (const j of this.#queue.splice(0)) j.resolve(null);
|
package/lib/wasm.js
CHANGED
|
@@ -9,10 +9,14 @@ const enc = new TextEncoder();
|
|
|
9
9
|
const dec = new TextDecoder();
|
|
10
10
|
|
|
11
11
|
export class Analyzer {
|
|
12
|
+
/** @type {any} */
|
|
12
13
|
#module;
|
|
14
|
+
/** @type {any} */
|
|
13
15
|
#x = null;
|
|
16
|
+
/** @type {Uint8Array | Buffer | null} */
|
|
14
17
|
#uarch = null; // bytes of uarch.json, kept to reload after a trap
|
|
15
|
-
#tables = new Map(); // table name -> bytes
|
|
18
|
+
#tables = new Map(); // table name -> its bytes, or a function that reads them again (for a reload after a trap)
|
|
19
|
+
#binary = false; // the module reads binary tables (wuica_load_arch_bin)
|
|
16
20
|
restarts = 0;
|
|
17
21
|
|
|
18
22
|
constructor(module) {
|
|
@@ -21,6 +25,7 @@ export class Analyzer {
|
|
|
21
25
|
for (const n of ['memory', 'wuica_alloc', 'wuica_free', 'wuica_result_ptr', 'wuica_load_uarch', 'wuica_load_arch', 'wuica_analyze']) {
|
|
22
26
|
if (!this.#x[n]) throw new Error(`not a wuica analyzer module: export "${n}" is missing`);
|
|
23
27
|
}
|
|
28
|
+
this.#binary = typeof this.#x.wuica_load_arch_bin === 'function';
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
// Arguments are byte arrays passed as (pointer, length); the result is the text at wuica_result_ptr(). Views of the
|
|
@@ -50,7 +55,7 @@ export class Analyzer {
|
|
|
50
55
|
if (this.#uarch) this.restarts++;
|
|
51
56
|
this.#x = new WebAssembly.Instance(this.#module, {}).exports;
|
|
52
57
|
if (this.#uarch) this.#load('wuica_load_uarch', [this.#uarch], 'uarch.json');
|
|
53
|
-
for (const [name,
|
|
58
|
+
for (const [name, t] of this.#tables) this.#loadTable(name, typeof t === 'function' ? t() : t);
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
#load(fn, inputs, what) {
|
|
@@ -64,14 +69,32 @@ export class Analyzer {
|
|
|
64
69
|
this.#uarch = bytes;
|
|
65
70
|
}
|
|
66
71
|
|
|
67
|
-
|
|
72
|
+
// bytes: the binary form of the table (data/arch/<name>.bin, see crates/wuica-core/src/table_bin.rs) or its JSON.
|
|
73
|
+
// reload: a function that returns the bytes again (then they are not kept: they are only needed after a trap)
|
|
74
|
+
/** @param {string} name @param {Uint8Array} bytes @param {(() => Uint8Array) | null} [reload] */
|
|
75
|
+
loadArch(name, bytes, reload = null) {
|
|
68
76
|
this.#live();
|
|
69
|
-
this.#
|
|
70
|
-
this.#tables.set(name, bytes);
|
|
77
|
+
this.#loadTable(name, bytes);
|
|
78
|
+
this.#tables.set(name, reload ?? bytes);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
#loadTable(name, bytes) {
|
|
82
|
+
if (!isBinaryTable(bytes)) return this.#load('wuica_load_arch', [enc.encode(name), bytes], `instruction table ${name}`);
|
|
83
|
+
if (!this.#binary) throw new Error(`instruction table ${name}: a binary table, and this analyzer module reads only JSON tables`);
|
|
84
|
+
this.#load('wuica_load_arch_bin', [enc.encode(name), bytes], `instruction table ${name}`);
|
|
71
85
|
}
|
|
72
86
|
|
|
73
87
|
hasArch(name) { return this.#tables.has(name); }
|
|
74
88
|
|
|
89
|
+
// The decoder alone (wuica_decode): the instructions of `bytes` for an XED chip ("ALL": every instruction XED knows),
|
|
90
|
+
// [{addr, opcode, asm, category, ...}], or throws.
|
|
91
|
+
decode(bytes, chip = 'ALL') {
|
|
92
|
+
this.#live();
|
|
93
|
+
const r = this.#call('wuica_decode', [bytes, enc.encode(chip)]);
|
|
94
|
+
if (!Array.isArray(r)) throw new Error(r?.error ?? 'the decoder failed');
|
|
95
|
+
return r;
|
|
96
|
+
}
|
|
97
|
+
|
|
75
98
|
// The size of the instance's memory in bytes (0 after a trap, until the next call).
|
|
76
99
|
get memoryBytes() { return this.#x?.memory.buffer.byteLength ?? 0; }
|
|
77
100
|
|
|
@@ -98,6 +121,12 @@ export class Analyzer {
|
|
|
98
121
|
}
|
|
99
122
|
}
|
|
100
123
|
|
|
124
|
+
// Whether bytes are the binary form of an instruction table (they start with the magic WUICATBL).
|
|
125
|
+
const MAGIC = [0x57, 0x55, 0x49, 0x43, 0x41, 0x54, 0x42, 0x4c];
|
|
126
|
+
export function isBinaryTable(bytes) {
|
|
127
|
+
return bytes?.length >= 8 && MAGIC.every((b, i) => bytes[i] === b);
|
|
128
|
+
}
|
|
129
|
+
|
|
101
130
|
// The module bytes with the maximum of every (32-bit, unshared) memory set to at most `maxPages` (64 KiB each): an
|
|
102
131
|
// instance of it traps where an allocation would grow the memory beyond that.
|
|
103
132
|
export function capMemory(bytes, maxPages) {
|
|
@@ -165,16 +194,18 @@ export function codeModeError(text) {
|
|
|
165
194
|
return null;
|
|
166
195
|
}
|
|
167
196
|
|
|
168
|
-
//
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
197
|
+
// The text as the assembler module gets it (a NUL as a space, {load}/{store}, clang 23's .prefalign, ...): one
|
|
198
|
+
// preparation, web/js/assembler.js prepareSource, shared with the page
|
|
199
|
+
export { stripHints, prepareSource } from './web/assembler.js';
|
|
200
|
+
import { prepareSource } from './web/assembler.js';
|
|
172
201
|
|
|
173
202
|
const OUT_CAP = 1 << 20;
|
|
174
203
|
const ERR_CAP = 1 << 16;
|
|
175
204
|
|
|
176
205
|
export class Assembler {
|
|
206
|
+
/** @type {any} */
|
|
177
207
|
#module;
|
|
208
|
+
/** @type {any} */
|
|
178
209
|
#x = null;
|
|
179
210
|
|
|
180
211
|
constructor(module) {
|
|
@@ -187,7 +218,7 @@ export class Assembler {
|
|
|
187
218
|
|
|
188
219
|
#live() {
|
|
189
220
|
if (this.#x) return;
|
|
190
|
-
const x = new WebAssembly.Instance(this.#module, {}).exports;
|
|
221
|
+
const x = /** @type {any} */ (new WebAssembly.Instance(this.#module, {}).exports);
|
|
191
222
|
x._initialize?.();
|
|
192
223
|
this.#x = x;
|
|
193
224
|
}
|
|
@@ -196,7 +227,7 @@ export class Assembler {
|
|
|
196
227
|
assemble(text, syntax) {
|
|
197
228
|
this.#live();
|
|
198
229
|
const x = this.#x;
|
|
199
|
-
const src = enc.encode(
|
|
230
|
+
const src = enc.encode(prepareSource(text) + '\0');
|
|
200
231
|
let textPtr = 0, outPtr = 0, errPtr = 0;
|
|
201
232
|
try {
|
|
202
233
|
textPtr = x.malloc(src.length); outPtr = x.malloc(OUT_CAP); errPtr = x.malloc(ERR_CAP);
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// A–B comparison: compares two analysis responses (docs/WASM-API.md): throughput, bottlenecks, limits, and an
|
|
2
|
+
// instruction-by-instruction alignment of the two uop tables with the change of every shared column.
|
|
3
|
+
// Pure: no DOM, runs under Node (tests-js/web_ab_diff.mjs).
|
|
4
|
+
|
|
5
|
+
import { columnKind } from './bound-core.js';
|
|
6
|
+
|
|
7
|
+
export const EPS = 0.005; // values are shown with two decimals: smaller differences are "the same"
|
|
8
|
+
// A change of one instruction's uops that is under this in every column (uops per iteration), with the same notes, is
|
|
9
|
+
// "minor": uiCA's port assignment moves a few hundredths of a uop between ports when the code around an instruction
|
|
10
|
+
// changes (±0.03 seen). The Markdown and text forms of A–B leave minor changes out; the page's Δ table (which frames
|
|
11
|
+
// every cell that differs at its two decimals) and the JSON keep them.
|
|
12
|
+
export const MINOR = 0.05;
|
|
13
|
+
|
|
14
|
+
// Prefixes that come before the mnemonic in a disassembly ("lock add", "rep movsb", "notrack jmp").
|
|
15
|
+
const PREFIXES = new Set(['lock', 'rep', 'repe', 'repz', 'repne', 'repnz', 'bnd', 'notrack', 'xacquire', 'xrelease',
|
|
16
|
+
'data16', 'data32', 'addr32', 'cs', 'ds', 'es', 'ss', 'fs', 'gs', 'rex', 'rex.w', '{vex}', '{vex3}', '{evex}']);
|
|
17
|
+
// Direct branches: their operand is an address that changes whenever the code before the target changes size.
|
|
18
|
+
const BRANCH = /^(?:j[a-z]{1,4}|loop[a-z]{0,2}|jrcxz|jecxz|call|xbegin)$/;
|
|
19
|
+
const TARGET = /^(?:0x[0-9a-f]+|[0-9a-f]+|[0-9]+|0x[0-9a-f]+ <.*>|[0-9a-f]+ <.*>)$/;
|
|
20
|
+
|
|
21
|
+
// The text of an instruction for matching, and its mnemonic. Direct branch targets are replaced by "→" so that
|
|
22
|
+
// "jnz 0xfffffffffffffff5" and "jnz 0xfffffffffffffff2" match.
|
|
23
|
+
export function normalizeInstr(label) {
|
|
24
|
+
const t = String(label ?? '').trim().toLowerCase().replace(/\s+/g, ' ').replace(/ ?, ?/g, ', ');
|
|
25
|
+
const words = t.split(' ');
|
|
26
|
+
let i = 0;
|
|
27
|
+
while (i < words.length - 1 && PREFIXES.has(words[i])) i++;
|
|
28
|
+
const mnemonic = words[i] ?? '';
|
|
29
|
+
const operands = words.slice(i + 1).join(' ');
|
|
30
|
+
let key = t;
|
|
31
|
+
if (BRANCH.test(mnemonic) && TARGET.test(operands)) key = [...words.slice(0, i + 1), '→'].join(' ');
|
|
32
|
+
return { key, mnemonic };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The instructions of a response, each with the extra uops the renamer inserts before it (regMerge, stackSync)
|
|
36
|
+
// added to its values: they are caused by it.
|
|
37
|
+
export function instructionUnits(response) {
|
|
38
|
+
const rows = Array.isArray(response?.rows) ? response.rows : [];
|
|
39
|
+
const n = Array.isArray(response?.columns) ? response.columns.length : 0;
|
|
40
|
+
const units = [];
|
|
41
|
+
let pending = [];
|
|
42
|
+
const unit = (row, extras) => {
|
|
43
|
+
const values = new Array(n).fill(0);
|
|
44
|
+
for (const r of [...extras, row]) for (let i = 0; i < n; i++) values[i] += Number(r.values?.[i]) || 0;
|
|
45
|
+
const { key, mnemonic } = row.kind === 'instr' ? normalizeInstr(row.label) : { key: `<${row.kind}>`, mnemonic: `<${row.kind}>` };
|
|
46
|
+
return { label: String(row.label ?? ''), key, mnemonic, notes: row.notes ?? '', values, extras: extras.map((x) => x.kind), row };
|
|
47
|
+
};
|
|
48
|
+
for (const row of rows) {
|
|
49
|
+
if (row.kind !== 'instr') { pending.push(row); continue; }
|
|
50
|
+
units.push(unit(row, pending));
|
|
51
|
+
pending = [];
|
|
52
|
+
}
|
|
53
|
+
for (const row of pending) units.push(unit(row, [])); // extra uops after the last instruction (not expected)
|
|
54
|
+
return units;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Longest common subsequence of two arrays of keys: [[i, j], ...] of the matched pairs, in order. The common
|
|
58
|
+
// prefix and suffix are matched first; the rest uses the quadratic table (up to `limit` cells), beyond that
|
|
59
|
+
// nothing more is matched.
|
|
60
|
+
export function lcsPairs(a, b, limit = 4e6) {
|
|
61
|
+
const pairs = [];
|
|
62
|
+
let lo = 0;
|
|
63
|
+
while (lo < a.length && lo < b.length && a[lo] === b[lo]) { pairs.push([lo, lo]); lo++; }
|
|
64
|
+
let ha = a.length, hb = b.length;
|
|
65
|
+
const tail = [];
|
|
66
|
+
while (ha > lo && hb > lo && a[ha - 1] === b[hb - 1]) { ha--; hb--; tail.push([ha, hb]); }
|
|
67
|
+
const n = ha - lo, m = hb - lo;
|
|
68
|
+
if (n > 0 && m > 0 && n * m <= limit) {
|
|
69
|
+
const w = m + 1;
|
|
70
|
+
const t = new Uint32Array((n + 1) * w); // t[i][j]: LCS length of a[lo+i..ha) and b[lo+j..hb)
|
|
71
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
72
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
73
|
+
t[i * w + j] = a[lo + i] === b[lo + j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
let i = 0, j = 0;
|
|
77
|
+
while (i < n && j < m) {
|
|
78
|
+
if (a[lo + i] === b[lo + j]) { pairs.push([lo + i, lo + j]); i++; j++; }
|
|
79
|
+
else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) i++;
|
|
80
|
+
else j++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (let k = tail.length - 1; k >= 0; k--) pairs.push(tail[k]);
|
|
84
|
+
return pairs;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Aligns two lists of instruction units: [{op, a, b}] with op
|
|
88
|
+
// 'same' the same instruction text (a and b are indices)
|
|
89
|
+
// 'modified' in a stretch between matches, the same mnemonic with other operands
|
|
90
|
+
// 'removed' only in A (b is null), 'added' only in B (a is null)
|
|
91
|
+
export function alignUnits(ua, ub) {
|
|
92
|
+
const out = [];
|
|
93
|
+
const gap = (a0, a1, b0, b1) => { // the unmatched stretches a0..a1 and b0..b1: pair them by mnemonic
|
|
94
|
+
const pa = lcsPairs(ua.slice(a0, a1).map((u) => u.mnemonic), ub.slice(b0, b1).map((u) => u.mnemonic));
|
|
95
|
+
let i = a0, j = b0;
|
|
96
|
+
for (const [x, y] of pa) {
|
|
97
|
+
while (i < a0 + x) out.push({ op: 'removed', a: i++, b: null });
|
|
98
|
+
while (j < b0 + y) out.push({ op: 'added', a: null, b: j++ });
|
|
99
|
+
out.push({ op: 'modified', a: i++, b: j++ });
|
|
100
|
+
}
|
|
101
|
+
while (i < a1) out.push({ op: 'removed', a: i++, b: null });
|
|
102
|
+
while (j < b1) out.push({ op: 'added', a: null, b: j++ });
|
|
103
|
+
};
|
|
104
|
+
let i = 0, j = 0;
|
|
105
|
+
for (const [x, y] of lcsPairs(ua.map((u) => u.key), ub.map((u) => u.key))) {
|
|
106
|
+
gap(i, x, j, y);
|
|
107
|
+
out.push({ op: 'same', a: x, b: y });
|
|
108
|
+
i = x + 1; j = y + 1;
|
|
109
|
+
}
|
|
110
|
+
gap(i, ua.length, j, ub.length);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const okResponse = (r) => !!r && typeof r === 'object' && !('error' in r) && Array.isArray(r.rows) && Array.isArray(r.columns);
|
|
115
|
+
const round = (v) => (Math.abs(v) < EPS ? 0 : v);
|
|
116
|
+
|
|
117
|
+
// The columns both responses have (by name), in A's order: [{name, kind, ia, ib}].
|
|
118
|
+
export function sharedColumns(ra, rb) {
|
|
119
|
+
return ra.columns.map((name, ia) => ({ name, kind: columnKind(name), ia, ib: rb.columns.indexOf(name) })).filter((c) => c.ib >= 0);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Two cycle counts (per iteration or per element) are the same when they differ by less than REL of the larger one:
|
|
123
|
+
// uiCA's throughputs are exact to its two decimals at about 2 cycles, and per element they can be 100× smaller, so the
|
|
124
|
+
// test is relative, on the unrounded values.
|
|
125
|
+
export const REL = 0.0025;
|
|
126
|
+
export const sameValue = (a, b) => Math.abs(b - a) <= REL * Math.max(Math.abs(a), Math.abs(b));
|
|
127
|
+
// verdict for a change of a cycle count from a to b (lower is better); verdict(delta) alone: against EPS (older form)
|
|
128
|
+
export function verdict(a, b) {
|
|
129
|
+
if (b === undefined) return Math.abs(a) < EPS ? 'same' : a < 0 ? 'better' : 'worse';
|
|
130
|
+
return sameValue(a, b) ? 'same' : b < a ? 'better' : 'worse';
|
|
131
|
+
}
|
|
132
|
+
// A cycle count as shown: two decimals, or three significant digits below 0.1 (per element: 0.0156)
|
|
133
|
+
export function cycles(v) {
|
|
134
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) return '–';
|
|
135
|
+
const a = Math.abs(v);
|
|
136
|
+
return a !== 0 && a < 0.1 ? v.toPrecision(3) : v.toFixed(2);
|
|
137
|
+
}
|
|
138
|
+
// a change of a cycle count, with its sign (a real minus sign): "+1.50", "−0.00313"
|
|
139
|
+
export const signedCycles = (v) => `${v < 0 ? '−' : '+'}${cycles(Math.abs(v))}`;
|
|
140
|
+
|
|
141
|
+
// The comparison of two responses. workA, workB: the elements (or bytes) one iteration of A and of B processes; the
|
|
142
|
+
// cycle counts are divided by them before they are compared (cycles per element). scale (older form): B does the work
|
|
143
|
+
// of `scale` iterations of A, i.e. workA = 1, workB = scale.
|
|
144
|
+
// Either response may be an error ({error}) or missing: then only what can be compared is filled in.
|
|
145
|
+
/**
|
|
146
|
+
* @param {any} ra
|
|
147
|
+
* @param {any} rb
|
|
148
|
+
* @param {{workA?: number, workB?: number | null, scale?: number}} [opts]
|
|
149
|
+
*/
|
|
150
|
+
export function compareResponses(ra, rb, { workA = 1, workB = null, scale = 1 } = {}) {
|
|
151
|
+
const wa = workA > 0 ? workA : 1, wb = workB !== null && workB > 0 ? workB : scale > 0 ? scale : 1;
|
|
152
|
+
const okA = okResponse(ra), okB = okResponse(rb);
|
|
153
|
+
/** @type {any} */
|
|
154
|
+
const out = { okA, okB, workA: wa, workB: wb, scale: wb / wa, perElement: wa !== 1 || wb !== 1, tp: null, bottlenecks: null, limits: [], diff: null };
|
|
155
|
+
if (!okA || !okB) return out;
|
|
156
|
+
const a = Number(ra.tp) / wa, b = Number(rb.tp) / wb;
|
|
157
|
+
const v = verdict(a, b);
|
|
158
|
+
const delta = v === 'same' ? 0 : b - a; // (unrounded; 0 when the same)
|
|
159
|
+
out.tp = { a, b, aRaw: Number(ra.tp), bRaw: Number(rb.tp), delta, pct: a > 0 ? (100 * delta) / a : null, speedup: b > 0 ? a / b : null, verdict: v };
|
|
160
|
+
|
|
161
|
+
const ba = ra.bottlenecks ?? [], bb = rb.bottlenecks ?? [];
|
|
162
|
+
out.bottlenecks = { a: ba, b: bb, same: ba.length === bb.length && ba.every((x) => bb.includes(x)),
|
|
163
|
+
gone: ba.filter((x) => !bb.includes(x)), new: bb.filter((x) => !ba.includes(x)), kept: ba.filter((x) => bb.includes(x)) };
|
|
164
|
+
|
|
165
|
+
const names = [...new Set([...(ra.limits ?? []).map((l) => l.name), ...(rb.limits ?? []).map((l) => l.name)])];
|
|
166
|
+
out.limits = names.map((name) => {
|
|
167
|
+
const la = ra.limits.find((l) => l.name === name), lb = rb.limits.find((l) => l.name === name);
|
|
168
|
+
const va = la ? Number(la.tp) / wa : null, vb = lb ? Number(lb.tp) / wb : null;
|
|
169
|
+
return { name, a: va, b: vb, delta: va !== null && vb !== null ? (sameValue(va, vb) ? 0 : vb - va) : null,
|
|
170
|
+
bottleneckA: ba.includes(name), bottleneckB: bb.includes(name) };
|
|
171
|
+
});
|
|
172
|
+
out.diff = diffTables(ra, rb);
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// The instruction-by-instruction difference of two uop tables.
|
|
177
|
+
// rows: [{status, a: unit|null, b: unit|null, deltas: [per shown column, B − A]}]
|
|
178
|
+
// status: 'same' | 'changed' (same instruction, other uops) | 'modified' | 'added' | 'removed'
|
|
179
|
+
// minor: a 'changed' row whose every shared column differs by less than MINOR (and the notes are the same)
|
|
180
|
+
// columns: the shared columns that are shown: the issued uops and every execution port either side uses
|
|
181
|
+
// totals: the sum of the deltas per shown column
|
|
182
|
+
// portsComparable: false if the two sides have different execution ports (e.g. Skylake and Zen 3)
|
|
183
|
+
// counts: rows per status
|
|
184
|
+
export function diffTables(ra, rb) {
|
|
185
|
+
const ua = instructionUnits(ra), ub = instructionUnits(rb);
|
|
186
|
+
const shared = sharedColumns(ra, rb);
|
|
187
|
+
const portsA = ra.columns.filter((c) => columnKind(c) === 'port'), portsB = rb.columns.filter((c) => columnKind(c) === 'port');
|
|
188
|
+
const portsComparable = portsA.length === portsB.length && portsA.every((c) => portsB.includes(c));
|
|
189
|
+
const used = (c) => [ra, rb].some((r, k) => r.rows.some((x) => Number(x.values?.[k ? c.ib : c.ia]) > 0));
|
|
190
|
+
const columns = shared.filter((c) => (c.name === 'Issued' || (c.kind === 'port' && portsComparable)) && used(c));
|
|
191
|
+
const counts = { same: 0, changed: 0, modified: 0, added: 0, removed: 0 };
|
|
192
|
+
const totals = new Array(columns.length).fill(0);
|
|
193
|
+
const rows = alignUnits(ua, ub).map(({ op, a, b }) => {
|
|
194
|
+
const x = a === null ? null : ua[a], y = b === null ? null : ub[b];
|
|
195
|
+
const deltas = columns.map((c, k) => {
|
|
196
|
+
const d = (y ? y.values[c.ib] : 0) - (x ? x.values[c.ia] : 0);
|
|
197
|
+
totals[k] += d;
|
|
198
|
+
return round(d);
|
|
199
|
+
});
|
|
200
|
+
let status = op, minor = false;
|
|
201
|
+
if (op === 'same') {
|
|
202
|
+
const allShared = shared.every((c) => Math.abs(y.values[c.ib] - x.values[c.ia]) < EPS);
|
|
203
|
+
status = allShared && x.notes === y.notes && (portsComparable || deltas.every((d) => d === 0)) ? 'same' : 'changed';
|
|
204
|
+
minor = status === 'changed' && x.notes === y.notes && shared.every((c) => Math.abs(y.values[c.ib] - x.values[c.ia]) < MINOR);
|
|
205
|
+
}
|
|
206
|
+
counts[status]++;
|
|
207
|
+
return { status, a: x, b: y, deltas, ...(minor ? { minor } : {}) };
|
|
208
|
+
});
|
|
209
|
+
return { rows, columns, totals: totals.map(round), portsComparable, counts };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// "+0.25", "−0.5" (a real minus sign), "" for zero
|
|
213
|
+
export function signed(v, digits = 2) {
|
|
214
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || Math.abs(v) < EPS) return '';
|
|
215
|
+
const s = String(Math.round(Math.abs(v) * 10 ** digits) / 10 ** digits);
|
|
216
|
+
return (v < 0 ? '−' : '+') + s;
|
|
217
|
+
}
|
package/lib/web/accum.js
CHANGED
|
@@ -12,12 +12,14 @@ const GPR = [
|
|
|
12
12
|
['rsi', 'esi', 'si', 'sil'], ['rdi', 'edi', 'di', 'dil'], ['rbp', 'ebp', 'bp', 'bpl'], ['rsp', 'esp', 'sp', 'spl'],
|
|
13
13
|
...Array.from({ length: 8 }, (_, k) => [`r${k + 8}`, `r${k + 8}d`, `r${k + 8}w`, `r${k + 8}b`]),
|
|
14
14
|
];
|
|
15
|
+
/** @type {Map<string, Family>} */
|
|
15
16
|
const FAMILY = new Map(GPR.flatMap((names) => names.map((n, size) => [n, { kind: 'gpr', base: names[0], size }])));
|
|
16
17
|
// the registers a copy can get, in this order (not rsp; the ones with implicit uses last)
|
|
17
18
|
const GPR_FREE = ['r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15', 'rbx', 'rbp', 'rsi', 'rdi', 'rcx', 'rdx', 'rax'];
|
|
18
19
|
// Instructions with implicit register operands (the response has no operand sets without the details: this list is
|
|
19
20
|
// the x86-64 instructions that read or write a register they do not name): [test, registers]. 'vall': every vector
|
|
20
21
|
// register. Renaming such a register would change what they do, and none of them may get a copy's register.
|
|
22
|
+
/** @type {[RegExp, string[]][]} */
|
|
21
23
|
const IMPLICIT = [
|
|
22
24
|
[/^(?:i?div|mul|cdq|cqo|cwd|rdtsc|xsave\w*|xrstor\w*|in|out)$/, ['rax', 'rdx']],
|
|
23
25
|
[/^(?:cbw|cwde|cdqe|lahf|sahf|cmpxchg|stos\w*|lods\w*|scas\w*)$/, ['rax']],
|
|
@@ -51,17 +53,21 @@ export const implicitUse = (mnemonic, operands) => {
|
|
|
51
53
|
const VEC = /^([xyz]mm)(\d+)$/;
|
|
52
54
|
|
|
53
55
|
// The family of a register name: {kind: 'gpr', base: 'rax', size} or {kind: 'vec', index}; null if not renamable.
|
|
56
|
+
/** @typedef {{kind: 'gpr', base: string, size: number} | {kind: 'vec', base: string, index: number}} Family */
|
|
57
|
+
/** @returns {Family | null} */
|
|
54
58
|
export function family(name) {
|
|
55
59
|
const n = String(name).toLowerCase();
|
|
56
60
|
const v = VEC.exec(n);
|
|
57
|
-
if (v) return { kind: 'vec', index: Number(v[2]), base: `v${v[2]}` };
|
|
61
|
+
if (v) return { kind: /** @type {const} */ ('vec'), index: Number(v[2]), base: `v${v[2]}` };
|
|
58
62
|
return FAMILY.get(n) ?? null;
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
// The registers on the critical loop-carried chain: {ok, bases: ['rax' | 'v0', ...], names} or {ok: false, reason}.
|
|
66
|
+
/** @returns {{ok: true, bases: string[], names: string[]} | {ok: false, reason: string}} */
|
|
62
67
|
export function chainRegisters(response) {
|
|
63
68
|
const edges = response?.criticalPath?.edges;
|
|
64
69
|
if (!Array.isArray(edges) || !edges.length) return { ok: false, reason: 'no loop-carried chain' };
|
|
70
|
+
/** @type {string[]} */
|
|
65
71
|
const bases = [], names = [];
|
|
66
72
|
for (const e of edges) {
|
|
67
73
|
const op = String(e.operand ?? '');
|
|
@@ -87,7 +93,7 @@ function renameText(text, map) {
|
|
|
87
93
|
if (!f || !map.has(f.base)) return tok;
|
|
88
94
|
const to = map.get(f.base);
|
|
89
95
|
if (f.kind === 'vec') return tok.slice(0, 3) + to.slice(1);
|
|
90
|
-
const names = GPR.find((g) => g[0] === to);
|
|
96
|
+
const names = GPR.find((g) => g[0] === to) ?? [];
|
|
91
97
|
const n = names[f.size];
|
|
92
98
|
if (!n) { bad = true; return tok; }
|
|
93
99
|
return tok === tok.toUpperCase() ? n.toUpperCase() : n;
|
|
@@ -125,6 +131,7 @@ const splitInstr = (label) => { const t = String(label).trim().replace(/\s+/g, '
|
|
|
125
131
|
|
|
126
132
|
// The variant with n accumulators: {ok: true, text, per: n, renamed: [{from, to: [names]}]} or {ok: false, reason}.
|
|
127
133
|
// response: the analysis of hex (a loop); the rows must make up the code (as for the unrolled variants).
|
|
134
|
+
/** @returns {{ok: true, text: string, per: number, renamed: {from: string, to: string[]}[]} | {ok: false, reason: string}} */
|
|
128
135
|
export function accumulatorText(response, hex, n) {
|
|
129
136
|
if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
|
|
130
137
|
const rows = Array.isArray(response.rows) ? response.rows : [];
|
|
@@ -145,6 +152,7 @@ export function accumulatorText(response, hex, n) {
|
|
|
145
152
|
const body = ins.slice(0, tailFrom), tail = ins.slice(tailFrom);
|
|
146
153
|
// registers in use (any form: al/ax/eax/rax, xmm/ymm/zmm are one register), and the implicit ones
|
|
147
154
|
const uses = (i) => { const s = splitInstr(i.label); return new Set([...regsIn(i.label).map((r) => family(r)?.base).filter(Boolean), ...implicitUse(s.mnemonic, s.operands)]); };
|
|
155
|
+
/** @type {Map<any, any>} */
|
|
148
156
|
const usesOf = new Map(ins.map((i) => [i, uses(i)]));
|
|
149
157
|
const used = new Set(ins.flatMap((i) => [...usesOf.get(i)]));
|
|
150
158
|
const implicit = new Set(ins.flatMap((i) => { const s = splitInstr(i.label); return implicitUse(s.mnemonic, s.operands); }));
|