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]>
120 lines
3.7 KiB
Go
120 lines
3.7 KiB
Go
package pass
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/goccy/wasm2go/internal/ssa"
|
|
)
|
|
|
|
// buildF16GatherFunc constructs the scalar-load form of the f16
|
|
// table-gather idiom the way the llama module carries it: four
|
|
// i32.load16_u at base+0/2/4/6 (the +2k as explicit adds), each
|
|
// shifted by 2, offset by the table base (lane 0's table rides the
|
|
// zero-load's memarg), rebuilt into an f32x4 by lane loads.
|
|
func buildF16GatherFunc() (*ssa.Func, *ssa.Value, [3]*ssa.Value, [4]*ssa.Value) {
|
|
b := ssa.NewFuncBuilder("Fn7", ssa.FuncSig{Params: []ssa.Type{ssa.TypeI32}, Results: []ssa.Type{ssa.TypeI32}})
|
|
f := b.Func()
|
|
entry := b.NewBlock(ssa.BlockRet)
|
|
b.SetEntry(entry)
|
|
b.SetCurrent(entry)
|
|
|
|
base := b.NewValueAuxInt(ssa.OpParam, ssa.TypeI32, 0)
|
|
c2 := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, 2)
|
|
tbl := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, 9013200)
|
|
zero := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, 0)
|
|
|
|
var lds [4]*ssa.Value
|
|
var addrs [4]*ssa.Value
|
|
for k := int64(0); k < 4; k++ {
|
|
a := base
|
|
if k > 0 {
|
|
off := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, 2*k)
|
|
a = b.NewValue(ssa.OpAdd32, ssa.TypeI32, base, off)
|
|
}
|
|
lds[k] = b.NewValueAuxInt(ssa.OpLoad16U, ssa.TypeI32, 0, a)
|
|
shl := b.NewValue(ssa.OpShl32, ssa.TypeI32, lds[k], c2)
|
|
if k == 0 {
|
|
addrs[k] = shl // table rides the zero-load's memarg
|
|
} else {
|
|
addrs[k] = b.NewValue(ssa.OpAdd32, ssa.TypeI32, shl, tbl)
|
|
}
|
|
}
|
|
var loads [3]*ssa.Value
|
|
loads[0] = b.NewValueAux(ssa.OpSimdMemCall, ssa.TypeV128, "simd_v128_load32_zero", addrs[0], tbl)
|
|
prev := loads[0]
|
|
var lanes [3]*ssa.Value
|
|
for k := int64(1); k <= 3; k++ {
|
|
lane := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, k)
|
|
v := b.NewValueAux(ssa.OpSimdMemCall, ssa.TypeV128, "simd_v128_load32_lane", addrs[k], zero, lane, prev)
|
|
if k < 3 {
|
|
loads[k] = v
|
|
} else {
|
|
lanes[2] = v
|
|
}
|
|
prev = v
|
|
}
|
|
tail := prev
|
|
// Keep the tail alive: extract a lane as the return value.
|
|
l3 := b.NewValueAuxInt(ssa.OpConst32, ssa.TypeI32, 3)
|
|
res := b.NewValueAux(ssa.OpSimdCall, ssa.TypeI32, "simd_i32x4_extract_lane", tail, l3)
|
|
entry.Control = res
|
|
return f, tail, loads, lds
|
|
}
|
|
|
|
func TestRecognizeF16Gather(t *testing.T) {
|
|
f, tail, loads, lds := buildF16GatherFunc()
|
|
verified := 0
|
|
ok := RecognizeF16Gather(f, func(base uint32) bool {
|
|
verified++
|
|
return base == 9013200
|
|
})
|
|
if !ok {
|
|
t.Fatal("gather not recognized")
|
|
}
|
|
if verified == 0 {
|
|
t.Error("table verification not consulted")
|
|
}
|
|
if tail.Op != ssa.OpSimdCall {
|
|
t.Fatalf("tail op = %s, want OpSimdCall", tail.Op)
|
|
}
|
|
if n, _ := tail.Aux.(string); n != "simd_f16x4_cvt" {
|
|
t.Fatalf("tail aux = %q, want simd_f16x4_cvt", tail.Aux)
|
|
}
|
|
if len(tail.Args) != 1 {
|
|
t.Fatalf("tail args = %d, want 1", len(tail.Args))
|
|
}
|
|
v := tail.Args[0]
|
|
if v.Op != ssa.OpSimdMemCall {
|
|
t.Fatalf("source op = %s, want the synthesized widening load", v.Op)
|
|
}
|
|
if n, _ := v.Aux.(string); n != "simd_v128_load16x4_u" {
|
|
t.Fatalf("source aux = %q, want simd_v128_load16x4_u", v.Aux)
|
|
}
|
|
// The inner lane loads are neutered to constants (they are pinned
|
|
// mem ops DCE would otherwise keep), and the consumed scalar loads
|
|
// become dead constants too.
|
|
for i, l := range loads {
|
|
if l.Op != ssa.OpSimdConst {
|
|
t.Errorf("inner load %d: op = %s, want OpSimdConst", i, l.Op)
|
|
}
|
|
}
|
|
for i, l := range lds {
|
|
if l.Op != ssa.OpConst32 {
|
|
t.Errorf("scalar load %d: op = %s, want OpConst32", i, l.Op)
|
|
}
|
|
}
|
|
if err := ssa.Verify(f); err != nil {
|
|
t.Fatalf("post-rewrite verify: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestRecognizeF16GatherUnverifiedTable(t *testing.T) {
|
|
f, tail, _, _ := buildF16GatherFunc()
|
|
if RecognizeF16Gather(f, func(uint32) bool { return false }) {
|
|
t.Fatal("rewrite happened without table verification")
|
|
}
|
|
if tail.Op != ssa.OpSimdMemCall {
|
|
t.Fatalf("tail mutated: %s", tail.Op)
|
|
}
|
|
}
|