wuica-cli 0.0.0-stage → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +436 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.json.br +0 -0
  6. package/dist/data/arch/BDW.json.br +0 -0
  7. package/dist/data/arch/CFL.json.br +0 -0
  8. package/dist/data/arch/CLX.json.br +0 -0
  9. package/dist/data/arch/HSW.json.br +0 -0
  10. package/dist/data/arch/ICL.json.br +0 -0
  11. package/dist/data/arch/ICX.json.br +0 -0
  12. package/dist/data/arch/IVB.json.br +0 -0
  13. package/dist/data/arch/KBL.json.br +0 -0
  14. package/dist/data/arch/RKL.json.br +0 -0
  15. package/dist/data/arch/SKL.json.br +0 -0
  16. package/dist/data/arch/SKX.json.br +0 -0
  17. package/dist/data/arch/SNB.json.br +0 -0
  18. package/dist/data/arch/TGL.json.br +0 -0
  19. package/dist/data/arch/ZEN3.json.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +81 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +372 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +430 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/files.js +18 -0
  30. package/lib/index.js +474 -0
  31. package/lib/insights.js +100 -0
  32. package/lib/mcp.js +366 -0
  33. package/lib/thread-worker.js +46 -0
  34. package/lib/threads.js +224 -0
  35. package/lib/wasm.js +221 -0
  36. package/lib/web/accum.js +202 -0
  37. package/lib/web/asm-regions.js +415 -0
  38. package/lib/web/assembler.js +188 -0
  39. package/lib/web/caveats.js +206 -0
  40. package/lib/web/loop-find.js +492 -0
  41. package/lib/whatif.js +136 -0
  42. package/licenses/LICENSE-LLVM.txt +279 -0
  43. package/licenses/LICENSE-XED.txt +178 -0
  44. package/package.json +58 -4
