mirror of
https://github.com/hanzoai/wasm2go.git
synced 2026-10-30 15:06:48 +00:00
* 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]>
160 lines
5.2 KiB
Go
160 lines
5.2 KiB
Go
package lower
|
|
|
|
import (
|
|
"bytes"
|
|
"testing"
|
|
|
|
"github.com/goccy/wasm2go/internal/ssa"
|
|
"github.com/goccy/wasm2go/internal/testfixture"
|
|
"github.com/goccy/wasm2go/internal/wasm"
|
|
)
|
|
|
|
// TestLowerSwitch3 covers the switch3 export — a br_table dispatcher.
|
|
// br_table lowers to a chain of equality-If blocks, so the lowering
|
|
// should succeed and produce a CFG dominated by goto-based emission.
|
|
func TestLowerSwitch3(t *testing.T) {
|
|
bin := testfixture.Wasm(t, "control")
|
|
mod, err := wasm.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("parse: %v", err)
|
|
}
|
|
idx := ^uint32(0)
|
|
for _, e := range mod.Exports {
|
|
if e.Kind == wasm.ExportFunc && e.Name == "switch3" {
|
|
idx = e.Index
|
|
break
|
|
}
|
|
}
|
|
if idx == ^uint32(0) {
|
|
t.Skip("switch3 not exported")
|
|
}
|
|
if _, err := LowerFunction(mod, idx, "switch3", testThrowSet(mod)); err != nil {
|
|
t.Fatalf("lower switch3: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestLowerBrTableLoopArity is a regression test for a br_table whose
|
|
// targets have different RESULT arities but the same BRANCH (label) arity —
|
|
// the pattern a computed-goto dispatch emits and which previously
|
|
// made lowering fail with "br_table target N has arity 0, default has 1".
|
|
//
|
|
// The hand-built function is:
|
|
//
|
|
// (func (param i32) (result i32)
|
|
// (block ;; $b: result [] -> branch arity 0
|
|
// (loop (result i32) ;; $l: result [i32] -> resultCount 1, but branch
|
|
// ;; arity 0 (a branch jumps to the header,
|
|
// ;; which consumes the loop's 0 params)
|
|
// local.get 0
|
|
// br_table 1 0 ;; case0 -> $b (block), default -> $l (loop)
|
|
// )
|
|
// )
|
|
// i32.const 0)
|
|
//
|
|
// The br_table mixes a block target (result arity 0) with a loop default
|
|
// (result arity 1). Before the fix the validator compared result arities
|
|
// (0 != 1) and rejected it; with branchArity() both are 0, so it lowers.
|
|
func TestLowerBrTableLoopArity(t *testing.T) {
|
|
bin := []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic + version
|
|
// type section: (param i32) (result i32)
|
|
0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
|
|
// function section: func0 : type0
|
|
0x03, 0x02, 0x01, 0x00,
|
|
// export section: "f" = func0
|
|
0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00,
|
|
// code section
|
|
0x0a, 0x12, 0x01, // section id, size, func count
|
|
0x10, // body size
|
|
0x00, // 0 local decls
|
|
0x02, 0x40, // block (empty blocktype)
|
|
0x03, 0x7f, // loop (result i32)
|
|
0x20, 0x00, // local.get 0
|
|
0x0e, 0x01, 0x01, 0x00, // br_table [1] default 0
|
|
0x0b, // end loop
|
|
0x0b, // end block
|
|
0x41, 0x00, // i32.const 0
|
|
0x0b, // end func
|
|
}
|
|
mod, err := wasm.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("parse: %v", err)
|
|
}
|
|
if _, err := LowerFunction(mod, 0, "f", testThrowSet(mod)); err != nil {
|
|
t.Fatalf("lower br_table-loop-arity func: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestLowerBrTableBlockKind pins the arity-0 br_table lowering to a
|
|
// single BlockBrTable: one successor per UNIQUE target, TableCases
|
|
// mapping selector values to successors, and the default index set.
|
|
// The hand-built function reuses TestLowerBrTableLoopArity's shape
|
|
// with a 3-case table where two cases and the default share targets:
|
|
//
|
|
// br_table [1 1 0] default 0
|
|
// case 0, case 1 -> $b (block) — one succ, cases [0 1]
|
|
// case 2, default -> $l (loop) — one succ, cases [2] + default
|
|
func TestLowerBrTableBlockKind(t *testing.T) {
|
|
bin := []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic + version
|
|
// type section: (param i32) (result i32)
|
|
0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
|
|
// function section: func0 : type0
|
|
0x03, 0x02, 0x01, 0x00,
|
|
// export section: "f" = func0
|
|
0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00,
|
|
// code section
|
|
0x0a, 0x14, 0x01, // section id, size, func count
|
|
0x12, // body size
|
|
0x00, // 0 local decls
|
|
0x02, 0x40, // block (empty blocktype)
|
|
0x03, 0x7f, // loop (result i32)
|
|
0x20, 0x00, // local.get 0
|
|
0x0e, 0x03, 0x01, 0x01, 0x00, 0x00, // br_table [1 1 0] default 0
|
|
0x0b, // end loop
|
|
0x0b, // end block
|
|
0x41, 0x00, // i32.const 0
|
|
0x0b, // end func
|
|
}
|
|
mod, err := wasm.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("parse: %v", err)
|
|
}
|
|
f, err := LowerFunction(mod, 0, "f", testThrowSet(mod))
|
|
if err != nil {
|
|
t.Fatalf("lower: %v", err)
|
|
}
|
|
var bt *ssa.Block
|
|
for _, b := range f.Blocks {
|
|
if b.Kind == ssa.BlockBrTable {
|
|
if bt != nil {
|
|
t.Fatalf("more than one BlockBrTable")
|
|
}
|
|
bt = b
|
|
}
|
|
}
|
|
if bt == nil {
|
|
t.Fatalf("no BlockBrTable produced; arity-0 br_table should not lower to an If chain:\n%s", ssa.FuncString(f))
|
|
}
|
|
if len(bt.Succs) != 2 {
|
|
t.Fatalf("want 2 deduped successors, got %d:\n%s", len(bt.Succs), ssa.FuncString(f))
|
|
}
|
|
if bt.Control == nil || bt.Control.Type != ssa.TypeI32 {
|
|
t.Fatalf("BrTable control missing or not i32")
|
|
}
|
|
// Succ 0 = the block target (cases 0,1); succ 1 = the loop header
|
|
// (case 2 + default).
|
|
if got := bt.TableCases[0]; len(got) != 2 || got[0] != 0 || got[1] != 1 {
|
|
t.Fatalf("succ0 cases = %v, want [0 1]", got)
|
|
}
|
|
if got := bt.TableCases[1]; len(got) != 1 || got[0] != 2 {
|
|
t.Fatalf("succ1 cases = %v, want [2]", got)
|
|
}
|
|
if bt.TableDefault != 1 {
|
|
t.Fatalf("TableDefault = %d, want 1", bt.TableDefault)
|
|
}
|
|
if err := ssa.Verify(f); err != nil {
|
|
t.Fatalf("verify: %v", err)
|
|
}
|
|
}
|