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.
- package/LICENSE +661 -0
- package/README.md +436 -2
- package/bin/wuica-mcp.js +16 -0
- package/bin/wuica.js +25 -0
- 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/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +81 -0
- package/dist/wuica_asm.wasm.br +0 -0
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +372 -0
- package/lib/archs.js +44 -0
- package/lib/cli.js +430 -0
- package/lib/core.js +36 -0
- package/lib/details.js +60 -0
- package/lib/files.js +18 -0
- package/lib/index.js +474 -0
- package/lib/insights.js +100 -0
- package/lib/mcp.js +366 -0
- package/lib/thread-worker.js +46 -0
- package/lib/threads.js +224 -0
- package/lib/wasm.js +221 -0
- package/lib/web/accum.js +202 -0
- package/lib/web/asm-regions.js +415 -0
- package/lib/web/assembler.js +188 -0
- package/lib/web/caveats.js +206 -0
- package/lib/web/loop-find.js +492 -0
- package/lib/whatif.js +136 -0
- package/licenses/LICENSE-LLVM.txt +279 -0
- package/licenses/LICENSE-XED.txt +178 -0
- package/package.json +58 -4
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// Find the loop in pasted assembly: a whole function (gcc -S, clang -S, objdump -d with or without the byte column, a
|
|
2
|
+
// Compiler Explorer import) is analyzed at its innermost loop, or at its body if it has none. No DOM and no assembling
|
|
3
|
+
// here (asm-regions.js assembles the plan; tests-js/web_loop_find.mjs runs this under Node; the npm package ships a
|
|
4
|
+
// copy, packages/wuica/lib/web).
|
|
5
|
+
//
|
|
6
|
+
// preparePaste(text, {loop}) reads the text once and returns what the assembly of an analysis needs:
|
|
7
|
+
// - objdump lines (" 40:\tcrc32 rax, ...", " 1c: jne 10 <psum+0x10>", with or without the bytes) become plain
|
|
8
|
+
// statements, line for line (diagnostics keep their lines): addresses that are branch targets become labels
|
|
9
|
+
// .Lwuica_a<hex>, a branch to an address outside the text a branch to a symbol. A line with its bytes is assembled
|
|
10
|
+
// as those bytes (the exact encoding); a line without them that the assembler rejects outside the analyzed code
|
|
11
|
+
// (padding: "cs nop ...") is left out. objdump text is told apart from assembly by a header line, a byte column or
|
|
12
|
+
// a <sym+off> branch target; without those, by three or more lines that are all address-prefixed, with
|
|
13
|
+
// increasing addresses whose steps fit their instructions and no branch to a GNU numeric label ("jnz 1b"). In
|
|
14
|
+
// objdump text, a branch target is always an address ("jne 1b <psum+0x1b>" goes to 0x1b).
|
|
15
|
+
// - line ends: CRLF and a lone CR are line feeds (normalizeText).
|
|
16
|
+
// - a ';' that starts a line is a comment (as '#'); one after a statement stays a separator unless the assembler
|
|
17
|
+
// rejects what follows it (asm-regions.js: commentFixes, separatorNotes).
|
|
18
|
+
// - the loops: backward branches to a label (or to an address); innermost first, in the order of the code. A span
|
|
19
|
+
// that holds a ret or a function's label is not a loop (a tail call to an earlier function). The pick is the first
|
|
20
|
+
// one, unless the text is that loop already; with no loop, a compiler's function (a function label, directives, or
|
|
21
|
+
// a prologue/epilogue) that ends in ret is analyzed without its prologue, epilogue and ret (its body); a bare snippet
|
|
22
|
+
// is analyzed as typed. Region markers (LLVM-MCA-BEGIN, wuica-begin, IACA) win: no pick. loop "whole": no pick.
|
|
23
|
+
// - conditional branches to a symbol the text does not define (the loop's exits: jae .Lout) are "not taken": the
|
|
24
|
+
// symbol is defined right after the analyzed code (stubs), so they assemble, short, as a compiler would emit them.
|
|
25
|
+
// An undefined target of a jmp is a warning (it is encoded as a 32-bit jump to an external symbol).
|
|
26
|
+
// - alignment: the analyzed code's address modulo 64, when the text has addresses.
|
|
27
|
+
|
|
28
|
+
const MARKER = /^\s*(?:#|\/\/|;)\s*(?:LLVM-MCA-BEGIN|wuica-begin)(?![\w-])/im;
|
|
29
|
+
const IACA = /^\s*mov[l]?\s+(?:ebx\s*,\s*111|\$111\s*,\s*%ebx)\s*$/im;
|
|
30
|
+
const LABELS = /^(?:\s*(?:[\w.$@]+|"[^"]*")\s*:)*\s*/;
|
|
31
|
+
const LABEL_ONE = /\s*([\w.$@]+|"[^"]*")\s*:/y;
|
|
32
|
+
const PREFIX = /^(?:lock|rep|repe|repz|repne|repnz|bnd|notrack|data16|data32|addr32|cs|ds|es|ss|fs|gs|rex(?:\.\w+)?|\{[\w ]+\})$/i;
|
|
33
|
+
export const JCC = /^(?:j(?:a|ae|b|be|c|e|g|ge|l|le|na|nae|nb|nbe|nc|ne|ng|nge|nl|nle|no|np|ns|nz|o|p|pe|po|s|z|rcxz|ecxz)|loop(?:e|ne|z|nz)?|xbegin)$/i;
|
|
34
|
+
export const JMP = /^jmp[lqw]?$/i;
|
|
35
|
+
const CALL = /^call[lqw]?$/i;
|
|
36
|
+
const RET = /^ret[lqw]?$/i;
|
|
37
|
+
const SYMBOL = /^[A-Za-z_.$@][\w.$@]*$/;
|
|
38
|
+
const GPR = /^(?:[re]?(?:ax|bx|cx|dx|si|di|sp|bp|ip)|[abcd][lh]|(?:si|di|sp|bp)l|r(?:[89]|1[0-5])[dwb]?)$/i;
|
|
39
|
+
|
|
40
|
+
export const OUTSIDE_PREFIX = '.Lwuica_x'; // an objdump branch to an address that is not in the text
|
|
41
|
+
const ADDR_LABEL = (a) => `.Lwuica_a${a.toString(16)}`;
|
|
42
|
+
|
|
43
|
+
// Splits a line (block comments already removed) into its statements outside comments: [{at, text}] (at: the column
|
|
44
|
+
// of the statement's first character, 0-based). '#' and '//' start a comment, ';' separates statements; quotes kept.
|
|
45
|
+
export function statements(line) {
|
|
46
|
+
const out = [];
|
|
47
|
+
let start = 0, q = false;
|
|
48
|
+
for (let i = 0; i <= line.length; i++) {
|
|
49
|
+
const c = line[i];
|
|
50
|
+
if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
|
|
51
|
+
if (c === '"') { q = true; continue; }
|
|
52
|
+
const end = i === line.length || c === '#' || c === ';' || (c === '/' && line[i + 1] === '/');
|
|
53
|
+
if (!end) continue;
|
|
54
|
+
const s = line.slice(start, i);
|
|
55
|
+
const lead = s.length - s.trimStart().length;
|
|
56
|
+
if (s.trim()) out.push({ at: start + lead, text: s.trim() });
|
|
57
|
+
if (c !== ';') break;
|
|
58
|
+
start = i + 1;
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The syntax of assembly text: 'att' or 'intel' (null: no sign of either). A directive (.att_syntax, .intel_syntax
|
|
64
|
+
// [noprefix]) before the first instruction decides; else the signs: AT&T's %registers, $immediates and (%base,...)
|
|
65
|
+
// memory operands against Intel's "ptr [" and [register...] operands. Comments are left out.
|
|
66
|
+
export function detectSyntax(text) {
|
|
67
|
+
const lines = normalizeText(text).split('\n');
|
|
68
|
+
let att = 0, intel = 0;
|
|
69
|
+
for (const l of lines) {
|
|
70
|
+
const code = l.replace(/(?:#|\/\/).*$/, '');
|
|
71
|
+
const d = /^\s*\.(att|intel)_syntax\b/i.exec(code);
|
|
72
|
+
if (d && att + intel === 0) return d[1].toLowerCase();
|
|
73
|
+
const n = syntaxSigns(code);
|
|
74
|
+
att += n.att;
|
|
75
|
+
intel += n.intel;
|
|
76
|
+
}
|
|
77
|
+
return att > intel ? 'att' : intel > att ? 'intel' : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The signs of each syntax in one line of code (comments left out): {att, intel} counts.
|
|
81
|
+
export function syntaxSigns(code) {
|
|
82
|
+
let att = (code.match(/%(?:[re]?(?:[abcd]x|[sd]i|[sb]p|ip)|[abcd][lh]|(?:[sd]i|[sb]p)l|r(?:[89]|1[0-5])[dwb]?|[xyz]mm\d+|k[0-7]|[cdefgs]s)\b/gi) ?? []).length;
|
|
83
|
+
att += (code.match(/(?:^|[\s,])\$-?(?:0x[0-9a-f]+|\d+)\b/gi) ?? []).length;
|
|
84
|
+
let intel = (code.match(/\bptr\s*\[|\[\s*(?:[re]?(?:[abcd]x|[sd]i|[sb]p|ip)|r(?:[89]|1[0-5]))\b/gi) ?? []).length;
|
|
85
|
+
if (!/%/.test(code)) intel += (code.match(/^\s*(?:\w+:\s*)*[a-z]\w*\s+(?:[re]?(?:[abcd]x|[sd]i|[sb]p)|r(?:[89]|1[0-5])[dwb]?|[xyz]mm\d+)\s*,/gi) ?? []).length;
|
|
86
|
+
return { att, intel };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// CRLF and a lone CR as LF (lines stay).
|
|
90
|
+
export const normalizeText = (text) => String(text ?? '').replace(/\r\n?/g, '\n');
|
|
91
|
+
|
|
92
|
+
// Block comments blanked (columns and lines stay).
|
|
93
|
+
function blankBlockComments(text) {
|
|
94
|
+
return text.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' '));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---- ';' comments ----------------------------------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
// A ';' at the start of a line (after white space) is a comment: it becomes '#' (same column).
|
|
100
|
+
export function leadingSemicolons(text) {
|
|
101
|
+
return String(text).replace(/^([ \t]*);/gm, '$1#');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---- objdump -------------------------------------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
const OD_ADDR = /^(\s*)([0-9a-fA-F]+):(\s+)(\S.*)$/;
|
|
107
|
+
const OD_HEADER = /^\s*[0-9a-fA-F]+\s+<[^>]*>:\s*$/;
|
|
108
|
+
const OD_NOISE = /^\s*(?:Disassembly of section\b.*|\S.*:\s+file format\s.*|[0-9a-fA-F]+:\s+R_X86_64_\S+.*|\.\.\.)\s*$/;
|
|
109
|
+
const OD_BRANCH = /^((?:\S+\s+)*?)(j[a-z]{1,4}|jmp[lqw]?|call[lqw]?|loop[a-z]{0,2}|xbegin)(\s+)(?:0x)?([0-9a-fA-F]+)(?:\s*<[^>]*>)?\s*(?:#.*)?$/i;
|
|
110
|
+
|
|
111
|
+
// The byte column at the start of `rest` (objdump: two hex digits separated by single spaces, ended by a tab or two
|
|
112
|
+
// spaces, or by the end of the line on a continuation line): {bytes, rest}.
|
|
113
|
+
function byteColumn(rest) {
|
|
114
|
+
const m = /^((?:[0-9a-fA-F]{2} )*[0-9a-fA-F]{2}) ?(?:\t| |\s*$)/.exec(rest);
|
|
115
|
+
if (!m) return { bytes: null, rest };
|
|
116
|
+
return { bytes: m[1].split(' ').map((b) => parseInt(b, 16)), rest: rest.slice(m[0].length).trim() };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// One-byte instructions that have operands (an objdump step of 1 for an instruction with operands must be one of these).
|
|
120
|
+
const ONE_BYTE = /^(?:push|pop|xchg|in|out|ins\w*|outs\w*|stos\w*|lods\w*|movs\w*|scas\w*|cmps\w*|bswap|int)$/i;
|
|
121
|
+
|
|
122
|
+
// {text, objdump: true, addresses: Map line -> address, bytes: Map line -> the line as .byte} or {objdump: false}.
|
|
123
|
+
export function fromObjdump(text) {
|
|
124
|
+
const lines = normalizeText(text).split('\n');
|
|
125
|
+
let header = false, symbolic = false, column = false, increasing = true, other = 0, plausible = true;
|
|
126
|
+
const rows = [];
|
|
127
|
+
for (const l of lines) {
|
|
128
|
+
if (OD_HEADER.test(l)) { header = true; continue; }
|
|
129
|
+
if (OD_NOISE.test(l) || /^\s*(?:$|#|\/\/|;)/.test(l)) continue;
|
|
130
|
+
const m = OD_ADDR.exec(l);
|
|
131
|
+
if (!m) { other++; continue; }
|
|
132
|
+
const a = parseInt(m[2], 16);
|
|
133
|
+
if (/<[^>]*>/.test(m[4])) symbolic = true;
|
|
134
|
+
const bc = byteColumn(m[4]);
|
|
135
|
+
if (bc.bytes && /\t| /.test(m[4])) column = true;
|
|
136
|
+
if (rows.length && a <= rows.at(-1).a) increasing = false;
|
|
137
|
+
rows.push({ a, rest: bc.rest });
|
|
138
|
+
}
|
|
139
|
+
if (rows.length < 2 || !increasing) return { objdump: false };
|
|
140
|
+
if (!(header || column || symbolic)) {
|
|
141
|
+
// weak evidence ("40: crc32 ..."): every line address-prefixed, at least three, the steps fit the instructions
|
|
142
|
+
// (an instruction with operands takes at least 2 bytes, at most 15), no branch to a GNU numeric label (1b, 1f)
|
|
143
|
+
if (other > 0 || rows.length < 3) return { objdump: false };
|
|
144
|
+
for (let k = 0; k + 1 < rows.length; k++) {
|
|
145
|
+
const step = rows[k + 1].a - rows[k].a;
|
|
146
|
+
const [mn, ops] = rows[k].rest.trim().split(/\s+(.*)/);
|
|
147
|
+
if (step > 15 || (step < 2 && ops && !ONE_BYTE.test(mn ?? ''))) plausible = false;
|
|
148
|
+
}
|
|
149
|
+
if (!plausible) return { objdump: false };
|
|
150
|
+
if (rows.some((r) => /^\s*(?:\S+\s+)*?(?:j[a-z]{1,4}|jmp\w*|call\w*|loop[a-z]*)\s+\d+[bf]\s*$/i.test(r.rest))) return { objdump: false };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const parsed = lines.map((l) => {
|
|
154
|
+
// a function's header ("0000000000000020 <fir8>:") becomes its label (the loops' function), if it is a plain name
|
|
155
|
+
const fh = /^\s*[0-9a-fA-F]+\s+<([A-Za-z_][\w.$]*)>:\s*$/.exec(l);
|
|
156
|
+
if (fh) return { kind: 'keep', text: `${fh[1]}:` };
|
|
157
|
+
if (OD_HEADER.test(l) || OD_NOISE.test(l)) return { kind: 'blank' };
|
|
158
|
+
const m = OD_ADDR.exec(l);
|
|
159
|
+
// other lines of a listing (objdump -S: the source) are not code
|
|
160
|
+
if (!m) return /^\s*(?:$|#|\/\/|;)/.test(l) ? { kind: 'keep', text: l } : { kind: 'blank' };
|
|
161
|
+
const { bytes, rest } = byteColumn(m[4]);
|
|
162
|
+
if (!rest) return { kind: 'more', bytes: bytes ?? [] }; // a continuation line: more bytes of the instruction above
|
|
163
|
+
return { kind: 'instr', indent: m[1] || ' ', address: parseInt(m[2], 16), bytes, text: rest.replace(/\s+#.*$/, '').replace(/\s+/g, ' ').trim() };
|
|
164
|
+
});
|
|
165
|
+
for (let k = parsed.length - 1; k > 0; k--) { // continuation bytes belong to the instruction above
|
|
166
|
+
if (parsed[k].kind !== 'more') continue;
|
|
167
|
+
let j = k - 1;
|
|
168
|
+
while (j >= 0 && parsed[j].kind === 'more') j--;
|
|
169
|
+
if (j >= 0 && parsed[j].kind === 'instr' && parsed[j].bytes) parsed[j].bytes = [...parsed[j].bytes, ...parsed.slice(j + 1, k + 1).flatMap((p) => p.bytes)];
|
|
170
|
+
}
|
|
171
|
+
const at = new Set(parsed.filter((p) => p.kind === 'instr').map((p) => p.address));
|
|
172
|
+
const targets = new Set();
|
|
173
|
+
for (const p of parsed) {
|
|
174
|
+
if (p.kind !== 'instr') continue;
|
|
175
|
+
const b = OD_BRANCH.exec(p.text);
|
|
176
|
+
if (!b) continue;
|
|
177
|
+
const mn = b[2].toLowerCase();
|
|
178
|
+
if (!JCC.test(mn) && !JMP.test(mn) && !CALL.test(mn)) continue;
|
|
179
|
+
const t = parseInt(b[4], 16);
|
|
180
|
+
let name;
|
|
181
|
+
if (at.has(t)) { name = ADDR_LABEL(t); targets.add(t); } else if (CALL.test(mn) || JMP.test(mn)) name = `wuica_ext_${t.toString(16)}`;
|
|
182
|
+
else name = `${OUTSIDE_PREFIX}${t.toString(16)}`;
|
|
183
|
+
p.text = `${b[1]}${b[2]}${b[3]}${name}`;
|
|
184
|
+
}
|
|
185
|
+
const addresses = new Map(), byteMap = new Map();
|
|
186
|
+
const out = parsed.map((p, k) => {
|
|
187
|
+
if (p.kind === 'blank' || p.kind === 'more') return '';
|
|
188
|
+
if (p.kind === 'keep') return p.text;
|
|
189
|
+
addresses.set(k + 1, p.address);
|
|
190
|
+
const label = targets.has(p.address) ? `${ADDR_LABEL(p.address)}: ` : '';
|
|
191
|
+
if (p.bytes?.length) byteMap.set(k + 1, `${p.indent}${label}.byte ${p.bytes.map((b) => '0x' + b.toString(16).padStart(2, '0')).join(', ')}`);
|
|
192
|
+
return `${p.indent}${label}${p.text}`;
|
|
193
|
+
});
|
|
194
|
+
return { objdump: true, text: out.join('\n'), addresses, bytes: byteMap };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---- the statements of a text ----------------------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
function splitInstr(body) {
|
|
200
|
+
const words = body.replace(/\s+/g, ' ').trim().split(' ');
|
|
201
|
+
let i = 0;
|
|
202
|
+
while (i < words.length - 1 && PREFIX.test(words[i])) i++;
|
|
203
|
+
return { mnemonic: (words[i] ?? '').toLowerCase(), operands: words.slice(i + 1).join(' ').trim() };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const sectionName = (args) => (/^\s*("?)([^",\s]+)\1/.exec(args)?.[2] ?? '');
|
|
207
|
+
// .text and the code sections of -ffunction-sections and gcc's main (.text.startup, .text.unlikely, .text.f)
|
|
208
|
+
export const isText = (args) => { const n = sectionName(args); return n === '.text' || n.startsWith('.text.'); };
|
|
209
|
+
|
|
210
|
+
// {labels: Map name -> line, symbols: Set (assigned with = / .set / .equ), instrs: [{line, col, mnemonic, operands,
|
|
211
|
+
// kind: 'jcc' | 'jmp' | 'call' | 'ret' | 'other', target}], numeric: [{name, line}]}. Lines 1-based; only .text code.
|
|
212
|
+
export function scan(text) {
|
|
213
|
+
const raw = String(text).split('\n');
|
|
214
|
+
const lines = blankBlockComments(String(text)).split('\n');
|
|
215
|
+
// clang's loop notes on a label's line or the comment line after it ("# =>This Inner Loop Header: Depth=2",
|
|
216
|
+
// "# in Loop: Header=BB0_4 Depth=1"): label -> text
|
|
217
|
+
const notes = new Map();
|
|
218
|
+
const labels = new Map(), symbols = new Set(), instrs = [], numeric = [], functions = new Set();
|
|
219
|
+
let inText = true, prev = true, directives = 0;
|
|
220
|
+
const stack = [];
|
|
221
|
+
for (let i = 0; i < lines.length; i++) {
|
|
222
|
+
for (const st of statements(lines[i])) {
|
|
223
|
+
const lead = LABELS.exec(st.text)[0].length;
|
|
224
|
+
LABEL_ONE.lastIndex = 0;
|
|
225
|
+
let m;
|
|
226
|
+
const head = st.text.slice(0, lead);
|
|
227
|
+
while ((m = LABEL_ONE.exec(head))) {
|
|
228
|
+
const name = m[1];
|
|
229
|
+
if (/^\d+$/.test(name)) numeric.push({ name, line: i + 1, inText });
|
|
230
|
+
else if (!labels.has(name)) {
|
|
231
|
+
labels.set(name, { line: i + 1, inText });
|
|
232
|
+
const note = `${raw[i] ?? ''} ${/^\s*#/.test(raw[i + 1] ?? '') ? raw[i + 1] : ''}`;
|
|
233
|
+
if (/Loop Header|in Loop:|Parent Loop/.test(note)) notes.set(name, note);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const body = st.text.slice(lead).trim();
|
|
237
|
+
if (!body) continue;
|
|
238
|
+
if (body[0] === '.') {
|
|
239
|
+
const d = /^\.([\w.]+)\s*(.*)$/.exec(body);
|
|
240
|
+
const name = d?.[1].toLowerCase() ?? '';
|
|
241
|
+
const args = d?.[2] ?? '';
|
|
242
|
+
directives++;
|
|
243
|
+
if (name === 'set' || name === 'equ' || name === 'equiv') { const s = /^([\w.$@]+)/.exec(args); if (s) symbols.add(s[1]); }
|
|
244
|
+
else if (name === 'globl' || name === 'global') { const s = /^([\w.$@]+)/.exec(args); if (s) functions.add(s[1]); }
|
|
245
|
+
else if (name === 'type') { const s = /^([\w.$@]+)\s*,\s*[@%]function/.exec(args); if (s) functions.add(s[1]); }
|
|
246
|
+
else if (name === 'text') { prev = inText; inText = true; }
|
|
247
|
+
else if (name === 'data' || name === 'bss') { prev = inText; inText = false; }
|
|
248
|
+
else if (name === 'section') { prev = inText; inText = isText(args); }
|
|
249
|
+
else if (name === 'pushsection') { stack.push(inText); prev = inText; inText = isText(args); }
|
|
250
|
+
else if (name === 'popsection') { prev = inText; inText = stack.pop() ?? true; }
|
|
251
|
+
else if (name === 'previous') { [inText, prev] = [prev, inText]; }
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const assign = /^([\w.$@]+)\s*=/.exec(body);
|
|
255
|
+
if (assign) { symbols.add(assign[1]); continue; }
|
|
256
|
+
if (!inText) continue;
|
|
257
|
+
const { mnemonic, operands } = splitInstr(body);
|
|
258
|
+
let kind = 'other', target = null;
|
|
259
|
+
if (JCC.test(mnemonic)) kind = 'jcc';
|
|
260
|
+
else if (JMP.test(mnemonic)) kind = 'jmp';
|
|
261
|
+
else if (CALL.test(mnemonic)) kind = 'call';
|
|
262
|
+
else if (RET.test(mnemonic)) kind = 'ret';
|
|
263
|
+
if (kind === 'jcc' || kind === 'jmp' || kind === 'call') {
|
|
264
|
+
const op = operands.replace(/^\*/, '');
|
|
265
|
+
if (/^\d+[bf]$/.test(op) || (SYMBOL.test(op) && !GPR.test(op) && !op.startsWith('%'))) target = op;
|
|
266
|
+
}
|
|
267
|
+
instrs.push({ line: i + 1, col: st.at + lead, end: st.at + st.text.length, mnemonic, operands, kind, target, body });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return { labels, symbols, instrs, numeric, functions, directives, notes };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// The line a branch target refers to (a label, or a numeric label "1b" / "1f" seen from `line`), or null.
|
|
274
|
+
function targetLine(s, target, line) {
|
|
275
|
+
const n = /^(\d+)([bf])$/.exec(target);
|
|
276
|
+
if (n) {
|
|
277
|
+
const cands = s.numeric.filter((x) => x.name === n[1] && x.inText);
|
|
278
|
+
const c = n[2] === 'b' ? cands.filter((x) => x.line <= line).pop() : cands.find((x) => x.line > line);
|
|
279
|
+
return c ? c.line : null;
|
|
280
|
+
}
|
|
281
|
+
const l = s.labels.get(target);
|
|
282
|
+
return l && l.inText ? l.line : null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// The loops: [{begin, end, label, inner}] (begin: the label's line, end: the last branch back to it; 1-based), innermost first,
|
|
286
|
+
// then the deepest, then in the order of the code (which may put a remainder loop first: clang often does).
|
|
287
|
+
export function findLoops(s) {
|
|
288
|
+
const loops = [];
|
|
289
|
+
for (const ins of s.instrs) {
|
|
290
|
+
if ((ins.kind !== 'jcc' && ins.kind !== 'jmp') || !ins.target) continue;
|
|
291
|
+
const t = targetLine(s, ins.target, ins.line);
|
|
292
|
+
if (t === null || t > ins.line) continue;
|
|
293
|
+
// several branches back to one label are one loop (to the last of them): an exit retargeted to the top is not a loop
|
|
294
|
+
const same = loops.find((l) => l.begin === t);
|
|
295
|
+
if (same) same.end = Math.max(same.end, ins.line);
|
|
296
|
+
else loops.push({ begin: t, end: ins.line, label: ins.target });
|
|
297
|
+
}
|
|
298
|
+
// not a loop: a span with a ret, or with a function's label in it (a tail call jumping back to an earlier function)
|
|
299
|
+
const fn = (name, l) => !name.startsWith('.L') && !/^\d+$/.test(name) && (s.functions?.has(name)
|
|
300
|
+
|| s.instrs.some((x) => (x.kind === 'call' || x.kind === 'jmp' || x.kind === 'jcc') && x.target === name && (x.line < l.begin || x.line > l.end)));
|
|
301
|
+
const real = loops.filter((l) => !s.instrs.some((x) => x.kind === 'ret' && x.line > l.begin && x.line < l.end)
|
|
302
|
+
&& ![...s.labels].some(([name, d]) => d.line > l.begin && d.line <= l.end && fn(name, l)));
|
|
303
|
+
// clang's notes: the loops whose labels belong to one loop header (its blocks, "in Loop: Header=BB0_4") are one loop,
|
|
304
|
+
// named after its header, at clang's depth
|
|
305
|
+
let merged = real;
|
|
306
|
+
if (s.notes?.size) {
|
|
307
|
+
const keyOf = (label) => {
|
|
308
|
+
const n = s.notes.get(label) ?? '';
|
|
309
|
+
if (/This (?:Inner )?Loop Header/.test(n) || !/Header=(\w+)/.test(n)) return label.replace(/^\.L/, '');
|
|
310
|
+
return /Header=(\w+)/.exec(n)[1];
|
|
311
|
+
};
|
|
312
|
+
const groups = new Map();
|
|
313
|
+
for (const l of real) {
|
|
314
|
+
const k = keyOf(l.label);
|
|
315
|
+
const g = groups.get(k);
|
|
316
|
+
if (g) { g.begin = Math.min(g.begin, l.begin); g.end = Math.max(g.end, l.end); } else groups.set(k, { ...l, key: k });
|
|
317
|
+
}
|
|
318
|
+
merged = [...groups.values()].map((g) => {
|
|
319
|
+
const header = `.L${g.key}`;
|
|
320
|
+
const label = s.labels.has(header) ? header : g.label;
|
|
321
|
+
const note = s.notes.get(label) ?? '';
|
|
322
|
+
const d = /Loop Header: Depth=(\d+)/.exec(note) ?? /Depth=(\d+)/.exec(note);
|
|
323
|
+
return { begin: g.begin, end: g.end, label, ...(d ? { clangDepth: Number(d[1]) } : {}) };
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
for (const l of merged) {
|
|
327
|
+
l.inner = !merged.some((o) => o !== l && o.begin >= l.begin && o.end <= l.end && (o.begin !== l.begin || o.end !== l.end));
|
|
328
|
+
// nesting depth: 1 for a loop in no other (clang's Depth when it says)
|
|
329
|
+
l.depth = l.clangDepth ?? 1 + merged.filter((o) => o !== l && o.begin <= l.begin && o.end >= l.end && (o.begin !== l.begin || o.end !== l.end)).length;
|
|
330
|
+
delete l.clangDepth;
|
|
331
|
+
l.instructions = s.instrs.filter((x) => x.line >= l.begin && x.line <= l.end).length;
|
|
332
|
+
// the function it is in: the last label before it that is not local
|
|
333
|
+
let fname = null, at = -1;
|
|
334
|
+
for (const [name, d] of s.labels) if (d.line <= l.begin && d.line > at && !name.startsWith('.L') && !/^\d+$/.test(name) && !name.startsWith('wuica')) { fname = name; at = d.line; }
|
|
335
|
+
l.function = fname;
|
|
336
|
+
}
|
|
337
|
+
// the innermost and deepest first; among equals, the first in the code (gcc puts the main loop first, clang often its
|
|
338
|
+
// remainder loop: -loops lists them all)
|
|
339
|
+
return merged.sort((a, b) => Number(b.inner) - Number(a.inner) || b.depth - a.depth || a.begin - b.begin || a.end - b.end);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const PROLOGUE = [
|
|
343
|
+
/^endbr64$/i,
|
|
344
|
+
/^push[q]?\s+%?[\w]+$/i,
|
|
345
|
+
/^mov[q]?\s+(?:rbp\s*,\s*rsp|%rsp\s*,\s*%rbp)$/i,
|
|
346
|
+
/^(?:sub|and)[q]?\s+(?:rsp\s*,\s*[-\w$]+|\$?[-\w]+\s*,\s*%rsp)$/i,
|
|
347
|
+
];
|
|
348
|
+
const EPILOGUE = [
|
|
349
|
+
/^(?:rep[z]?\s+)?ret[q]?(?:\s+\S+)?$/i,
|
|
350
|
+
/^leave[q]?$/i,
|
|
351
|
+
/^pop[q]?\s+%?[\w]+$/i,
|
|
352
|
+
/^add[q]?\s+(?:rsp\s*,\s*[-\w$]+|\$?[-\w]+\s*,\s*%rsp)$/i,
|
|
353
|
+
/^lea[q]?\s+(?:rsp\s*,.*|.*,\s*%rsp)$/i,
|
|
354
|
+
/^mov[q]?\s+(?:rsp\s*,\s*rbp|%rbp\s*,\s*%rsp)$/i,
|
|
355
|
+
/^vzeroupper$/i,
|
|
356
|
+
];
|
|
357
|
+
|
|
358
|
+
// A function without a loop: its body without the prologue and the epilogue ({begin, end} lines), or null (no ret at
|
|
359
|
+
// the end, or nothing left).
|
|
360
|
+
export function functionBody(s) {
|
|
361
|
+
const ins = s.instrs;
|
|
362
|
+
let last = ins.length - 1;
|
|
363
|
+
// padding after the last ret (nop, int3, ud2) is not code of the function
|
|
364
|
+
while (last >= 0 && /^(?:nop[wlq]?|int3|ud2|xchg)$/i.test(ins[last].mnemonic)) last--;
|
|
365
|
+
if (last < 0 || ins[last].kind !== 'ret') return null;
|
|
366
|
+
let a = 0, b = last;
|
|
367
|
+
while (a <= b && PROLOGUE.some((re) => re.test(ins[a].body.replace(/\s+/g, ' ')))) a++;
|
|
368
|
+
while (b >= a && EPILOGUE.some((re) => re.test(ins[b].body.replace(/\s+/g, ' ')))) b--;
|
|
369
|
+
if (a > b) return null;
|
|
370
|
+
// trimmed: prologue and epilogue instructions besides the ret
|
|
371
|
+
return { begin: ins[a].line, end: ins[b].line, trimmed: a + (last - b - 1) };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// What to analyze: see the top. text: the pasted assembly; loop: 'auto' (default), 'whole', or the index of a loop.
|
|
375
|
+
// Returns {text, objdump, loops: [{begin, end, label}], choice: index | 'body' | null, choosable (there is code around the
|
|
376
|
+
// loop or the body: a choice matters), pick: {begin, end, lines: [the line of each instruction]} | null,
|
|
377
|
+
// body: {begin, end} | null, alignment: number | null, address: number | null, stubs: [names],
|
|
378
|
+
// notes: [{line, column, severity, message}], fallback: Map line -> text, error?}
|
|
379
|
+
export function preparePaste(text, { loop = 'auto', func = null } = {}) {
|
|
380
|
+
let t = leadingSemicolons(normalizeText(text).replace(/^/, ''));
|
|
381
|
+
const od = fromObjdump(t);
|
|
382
|
+
if (od.objdump) t = od.text;
|
|
383
|
+
// code sections other than .text (gcc's main in .text.startup, -ffunction-sections): into .text, which the assembler
|
|
384
|
+
// returns (the statement keeps its line; it is the same layout as one .text)
|
|
385
|
+
t = t.replace(/^([ \t]*)\.(?:section|pushsection)[ \t]+"?\.text\.[^\n#;]*/gm, (m, ind) => (/^\s*\.push/.test(m) ? `${ind}.pushsection .text` : `${ind}.text`));
|
|
386
|
+
const s = scan(t);
|
|
387
|
+
const marked = MARKER.test(t) || IACA.test(t);
|
|
388
|
+
const all = findLoops(s);
|
|
389
|
+
let loops = marked ? [] : all;
|
|
390
|
+
// -func: the loops of one function
|
|
391
|
+
if (func !== null && func !== undefined && func !== '') {
|
|
392
|
+
const fnames = new Set(all.map((l) => l.function).filter(Boolean));
|
|
393
|
+
if (!s.labels.has(func)) return { error: `func: ${JSON.stringify(func)} is not a label of the text${fnames.size ? ` (functions with loops: ${[...fnames].join(', ')})` : ''}`, loops: [] };
|
|
394
|
+
loops = loops.filter((l) => l.function === func);
|
|
395
|
+
}
|
|
396
|
+
const named = (l) => (l.label.startsWith('.Lwuica_a') ? `0x${l.label.slice(9)}` : l.label);
|
|
397
|
+
// a loop by its label ("-loop .LBB0_12", "-loop 0x10"): as its index
|
|
398
|
+
if (typeof loop === 'string' && loop !== 'auto' && loop !== 'whole') {
|
|
399
|
+
const hits = loops.flatMap((l, i) => (named(l) === loop || l.label === loop || named(l) === `.${loop}` || (/^0x/i.test(loop) && named(l).toLowerCase() === loop.toLowerCase()) ? [i] : []));
|
|
400
|
+
const k = hits.length ? hits[0] : -1;
|
|
401
|
+
// the same label in several functions (numeric labels: "1:" ... "jnz 1b"): not a guess
|
|
402
|
+
if (hits.length > 1) return { error: `loop: ${JSON.stringify(loop)} names ${hits.length} loops (${hits.map((i) => `${i} in ${loops[i].function ?? 'no function'}`).join(', ')}): -func NAME or -loop N (0-based) picks one`, loops: [] };
|
|
403
|
+
if (k < 0) return { error: `loop: ${JSON.stringify(loop)} is not the label of a loop${func ? ` in ${func}` : ''} (${loops.length ? `the loops: ${loops.map(named).join(', ')}` : 'the text has none'})`, loops: [] };
|
|
404
|
+
loop = k;
|
|
405
|
+
}
|
|
406
|
+
// objdump lines with their bytes are assembled as those bytes (the exact encodings); their text is only read
|
|
407
|
+
let asm = t;
|
|
408
|
+
if (od.objdump && od.bytes.size) {
|
|
409
|
+
const lines = t.split('\n');
|
|
410
|
+
for (const [line, b] of od.bytes) lines[line - 1] = b;
|
|
411
|
+
asm = lines.join('\n');
|
|
412
|
+
}
|
|
413
|
+
const out = { text: asm, objdump: od.objdump, loops: loops.map((l) => ({ begin: l.begin, end: l.end, label: named(l), function: l.function, instructions: l.instructions, depth: l.depth, inner: l.inner })),
|
|
414
|
+
choice: null, choosable: false, pick: null, body: null, alignment: null, address: null, stubs: [], notes: [], fallback: new Map() };
|
|
415
|
+
if (loop !== 'auto' && loop !== 'whole' && !(Number.isInteger(loop) && loop >= 0)) {
|
|
416
|
+
out.error = `loop: ${JSON.stringify(loop)} is not "auto", "whole", the index of a loop (0-based) or its label`;
|
|
417
|
+
return out;
|
|
418
|
+
}
|
|
419
|
+
const code = s.instrs;
|
|
420
|
+
if (Number.isInteger(loop) && loop >= loops.length) {
|
|
421
|
+
out.error = `loop: ${loop} is not the index of a loop (0-based; the text has ${loops.length === 0 ? 'none' : `${loops.length}: 0 to ${loops.length - 1}`})`;
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
if (!marked) {
|
|
425
|
+
// choosable: there is code around the loop (or a prologue around the body), so the choice matters
|
|
426
|
+
if (loops.length) out.choosable = !(loops.length === 1 && code.every((x) => x.line >= loops[0].begin && x.line <= loops[0].end));
|
|
427
|
+
else {
|
|
428
|
+
// a compiler's function (a function label, directives, objdump, or a prologue/epilogue): its body; a bare snippet
|
|
429
|
+
// ("add rax, 1 / ret") is analyzed as typed
|
|
430
|
+
const b = functionBody(s);
|
|
431
|
+
const compiled = od.objdump || s.directives > 0 || [...s.labels.keys()].some((n) => !n.startsWith('.L') && !/^\d+$/.test(n)) || b?.trimmed > 0;
|
|
432
|
+
out.body = b && compiled ? { begin: b.begin, end: b.end } : null;
|
|
433
|
+
out.choosable = !!out.body;
|
|
434
|
+
}
|
|
435
|
+
if (out.choosable && loop !== 'whole') {
|
|
436
|
+
if (loops.length) {
|
|
437
|
+
const k = Number.isInteger(loop) ? loop : 0;
|
|
438
|
+
out.choice = k;
|
|
439
|
+
out.pick = { begin: loops[k].begin, end: loops[k].end };
|
|
440
|
+
} else {
|
|
441
|
+
out.choice = 'body';
|
|
442
|
+
out.pick = out.body;
|
|
443
|
+
}
|
|
444
|
+
// the source line of each instruction of the pick (caveats.js names lines with them)
|
|
445
|
+
out.pick = { ...out.pick, lines: code.filter((x) => x.line >= out.pick.begin && x.line <= out.pick.end).map((x) => x.line) };
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// the exits: conditional branches (and jumps to .L labels) whose target the text does not define
|
|
449
|
+
const defined = (name) => s.labels.has(name) || s.symbols.has(name);
|
|
450
|
+
const seen = new Set();
|
|
451
|
+
for (const x of code) {
|
|
452
|
+
if (!x.target || /^\d+[bf]$/.test(x.target) || defined(x.target)) continue;
|
|
453
|
+
if (x.kind === 'jcc' || (x.kind === 'jmp' && (x.target.startsWith('.L') || x.target.startsWith(OUTSIDE_PREFIX)))) {
|
|
454
|
+
if (seen.has(x.target)) continue;
|
|
455
|
+
seen.add(x.target);
|
|
456
|
+
out.stubs.push(x.target);
|
|
457
|
+
if (!x.target.startsWith(OUTSIDE_PREFIX)) out.notes.push({ line: x.line, column: x.col + 1, severity: 'note', message: `${x.target} is not in the code: taken as an exit, not taken` });
|
|
458
|
+
} else if (x.kind === 'jmp' && !x.target.startsWith('wuica_ext_')) {
|
|
459
|
+
if (seen.has(x.target)) continue;
|
|
460
|
+
seen.add(x.target);
|
|
461
|
+
out.notes.push({ line: x.line, column: x.col + 1, severity: 'warning', message: `${x.target} is not defined: encoded as a 32-bit jump to an external symbol` });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (od.objdump) {
|
|
465
|
+
// a line the assembler rejects is left out only outside the analyzed code (padding around a loop); in it, an error
|
|
466
|
+
if (out.pick) for (const line of od.addresses.keys()) if (!od.bytes.has(line) && (line < out.pick.begin || line > out.pick.end)) out.fallback.set(line, '');
|
|
467
|
+
const first = code.find((x) => !out.pick || x.line >= out.pick.begin);
|
|
468
|
+
const a = first ? od.addresses.get(first.line) : undefined;
|
|
469
|
+
if (a !== undefined) { out.address = a; out.alignment = a % 64; }
|
|
470
|
+
}
|
|
471
|
+
return out;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// A text that replaces an editor's text (a paste over most of it, an example, an import) starts with the first loop again (the page's
|
|
475
|
+
// pick goes back to auto).
|
|
476
|
+
// Not an edit: what the old and the new text share at their start and end is less than half of the old one.
|
|
477
|
+
export function replacesText(before, after) {
|
|
478
|
+
if (before === after) return false;
|
|
479
|
+
let p = 0;
|
|
480
|
+
const n = Math.min(before.length, after.length);
|
|
481
|
+
while (p < n && before[p] === after[p]) p++;
|
|
482
|
+
let s = 0;
|
|
483
|
+
while (s < n - p && before[before.length - 1 - s] === after[after.length - 1 - s]) s++;
|
|
484
|
+
return p + s < before.length / 2;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// The loops as the page's chip names them: "loop .L3", "loop 0x10", "body".
|
|
488
|
+
export function loopName(prep) {
|
|
489
|
+
if (prep.choice === 'body') return 'body';
|
|
490
|
+
if (prep.choice === null) return null;
|
|
491
|
+
return `loop ${prep.loops[prep.choice].label}`;
|
|
492
|
+
}
|
package/lib/whatif.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The what-if experiments of the web page (web/js/whatif.js), for the MCP tool `what_if`: the block re-analyzed with one
|
|
2
|
+
// change each: unrolled ×2/×4/×8 (n copies of the body and the loop's branch once, per original iteration), N
|
|
3
|
+
// accumulators (unrolled ×N with the chain's register renamed in each copy: the page's accum.js, assembled), the front
|
|
4
|
+
// end limited only by the issue width, macro- or micro-fusion switched; and the estimate without the loop-carried chain
|
|
5
|
+
// (the largest other limit, no analysis). tests-js/web_whatif.mjs checks that the variants agree with the page's.
|
|
6
|
+
|
|
7
|
+
import { ACCUMULATORS, accumulatorText, bestAccumulators } from './web/accum.js';
|
|
8
|
+
|
|
9
|
+
export const VARIANTS = Object.freeze(['unroll2', 'unroll4', 'unroll8', 'acc2', 'acc3', 'acc4', 'acc8', 'simpleFrontEnd', 'noMacroFusion', 'noMicroFusion', 'nochain']);
|
|
10
|
+
const UNROLL = [2, 4, 8];
|
|
11
|
+
const FLAGS = [
|
|
12
|
+
['simpleFrontEnd', 'simple front end', 'detailed front end'],
|
|
13
|
+
['noMacroFusion', 'no macro-fusion', 'macro-fusion'],
|
|
14
|
+
['noMicroFusion', 'no micro-fusion', 'micro-fusion'],
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
// The instructions as byte ranges of the code, or null if the rows do not make up the code (undecodable bytes).
|
|
18
|
+
function instrRanges(response, hex) {
|
|
19
|
+
const out = [];
|
|
20
|
+
let at = 0;
|
|
21
|
+
for (const x of response?.rows ?? []) {
|
|
22
|
+
if (x.kind !== 'instr') continue;
|
|
23
|
+
const op = String(x.opcode ?? '').toLowerCase();
|
|
24
|
+
out.push({ start: at, op, fused: x.notes === 'M' });
|
|
25
|
+
at += op.length / 2;
|
|
26
|
+
}
|
|
27
|
+
return out.length && out.map((i) => i.op).join('') === String(hex ?? '').toLowerCase() ? out : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The loop unrolled n times (as the page): {ok, hex, tail} or {ok: false, reason}
|
|
31
|
+
export function unrollHex(response, hex, n) {
|
|
32
|
+
if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
|
|
33
|
+
const ins = instrRanges(response, hex);
|
|
34
|
+
if (!ins) return { ok: false, reason: 'the code has bytes that are not instructions' };
|
|
35
|
+
const last = ins.length - 1;
|
|
36
|
+
const tailFrom = ins[last].fused && last > 0 ? ins[last - 1].start : ins[last].start;
|
|
37
|
+
if (tailFrom === 0) return { ok: false, reason: 'nothing but the branch' };
|
|
38
|
+
const code = String(hex).toLowerCase();
|
|
39
|
+
return { ok: true, hex: code.slice(0, 2 * tailFrom).repeat(n) + code.slice(2 * tailFrom), tail: tailFrom === ins[last].start ? 1 : 2 };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The experiments for a response: [{id, label, per, hex, options} | {id: 'nochain', label, estimate, per}] (as the page's
|
|
43
|
+
// experiments()); options: the simulation options of the base analysis.
|
|
44
|
+
export function experiments(response, hex, options = {}) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const n of UNROLL) {
|
|
47
|
+
const u = unrollHex(response, hex, n);
|
|
48
|
+
if (u.ok) out.push({ id: `unroll${n}`, label: `unroll ×${n}`, per: n, hex: u.hex, options });
|
|
49
|
+
}
|
|
50
|
+
if (response?.mode === 'loop' && response.criticalPath?.edges?.length) {
|
|
51
|
+
for (const n of ACCUMULATORS) {
|
|
52
|
+
const a = accumulatorText(response, hex, n);
|
|
53
|
+
if (!a.ok && n === ACCUMULATORS[0]) { out.push({ id: 'acc', label: 'accumulators', per: 1, error: a.reason, options }); break; }
|
|
54
|
+
if (!a.ok) { out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, error: a.reason, options }); continue; }
|
|
55
|
+
out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, text: a.text, options, renamed: a.renamed });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const [k, on, off] of FLAGS) {
|
|
59
|
+
const v = !options?.[k];
|
|
60
|
+
out.push({ id: k, label: v ? on : off, per: 1, hex: String(hex).toLowerCase(), options: { ...options, [k]: v } });
|
|
61
|
+
}
|
|
62
|
+
const lims = Array.isArray(response?.limits) ? response.limits : [];
|
|
63
|
+
const others = lims.filter((l) => l.name !== 'Dependencies').map((l) => Number(l.tp));
|
|
64
|
+
if (lims.some((l) => l.name === 'Dependencies') && others.length) out.push({ id: 'nochain', label: 'no chain', estimate: Math.max(...others), per: 1 });
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The label of a variant as experiments() gives it (for the variants it does not make).
|
|
69
|
+
function labelOf(id, options) {
|
|
70
|
+
if (id.startsWith('unroll')) return `unroll ×${id.slice(6)}`;
|
|
71
|
+
if (id.startsWith('acc')) return `${id.slice(3)} accumulators`;
|
|
72
|
+
const f = FLAGS.find(([k]) => k === id);
|
|
73
|
+
return f ? (options?.[id] ? f[2] : f[1]) : 'no chain';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const round = (x) => Math.round(x * 100) / 100;
|
|
77
|
+
|
|
78
|
+
// What the tool returns for one experiment, from the base result and the variant's (or its estimate).
|
|
79
|
+
export function outcome(base, exp, r) {
|
|
80
|
+
const row = { id: exp.id, label: exp.label };
|
|
81
|
+
if (exp.renamed) row.renamed = exp.renamed;
|
|
82
|
+
let tp;
|
|
83
|
+
if (exp.error) return { ...row, error: exp.error };
|
|
84
|
+
if (exp.estimate !== undefined) { tp = exp.estimate; row.estimate = true; }
|
|
85
|
+
else if (!r || r.code !== 0) {
|
|
86
|
+
const error = r?.error ?? 'not analyzed';
|
|
87
|
+
// a limit or failure of the unrolled code, not of the caller's block: say so
|
|
88
|
+
return { ...row, error: exp.per > 1 && exp.hex ? `the block unrolled ×${exp.per} (${exp.hex.length} hex characters) could not be analyzed: ${error}` : error };
|
|
89
|
+
}
|
|
90
|
+
else if (r.mode !== base.mode) return { ...row, error: `analyzed ${r.mode === 'loop' ? 'as a loop' : 'unrolled'}: not comparable` };
|
|
91
|
+
else { tp = r.tp / exp.per; row.bottlenecks = r.bottlenecks; }
|
|
92
|
+
return { ...row, tp: round(tp), delta: round(tp - base.tp), speedup: tp > 0 ? round(base.tp / tp) : null };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Runs the experiments with analyze(arch, {hex, options}) (one after another). request: as analyze's ({source | hex,
|
|
96
|
+
// syntax, loop, options}); variants: ids of VARIANTS (default: all); assemble(text) -> {code, hex} (the accumulator
|
|
97
|
+
// variants; Intel syntax). Resolves to {code: 0, arch, tp, mode, bottlenecks, loop?, variants: [{id, label, tp, delta,
|
|
98
|
+
// speedup, estimate?, bottlenecks?, renamed?, error?}], accumulators?: {best, tp}} or the base's failure.
|
|
99
|
+
// accumulators: the best number of accumulators (the smallest within 1% of the fastest, 1 = as it is) among those run.
|
|
100
|
+
export async function whatIf(analyze, arch, request, variants = VARIANTS, { assemble = null } = {}) {
|
|
101
|
+
const unknown = (variants ?? []).filter((v) => !VARIANTS.includes(v));
|
|
102
|
+
if (unknown.length) return { code: 1, error: `unknown variant(s): ${unknown.join(', ')} (known: ${VARIANTS.join(', ')})`, stderr: [] };
|
|
103
|
+
const base = await analyze(arch, request);
|
|
104
|
+
if (base.code !== 0) return base;
|
|
105
|
+
// the code as the rows have it (the analyzed bytes, if every byte was decoded), for the unrolled copies; the other
|
|
106
|
+
// variants analyze the caller's code as given (hex in any form the library accepts, or the assembled bytes)
|
|
107
|
+
const rowsHex = base.decodeErrors ? '' : base.rows.filter((x) => x.kind === 'instr').map((x) => String(x.opcode ?? '').toLowerCase()).join('');
|
|
108
|
+
const code = base.hex !== undefined ? { hex: base.hex } : { hex: request.hex };
|
|
109
|
+
const options = { ...(request.options ?? {}) };
|
|
110
|
+
const want = new Set(variants ?? VARIANTS);
|
|
111
|
+
const out = [];
|
|
112
|
+
// the alignment offset the base got from the code's addresses (objdump input) holds for the variants too
|
|
113
|
+
if (options.alignmentOffset === undefined && request.alignmentOffset === undefined && base.loop?.alignmentOffset !== undefined) options.alignmentOffset = base.loop.alignmentOffset;
|
|
114
|
+
const exps = experiments(base, rowsHex, options);
|
|
115
|
+
const accError = exps.find((x) => x.id === 'acc')?.error;
|
|
116
|
+
for (const exp of exps) {
|
|
117
|
+
if (!want.has(exp.id)) continue;
|
|
118
|
+
if (exp.text && !exp.hex) {
|
|
119
|
+
const a = assemble ? await assemble(exp.text) : null;
|
|
120
|
+
if (a?.code === 0 && a.hex) exp.hex = a.hex;
|
|
121
|
+
else { out.push(outcome(base, { ...exp, error: a ? `the variant does not assemble: ${a.error}` : 'no assembler' }, null)); continue; }
|
|
122
|
+
}
|
|
123
|
+
const r = exp.estimate !== undefined ? null : await analyze(base.arch, exp.per > 1 ? { hex: exp.hex, options: exp.options } : { ...code, options: exp.options });
|
|
124
|
+
out.push(outcome(base, exp, r));
|
|
125
|
+
}
|
|
126
|
+
for (const id of want) {
|
|
127
|
+
if (!out.some((x) => x.id === id)) {
|
|
128
|
+
out.push({ id, label: labelOf(id, options), error: base.mode !== 'loop' && (id.startsWith('unroll') || id.startsWith('acc')) ? 'not a loop' : id === 'nochain' || id.startsWith('acc') ? (id.startsWith('acc') && accError) || 'no loop-carried chain' : 'not applicable' });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
out.sort((a, b) => VARIANTS.indexOf(a.id) - VARIANTS.indexOf(b.id));
|
|
132
|
+
const accs = out.filter((x) => x.id.startsWith('acc') && x.tp !== undefined);
|
|
133
|
+
const best = accs.length ? bestAccumulators(new Map([[1, base.tp], ...accs.map((x) => [Number(x.id.slice(3)), x.tp])])) : null;
|
|
134
|
+
return { code: 0, arch: base.arch, tp: base.tp, mode: base.mode, bottlenecks: base.bottlenecks, ...(base.loop ? { loop: base.loop } : {}), unit: 'cycles per original iteration', variants: out,
|
|
135
|
+
...(best ? { accumulators: { best: best.n, tp: round(best.tp) } } : {}) };
|
|
136
|
+
}
|