wuica-cli 0.0.0-stage → 0.1.9

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 (48) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +546 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.bin.br +0 -0
  6. package/dist/data/arch/BDW.bin.br +0 -0
  7. package/dist/data/arch/CFL.bin.br +0 -0
  8. package/dist/data/arch/CLX.bin.br +0 -0
  9. package/dist/data/arch/HSW.bin.br +0 -0
  10. package/dist/data/arch/ICL.bin.br +0 -0
  11. package/dist/data/arch/ICX.bin.br +0 -0
  12. package/dist/data/arch/IVB.bin.br +0 -0
  13. package/dist/data/arch/KBL.bin.br +0 -0
  14. package/dist/data/arch/RKL.bin.br +0 -0
  15. package/dist/data/arch/SKL.bin.br +0 -0
  16. package/dist/data/arch/SKX.bin.br +0 -0
  17. package/dist/data/arch/SNB.bin.br +0 -0
  18. package/dist/data/arch/TGL.bin.br +0 -0
  19. package/dist/data/arch/ZEN3.bin.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +160 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +410 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +693 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/examples.js +26 -0
  30. package/lib/files.js +40 -0
  31. package/lib/index.js +577 -0
  32. package/lib/insights.js +100 -0
  33. package/lib/mcp.js +366 -0
  34. package/lib/objfile.js +216 -0
  35. package/lib/thread-worker.js +49 -0
  36. package/lib/threads.js +235 -0
  37. package/lib/wasm.js +246 -0
  38. package/lib/web/accum.js +202 -0
  39. package/lib/web/asm-regions.js +415 -0
  40. package/lib/web/assembler.js +188 -0
  41. package/lib/web/caveats.js +214 -0
  42. package/lib/web/examples.js +99 -0
  43. package/lib/web/loop-find.js +492 -0
  44. package/lib/web/showcase.js +368 -0
  45. package/lib/whatif.js +136 -0
  46. package/licenses/LICENSE-LLVM.txt +279 -0
  47. package/licenses/LICENSE-XED.txt +178 -0
  48. 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
+ }