wuica-cli 0.1.9 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -30
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +6 -6
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +164 -10
- package/lib/cli.js +194 -39
- package/lib/core.js +9 -1
- package/lib/details.js +4 -23
- package/lib/examples.js +1 -0
- package/lib/files.js +2 -1
- package/lib/index.js +100 -17
- package/lib/mcp.js +107 -84
- package/lib/objfile.js +4 -2
- package/lib/thread-worker.js +9 -6
- package/lib/threads.js +8 -2
- package/lib/wasm.js +12 -6
- 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 +107 -3
- package/lib/web/details.js +91 -0
- package/lib/web/examples.js +5 -1
- package/lib/web/loop-find.js +139 -16
- package/lib/web/markdown.js +437 -0
- package/lib/web/whatif-core.js +339 -0
- package/package.json +3 -1
- package/lib/insights.js +0 -100
- package/lib/whatif.js +0 -136
package/lib/mcp.js
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
|
|
10
10
|
import fs from 'node:fs';
|
|
11
11
|
import readline from 'node:readline';
|
|
12
|
-
import { createWuica } from './index.js';
|
|
13
|
-
import {
|
|
12
|
+
import { createWuica, listLoops } from './index.js';
|
|
13
|
+
import { whatIfRequest, VARIANTS, OPT_IN_VARIANTS } from './web/whatif-core.js';
|
|
14
|
+
import { diffRequest } from './web/block-diff.js';
|
|
14
15
|
|
|
15
16
|
const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
16
17
|
|
|
@@ -19,29 +20,17 @@ export const SERVER_INFO = Object.freeze({ name: 'wuica', version: pkg.version }
|
|
|
19
20
|
export const CAPABILITIES = Object.freeze({ tools: { listChanged: true } });
|
|
20
21
|
|
|
21
22
|
const ASSUMPTIONS =
|
|
22
|
-
'
|
|
23
|
-
'
|
|
24
|
-
'
|
|
25
|
-
|
|
26
|
-
'dependencies. ZEN3, ADL-P and ICX are prototype models (experimental, from the fork jtl06/uiCA), less validated than ' +
|
|
27
|
-
"uiCA's Intel models (SNB through RKL).";
|
|
23
|
+
'tp is the predicted steady-state throughput in core cycles per iteration (lower is faster): a block that ends with a ' +
|
|
24
|
+
'branch is simulated as a loop body, any other as if repeated back to back. Assumes all data in L1, no branch ' +
|
|
25
|
+
'mispredictions, nothing else on the core. ZEN3, ADL-P and ICX are prototype models (the fork jtl06/uiCA), less ' +
|
|
26
|
+
"validated than uiCA's Intel models.";
|
|
28
27
|
|
|
29
28
|
const INPUT_NOTE =
|
|
30
|
-
'
|
|
31
|
-
'
|
|
32
|
-
'
|
|
33
|
-
'without the bytes) is fine: by default (`loop: "auto"`) its innermost loop is analyzed (the first one in the code), ' +
|
|
34
|
-
'or the body without prologue and epilogue if it is a compiler\'s function without a loop; the deepest loop is ' +
|
|
35
|
-
'preferred (clang\'s "Inner Loop Header" notes count), among equals the first; branches out of the loop count as not taken (so an exit ' +
|
|
36
|
-
'to a label that is not in the text assembles); with addresses, the alignment offset is the loop\'s address mod 64 ' +
|
|
37
|
-
'unless options.alignmentOffset is given. The response\'s `loop` says what was analyzed (index, count, name, lines, ' +
|
|
38
|
-
'address, function, depth). `loop: "whole"` analyzes the whole text; `loop: N` the N-th loop (0-based: deepest first, ' +
|
|
39
|
-
'then in code order); `loop: ".LBB0_12"` a loop by its label; `func: "name"` only the loops of that function.';
|
|
29
|
+
'The block: `source` (x86-64 assembly, Intel or AT&T, detected; a whole function, gcc/clang -S or objdump -d output ' +
|
|
30
|
+
'is fine: its innermost loop is analyzed; `loop` picks another: "whole", an index or a label; `func` one ' +
|
|
31
|
+
"function's) or `hex` (machine code).";
|
|
40
32
|
|
|
41
|
-
const ERRORS_NOTE =
|
|
42
|
-
'Failures are tool errors whose JSON is {code, error, stderr}: code 1 = bad request (e.g. unknown arch, bad hex), ' +
|
|
43
|
-
'2 = assembler error (stderr lines as llvm-mc prints them; positioned ones carry tag {line, column, severity, text}), ' +
|
|
44
|
-
'3 = the analysis failed for this input.';
|
|
33
|
+
const ERRORS_NOTE = 'A failure is a tool error {code, error, stderr}: 1 bad request, 2 assembler error (positioned stderr), 3 analysis failed.';
|
|
45
34
|
|
|
46
35
|
// ---- the input schemas (JSON Schema, draft-07 as before) ----------------------------------------------------------------
|
|
47
36
|
|
|
@@ -66,17 +55,19 @@ const optionsShape = {
|
|
|
66
55
|
description: 'simulation options of uiCA; all optional',
|
|
67
56
|
type: 'object',
|
|
68
57
|
properties: {
|
|
69
|
-
alignmentOffset: int('offset of the block from a 64-byte boundary (default 0); affects the front end',
|
|
58
|
+
alignmentOffset: int('offset of the block from a 64-byte boundary (default 0; usually 0-63, other values are simulated as given); affects the front end', -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
|
|
70
59
|
initPolicy: str('initial register values: "diff" (default: all registers differ), "same", "stack"', { enum: ['diff', 'same', 'stack'] }),
|
|
71
60
|
simpleFrontEnd: bool('model a front end limited only by the issue width (default false)'),
|
|
72
61
|
noMicroFusion: bool('disable micro-fusion (default false)'),
|
|
73
62
|
noMacroFusion: bool('disable macro-fusion (default false)'),
|
|
74
|
-
minIterations: int('simulate at least this many iterations (default 10)', 1, 100000),
|
|
75
|
-
minCycles: int('simulate at least this many cycles (default 500)', 1, 1000000),
|
|
63
|
+
minIterations: int('simulate at least this many iterations (default 10; the API server allows at most 1000)', 1, 100000),
|
|
64
|
+
minCycles: int('simulate at least this many cycles (default 500; the API server allows at most 20000)', 1, 1000000),
|
|
76
65
|
},
|
|
77
66
|
additionalProperties: false,
|
|
78
67
|
};
|
|
79
68
|
|
|
69
|
+
const PER = { description: 'elements (bytes, floats, ...) one iteration of the loop processes: the result also gives cycles per element (`perElement`)', type: 'number', exclusiveMinimum: 0 };
|
|
70
|
+
|
|
80
71
|
const json = (value) => ({ type: 'text', text: JSON.stringify(value, null, 1) });
|
|
81
72
|
const omitBytes = ({ bytes, ...rest }) => rest;
|
|
82
73
|
|
|
@@ -88,23 +79,23 @@ export const INSTRUCTIONS =
|
|
|
88
79
|
'wuica predicts the throughput of x86-64 basic blocks (loop bodies) with uiCA\'s cycle-level pipeline model, ' +
|
|
89
80
|
'locally. Use `analyze` for one block on one microarchitecture (bottlenecks, per-port usage, full report), ' +
|
|
90
81
|
'`what_if` for the effect of unrolling, an ideal front end, fusion, or removing the dependency chain, ' +
|
|
91
|
-
'`compare_archs` to see a block on several microarchitectures, `
|
|
82
|
+
'`compare_archs` to see a block on several microarchitectures, `diff_blocks` for the effect of a code change ' +
|
|
83
|
+
'(before and after), `list_loops` for the loops of a text, `list_archs` for the ids, `assemble` to check ' +
|
|
92
84
|
'that assembly text is accepted and see its encoding. ' + ASSUMPTIONS;
|
|
93
85
|
|
|
94
86
|
const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
|
|
95
87
|
const execution = { taskSupport: 'forbidden' };
|
|
96
88
|
|
|
97
89
|
// The tools: [{name, title, description, inputSchema, annotations, execution, handler(args) -> CallToolResult}]. w: a
|
|
98
|
-
// wuica instance (createWuica) or anything with its analyze, compare, assemble, archs and summarize.
|
|
90
|
+
// wuica instance (createWuica) or anything with its analyze, compare, whatIf, diff, assemble, archs and summarize.
|
|
99
91
|
export function mcpTools(w) {
|
|
100
92
|
return [
|
|
101
93
|
{
|
|
102
94
|
name: 'list_archs',
|
|
103
95
|
title: 'List microarchitectures',
|
|
104
96
|
description:
|
|
105
|
-
'
|
|
106
|
-
'
|
|
107
|
-
'validated than uiCA\'s Intel models). `fields` selects fields (also available: table, xedChip).',
|
|
97
|
+
'The microarchitecture models in order of release: id (the `arch` of the other tools), name, year, and `prototype` ' +
|
|
98
|
+
'(ZEN3, ADL-P, ICX: experimental models of the fork jtl06/uiCA). `fields` selects (also table, xedChip).',
|
|
108
99
|
inputSchema: obj({
|
|
109
100
|
fields: { description: 'fields to return (default: id, name, year, prototype)', type: 'array', items: { type: 'string', enum: ['id', 'name', 'year', 'prototype', 'table', 'xedChip'] } },
|
|
110
101
|
}),
|
|
@@ -115,39 +106,22 @@ export function mcpTools(w) {
|
|
|
115
106
|
name: 'analyze',
|
|
116
107
|
title: 'Predict basic-block throughput (uiCA)',
|
|
117
108
|
description:
|
|
118
|
-
'
|
|
119
|
-
'
|
|
120
|
-
|
|
121
|
-
'
|
|
122
|
-
'
|
|
123
|
-
'
|
|
124
|
-
'
|
|
125
|
-
'
|
|
126
|
-
'
|
|
127
|
-
'
|
|
128
|
-
'result is unreliable); `stderr` = assembler warnings and decode warnings (`decodeErrors` > 0: some bytes could ' +
|
|
129
|
-
'not be decoded); `insights` = a derived diagnosis: `utilization` (each limit and execution port as a fraction ' +
|
|
130
|
-
'of tp; 1 = saturated), `binding` (the limiting component: the same as `bottlenecks`; [] when uiCA names none, then ' +
|
|
131
|
-
'`largest` is the largest limit, the nearest bound, which alone does not reach tp), `next` (the next limit and `maxSpeedup`, an upper ' +
|
|
132
|
-
'bound of the speedup if the binding component were removed), `unexplained` (cycles no single limit explains), ' +
|
|
133
|
-
'`chain` (the loop-carried critical dependency chain: `index` into `instructions`, operand, latency, carried ' +
|
|
134
|
-
'into the next iteration), `hot` (the instructions with the largest share of the binding resource: fix these ' +
|
|
135
|
-
'first), `caveats` (known blind spots of the model the block meets, not simulated: rmw-index = a read-modify-write ' +
|
|
136
|
-
'to an indexed address, whose store forwarding between iterations depends on the data; exit = an exit before the ' +
|
|
137
|
-
'loop\'s branch, whose mispredict is not modelled; split = loads at an offset that is not a multiple of their width, ' +
|
|
138
|
-
'which may cross a cache line (on ZEN3, ADL-P and ICX, whose models charge crossings, only loads whose address register ' +
|
|
139
|
-
'is written other than by adding an immediate); `instructions` = indexes into `instructions`). With `details: true`, each instruction also has `allowedPorts` (uops.info notation, e.g. 1*p0156+1*p23), ' +
|
|
140
|
-
'`uops`, `fusedUops`, `latencies` ("input->output:cycles"), `frontEnd` (length, offset = alignment offset + position in the block, crosses ' +
|
|
141
|
-
'16/32/64-byte boundaries, lcp = length-changing prefix, microcoded, macro-fusion), and `insights` has `portSet` (the ' +
|
|
142
|
-
'ports behind the Ports limit and the instructions whose uops can only use them) and `issueSlots` (issue slots per ' +
|
|
143
|
-
'iteration: issued, or lost to the front end, a full reorder buffer (rob) or scheduler (rs), other). ' +
|
|
144
|
-
'Format "text" (or the second item of "both") is uiCA\'s complete text report. ' + ERRORS_NOTE,
|
|
109
|
+
'One x86-64 block on one microarchitecture with uiCA\'s pipeline model. ' + INPUT_NOTE + ' ' + ASSUMPTIONS +
|
|
110
|
+
'\n\nResult (format "json"): `tp` (cycles per iteration), `mode` (loop or unroll), `bottlenecks` (Dependencies = a ' +
|
|
111
|
+
'loop-carried chain, Ports, Issue, Decoder, Predecoder, DSB, LSD), `limits` (the tp each component alone would allow), ' +
|
|
112
|
+
'`loop` (what was analyzed) and `otherLoops`, `instructions[]` (per instruction: uops issued and executed per iteration, ' +
|
|
113
|
+
'`ports`, `uopSource` MITE/DSB/LSD/MS, `notes` M macro-fused, J JCC erratum, X not modelled; `line`, and `loc`, ' +
|
|
114
|
+
'`source`, `samples` when the input has them), `stderr`, and `insights`: `utilization` (each limit and port as a ' +
|
|
115
|
+
'fraction of tp), `binding`, `largest` (when uiCA names no bottleneck), `next` (the next limit, `maxSpeedup`), `chain` ' +
|
|
116
|
+
'(the critical dependency chain), `hot` (the instructions to fix first), `caveats` (what the model does not simulate: ' +
|
|
117
|
+
'rmw-index, exit, split, paths). `details: true` adds per instruction allowed ports, latencies and front-end facts, ' +
|
|
118
|
+
'and the issue slots. Format "text" is uiCA\'s report; "both" (default) gives both. ' + ERRORS_NOTE,
|
|
145
119
|
inputSchema: obj({
|
|
146
120
|
arch: str('microarchitecture id (default "SKL"); see list_archs, e.g. SKL, ICL, TGL, RKL, ADL-P, ZEN3'),
|
|
147
121
|
...codeShape,
|
|
148
122
|
options: optionsShape,
|
|
149
123
|
format: str('"json" (summary), "text" (uiCA\'s report) or "both" (default)', { enum: ['json', 'text', 'both'] }),
|
|
150
|
-
details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and
|
|
124
|
+
details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and the issue slots (slower; default false)'),
|
|
151
125
|
}),
|
|
152
126
|
annotations: readOnly, execution,
|
|
153
127
|
handler: async ({ arch, format, details, ...request }) => {
|
|
@@ -163,52 +137,83 @@ export function mcpTools(w) {
|
|
|
163
137
|
name: 'what_if',
|
|
164
138
|
title: 'What-if experiments on a basic block',
|
|
165
139
|
description:
|
|
166
|
-
'Re-analyzes
|
|
167
|
-
'
|
|
168
|
-
'
|
|
169
|
-
'
|
|
170
|
-
'
|
|
171
|
-
'
|
|
172
|
-
'result\'s `accumulators.best` is the smallest N within 1% of the fastest, 1 = as it is: call it per arch for the ' +
|
|
173
|
-
'best N per CPU; not possible when the chain goes through memory or flags or an implicit operand), simpleFrontEnd (a front end limited only by the ' +
|
|
174
|
-
'issue width), noMacroFusion / noMicroFusion (switched; if the base already has the option set, the variant ' +
|
|
175
|
-
'switches it back), nochain (no analysis: the largest limit other than Dependencies, an estimate of the ' +
|
|
176
|
-
'throughput without the loop-carried chain; `estimate: true`). A variant that cannot be made or analyzed has ' +
|
|
177
|
-
'`error`. Use it to decide whether unrolling, breaking the chain or front-end work is worth it. ' + INPUT_NOTE + ' ' +
|
|
178
|
-
ASSUMPTIONS + ' ' + ERRORS_NOTE,
|
|
140
|
+
'Re-analyzes a block with one change each; per variant `tp` per ORIGINAL iteration, `delta` (negative = faster), ' +
|
|
141
|
+
'`speedup`, or `error`: unroll2/4/8 (the body n times, the branch once), acc2/3/4/8 (unrolled with the chain\'s ' +
|
|
142
|
+
'register renamed in each copy: N independent accumulators; `accumulators.best` = the smallest N within 1% of the ' +
|
|
143
|
+
'fastest), simpleFrontEnd, noMacroFusion, noMicroFusion, nochain (an estimate without the loop-carried chain). Only ' +
|
|
144
|
+
'when asked for: align (the 64 alignment offsets, 64 analyses: `tp` the median, `alignment` min, median, max, best, ' +
|
|
145
|
+
'worst, spread). `per`: also cycles per element. ' + INPUT_NOTE + ' ' + ERRORS_NOTE,
|
|
179
146
|
inputSchema: obj({
|
|
180
147
|
arch: str('microarchitecture id (default "SKL"); see list_archs'),
|
|
181
148
|
...codeShape,
|
|
182
149
|
options: optionsShape,
|
|
183
|
-
variants: { description: `the experiments (default:
|
|
150
|
+
variants: { description: `the experiments (default: ${VARIANTS.join(', ')}; also align)`, type: 'array', items: { type: 'string', enum: [...VARIANTS, ...OPT_IN_VARIANTS] } },
|
|
151
|
+
per: PER,
|
|
184
152
|
}),
|
|
185
153
|
annotations: readOnly, execution,
|
|
186
|
-
handler: async ({ arch,
|
|
154
|
+
handler: async ({ arch, ...request }) => result(await (w.whatIf ? w.whatIf(arch ?? 'SKL', request) : whatIfRequest(w, arch ?? 'SKL', request))),
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
name: 'diff_blocks',
|
|
158
|
+
title: 'Compare two versions of a block',
|
|
159
|
+
description:
|
|
160
|
+
'Two blocks, A (before) and B (after), on one microarchitecture, in one result: `a` and `b` (tp, bottlenecks, ' +
|
|
161
|
+
'decodeErrors), `delta` (B - A), `speedup` (A / B), `verdict`, `perElement` (with `per`), `bottlenecks` (gone, new), ' +
|
|
162
|
+
'`limits` and `ports` (uops per iteration) before and after, and `instructions` (the ones changed, added or removed, ' +
|
|
163
|
+
'with the change of their uops). Each block as analyze takes it; `options` apply to both unless a block has its own. ' +
|
|
164
|
+
'A loop against a block without a branch is not comparable. A failure of one block starts with "A: " or "B: ".',
|
|
165
|
+
inputSchema: obj({
|
|
166
|
+
arch: str('microarchitecture id (default "SKL"); see list_archs'),
|
|
167
|
+
a: { description: 'block A (before)', type: 'object', properties: { ...codeShape, options: optionsShape }, additionalProperties: false },
|
|
168
|
+
b: { description: 'block B (after)', type: 'object', properties: { ...codeShape, options: optionsShape }, additionalProperties: false },
|
|
169
|
+
options: optionsShape,
|
|
170
|
+
per: {
|
|
171
|
+
description: 'elements per iteration: a number for both, or [A, B] (e.g. [8, 32] after unrolling ×4): also cycles per element',
|
|
172
|
+
anyOf: [{ type: 'number', exclusiveMinimum: 0 }, { type: 'array', items: { type: 'number', exclusiveMinimum: 0 }, minItems: 2, maxItems: 2 }],
|
|
173
|
+
},
|
|
174
|
+
}, ['a', 'b']),
|
|
175
|
+
annotations: readOnly, execution,
|
|
176
|
+
handler: async ({ arch, ...request }) => result(await (w.diff ? w.diff(arch ?? 'SKL', request) : diffRequest(w, arch ?? 'SKL', request))),
|
|
187
177
|
},
|
|
188
178
|
{
|
|
189
179
|
name: 'compare_archs',
|
|
190
180
|
title: 'Compare a block across microarchitectures',
|
|
191
181
|
description:
|
|
192
|
-
'
|
|
193
|
-
'
|
|
194
|
-
'microarchitecture). Use it to see how a loop behaves on older vs. newer Intel cores or on AMD Zen 3. ' +
|
|
195
|
-
INPUT_NOTE + ' ' + ASSUMPTIONS + ' ' + ERRORS_NOTE,
|
|
182
|
+
'One block on several microarchitectures (default: all): per microarchitecture `tp` and `bottlenecks` (a row with ' +
|
|
183
|
+
'code != 0 failed there); `per`: also cycles per element. ' + INPUT_NOTE + ' ' + ERRORS_NOTE,
|
|
196
184
|
inputSchema: obj({
|
|
197
185
|
...codeShape,
|
|
198
186
|
archs: { description: 'microarchitecture ids to compare (default: all of list_archs)', type: 'array', items: { type: 'string' } },
|
|
199
187
|
options: optionsShape,
|
|
188
|
+
per: PER,
|
|
200
189
|
}),
|
|
201
190
|
annotations: readOnly, execution,
|
|
202
191
|
handler: async (request) => result(await w.compare(request)),
|
|
203
192
|
},
|
|
193
|
+
{
|
|
194
|
+
name: 'list_loops',
|
|
195
|
+
title: 'List the loops of assembly text',
|
|
196
|
+
description:
|
|
197
|
+
'The loops of assembly text (a function or file; gcc/clang -S, objdump -d, perf annotate) without analyzing it: ' +
|
|
198
|
+
'`index` and `label` (what analyze\'s `loop` takes), `function`, `line`, `endLine`, `instructions`, `depth` (1 = ' +
|
|
199
|
+
'outermost), `auto` (the one analyze picks by default). `func` keeps one function\'s loops.',
|
|
200
|
+
inputSchema: obj({
|
|
201
|
+
source: str('the assembly text'),
|
|
202
|
+
func: codeShape.func,
|
|
203
|
+
}, ['source']),
|
|
204
|
+
annotations: readOnly, execution,
|
|
205
|
+
handler: async ({ source, func }) => {
|
|
206
|
+
const ls = listLoops(source, { func: func ?? null });
|
|
207
|
+
if (!Array.isArray(ls)) return result({ code: 1, error: ls.error, stderr: [{ text: ls.error }] });
|
|
208
|
+
return result({ code: 0, loops: ls, ...(ls.length ? {} : { note: loopsNote(source) }) });
|
|
209
|
+
},
|
|
210
|
+
},
|
|
204
211
|
{
|
|
205
212
|
name: 'assemble',
|
|
206
213
|
title: 'Assemble x86-64 code',
|
|
207
214
|
description:
|
|
208
|
-
'Assembles x86-64
|
|
209
|
-
'{code:
|
|
210
|
-
'line/column tags. The syntax is detected unless given (Intel noprefix or AT&T); the text may switch with .intel_syntax noprefix / ' +
|
|
211
|
-
'.att_syntax. Only .text is returned.',
|
|
215
|
+
'Assembles x86-64 text with LLVM\'s assembler (LLVM 22, the bytes of llvm-mc): {code: 0, hex, length, stderr}, or ' +
|
|
216
|
+
'{code: 2, error, stderr} with line/column tags. The syntax is detected unless given. Only .text is returned.',
|
|
212
217
|
inputSchema: obj({
|
|
213
218
|
source: { description: 'the assembly text', type: 'string' },
|
|
214
219
|
syntax: codeShape.syntax,
|
|
@@ -219,22 +224,37 @@ export function mcpTools(w) {
|
|
|
219
224
|
];
|
|
220
225
|
}
|
|
221
226
|
|
|
227
|
+
// Why a text has no loops to list: a marked region (analyze takes the region, not a loop), or no backward branch.
|
|
228
|
+
function loopsNote(source) {
|
|
229
|
+
if (/^\s*(?:#|\/\/|;)\s*(?:LLVM-MCA-BEGIN|wuica-begin)(?![\w-])/im.test(source) || /^\s*mov[l]?\s+(?:ebx\s*,\s*111|\$111\s*,\s*%ebx)\s*$/im.test(source)) {
|
|
230
|
+
return 'the text has a marked region (LLVM-MCA-BEGIN, wuica-begin or IACA markers): analyze takes the region, not a loop';
|
|
231
|
+
}
|
|
232
|
+
return 'no backward branch to a label of the text: analyze takes the whole text (or a function\'s body)';
|
|
233
|
+
}
|
|
234
|
+
|
|
222
235
|
// The tool as tools/list shows it (without the handler).
|
|
223
236
|
export const toolListing = ({ handler, ...t }) => t;
|
|
224
237
|
|
|
225
238
|
// ---- a validator for the keywords these schemas use ------------------------------------------------------------------------
|
|
226
239
|
// type (object, array, string, integer, number, boolean), properties, required, additionalProperties: false, enum, items,
|
|
227
|
-
// minimum, maximum, minLength, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
|
|
240
|
+
// minimum, maximum, exclusiveMinimum, minLength, minItems, maxItems, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
|
|
228
241
|
// got \"many\""), or null.
|
|
229
242
|
const kind = (v) => (v === null ? 'null' : Array.isArray(v) ? 'an array' : typeof v === 'object' ? 'an object' : typeof v === 'string' ? 'a string' : typeof v === 'boolean' ? 'a boolean' : typeof v === 'number' ? (Number.isInteger(v) ? 'an integer' : 'a number') : typeof v);
|
|
230
243
|
const show = (v) => JSON.stringify(v)?.slice(0, 60) ?? String(v);
|
|
244
|
+
// what a schema of anyOf allows, in words: "an integer >= 0", "a non-empty string", "an array of 2 numbers > 0"
|
|
245
|
+
function describe(s, plural = false) {
|
|
246
|
+
if (s.enum) return s.enum.map((x) => JSON.stringify(x)).join(' or ');
|
|
247
|
+
const noun = s.type === 'string' && s.minLength ? 'non-empty string' : s.type === 'array' ? 'array' : String(s.type);
|
|
248
|
+
const bounds = `${s.minimum !== undefined ? ` >= ${s.minimum}` : ''}${s.exclusiveMinimum !== undefined ? ` > ${s.exclusiveMinimum}` : ''}`;
|
|
249
|
+
const of = s.type === 'array' && s.items ? ` of ${s.minItems !== undefined && s.minItems === s.maxItems ? `${s.minItems} ` : ''}${describe(s.items, true)}` : '';
|
|
250
|
+
return `${plural ? `${noun}s` : `${/^[aeiou]/.test(noun) ? 'an' : 'a'} ${noun}`}${of}${bounds}`;
|
|
251
|
+
}
|
|
231
252
|
export function validate(schema, value, at = '') {
|
|
232
253
|
const where = at || 'arguments';
|
|
233
254
|
if (schema.anyOf) {
|
|
234
255
|
const errs = schema.anyOf.map((s) => validate(s, value, at));
|
|
235
256
|
if (errs.some((e) => e === null)) return null;
|
|
236
|
-
|
|
237
|
-
return `${where}: expected ${allowed.join(', or ')}, got ${show(value)}`;
|
|
257
|
+
return `${where}: expected ${schema.anyOf.map((s) => describe(s)).join(', or ')}, got ${show(value)}`;
|
|
238
258
|
}
|
|
239
259
|
switch (schema.type) {
|
|
240
260
|
case 'object': {
|
|
@@ -254,6 +274,8 @@ export function validate(schema, value, at = '') {
|
|
|
254
274
|
}
|
|
255
275
|
case 'array': {
|
|
256
276
|
if (!Array.isArray(value)) return `${where}: expected an array, got ${kind(value)}`;
|
|
277
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) return `${where}: expected at least ${schema.minItems} items, got ${value.length}`;
|
|
278
|
+
if (schema.maxItems !== undefined && value.length > schema.maxItems) return `${where}: expected at most ${schema.maxItems} items, got ${value.length}`;
|
|
257
279
|
for (let i = 0; i < value.length; i++) { const e = schema.items ? validate(schema.items, value[i], `${where}[${i}]`) : null; if (e) return e; }
|
|
258
280
|
return null;
|
|
259
281
|
}
|
|
@@ -276,6 +298,7 @@ export function validate(schema, value, at = '') {
|
|
|
276
298
|
if (schema.enum && !schema.enum.includes(value)) return `${where}: expected one of ${schema.enum.map((x) => JSON.stringify(x)).join(', ')}, got ${show(value)}`;
|
|
277
299
|
if (schema.minimum !== undefined && value < schema.minimum) return `${where}: expected at least ${schema.minimum}, got ${value}`;
|
|
278
300
|
if (schema.maximum !== undefined && value > schema.maximum) return `${where}: expected at most ${schema.maximum}, got ${value}`;
|
|
301
|
+
if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) return `${where}: expected more than ${schema.exclusiveMinimum}, got ${value}`;
|
|
279
302
|
return null;
|
|
280
303
|
}
|
|
281
304
|
|
package/lib/objfile.js
CHANGED
|
@@ -24,13 +24,14 @@ export function objectKind(b) {
|
|
|
24
24
|
const ARCH_HELP = 'compile for x86-64: clang --target=x86_64-linux-gnu -c (Linux objects) or clang -arch x86_64 -c (macOS)';
|
|
25
25
|
|
|
26
26
|
// The code of an object file: {format, functions: [{name, section, address, size, bytes}]} or {error}.
|
|
27
|
+
/** @returns {any} */
|
|
27
28
|
export function readObject(bytes) {
|
|
28
29
|
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
29
30
|
const k = objectKind(b);
|
|
30
31
|
if (!k) return { error: 'not an object file' };
|
|
31
32
|
try {
|
|
32
33
|
if (k.kind === 'elf') return readElf(b);
|
|
33
|
-
if (k.kind === 'macho') return readMachO(b
|
|
34
|
+
if (k.kind === 'macho') return readMachO(b);
|
|
34
35
|
if (k.kind === 'fat') return readFat(b);
|
|
35
36
|
if (k.kind === 'macho32') return { error: `a 32-bit Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
|
|
36
37
|
if (k.kind === 'archive') return { error: 'an archive (.a): extract an object from it (ar x lib.a foo.o) and give that' };
|
|
@@ -122,7 +123,7 @@ function readFat(b) {
|
|
|
122
123
|
}
|
|
123
124
|
const x = archs.find((a) => a.cpu === MACHO_X86_64);
|
|
124
125
|
if (!x) return { error: `a universal Mach-O file without x86-64 code (${archs.map((a) => cpuName(a.cpu)).join(', ')}): wuica analyzes x86-64 code; ${ARCH_HELP}` };
|
|
125
|
-
return readMachO(b.subarray(x.offset, x.offset + x.size)
|
|
126
|
+
return readMachO(b.subarray(x.offset, x.offset + x.size));
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
const cpuName = (c) => (c === MACHO_ARM64 ? 'arm64' : c === MACHO_X86_64 ? 'x86_64' : c === MACHO_I386 ? 'i386' : `cpu ${c}`);
|
|
@@ -132,6 +133,7 @@ function readMachO(b) {
|
|
|
132
133
|
const cpu = dv.getUint32(4, true), filetype = dv.getUint32(12, true), ncmds = dv.getUint32(16, true);
|
|
133
134
|
if (cpu !== MACHO_X86_64) return { error: `${cpu === MACHO_ARM64 ? 'an arm64' : `a ${cpuName(cpu)}`} Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
|
|
134
135
|
const sects = [];
|
|
136
|
+
/** @type {{symoff: number, nsyms: number, stroff: number} | null} */
|
|
135
137
|
let symtab = null;
|
|
136
138
|
let o = 32;
|
|
137
139
|
for (let i = 0; i < ncmds; i++) {
|
package/lib/thread-worker.js
CHANGED
|
@@ -17,33 +17,36 @@ import { Analyzer } from './wasm.js';
|
|
|
17
17
|
import { readMaybeCompressed, readMaybeCompressedSync, tableFile } from './files.js';
|
|
18
18
|
import { analysisResult, compareFields } from './core.js';
|
|
19
19
|
|
|
20
|
+
if (!parentPort) throw new Error('thread-worker.js runs as a worker thread');
|
|
21
|
+
const port = parentPort;
|
|
20
22
|
const { module, uarch, dataDir, recycleBytes } = workerData;
|
|
23
|
+
/** @type {Analyzer | null} */
|
|
21
24
|
let analyzer = null;
|
|
22
25
|
try {
|
|
23
26
|
analyzer = new Analyzer(module);
|
|
24
27
|
analyzer.loadUarch(uarch);
|
|
25
28
|
} catch (e) {
|
|
26
|
-
|
|
29
|
+
port.postMessage({ type: 'init-error', message: String(e?.message ?? e) });
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
if (analyzer) {
|
|
30
|
-
|
|
33
|
+
port.on('message', async ({ id, table, request, full }) => {
|
|
31
34
|
if (!analyzer.hasArch(table)) {
|
|
32
35
|
try {
|
|
33
36
|
const file = tableFile(dataDir, table);
|
|
34
37
|
analyzer.loadArch(table, await readMaybeCompressed(file), () => readMaybeCompressedSync(file));
|
|
35
38
|
} catch {
|
|
36
|
-
|
|
39
|
+
port.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
|
|
37
40
|
return;
|
|
38
41
|
}
|
|
39
42
|
}
|
|
40
43
|
const response = analyzer.analyze(request);
|
|
41
44
|
if (response.trapped || analyzer.memoryBytes === 0) { // trapped, or could not be restarted after an earlier trap
|
|
42
|
-
|
|
45
|
+
port.postMessage({ id, fields: null, recycle: true });
|
|
43
46
|
return;
|
|
44
47
|
}
|
|
45
48
|
const result = analysisResult(response);
|
|
46
|
-
|
|
49
|
+
port.postMessage({ id, fields: full ? result : compareFields(result), recycle: analyzer.memoryBytes > recycleBytes });
|
|
47
50
|
});
|
|
48
|
-
|
|
51
|
+
port.postMessage({ type: 'ready' });
|
|
49
52
|
}
|
package/lib/threads.js
CHANGED
|
@@ -74,15 +74,20 @@ export function threadsForWork(jobs, limit, cores = os.availableParallelism()) {
|
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
export class ThreadPool {
|
|
77
|
+
/** @type {any} */
|
|
77
78
|
#workerData = null;
|
|
78
79
|
#wasm; #uarch; #dataDir;
|
|
80
|
+
/** @type {Promise<WebAssembly.Module> | null} */
|
|
79
81
|
#compiled = null; // promise of the module with the threads' memory limit
|
|
80
82
|
#limit;
|
|
83
|
+
/** @type {any[]} */
|
|
81
84
|
#slots = []; // {worker, ready, job, tables: Set}
|
|
82
85
|
#warmed = false;
|
|
83
86
|
#want; // the threads the latest run() may start
|
|
87
|
+
/** @type {any[]} */
|
|
84
88
|
#queue = []; // {id, table, request, resolve}
|
|
85
89
|
#nextId = 1;
|
|
90
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
86
91
|
#idleTimer = null;
|
|
87
92
|
broken = false;
|
|
88
93
|
|
|
@@ -100,7 +105,7 @@ export class ThreadPool {
|
|
|
100
105
|
// than `threads` (and `limit`) and jobs wait.
|
|
101
106
|
async run(jobs, threads = this.#limit) {
|
|
102
107
|
this.#want = Math.min(this.#limit, threads);
|
|
103
|
-
clearTimeout(this.#idleTimer);
|
|
108
|
+
clearTimeout(this.#idleTimer ?? undefined);
|
|
104
109
|
this.#idleTimer = null;
|
|
105
110
|
if (!this.#workerData) {
|
|
106
111
|
const maxBytes = maxMemoryBytes(this.#limit);
|
|
@@ -173,6 +178,7 @@ export class ThreadPool {
|
|
|
173
178
|
|
|
174
179
|
#spawn(job) {
|
|
175
180
|
const worker = new Worker(WORKER, { workerData: this.#workerData, stdout: true, stderr: true });
|
|
181
|
+
/** @type {{worker: Worker, ready: boolean, job: any, tables: Set<string>}} */
|
|
176
182
|
const slot = { worker, ready: false, job: null, tables: new Set() };
|
|
177
183
|
this.#slots.push(slot);
|
|
178
184
|
this.#start(slot, job);
|
|
@@ -222,7 +228,7 @@ export class ThreadPool {
|
|
|
222
228
|
|
|
223
229
|
// Stops the threads; waiting and running jobs resolve to null. The next run() starts new ones.
|
|
224
230
|
async close() {
|
|
225
|
-
clearTimeout(this.#idleTimer);
|
|
231
|
+
clearTimeout(this.#idleTimer ?? undefined);
|
|
226
232
|
this.#idleTimer = null;
|
|
227
233
|
const slots = this.#slots.splice(0);
|
|
228
234
|
for (const j of this.#queue.splice(0)) j.resolve(null);
|
package/lib/wasm.js
CHANGED
|
@@ -9,8 +9,11 @@ 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
18
|
#tables = new Map(); // table name -> its bytes, or a function that reads them again (for a reload after a trap)
|
|
16
19
|
#binary = false; // the module reads binary tables (wuica_load_arch_bin)
|
|
@@ -68,6 +71,7 @@ export class Analyzer {
|
|
|
68
71
|
|
|
69
72
|
// bytes: the binary form of the table (data/arch/<name>.bin, see crates/wuica-core/src/table_bin.rs) or its JSON.
|
|
70
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] */
|
|
71
75
|
loadArch(name, bytes, reload = null) {
|
|
72
76
|
this.#live();
|
|
73
77
|
this.#loadTable(name, bytes);
|
|
@@ -190,16 +194,18 @@ export function codeModeError(text) {
|
|
|
190
194
|
return null;
|
|
191
195
|
}
|
|
192
196
|
|
|
193
|
-
//
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
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';
|
|
197
201
|
|
|
198
202
|
const OUT_CAP = 1 << 20;
|
|
199
203
|
const ERR_CAP = 1 << 16;
|
|
200
204
|
|
|
201
205
|
export class Assembler {
|
|
206
|
+
/** @type {any} */
|
|
202
207
|
#module;
|
|
208
|
+
/** @type {any} */
|
|
203
209
|
#x = null;
|
|
204
210
|
|
|
205
211
|
constructor(module) {
|
|
@@ -212,7 +218,7 @@ export class Assembler {
|
|
|
212
218
|
|
|
213
219
|
#live() {
|
|
214
220
|
if (this.#x) return;
|
|
215
|
-
const x = new WebAssembly.Instance(this.#module, {}).exports;
|
|
221
|
+
const x = /** @type {any} */ (new WebAssembly.Instance(this.#module, {}).exports);
|
|
216
222
|
x._initialize?.();
|
|
217
223
|
this.#x = x;
|
|
218
224
|
}
|
|
@@ -221,7 +227,7 @@ export class Assembler {
|
|
|
221
227
|
assemble(text, syntax) {
|
|
222
228
|
this.#live();
|
|
223
229
|
const x = this.#x;
|
|
224
|
-
const src = enc.encode(
|
|
230
|
+
const src = enc.encode(prepareSource(text) + '\0');
|
|
225
231
|
let textPtr = 0, outPtr = 0, errPtr = 0;
|
|
226
232
|
try {
|
|
227
233
|
textPtr = x.malloc(src.length); outPtr = x.malloc(OUT_CAP); errPtr = x.malloc(ERR_CAP);
|