Files
f30ec292fd Support the wasm SIMD proposal with native asm lowering (arm64/amd64) (#40)
* Support the wasm SIMD proposal with native asm lowering (arm64/amd64)

One revision spanning the SIMD (0xfd v128) proposal end to end: SSA
representation, lowering, scalar reference helpers, and a gcasm asm
backend that turns the hot paths into native SIMD — measured on a
full llama.cpp build transpiled to pure Go, which this makes run at
V8-class speed (prompt eval beats V8 on arm64).

Frontend and SSA:
- v128 values are [2]uint64 pairs in little-endian lane order; pure
  ops lower to CSE-able helper calls, memory ops keep statement
  order, v128.const/shuffle ride as [2]uint64 aux. The full scalar
  helper set is the reference semantics (saturation, NaN
  propagation, round-to-even, swizzle OOB, shift masking).
- Exception handling lowers to plain branches instead of
  panic/recover — a check-and-branch after each may-raise call, a
  per-try dispatch block running the catch-clause chain — covering
  the C++-shaped patterns (multi-clause catch, delegate targets,
  rethrow depths) without runtime unwinding, so EH bodies stay
  eligible for the asm backend. This replaces the closure/recover
  lowering that #39 extended; its tests are retained unchanged.
- Giant functions outline into tractable units (whole loops
  included, packed u64 boundaries for v128 values), keeping gc
  compile times and register pressure sane on llama.cpp-sized
  modules.

gcasm backend:
- SIMD helper calls splice inline as native NEON/SSE instead of
  marshalled calls; v128 SSA values travel register-to-register in
  pair form. Call-tree windows fuse into single splices with region
  invariant hoisting, bounds-check coalescing, store sinks and
  scalar-chain internalization; whole countdown loops fuse with an
  in-splice unroll lane.
- Superinstruction selection inside fused regions: 8-bit dot
  patterns (SMULL+SADALP), SDOT for full 16-byte dots, FMUL by
  element, scale-lookup addressing, inlined integer division, the
  software fp32->fp16 idiom lowered to FCVT (both the table-gather
  and the packed store form), and ggml q8_0 row/column pairing via
  the traits nrows patch with an SMMLA 2x2 tile kernel.
- Runtime CPU-feature dispatch gates spliced bodies (dotprod on
  arm64, x86-64-v2 SSE on amd64); WASM2GO_FAST_MATH opts into
  raw-SDOT/FMLA/dual-accumulator forms that trade wasm bit-exactness
  for native-build-style rounding, validated by token-level
  equivalence against native llama.cpp.
- Guard-page linear memory eliminates per-access bounds checks;
  jump tables replace the compare tree for br_table.

Tooling and CI:
- WASM2GO_F16_TABLE asserts the address of ggml's runtime-built f16
  table; the transpiler warns when the asserted address matches no
  gather site (the address moves with every data-layout shift, and a
  stale assertion silently costs ~7% decode throughput).
- The coverage gate runs with -count=1: a cached package result
  merges incomplete coverage data into the -coverpkg profile,
  deflating the total by 10+ points depending on what the runner's
  restored cache contained — the gate must never consume cached
  results.
- Coverage threshold moves to 83% for the enlarged tree; transpile
  output is deterministic and outline rejections are explained in
  the build log.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Replace environment-variable switches with typed Options; drop debug code

Configuration now flows through one channel: transpile.Options gains
OutlineMinValues, SIMDUnroll, FuseLoops, FuseLoopUnroll, F16TableAddr
and FastMath (with matching CLI flags), the gcasm backend receives
them as a Config threaded through ModuleOffsets, and no code path
branches on an environment variable anymore. Integrator entry points
(the wasmify protoc plugin, the CLI) convert their external
configuration into these options exactly once.

Deleted outright, per the no-env rule and because they were
diagnostics rather than build modes:
- every WASM2GO_NO_* kill switch and bisection knob (SSA pass
  disabling, fallback ranges, fuse-window caps, outline limits,
  inliner windows) — git history keeps them for the next hunt;
- every env-gated debug printer (fuse/inline/outline/nrc2/f16/SSA
  dumps and the near-miss tracers) and the capture-tree keepers;
- the dormant multi-exit loop structuring (opt-in, measured slower)
  and the SSA f32->f16 rewrite entry superseded by the gcasm
  peephole (its shared idiom matchers stay for the f16 store pass);
- the runtime WASM2GO_CPU_PORTABLE override in the generated CPU
  feature probes.

The nil-offsets error paths exposed by the threading get nil-safe
Config accessors, and the outline share/v128-min/inliner caps become
plain constants at their measured production values.

Behavior under default options is unchanged: transpiled output for
the non-SIMD and EH fixtures is byte-identical to the previous
commit, and the only SIMD-bundle difference is the removed env check
in the emitted cpufeat runtime files.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 23:28:14 +09:00

247 lines
6.8 KiB
Go

package lower
import (
"github.com/goccy/wasm2go/internal/wasm"
)
// ThrowSet answers "can a call to this function leave an exception
// pending?" — the question the branch-based EH lowering asks at every call
// site to decide whether to emit a check-and-branch.
//
// A function may throw when its body contains `throw` or `rethrow`, when it
// calls a may-throw function, or when it performs a `call_indirect` whose
// type could resolve to one (conservatively: any indirect call to a
// signature some may-throw function has). Host imports never throw: a wasm
// exception can only be raised by wasm code, and the generated host
// interfaces have no way to set the pending state.
//
// Being conservative only costs a predictable branch on a flag that is
// almost always false, so the analysis stays simple: no attempt is made to
// prove that an enclosing catch_all swallows everything.
type ThrowSet struct {
may map[uint32]bool // function index → may leave an exception pending
indirectTypes map[uint32]bool // type index → some may-throw function has it
anyIndirect bool // any may-throw function is a call_indirect target
}
// MayThrow reports whether calling funcIdx can leave an exception pending.
func (t *ThrowSet) MayThrow(funcIdx uint32) bool {
if t == nil {
return true // no analysis available: assume the worst
}
return t.may[funcIdx]
}
// IndirectMayThrow reports whether a call_indirect of the given type index
// can leave an exception pending.
func (t *ThrowSet) IndirectMayThrow(typeIdx uint32) bool {
if t == nil {
return true
}
return t.indirectTypes[typeIdx]
}
// AnyThrows reports whether the module contains any throwing code at all.
// When false the whole EH machinery (module state, call-site checks) can be
// skipped.
func (t *ThrowSet) AnyThrows() bool { return t != nil && len(t.may) > 0 }
// ComputeThrowSet runs the analysis over a module. callees maps a function
// index to the indices it calls directly (the call graph codegen already
// builds); when nil the direct-call edges are rescanned here.
func ComputeThrowSet(mod *wasm.Module, callees map[uint32][]uint32) (*ThrowSet, error) {
ts := &ThrowSet{may: map[uint32]bool{}, indirectTypes: map[uint32]bool{}}
// Seed: functions whose own body raises. Also record which of them can
// be reached indirectly, and whether any body uses call_indirect at all
// (a may-throw callee reached that way propagates to its caller).
hasIndirect := map[uint32]bool{}
for i := range mod.Functions {
idx := mod.NumImportedFuncs + uint32(i)
raises, indirect, err := scanThrowOps(mod.Functions[i].Body)
if err != nil {
return nil, err
}
if raises {
ts.may[idx] = true
}
hasIndirect[idx] = indirect
}
if len(ts.may) == 0 {
return ts, nil // module has no EH at all
}
// Propagate along the call graph to a fixpoint. The graph is small
// relative to the body scan, so a simple worklist is plenty.
if callees == nil {
callees = map[uint32][]uint32{}
for i := range mod.Functions {
idx := mod.NumImportedFuncs + uint32(i)
cs, err := scanDirectCallees(mod.Functions[i].Body)
if err != nil {
return nil, err
}
callees[idx] = cs
}
}
callers := map[uint32][]uint32{}
for caller, cs := range callees {
for _, callee := range cs {
callers[callee] = append(callers[callee], caller)
}
}
work := make([]uint32, 0, len(ts.may))
for idx := range ts.may {
work = append(work, idx)
}
for len(work) > 0 {
idx := work[len(work)-1]
work = work[:len(work)-1]
for _, c := range callers[idx] {
if !ts.may[c] {
ts.may[c] = true
work = append(work, c)
}
}
}
// Indirect edges: any may-throw function that appears in an element
// segment makes its signature (and every caller doing call_indirect of
// that signature) may-throw. Iterate until stable, since a newly
// may-throw caller can itself be an indirect target.
elemTargets := map[uint32]bool{}
for _, seg := range mod.Elements {
for _, fi := range seg.FuncIdxs {
elemTargets[fi] = true
}
}
for {
changed := false
for idx := range elemTargets {
if !ts.may[idx] || idx < mod.NumImportedFuncs {
continue
}
ti := mod.Functions[idx-mod.NumImportedFuncs].TypeIdx
if !ts.indirectTypes[ti] {
ts.indirectTypes[ti] = true
ts.anyIndirect = true
changed = true
}
}
if !changed {
break
}
// A caller whose call_indirect can now reach a may-throw target
// becomes may-throw itself; that may in turn open new indirect
// signatures on the next round.
for i := range mod.Functions {
idx := mod.NumImportedFuncs + uint32(i)
if ts.may[idx] || !hasIndirect[idx] {
continue
}
reaches, err := indirectReachesThrow(mod.Functions[i].Body, ts)
if err != nil {
return nil, err
}
if reaches {
ts.may[idx] = true
work = append(work, idx)
}
}
for len(work) > 0 {
idx := work[len(work)-1]
work = work[:len(work)-1]
for _, c := range callers[idx] {
if !ts.may[c] {
ts.may[c] = true
work = append(work, c)
}
}
}
}
return ts, nil
}
// scanThrowOps reports whether a body raises an exception itself and
// whether it contains any call_indirect.
func scanThrowOps(body []byte) (raises, indirect bool, err error) {
r := wasm.NewInstrReader(body)
if err := skipLocalDecls(r); err != nil {
return false, false, err
}
for !r.EOF() {
op, err := r.ReadByte()
if err != nil {
return false, false, err
}
switch op {
case wasm.OpThrow, wasm.OpRethrow:
raises = true
case wasm.OpCallIndirect:
indirect = true
}
if err := r.SkipImmediates(op); err != nil {
return false, false, err
}
}
return raises, indirect, nil
}
func scanDirectCallees(body []byte) ([]uint32, error) {
r := wasm.NewInstrReader(body)
if err := skipLocalDecls(r); err != nil {
return nil, err
}
var out []uint32
for !r.EOF() {
op, err := r.ReadByte()
if err != nil {
return nil, err
}
if op == wasm.OpCall {
idx, err := r.ReadU32()
if err != nil {
return nil, err
}
out = append(out, idx)
continue
}
if err := r.SkipImmediates(op); err != nil {
return nil, err
}
}
return out, nil
}
// indirectReachesThrow reports whether the body performs a call_indirect
// whose type is one a may-throw function has.
func indirectReachesThrow(body []byte, ts *ThrowSet) (bool, error) {
r := wasm.NewInstrReader(body)
if err := skipLocalDecls(r); err != nil {
return false, err
}
for !r.EOF() {
op, err := r.ReadByte()
if err != nil {
return false, err
}
if op == wasm.OpCallIndirect {
ti, err := r.ReadU32()
if err != nil {
return false, err
}
if _, err := r.ReadU32(); err != nil { // table index
return false, err
}
if ts.indirectTypes[ti] {
return true, nil
}
continue
}
if err := r.SkipImmediates(op); err != nil {
return false, err
}
}
return false, nil
}