// wasm-branch-hints.mjs FILE: hint every status-channel and preempt-word branch as not taken. // // A status check follows every call of a marked function and a poll sits on every kept back edge. Their arms // are the park path, which almost never runs, and the optimizer has no way to know: LLVM's probabilities do not // survive into wasm, so V8 lays the cold arm inline and allocates registers as if it were as likely as the rest. // The branch hinting section tells it. Interleaved in one boot, against the same binaries without it: gd-msort // 19% faster (88.2 -> 71.2 ms), js and sql 4%, a geomean of 3.2% over twelve workloads, for a section that is // half a percent of the module. // // The pattern is the one the pass emits (CoroutinizePass.cpp, the status check and insertSafepointOnEdge), and // the optimizer has usually kept the channel's address, or address + 12, in a local: // (global.get $__hwjs_status_channel_addr | local.get base) i32.load 0 [local.tee n] [i32.eqz]; br_if // (global.get $... | local.get base) i32.const 12; i32.add; i32.atomic.load 0 ...; br_if // local.get preempt; i32.atomic.load 0 ...; br_if // A module that imports no such global has no status channel and is left as it was. brint-tool's branch-hints // is the same walk, for an installed toolchain with no node (test/branch-hints.sh holds them to the same bytes). // // WHAT A LOCAL HOLDS is a must-fact over the function's structured control flow: the facts on every path // that reaches an instruction, met at block ends, at if/else and at loop headers (iterated until they stop // shrinking). The first walk was one pass in byte order, and any write to a local anywhere earlier deleted the // fact, including a write on a path that branches away and never reaches the check. The register allocator // reuses the channel's local for the park state's index on every park exit (`i32.const 320; local.set 1; // br `), so every later check in the function went unseen: neither hinted nor counted, in the census or // in status-hint-coverage. In a musl bash that was 4,625 provable status and poll br_ifs shipped with no hint // (_rl_overwrite_char: 2 of its 8 hinted), and the census of a register-allocation change read "-109 hinted" // with the shape unchanged. A local also keeps a status or preempt word it was given, and a branch on it later // is a status branch (a resume clone loads the word once at entry and tests it at every resume point). // // RESUME CLONES reload the channel's address from their coroutine frame: CoroSplit spills the one invariant // load of the address global across the suspends, the ramp stores it (`local.get frame; local.get chan; // i32.store K`) and `.resume` reads `local.get 0; i32.load K` back. A walk that knew only the global saw none // of those checks: 5,664 in a musl bash, 0 hinted, and they are the checks a long-lived function runs once it // has parked. A frame slot is the channel's when the ramp stores a channel value there; the ramp is found by // name (`` for `.resume`), and a name that is not unique in the name section seeds nothing, since two // static functions of one name are two frames. A module with no name section gets no resume hints, and the // report says names=0. // // HWJS_BRANCH_HINTS_REPORT=1 also prints what the walk found on a status or preempt word that it could NOT // hint: a br_table or an if consuming one (test/status-hint-coverage.sh), then the per-function census below. // The output bytes do not change. // // A DENOMINATOR THE RECOGNIZER DOES NOT WRITE. The report and the census summary also count the dispatch-shaped // checks: `local.{get,tee} s; i32.eqz; br_if`, then (past empty `block`s) `local.get s; i32.const -1|-2; // i32.add; br_table`, the peeled NORMAL arm ahead of the cold dispatch every status check carries. That shape // is found by its bytes alone, with no idea where s came from, so `dispatch_unrecognized` counts the status // checks the walk above missed (and any program switch of the same shape, which is why it is a count and not a // refusal). HWJS_BRANCH_HINTS_RED_LINEAR=1 (with WASMLD_HWJS_ALLOW_RED_KNOBS=1) is the first walk, one linear // pass with no frame slots and no words in locals, for status-hint-coverage.sh's RED arm; brint-tool has no // such knob, so a link never writes its hints. // // THE STATUS-SITE CENSUS. `node wasm-branch-hints.mjs --census FILE` writes nothing. It prints one line per // (function, callee, kind, shape, hinted) with the number of sites of that kind: // census <1|0> // callee is the function the last call before a status check named (`indirect` for a call_indirect, `-` for a // poll), by name from the name section. hinted is read from FILE's own metadata.code.branch_hint section, so // the census of a shipped image says what ships. The shape is a contract: docs/STATUS-CHANNEL-CONTRACT.md // freezes the check as `i32.load; br_if`, and twice a change to the lowering moved it without anything // saying so (a static lua went from 1,903 hinted status branches to 2,754 unhintable br_tables when the // NORMAL edge lost its weight; wasm-opt moved 59-77% of them into `if` form). test/status-site-census.sh // compares a census with a recorded one, function by function. Each dispatch-shaped check the walk did not // recognize is listed as `unrecognized `. import fs from 'node:fs'; const census = process.argv[2] === '--census'; const file = process.argv[census ? 3 : 2]; const red = process.env.HWJS_BRANCH_HINTS_RED_LINEAR === '1'; if (red && process.env.WASMLD_HWJS_ALLOW_RED_KNOBS !== '1') throw new Error('wasm-branch-hints: HWJS_BRANCH_HINTS_RED_LINEAR=1 is a RED knob (the walk that misses checks): set WASMLD_HWJS_ALLOW_RED_KNOBS=1 too, or unset it'); if (process.env.HWJS_BRANCH_HINTS_RED_LINEAR && !['0', '1'].includes(process.env.HWJS_BRANCH_HINTS_RED_LINEAR)) throw new Error(`wasm-branch-hints: HWJS_BRANCH_HINTS_RED_LINEAR='${process.env.HWJS_BRANCH_HINTS_RED_LINEAR}' is a switch: 1, 0 or unset`); const b = fs.readFileSync(file); let p = 8; const leb = () => { let r = 0, s = 0, x; do { x = b[p++]; r += (x & 0x7f) * 2 ** s; s += 7; } while (x & 0x80); return r; }; const sleb = () => { let x; do { x = b[p++]; } while (x & 0x80); }; const sections = []; while (p < b.length) { const at = p, id = b[p++], size = leb(); sections.push({ id, at, start: p, size }); p += size; } let nImportedFns = 0, nImportedGlobals = 0, channel = -1; const imports = sections.find((s) => s.id === 2); if (imports) { p = imports.start; for (let n = leb(); n > 0; n--) { let l = leb(); p += l; l = leb(); const name = b.subarray(p, p + l).toString(); p += l; const kind = b[p++]; if (kind === 0) { leb(); nImportedFns++; } else if (kind === 1) { p++; const f = b[p++]; leb(); if (f & 1) leb(); } else if (kind === 2) { const f = b[p++]; leb(); if (f & 1) leb(); } else if (kind === 3) { if (name === '__hwjs_status_channel_addr') channel = nImportedGlobals; p += 2; nImportedGlobals++; } else throw new Error(`wasm-branch-hints: ${file}: import kind ${kind} at ${p - 1}`); } } const code = sections.find((s) => s.id === 10); if (channel < 0 || !code) { if (census) console.log(`census-summary: ${file}: no status channel`); process.exit(0); } // Function names (the census, and finding a resume clone's ramp), and for the census the hints the file // already carries (function -> offsets). const names = new Map(), carried = new Map(); const report = census || !!process.env.HWJS_BRANCH_HINTS_REPORT; for (const s of sections.filter((x) => x.id === 0)) { p = s.start; let l = leb(); const nm = b.subarray(p, p + l).toString(); p += l; const end = s.start + s.size; if (nm === 'name') { while (p < end) { const sub = b[p++], n = leb(), subEnd = p + n; if (sub === 1) for (let k = leb(); k > 0; k--) { const idx = leb(); l = leb(); names.set(idx, b.subarray(p, p + l).toString()); p += l; } p = subEnd; } } else if (nm === 'metadata.code.branch_hint' && census) { for (let k = leb(); k > 0; k--) { const f = leb(), offs = new Set(); for (let m = leb(); m > 0; m--) { offs.add(leb()); const w = leb(); p += w; } carried.set(f, offs); } } } const fnName = (i) => names.get(i) ?? `#${i}`; const sites = new Map(); const site = (fn, callee, kind, shape, hinted) => { const k = `${fnName(fn)}\t${callee}\t${kind}\t${shape}\t${hinted}`; sites.set(k, (sites.get(k) ?? 0) + 1); }; // What a local or the top of the stack holds: the channel's address; that address with a constant 12 above it // (on the stack only); the preempt word's address; a resume clone's frame; a status or preempt word, as loaded // or under an odd number of i32.eqz. const CHAN = 1, CHAN12 = 3, PREEMPT = 4, FRAME = 5, STATUS = 8, STATUS_NOT = 9, POLL = 10, POLL_NOT = 11; const isWord = (v) => v >= STATUS; const keeps = (v) => (red ? v === CHAN || v === PREEMPT : v !== 0 && v !== CHAN12); // Meet a path's facts into a join point's: what both say. null is no path (unreachable). const meet = (into, from) => { if (from === null) return into; if (into === null) return new Map(from); for (const [k, v] of into) if (from.get(k) !== v) into.delete(k); return into; }; const same = (x, y) => { if (x === null || y === null) return x === y; if (x.size !== y.size) return false; for (const [k, v] of x) if (y.get(k) !== v) return false; return true; }; const memarg = () => { const a = leb(); if (a & 0x40) leb(); return leb(); }; p = code.start; const nFns = leb(); const bodies = []; for (let i = 0; i < nFns; i++) { const size = leb(); bodies.push([p, p + size]); p += size; } // walk(i, slots): function i's status branches, with `slots` the frame offsets that hold the channel's address // (a resume clone) or null. Returns its hints, its census sites, the offsets it stores a channel value at, and // the dispatch-shaped checks with the ones it did not recognize. function walk(i, slots) { const [fnStart, end] = bodies[i]; p = fnStart; for (let n = leb(); n > 0; n--) { leb(); p++; } const bodyStart = p; const fn = nImportedFns + i, has = carried.get(fn); const header = new Map(); // loop offset -> the facts its back edges carried on the previous iteration for (let iter = 0; ; iter++) { if (iter > 4096) throw new Error(`wasm-branch-hints: ${file}: function ${i}: the loop facts did not settle in ${iter} iterations`); p = bodyStart; const backs = new Map(), hints = [], found = [], stores = new Set(), unrecognized = []; let st = 0, callee = '?', dispatch = 0; let state = new Map(slots ? [[0, FRAME]] : []); const ctl = [{ k: 'fn' }]; // The dispatch shape: the last two ops and their locals, then the check waiting for its br_table. let op1 = -1, l1 = -1, op2 = -1, l2 = -1, pend = null, step = 0; const branch = (L, facts) => { if (red || facts === null) return; const f = ctl[ctl.length - 1 - L]; if (!f) throw new Error(`wasm-branch-hints: ${file}: function ${i}: a branch to label ${L} outside the function`); if (f.k === 'loop') backs.set(f.at, meet(backs.get(f.at) ?? null, facts)); else if (f.k !== 'fn') f.out = meet(f.out, facts); }; const record = (shape, at) => { const kind = st === POLL || st === POLL_NOT ? 'poll' : 'status'; found.push([kind === 'poll' ? '-' : callee, kind, shape, census ? (has && has.has(at) ? 1 : 0) : (shape === 'br_if' ? 1 : 0)]); }; while (p < end) { const at = p, op = b[p++]; let next = 0, local = -1, c0 = -1; const live = red || state !== null; if (op === 0x04 && isWord(st) && live) record('if', at - fnStart); if (op === 0x02 || op === 0x03 || op === 0x04 || op === 0x06 || op === 0x1f) { const t = b[p]; if (t === 0x40 || (t & 0xc0) === 0x40) p++; else sleb(); if (op === 0x1f) for (let n = leb(); n > 0; n--) { const c = b[p++]; if (c <= 1) leb(); branch(leb(), new Map()); } if (op === 0x03) { const h = header.get(at); if (!red && state !== null && h !== undefined) state = meet(new Map(state), h); ctl.push({ k: 'loop', at }); } else if (op === 0x04) ctl.push({ k: 'if', out: null, entry: red || state === null ? state : new Map(state), alt: false }); else ctl.push({ k: 'block', out: null }); } else if (op === 0x05 || op === 0x07 || op === 0x19) { // else; catch and catch_all, whose handler is entered from anywhere in the try: nothing is known there. if (op === 0x07) leb(); const f = ctl[ctl.length - 1]; if (!red) { f.out = meet(f.out, state); state = op === 0x05 ? (f.entry === null ? null : new Map(f.entry)) : new Map(); } f.alt = true; } else if (op === 0x0b || op === 0x18) { if (op === 0x18) leb(); const f = ctl.pop(); if (!f) throw new Error(`wasm-branch-hints: ${file}: function ${i}: an end with no block open`); if (!red && f.k !== 'loop' && f.k !== 'fn') { if (f.k === 'if' && !f.alt) f.out = meet(f.out, f.entry); state = meet(f.out, state); } } else if (op === 0x00 || op === 0x0f || op === 0x0a) { if (!red) state = null; } else if (op === 0x08 || op === 0x09) { leb(); if (!red) state = null; } else if (op === 0x0c) { branch(leb(), state); if (!red) state = null; } else if (op === 0x0d) { const L = leb(); if (isWord(st) && live) { hints.push([at - fnStart, st === STATUS_NOT || st === POLL_NOT ? 1 : 0]); record('br_if', at - fnStart); } pend = op1 === 0x45 && (op2 === 0x20 || op2 === 0x22) ? { s: l2, at: at - fnStart, seen: isWord(st) && live } : null; step = 0; branch(L, state); } else if (op === 0x0e) { if (isWord(st) && live) record('br_table', at - fnStart); for (let n = leb(); n > 0; n--) branch(leb(), state); branch(leb(), state); if (!red) state = null; } else if (op === 0x10) { const t = leb(); callee = fnName(t); } else if (op === 0x12) { const t = leb(); callee = fnName(t); if (!red) state = null; } else if (op === 0x11) { leb(); leb(); callee = 'indirect'; } else if (op === 0x13) { leb(); leb(); callee = 'indirect'; if (!red) state = null; } else if (op === 0x1c) { for (let n = leb(); n > 0; n--) p++; } else if (op === 0x20) { local = leb(); next = state === null ? 0 : (state.get(local) ?? 0); } else if (op === 0x21 || op === 0x22) { local = leb(); if (op === 0x22) next = st; if (state !== null) { if (keeps(st)) state.set(local, st); else state.delete(local); } } else if (op === 0x24 || op === 0x25 || op === 0x26) leb(); else if (op === 0x23) { if (leb() === channel) next = CHAN; } else if (op === 0x28) { const off = memarg(); if (off === 0 && st === CHAN) next = STATUS; else if (st === FRAME && slots.has(off)) next = CHAN; } else if (op === 0x36) { const off = memarg(); if (st === CHAN && live) stores.add(off); } else if (op >= 0x29 && op <= 0x3e) memarg(); else if (op === 0x3f || op === 0x40 || op === 0xd0) p++; else if (op === 0x41) { c0 = b[p]; if (st === CHAN && c0 === 12) next = CHAN12; sleb(); } else if (op === 0x42) sleb(); else if (op === 0x6a) { if (st === CHAN12) next = PREEMPT; } else if (op === 0x43) p += 4; else if (op === 0x44) p += 8; else if (op === 0x45) { if (isWord(st)) next = st ^ 1; } else if (op === 0xd2) leb(); else if (op === 0xfc) { const s = leb(); if (s === 8) { leb(); p++; } else if (s === 9 || s === 13 || s === 15 || s === 16 || s === 17) leb(); else if (s === 10) p += 2; else if (s === 11) p++; else if (s === 12 || s === 14) { leb(); leb(); } } else if (op === 0xfe) { const s = leb(); if (s === 3) p++; else { const off = memarg(); if (s === 0x10 && ((off === 12 && st === CHAN) || (off === 0 && st === PREEMPT))) next = POLL; } } else if (op === 0xfd) { const s = leb(); if (s <= 11 || s === 92 || s === 93) memarg(); else if (s === 12 || s === 13) p += 16; else if (s >= 21 && s <= 34) p++; else if (s >= 84 && s <= 91) { memarg(); p++; } } // The dispatch shape, by bytes alone (the br_if that opens it was handled above): empty blocks, then // local.get s; i32.const -1|-2; i32.add; br_table. if (pend && op !== 0x0d) { if (step === 0 && op === 0x02 && b[at + 1] === 0x40) { /* an empty block between them */ } else if (step === 0 && op === 0x20 && local === pend.s) step = 1; else if (step === 1 && op === 0x41 && (c0 === 0x7f || c0 === 0x7e)) step = 2; else if (step === 2 && op === 0x6a) step = 3; else if (step === 3 && op === 0x0e) { dispatch++; if (!pend.seen) unrecognized.push(pend.at); pend = null; } else pend = null; if (!pend) step = 0; } op2 = op1; l2 = l1; op1 = op; l1 = local; st = next; } if (p !== end) throw new Error(`wasm-branch-hints: ${file}: function ${i} decoded to ${p}, its body ends at ${end}: an opcode this walk does not know`); // The loop headers: what every back edge carried, met with what the previous iteration assumed. Facts only // shrink, so this settles; the iteration that assumed the settled facts is the one that counts. let changed = false; for (const [at, facts] of backs) { const old = header.get(at); const now = old === undefined ? new Map(facts) : meet(new Map(old), facts); if (old === undefined || !same(old, now)) { header.set(at, now); changed = true; } } if (red || !changed) return { hints, found, stores, dispatch, unrecognized }; } } // Ramps first: a resume clone's frame slots are the offsets its ramp stored a channel value at. const nameCount = new Map(); for (const n of names.values()) nameCount.set(n, (nameCount.get(n) ?? 0) + 1); const byName = new Map(); for (const [idx, n] of names) if (nameCount.get(n) === 1) byName.set(n, idx); const results = new Array(nFns); const resumes = []; for (let i = 0; i < nFns; i++) { const n = names.get(nImportedFns + i); if (!red && n !== undefined && n.endsWith('.resume')) resumes.push(i); else results[i] = walk(i, null); } let nResume = 0, nSeeded = 0; for (const i of resumes) { nResume++; const n = names.get(nImportedFns + i), ramp = byName.get(n.slice(0, -'.resume'.length)); let slots = null; if (nameCount.get(n) === 1 && ramp !== undefined && ramp >= nImportedFns && results[ramp - nImportedFns]) { const s = results[ramp - nImportedFns].stores; if (s.size) { slots = s; nSeeded++; } } results[i] = walk(i, slots); } const out = []; let nHints = 0, nTables = 0, nIfs = 0, nDispatch = 0, nUnrec = 0; for (let i = 0; i < nFns; i++) { const r = results[i]; for (const s of r.found) { if (s[2] === 'br_if') nHints++; else if (s[2] === 'br_table') nTables++; else nIfs++; if (report) site(nImportedFns + i, ...s); } nDispatch += r.dispatch; nUnrec += r.unrecognized.length; if (r.hints.length) out.push([nImportedFns + i, r.hints]); } const extra = `dispatch=${nDispatch} dispatch_unrecognized=${nUnrec} resume=${nResume} resume_seeded=${nSeeded} names=${names.size}${red ? ' walk=red-linear' : ''}`; if (process.env.HWJS_BRANCH_HINTS_REPORT && !census) console.log(`branch-hints: ${file}: status-branches hinted=${nHints} br_table=${nTables} if=${nIfs} ${extra}`); if (report) { let n = 0, h = 0; const fns = new Set(), shape = { br_if: 0, br_table: 0, if: 0 }; for (const k of [...sites.keys()].sort()) { const c = sites.get(k), f = k.split('\t'); console.log(`census\t${k}\t${c}`); n += c; fns.add(f[0]); shape[f[3]] += c; if (f[4] === '1') h += c; } for (let i = 0; i < nFns; i++) for (const at of results[i].unrecognized) console.log(`unrecognized\t${fnName(nImportedFns + i)}\t${at}`); console.log(`census-summary: ${file}: functions=${fns.size} sites=${n} br_if=${shape.br_if} br_table=${shape.br_table} if=${shape.if} hinted=${h} unhinted=${n - h} ${extra}`); } if (census || !out.length) process.exit(0); const wleb = (v) => { const a = []; do { let x = v & 0x7f; v = Math.floor(v / 128); if (v) x |= 0x80; a.push(x); } while (v); return a; }; const name = Buffer.from('metadata.code.branch_hint'); const body = [...wleb(name.length), ...name, ...wleb(out.length)]; for (const [f, hs] of out) { body.push(...wleb(f), ...wleb(hs.length)); for (const [o, v] of hs) body.push(...wleb(o), 1, v); } const sec = Buffer.from([0, ...wleb(body.length), ...body]); const r = Buffer.concat([b.subarray(0, code.at), sec, b.subarray(code.at)]); new WebAssembly.Module(r); fs.writeFileSync(file, r);