package/README.md CHANGED
@@ -1,3 +1,437 @@
1
- # Temporary Holding Version
1
+ # wuica
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Throughput prediction for x86-64 basic blocks, running locally in Node. **wuica** (WebAssembly uiCA) is an independent
4
+ Rust/WebAssembly port of [uiCA](https://github.com/andreas-abel/uiCA). Its reports are bit-identical to the Python uiCA on the
5
+ port's test corpus. The package contains:
6
+
7
+ - a **library**: `import { createWuica } from 'wuica-cli'`
8
+ - a **command-line tool**: `npx wuica-cli loop.s -arch SKL`
9
+ - a local **MCP server** (stdio) for AI agents: `npx wuica-cli mcp`
10
+
11
+ This is **not the official uiCA** (that is [uiCA.uops.info](https://uiCA.uops.info) and the
12
+ [uiCA repository](https://github.com/andreas-abel/uiCA)). The instruction data (latencies, throughputs, port usage) comes
13
+ from [uops.info](https://www.uops.info). Besides uiCA's Intel models (Sandy Bridge to Rocket Lake), wuica includes the
14
+ experimental models of the fork [jtl06/uiCA](https://github.com/jtl06/uiCA): **AMD Zen 3 (ZEN3), Alder Lake P-core
15
+ (ADL-P) and Ice Lake server (ICX)**. They are marked `prototype` and are less validated than the Intel models.
16
+
17
+ Everything runs offline. The two WebAssembly modules (the analyzer, and LLVM's x86 assembler for assembly input) and the
18
+ instruction tables are shipped brotli-compressed. A table is loaded the first time its microarchitecture is used.
19
+ Requirements: Node.js 20 or later. **No dependencies**: `npm install wuica-cli` (or `npx wuica-cli`) adds this one
20
+ package, 2.3 MB unpacked; the MCP server is part of it.
21
+
22
+ The commands are `wuica` and `wuica-mcp`. Install them with `npm install -g wuica-cli`, or run without installing
23
+ with `npx wuica-cli ...`. The examples below write `wuica`.
24
+
25
+ ## The CLI in five minutes
26
+
27
+ ```
28
+ clang -O3 -march=haswell -S dot.c -o dot.s # AT&T, as clang and gcc write it: detected, no flag needed
29
+ wuica dot.s # uiCA's report for SKL, of the loop wuica picked
30
+ wuica dot.s -arch SKL,ZEN3,ADL-P # one table for several CPUs ("all": every one)
31
+ wuica dot.s -per 8 # the loop does 8 elements per iteration: cycles per element too
32
+ wuica dot.s -loops # the loops in the file; -loop N or -loop .LBB0_12 picks one
33
+ wuica dot.s -whatif # unrolled, N accumulators, front end and fusion variants
34
+ objdump -d dot.o | wuica # objdump output: the loop's real alignment from its address
35
+ ```
36
+
37
+ - **Syntax.** Intel (noprefix) or AT&T is detected from the text (`%rdx`, `$8`, `(%rdi,%rcx,4)` are AT&T);
38
+ stderr says which (`analyzed: loop .LBB0_9 (lines 28-47, in dot), AT&T syntax (detected)`). `-att` or `-intel`
39
+ force one.
40
+ - **Per iteration.** `tp` is cycles per iteration of the loop as the compiler wrote it. Compilers unroll and vectorize
41
+ (×8, ×16, ×32 elements per iteration), so compare per element: `-per N` prints `Per element: … cycles` (JSON
42
+ `perElement`; under 0.1 with 3 significant digits, `0.0625`); without it, stderr shows the loop's step when it can,
43
+ in the register's units: `rcx += 8 per iteration (index; ×4 bytes in [rdi+rcx*4])` is 8 elements of 4 bytes,
44
+ `r13 += 64 per iteration (bytes; the base of [r13+0x20])` is 64 bytes (16 floats: `-per 16`), `(register step)` a
45
+ counter no address uses.
46
+ - **Which loop.** A whole function or file is analyzed at one loop: the deepest one (clang's
47
+ `# =>This Inner Loop Header` notes count), among equals the first in the code. That can be a remainder loop: clang
48
+ often emits it before the main loop, gcc after it. Stderr says what was picked and how many others there are;
49
+ `-loops` lists them (index, label, function, lines, instructions, depth, auto), `-loop N` (0-based) or
50
+ `-loop LABEL` picks one, `-func NAME` keeps one function's loops, `-loop whole` analyzes the whole text. A label
51
+ that names loops in several functions (`1:` … `jnz 1b`) is an error that lists them; `-func` or the index picks one.
52
+ - **Branches inside the loop.** uiCA runs the analyzed code straight through: in a loop with an if/else (or two back
53
+ edges, as clang's remainder loops often have), both sides of the branch are simulated, one after the other, while a
54
+ real iteration takes one. A `Not modelled: both paths: both sides of the branch at line N …` line (table note
55
+ `both paths`; JSON caveat `paths`) says so. To analyze one side, put `# wuica-begin` and `# wuica-end` around it.
56
+ - **One input per run**: a file, `-` or nothing for stdin, a hex argument, `-hex` or `-raw FILE` (bare machine code:
57
+ for an object file, `objdump -d file.o | wuica`).
58
+ - **Tables.** `-arch A,B,C` prints one row per CPU; `-` means unknown (uiCA names no single bottleneck; the notes
59
+ give the nearest limit), `5.00*` that the CPU could not decode some instructions (they are left out), and the notes
60
+ column the caveats (what the model does not simulate, such as store forwarding through an indexed address).
61
+ - **After the report** come what uiCA's text leaves out: the nearest limit when the bottleneck is unknown, the next
62
+ limit, and `Not modelled:` lines.
63
+ - **Exit status**: 0 ok, 1 bad request or usage, 2 assembler error, 3 the analysis failed; with several CPUs, the
64
+ largest of their codes, which is also the JSON's `code`. A reader that closes the pipe (`| head`) does not change it.
65
+ - **What if** (`-whatif`): a table per CPU, in cycles per original iteration, or per element with `-per N`. With
66
+ `-TPonly`, one `variant cycles` line per variant after the throughput (`acc2 16.00`; with `-per`, `acc2 16.00
67
+ 2.00`; with several CPUs, each line starts with the CPU). Estimates (`>=` in the table) are printed as plain numbers.
68
+ - **JSON** (`-json`): one CPU gives the analyze response (`tp`, `bottlenecks`, `limits`, `rows`, `criticalPath`,
69
+ `insights`, `loop`, `syntax`, and `perElement` / `whatIf` when asked); several give `{code, hex, loop, stderr,
70
+ results: [{arch, tp, bottlenecks, limits, decodeErrors, perElement?, caveats?}]}`. The shapes are the same for one
71
+ CPU and several: `whatIf` is keyed by CPU (`{SKL: {tp, variants: [{id, tp, …, perElement?}], perElement?}}`), and a
72
+ caveat is `{id, text, title, instructions}` (in `insights.caveats` with one CPU, `results[].caveats` with several).
73
+ Types: `CliAnalyzeJson`, `CliCompareJson`, `CliWhatIf` in index.d.ts. `--version -json` gives `{wuica, uiCA:
74
+ {repository, commit, branch}, node}`: the uiCA commit whose data and model the package has.
75
+ - **Syntax mistakes.** When the assembler fails, a `hint:` line names a line with the other syntax's operands (mixed
76
+ AT&T and Intel lines, a `.intel_syntax` directive over AT&T code, `mov rdx, $8` in Intel code) and the flag to try.
77
+ - No colours and no links, on a terminal or not.
78
+
79
+ ## What the numbers mean
80
+
81
+ `tp` is the predicted steady-state throughput in **core cycles per iteration** of the block (lower is faster). How the
82
+ block is simulated depends on how it ends:
83
+
84
+ - A block that ends with a branch is simulated as a loop body (`mode: "loop"`).
85
+ - Any other block is simulated as if it were unrolled, i.e. repeated back to back (`mode: "unroll"`).
86
+
87
+ The model assumes that all data is in the L1 cache, that no branches are mispredicted, and that nothing else is running
88
+ on the core. `bottlenecks` names what limits the throughput, such as Dependencies (a loop-carried chain), Ports, Issue,
89
+ Decoder or DSB. `limits` gives the throughput each component alone would allow. `text` is uiCA's complete report.
90
+
91
+ ## Library
92
+
93
+ ```js
94
+ import { createWuica } from 'wuica-cli';
95
+
96
+ const w = await createWuica();
97
+ const r = await w.analyze('SKL', { source: 'loop:\n add rax, [rsi]\n add rsi, 8\n dec rcx\n jnz loop\n' });
98
+ if (r.code === 0) {
99
+ console.log(r.tp, r.mode, r.bottlenecks); // cycles per iteration, "loop", [...]
100
+ console.log(r.text); // uiCA's report
101
+ console.log(r.hex); // the assembled bytes
102
+ } else {
103
+ console.error(r.error, r.stderr); // e.g. assembler diagnostics with line/column
104
+ }
105
+
106
+ await w.analyze('ZEN3', { hex: '4801d84801c349ffcf75f5', options: { noMacroFusion: true } });
107
+ await w.analyze({ arch: 'ADL-P', source: 'addq %rbx, %rax', syntax: 'att' }); // single-object form
108
+ await w.compare({ source: 'imul rax, rbx' }); // every microarchitecture
109
+ w.archs(); // [{id, name, year, prototype, table, xedChip}, ...]
110
+ await w.assemble('vaddps zmm0, zmm1, zmm2'); // {code: 0, hex, length, bytes, stderr}
111
+ w.summarize(r); // compact form (the MCP analyze result)
112
+ w.insights(r); // the diagnosis alone (REST's insights)
113
+ ```
114
+
115
+ Methods never throw for bad input: they resolve to a failure `{code, error, stderr}` (see the contract below).
116
+ `createWuica({ dataDir })` reads the tables from another directory (`uarch.json` and `arch/<NAME>.json`, plain or
117
+ `.br`). TypeScript declarations are included (`index.d.ts`).
118
+
119
+ `compare` analyzes the microarchitectures in parallel on worker threads: by default one thread per two
120
+ microarchitectures (a thread's start costs about one analysis), at most `os.availableParallelism()`.
121
+ `createWuica({ threads: N })` or the environment variable `WUICA_THREADS=N` uses up to N threads, one per
122
+ microarchitecture; 1 runs them one after another on the calling thread. The response is the same either way. Each thread loads only the
123
+ tables of the microarchitectures it analyzes and keeps them for the next `compare`; idle threads do not keep the process
124
+ alive and stop after 30 s (`w.close()` stops them at once). A thread's WebAssembly memory has a lower limit (a quarter
125
+ of the RAM shared by the threads, 256 MB to 1 GB each); an analysis that exceeds it is done again on the calling thread.
126
+
127
+ Inputs on which the original uiCA fails can make the WebAssembly module trap. In that case the call resolves to
128
+ `{code: 3, error, trapped: true}`. The module is then re-instantiated and its tables are reloaded, so the next call works.
129
+
130
+ ## Command line
131
+
132
+ ```
133
+ wuica loop.s # assembly file (syntax detected), uiCA's report for SKL
134
+ wuica loop.s -arch ICL -TPonly # only the throughput
135
+ cat loop.s | wuica -arch ZEN3 # stdin (or "-")
136
+ wuica -att loop_att.s # AT&T syntax, forced (-intel forces Intel)
137
+ wuica 4801d84801c349ffcf75f5 # a hex argument (as in the Rust CLI)
138
+ wuica -hex code.txt # hex from a file or stdin ("48 01 d8", "0x48,0x01" are fine)
139
+ wuica -raw code.bin # raw machine code
140
+ wuica loop.s -arch all # throughput table for every microarchitecture (in parallel)
141
+ wuica loop.s -arch SKL,ICL,ZEN3 # throughput table for these
142
+ wuica -list # the microarchitectures
143
+ wuica loop.s -json # the JSON result (the contract's analyze response)
144
+ wuica psum.s -loop whole # the whole text, not the loop found in it (-loop auto, the default, or -loop N)
145
+ wuica psum.s -loops # list the loops; -loop .LBB0_12 or -func psum to choose
146
+ wuica psum.s -whatif -per 8 # what-if variants; cycles per element (8 elements per iteration)
147
+ wuica --version
148
+ ```
149
+
150
+ The simulation options are uiCA's: `-alignmentOffset N`, `-initPolicy diff|same|stack`, `-simpleFrontEnd`,
151
+ `-noMicroFusion`, `-noMacroFusion`, `-minIterations N`, `-minCycles N`, and `-trace` (with `-json`). Every flag also
152
+ takes `--flag` and `--flag=value`, in any case (`--tponly`, `--arch=zen3`). With several
153
+ microarchitectures, `-threads N` analyzes them on at most N threads at a time (`-threads 1`: one after another).
154
+ Diagnostics go to stderr. The exit status is the result code: 0 ok, 1 bad request or usage, 2 assembler error, 3 analysis failed.
155
+ `wuica -h` lists everything.
156
+
157
+ ## MCP server
158
+
159
+ `wuica mcp` (or the `wuica-mcp` binary) is a Model Context Protocol server on stdio, written without an MCP library:
160
+ newline-delimited JSON-RPC 2.0 with the `initialize` handshake of the protocol revisions 2025-11-25, 2025-06-18,
161
+ 2025-03-26 and 2024-11-05 (the client's revision if it is one of these, else 2025-11-25; batches only under 2025-03-26),
162
+ `ping`, `tools/list` and `tools/call`. Arguments are checked against the tools' JSON Schemas; a mismatch is a tool error
163
+ (`isError`) that says what is wrong, an unknown tool a JSON-RPC error. The server ends with its stdin, and writes only
164
+ protocol messages to stdout. `wuica mcp --help` prints the usage. The tool table itself (names, descriptions, JSON
165
+ Schemas, handlers) is exported as `mcpTools(w)` from `wuica/mcp`, with `callTool` and `validate`; the remote server
166
+ (`server/`) serves the same table over HTTP. It has five tools:
167
+
168
+ | Tool | What it does |
169
+ |---|---|
170
+ | `analyze` | one block on one microarchitecture: `tp`, bottlenecks, limits, a compact per-instruction table (ports, uop sources, fusion notes) and uiCA's text report (`format`: `json`, `text`, `both`) |
171
+ | `what_if` | one block re-analyzed with one change each (the web page's "try" row): `unroll2`/`unroll4`/`unroll8` (per original iteration), `acc2`/`acc3`/`acc4`/`acc8` (N accumulators: unrolled ×N with the loop-carried register renamed in each copy; `renamed` lists the registers, `accumulators.best` is the best N, 1 = as it is), `simpleFrontEnd`, `noMacroFusion`, `noMicroFusion`, and `nochain` (an estimate without the loop-carried chain); per variant `tp`, `delta`, `speedup` |
172
+ | `compare_archs` | one block on several or all microarchitectures: `tp` and bottlenecks per microarchitecture |
173
+ | `list_archs` | ids, names, years, prototype flags |
174
+ | `assemble` | assembly → hex bytes, or diagnostics with line/column |
175
+
176
+ Add it to **Claude Code** from a local checkout (after `build.sh` and `npm install`) or an installed tarball:
177
+
178
+ ```
179
+ claude mcp add wuica -- node /absolute/path/to/packages/wuica/bin/wuica.js mcp
180
+ ```
181
+
182
+ Once the package is published on npm:
183
+
184
+ ```
185
+ claude mcp add wuica -- npx -y wuica-cli mcp
186
+ ```
187
+
188
+ Other MCP clients (Claude Desktop, Cursor, VS Code, ...) use the same command in their JSON configuration:
189
+
190
+ ```json
191
+ {
192
+ "mcpServers": {
193
+ "wuica": { "command": "npx", "args": ["-y", "wuica", "mcp"] }
194
+ }
195
+ }
196
+ ```
197
+
198
+ Example prompt: *"Use wuica to compare this loop on Skylake, Ice Lake and Zen 3 and explain the bottleneck."*
199
+
200
+ ## API contract
201
+
202
+ The library, the MCP tools and the REST API (https://api.wuica.jacen.li, server/) share these shapes. They follow
203
+ [Compiler Explorer's API](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/API.md): a list
204
+ endpoint like `/api/compilers`, a call keyed by id like `/api/compiler/<id>/compile`, results as JSON or plain
205
+ text, and errors with structured stderr.
206
+
207
+ | REST | Library | MCP tool |
208
+ |---|---|---|
209
+ | `GET /api/archs[?fields=id,name]` | `w.archs(fields?)` | `list_archs {fields?}` |
210
+ | `POST /api/analyze/<arch>` | `w.analyze(arch, request)` | `analyze {arch, ...request, format?}` |
211
+ | `POST /api/compare` | `w.compare(request)` | `compare_archs {...request}` |
212
+ | — | `whatIf((a, r) => w.analyze(a, r), arch, request, variants?, {assemble: (t) => w.assemble(t)})` | `what_if {arch, ...request, variants?}` |
213
+ | `POST /api/assemble` | `w.assemble(source, syntax)` | `assemble {source, syntax?}` |
214
+
215
+ ### Microarchitectures: `GET /api/archs`
216
+
217
+ ```json
218
+ [{"id": "SKL", "name": "Skylake", "year": 2015, "prototype": false, "table": "SKL", "xedChip": "SKYLAKE"}, ...]
219
+ ```
220
+
221
+ The list is in order of release. `prototype` is true for ZEN3, ADL-P and ICX. `fields` (comma-separated, or an
222
+ array in the library) selects fields; the default is all fields (`list_archs` defaults to `id,name,year,prototype`).
223
+ uiCA's ablation variants (ids containing `_`) are not listed, but `analyze` accepts them. Ids are matched exactly,
224
+ or failing that case-insensitively with `-` optional (`adlp` → `ADL-P`). The default arch is `SKL`.
225
+
226
+ ### Analysis: `POST /api/analyze/<arch>`
227
+
228
+ Request:
229
+
230
+ ```json
231
+ {
232
+ "source": "loop: add rax, rbx\n dec rcx\n jnz loop",
233
+ "hex": "4801d8...",
234
+ "syntax": "intel",
235
+ "options": {
236
+ "alignmentOffset": 0, "initPolicy": "diff", "simpleFrontEnd": false, "noMicroFusion": false,
237
+ "noMacroFusion": false, "minIterations": 10, "minCycles": 500, "includeTrace": false, "details": false
238
+ }
239
+ }
240
+ ```
241
+
242
+ - Give exactly one of `source` (assembly; the library also accepts `asm`) and `hex` (machine code; spaces, commas and
243
+ `0x` are allowed).
244
+ - `source` is read as the web page reads pasted assembly. `loop` (optional) says what of it is analyzed:
245
+ - `"auto"` (the default): a whole function (`gcc -S`, `clang -S`, `objdump -d` lines with addresses, with or
246
+ without the bytes, Intel or AT&T) is analyzed at its deepest loop (clang's `Inner Loop Header` notes count;
247
+ among equals the first in the code, which may be a remainder loop: clang often emits it first). A span that holds a `ret` or another function's label is not a loop (a tail
248
+ call jumping back). A compiler's function without a loop (it has a function label, directives or a
249
+ prologue/epilogue, and ends in `ret`) is analyzed at its body, without prologue, epilogue and `ret`; a bare snippet
250
+ such as `add rax, 1` / `ret` is analyzed as typed. A text that is one loop already, or has region markers, is
251
+ analyzed as it is.
252
+ - `"whole"`: the whole text, never a pick; a number: that loop (0-based: deepest first, then in code order); any
253
+ other string: the loop with that label (`".LBB0_12"`, `"0x10"`). `func` (optional) keeps one function's loops.
254
+ - `syntax` is `"auto"` (the default: detected from the text), `"intel"` or `"att"`; the response's `syntax` says
255
+ which was used.
256
+
257
+ objdump text is recognised by a header line (`0000… <f>:`), a byte column or `<sym+off>` branch targets; without
258
+ those, only when every line is address-prefixed, there are at least three, and the steps between the addresses fit
259
+ the instructions (so `a: add rax, 1` / `b: dec rcx` / `jnz a` stays assembly). In objdump text a branch target is
260
+ always an address (`jne 1b <psum+0x1b>`); GNU numeric labels (`1:` … `jnz 1b`) keep working in assembly. Code in
261
+ `.text.*` sections (gcc's `main` in `.text.startup`, `-ffunction-sections`) is analyzed as `.text`. CRLF and lone CR
262
+ line ends are line feeds (REST, MCP, the library, the CLI).
263
+
264
+ Conditional branches to a symbol the text does not define (a loop's exits, `jae .Lout`, `.L` or not) are taken as
265
+ not taken: the symbol is defined right after the analyzed code, so they assemble as short jumps; a note says so in
266
+ `stderr`. An undefined target of a `jmp` gives a warning (it is encoded as a 32-bit jump to an external symbol).
267
+ objdump lines with their bytes are assembled as those bytes. With addresses, the alignment offset is the analyzed
268
+ code's address modulo 64, unless `options.alignmentOffset` is given. When something other than the whole text was
269
+ analyzed, the response has `loop`: `{index, count, name, line, endLine, lines?, address?, alignmentOffset?}` (`name`:
270
+ `"loop .L3"`, `"loop 0x10"`, `"body"`; `lines`: the source line of each instruction).
271
+ Region markers (`# LLVM-MCA-BEGIN` … `# LLVM-MCA-END`, `# wuica-begin` … `# wuica-end`, IACA's byte markers) select
272
+ the first marked region. A `;` that starts a line is a comment. After a statement, LLVM reads `;` as a separator. If
273
+ what follows assembles, it is assembled, with a note in `stderr` naming it (`';' separates statements: 'call helper'
274
+ was assembled (use # for a comment)`), unless the `;` follows the statement without a space, as GNU as code chains
275
+ statements (`dec rcx; jnz 1b`). If it does not assemble, for any reason, it is a comment: nothing after a `;` makes a
276
+ valid line an error; a note says so when it starts with a mnemonic (`add the next element`), and nothing when it does
277
+ not (`sum += a[i]`). A line the assembler rejects inside the analyzed code is an error with its line number (objdump
278
+ lines outside the picked loop that the assembler rejects, such as padding, are left out).
279
+ - `syntax` is `auto` (the default), `intel` (noprefix) or `att`. The source may also switch syntax itself with
280
+ `.intel_syntax noprefix` / `.att_syntax`.
281
+ - Every field of `options` is optional; the defaults are shown. Unknown options and unknown request fields are an
282
+ error (code 1), not ignored. The library also accepts the options at the top level of the request
283
+ (`{hex, arch, minIterations}`); `options` takes precedence. The MCP tools accept only the nested form.
284
+ - The source must be 64-bit code: `.code16`, `.code16gcc` and `.code32` are an error (code 1), since the analyzer
285
+ only models 64-bit mode. `assemble` alone accepts them.
286
+ - `loop` exists in the library, REST (`/api/analyze`, `/api/compare`), the MCP tools `analyze`, `what_if` and
287
+ `compare_archs`, and the package's CLI (`wuica -loop auto|whole|N`). The native CLI (`crates/wuica-cli`) reads
288
+ machine code only (hex or `-raw`), so it has no `-loop`.
289
+
290
+ ### Option ranges per interface
291
+
292
+ All interfaces run the same analyzer, but they accept different ranges for the numeric options. A value outside the
293
+ range is refused (code 1, REST 400; the MCP tools' schema rejects it as invalid arguments), except in the web page,
294
+ which clamps it into its range.
295
+
296
+ | Interface | `alignmentOffset` | `minIterations` | `minCycles` | Other limits |
297
+ |---|---|---|---|---|
298
+ | library, `wuica` CLI, native CLI (`crates/wuica-cli`) | any integer (negative values and values above 63 are simulated as given) | any integer | any integer | none; very large values run out of memory (library: code 3) |
299
+ | MCP tools of `wuica mcp` (stdio) | 0–63 | 1–100000 | 1–1000000 | |
300
+ | REST API (`server/`) | any integer | at most 1000 | at most 20000 | `source` at most 64 KB, `hex` at most 65536 characters, at most 10,000 instructions |
301
+ | remote MCP (`server/`, `/mcp`) | 0–63 | 1–1000 | 1–20000 | as REST |
302
+ | web page | 0–63 | 1–10000 | 1–100000 | at most 1 MiB of machine code (assembled or as hex) |
303
+
304
+ Microarchitecture ids are accepted the same way everywhere: exactly, or case-insensitively with `-` optional (`adlp`,
305
+ `adl-p` → `ADL-P`). Hex may contain spaces, commas and `0x` / `\x` prefixes everywhere.
306
+
307
+ Response (JSON), on success:
308
+
309
+ ```json
310
+ {
311
+ "code": 0,
312
+ "arch": "SKL", "tp": 1.25, "mode": "loop", "decodeErrors": 0,
313
+ "bottlenecks": ["Dependencies"],
314
+ "limits": [{"name": "Issue", "tp": 0.75}, {"name": "Dependencies", "tp": 1.0}],
315
+ "columns": ["MITE", "MS", "DSB", "LSD", "Issued", "Exec.", "Port 0", "..."],
316
+ "rows": [{"kind": "instr", "label": "add rax, rbx", "opcode": "4801D8", "instrStr": "ADD (R64, R64)",
317
+ "url": "https://www.uops.info/html-instr/ADD_01_R64_R64.html", "notes": "", "values": [0, 0, 1.0, "..."]}],
318
+ "text": "Throughput (in cycles per iteration): 1.25\n...",
319
+ "trace": null,
320
+ "hex": "4801d8...",
321
+ "stderr": [],
322
+ "insights": {"utilization": {"Issue": 0.6, "Dependencies": 0.8, "Port 0": 0.25}, "binding": ["Dependencies"], "...": "..."}
323
+ }
324
+ ```
325
+
326
+ The fields from `arch` to `trace` are the analysis response of the WebAssembly module (`docs/WASM-API.md` in the wuica
327
+ repository: `rows[].values[i]` belongs to `columns[i]`, and `notes` is `M` macro-fused, `J` JCC erratum or `X`
328
+ unsupported). `hex` is present when `source` was given and holds the assembled bytes. `stderr` holds the assembler's
329
+ warnings, the notes on exits taken as not taken, and the warning "N position(s) could not be decoded". `insights` (REST only; the library's `analyze()` result
330
+ does not have it, `w.insights(r)` computes it) is the diagnosis described under the compact form below, with `portSet`
331
+ and `issueSlots` when `options.details` is true.
332
+
333
+ **Plain text** (CE's `Accept: text/plain`): the response is `text` (uiCA's report), or the `stderr` lines on failure.
334
+ In the library this is `r.text`; the MCP tool takes `format: "text"`.
335
+
336
+ **Compact form** (the MCP `analyze` JSON, `w.summarize(r)`): `{code, arch, name, year, prototype, tp, unit, mode,
337
+ bottlenecks, limits, decodeErrors, hex?, loop?, stderr, instructions, insights}`. Each entry of `instructions` is
338
+ `{instr, bytes, issued, executed, uopSource: {MITE|DSB|LSD|MS: n}, ports: {"Port 0": n, ...}, notes, uopsInfo}`
339
+ (zero values omitted, numbers rounded to 2 decimals). `insights` is a diagnosis derived from the analysis (as the web
340
+ page's "bound" view): `utilization` (each limit and port: cycles / tp), `binding` (the bottlenecks uiCA names: always
341
+ the same as `bottlenecks`, `[]` when it names none), `largest` (only when `binding` is `[]`: the largest limit, the
342
+ nearest bound, which alone does not reach tp; the web page shows "unknown · nearest Ports"), `next` (`{limit, tp,
343
+ maxSpeedup}`: the next limit, and the speedup at most if the binding one went away), `unexplained` (cycles no single
344
+ limit explains),
345
+ `chain` (the critical loop-carried chain: `{index, instr, operand, latency, carried}`) and `hot` (`{resource, ports?,
346
+ instructions: [{index, instr, share}]}`: the largest shares of the binding resource, or of the largest limit), and
347
+ `caveats` (only if any: `[{id, text, title, instructions}]`, known blind spots of the model that the block meets:
348
+ `rmw-index` a read-modify-write to an indexed address, whose store forwarding between iterations depends on the data;
349
+ `paths` a conditional branch inside the block (an if/else, a second back edge), both of whose sides are simulated one
350
+ after the other while a real iteration takes one (named by its source line); `exit` an exit before the loop's branch,
351
+ whose mispredict is not modelled; `split` loads at an offset that is not a
352
+ multiple of their width, which may cross a cache line: on the CPUs whose model charges line crossings (ZEN3, ADL-P,
353
+ ICX: `splitLoadCycles` in uarch.json) only the loads whose address the model cannot follow (an address register written
354
+ other than by adding an immediate); the web page shows them in one line under the throughput). With `options.details` (MCP:
355
+ `details: true`), each instruction also has `allowedPorts` (`1*p0156+1*p23`), `uops`, `fusedUops`, `latencies`
356
+ (`"RAX->RAX:1"`) and `frontEnd` (`length`, `offset`, `crosses`, `lcp`, `microcoded`, fusion), and `insights` has `portSet`
357
+ (the ports behind the Ports limit, `cycles` = uops / ports, and the instructions that load them) and `issueSlots` (per
358
+ iteration: issued, and lost to the front end, a full ROB or RS, or other).
359
+
360
+ ### Failures
361
+
362
+ Every call can fail like a compiler run in Compiler Explorer, with a non-zero `code` and stderr lines:
363
+
364
+ ```json
365
+ {
366
+ "code": 2,
367
+ "error": "assembly failed: line 2: invalid instruction mnemonic 'frobnicate'",
368
+ "stderr": [
369
+ {"text": "<input>:2:1: error: invalid instruction mnemonic 'frobnicate'",
370
+ "tag": {"line": 2, "column": 1, "severity": "error", "text": "invalid instruction mnemonic 'frobnicate'"}},
371
+ {"text": "frobnicate rax"},
372
+ {"text": "^~~~~~~~~~"}
373
+ ]
374
+ }
375
+ ```
376
+
377
+ | code | meaning | REST status |
378
+ |---|---|---|
379
+ | 0 | success | 200 |
380
+ | 1 | bad request: neither or both of source/hex, bad hex, unknown arch, unknown option, bad option value or syntax | 400 (unknown arch: 404) |
381
+ | 2 | assembler error (stderr as `llvm-mc` prints it; positioned lines carry `tag`) | 200, like a failed compile in CE |
382
+ | 3 | the analysis failed for this input (as the Python uiCA would); `trapped: true` if the module trapped | 200 |
383
+
384
+ ### Compare: `POST /api/compare`
385
+
386
+ The request is the same as for analyze, plus an optional `archs` (ids; missing or empty: all listed ones; a repeated id counts once). The response:
387
+
388
+ ```json
389
+ {
390
+ "code": 0, "hex": "...", "stderr": [],
391
+ "results": [
392
+ {"arch": "SKL", "name": "Skylake", "year": 2015, "prototype": false, "code": 0, "tp": 2.0, "mode": "loop",
393
+ "bottlenecks": ["Dependencies"], "decodeErrors": 0},
394
+ {"arch": "K8", "name": "K8", "year": null, "prototype": false, "code": 1, "error": "unknown microarchitecture: K8 ..."}
395
+ ]
396
+ }
397
+ ```
398
+
399
+ The top-level `code` is non-zero only if the request or the assembly fails. A failure on one microarchitecture is
400
+ reported in its row.
401
+
402
+ ### Assemble: `POST /api/assemble`
403
+
404
+ Request: `{"source": "...", "syntax": "intel"}`. The whole text is assembled as it is (no loop finding, no region
405
+ markers; `;` comments as above). Response: `{"code": 0, "hex": "4801d8", "length": 3, "stderr": []}`;
406
+ the library also returns `bytes` (a `Uint8Array`). On failure: `{code: 2, error, stderr}` as above. The assembler is
407
+ LLVM 22.1.2's (the same bytes as `llvm-mc`). Only `.text` is returned. `.include`/`.incbin` always fail. GNU as's
408
+ `{load}`/`{store}` hints, which LLVM rejects, are removed at the start of a line.
409
+
410
+ ## Building from the repository
411
+
412
+ ```
413
+ packages/wuica/build.sh # copies and compresses the wasm modules and tables into dist/, copies the licenses
414
+ cd packages/wuica && npm install && npm test
415
+ npm pack # wuica-<version>.tgz
416
+ ```
417
+
418
+ `build.sh` uses `target/wasm32-unknown-unknown/release/wuica_wasm.wasm` (it runs `./build-wasm.sh` if the file is
419
+ missing), `assembler/dist/wuica_asm.wasm` and `data/`. `dist/manifest.json` records the size and SHA-256 of each
420
+ uncompressed file.
421
+
422
+ ## Licenses
423
+
424
+ - wuica is a derivative work of uiCA and, like uiCA, is licensed under the **GNU Affero General Public License v3.0
425
+ only** (`LICENSE`).
426
+ - The analyzer contains a subset of [Intel XED](https://github.com/intelxed/xed) (Apache License 2.0,
427
+ `licenses/LICENSE-XED.txt`).
428
+ - The assembler module is a modified build of [LLVM](https://llvm.org) 22.1.2 (Apache License 2.0 with LLVM
429
+ Exceptions, `licenses/LICENSE-LLVM.txt`). The changes are in `assembler/llvm-22.1.2-wasi.patch` in the wuica
430
+ repository. It also contains wasi-libc and libc++ from wasi-sdk (Apache-2.0 WITH LLVM-exception, MIT and other
431
+ permissive licenses).
432
+ - The instruction data comes from [uops.info](https://www.uops.info) by Andreas Abel and Jan Reineke.
433
+ - The MCP server uses the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) (MIT) and
434
+ [zod](https://zod.dev) (MIT), installed as npm dependencies.
435
+
436
+ If you use uiCA's models in research, cite the uiCA paper: Andreas Abel and Jan Reineke, *uiCA: Accurate Throughput
437
+ Prediction of Basic Blocks on Recent Intel Microarchitectures*, ICS 2022.
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ // The wuica MCP server on stdio (same as `wuica mcp`). --help, --version: print and exit.
3
+ const args = process.argv.slice(2);
4
+ if (args.some((a) => /^(?:-h|-help|--help)$/i.test(a))) {
5
+ const { MCP_USAGE } = await import('../lib/cli.js');
6
+ process.stdout.write(MCP_USAGE);
7
+ } else if (args.some((a) => /^(?:-v|-V|-version|--version)$/i.test(a))) {
8
+ const { VERSION } = await import('../lib/cli.js');
9
+ process.stdout.write(`wuica-mcp ${VERSION}\n`);
10
+ } else if (args.length) {
11
+ process.stderr.write(`wuica-mcp: unknown argument ${args[0]} (--help for usage)\n`);
12
+ process.exitCode = 1;
13
+ } else {
14
+ const { runServer } = await import('../lib/mcp.js');
15
+ await runServer();
16
+ }
package/bin/wuica.js ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ // wuica [options] [FILE | - | HEX] or wuica mcp [--help | --version]
3
+ const args = process.argv.slice(2);
4
+ if (args[0] === 'mcp') {
5
+ const rest = args.slice(1);
6
+ if (rest.some((a) => /^(?:-h|-help|--help)$/i.test(a))) {
7
+ const { MCP_USAGE } = await import('../lib/cli.js');
8
+ process.stdout.write(MCP_USAGE);
9
+ } else if (rest.some((a) => /^(?:-v|-V|-version|--version)$/i.test(a))) {
10
+ const { VERSION } = await import('../lib/cli.js');
11
+ process.stdout.write(`wuica-mcp ${VERSION}\n`);
12
+ } else if (rest.length) {
13
+ process.stderr.write(`wuica mcp: unknown argument ${rest[0]} (--help for usage)\n`);
14
+ process.exitCode = 1;
15
+ } else {
16
+ const { runServer } = await import('../lib/mcp.js');
17
+ await runServer();
18
+ }
19
+ } else {
20
+ // a reader that closes the pipe early (wuica ... | head): the rest of the output is dropped quietly, and the exit
21
+ // status stays the result's code
22
+ for (const s of [process.stdout, process.stderr]) s.on('error', (e) => { if (e?.code !== 'EPIPE') throw e; });
23
+ const { main } = await import('../lib/cli.js');
24
+ process.exitCode = await main(args);
25
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,81 @@
1
+ {
2
+ "uiCA": {
3
+ "repository": "https://github.com/jtl06/uiCA",
4
+ "commit": "640e40e",
5
+ "branch": "improve-r9"
6
+ },
7
+ "files": {
8
+ "wuica_wasm.wasm": {
9
+ "size": 4307652,
10
+ "sha256": "6af065d98b90c2d945903fafccd0b6b749bdfe7dbc2d364adc98f50dfa310773"
11
+ },
12
+ "wuica_asm.wasm": {
13
+ "size": 3802001,
14
+ "sha256": "ee66811d0671cdea73176a3670f82816dcbb3cbb1fed13cd7dc2acbb69cb627d"
15
+ },
16
+ "data/uarch.json": {
17
+ "size": 51318,
18
+ "sha256": "f543714ba2927986671f1de045a6162296ce860c5d34a086cc4c72d6c828e7a1"
19
+ },
20
+ "data/arch/ADL-P.json": {
21
+ "size": 1771348,
22
+ "sha256": "1632dd7f57d26efa6e465c25c72e38523302c906f8db403af6ba1c432b1e1ccb"
23
+ },
24
+ "data/arch/BDW.json": {
25
+ "size": 526864,
26
+ "sha256": "48e3e00ba260d97abcdae17a330c1e426b09b8e55b35c6d65932cc226237be0e"
27
+ },
28
+ "data/arch/CFL.json": {
29
+ "size": 535543,
30
+ "sha256": "26806383a9a25e1fdd327ad3140c32f2b0a2b919c23d72cbd017e268177bfb7a"
31
+ },
32
+ "data/arch/CLX.json": {
33
+ "size": 1397578,
34
+ "sha256": "368c51d6fb60c91480346dd592239f09b5dce8e523034e27da439f19f97673d7"
35
+ },
36
+ "data/arch/HSW.json": {
37
+ "size": 537696,
38
+ "sha256": "52ca060485b45c73e7c4229bb77f3637cacb5544349789cf0913fd329d6f18c9"
39
+ },
40
+ "data/arch/ICL.json": {
41
+ "size": 1465390,
42
+ "sha256": "3315a5d3463e3b2453943e9984d28c8135b8b20168c283a4d4d4c610a99e94de"
43
+ },
44
+ "data/arch/ICX.json": {
45
+ "size": 1495406,
46
+ "sha256": "dd45538e22584305d5186d78673b3d4f8bc83fd2d0c0e600ec98540a6d0f2eff"
47
+ },
48
+ "data/arch/IVB.json": {
49
+ "size": 464357,
50
+ "sha256": "53c297d60bba360223c44c1403c820555a2c01c2dc680f229c44036f8c89bda8"
51
+ },
52
+ "data/arch/KBL.json": {
53
+ "size": 541457,
54
+ "sha256": "a5381d040f4c38e2c67a740d28e522b6918650044bb4cbd3e92e45c749a2a607"
55
+ },
56
+ "data/arch/RKL.json": {
57
+ "size": 1487905,
58
+ "sha256": "8b2fee3a39a5632e845add182f1f1f0a5ab6158b6c2141952accb37b85ecc2a6"
59
+ },
60
+ "data/arch/SKL.json": {
61
+ "size": 532918,
62
+ "sha256": "c4c216edb3af2bf19847a9398dbc3c2cc46e5ad1fe609b2dd2db07203d2d191f"
63
+ },
64
+ "data/arch/SKX.json": {
65
+ "size": 1379117,
66
+ "sha256": "5dea6ecf323367fe217fafe624c92a5e6085ed3112fb3a173ab081353fd11480"
67
+ },
68
+ "data/arch/SNB.json": {
69
+ "size": 460620,
70
+ "sha256": "3ba130e0858faa73bd16677e740b9fda75329df87eae339326a74a4a27e16e69"
71
+ },
72
+ "data/arch/TGL.json": {
73
+ "size": 1461441,
74
+ "sha256": "6f799ff308e1f9e62c0b5118921dcca3253644b7a028e50d0737cc4d731f2780"
75
+ },
76
+ "data/arch/ZEN3.json": {
77
+ "size": 527963,
78
+ "sha256": "72097d0e154b17ef71c12547946c2750f388cdae479b9af99ed5633959c9059a"
79
+ }
80
+ }
81
+ }
Binary file
Binary file