Files
wasm2go/internal/codegen/helpers/simd_scalar_rest_amd64.go
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

394 lines
7.5 KiB
Go

// Code generated by tools/gen-simd-asm/gen.py; DO NOT EDIT.
//
// The scalar bodies this arch still needs: every op its assembly
// does not cover, plus the shared lane/saturation utilities. The
// full reference set lives in simd_scalar.go, which is tagged out
// of the asm arches to keep generated Go small.
//go:build amd64.v2 && !simdmatrix
package helpers
import "math"
import "math/bits"
var _ = bits.OnesCount8
var _ = math.Sqrt
func simdToU8(v [2]uint64) (r [16]uint8) {
for i := range r {
r[i] = uint8(v[i>>3] >> (8 * uint(i&7)))
}
return
}
func simdFromU8(r [16]uint8) (v [2]uint64) {
for i, b := range r {
v[i>>3] |= uint64(b) << (8 * uint(i&7))
}
return
}
func simdToU16(v [2]uint64) (r [8]uint16) {
for i := range r {
r[i] = uint16(v[i>>2] >> (16 * uint(i&3)))
}
return
}
func simdFromU16(r [8]uint16) (v [2]uint64) {
for i, x := range r {
v[i>>2] |= uint64(x) << (16 * uint(i&3))
}
return
}
func simdToU32(v [2]uint64) (r [4]uint32) {
for i := range r {
r[i] = uint32(v[i>>1] >> (32 * uint(i&1)))
}
return
}
func simdFromU32(r [4]uint32) (v [2]uint64) {
for i, x := range r {
v[i>>1] |= uint64(x) << (32 * uint(i&1))
}
return
}
func simdToF32(v [2]uint64) (r [4]float32) {
u := simdToU32(v)
for i := range r {
r[i] = math.Float32frombits(u[i])
}
return
}
func simdFromF32(r [4]float32) [2]uint64 {
var u [4]uint32
for i := range r {
u[i] = math.Float32bits(r[i])
}
return simdFromU32(u)
}
func simdToF64(v [2]uint64) [2]float64 {
return [2]float64{math.Float64frombits(v[0]), math.Float64frombits(v[1])}
}
func simdFromF64(r [2]float64) [2]uint64 {
return [2]uint64{math.Float64bits(r[0]), math.Float64bits(r[1])}
}
func simdBoolLane64(b bool) uint64 {
if b {
return ^uint64(0)
}
return 0
}
// Saturation clamps.
func simdSatI8(x int32) int8 {
if x > 127 {
return 127
}
if x < -128 {
return -128
}
return int8(x)
}
func simdSatU8(x int32) uint8 {
if x > 255 {
return 255
}
if x < 0 {
return 0
}
return uint8(x)
}
func simdSatI16(x int32) int16 {
if x > 32767 {
return 32767
}
if x < -32768 {
return -32768
}
return int16(x)
}
func simdSatU16(x int32) uint16 {
if x > 65535 {
return 65535
}
if x < 0 {
return 0
}
return uint16(x)
}
// Wasm float min/max (NaN-propagating, -0 < +0) and pmin/pmax
// (pseudo-min/max: plain b<a / a<b selects).
// simdPropNaN64 / simdPropNaN32 mirror the ARM FPProcessNaNs priority the
// asm bodies inherit from FMIN/FMAX: a signaling NaN in the first operand
// wins, then a signaling second, then a quiet first, then a quiet second —
// always quieted. Wasm permits any arithmetic NaN here; matching the
// hardware exactly keeps the asm-vs-scalar differential bit-exact.
func simdPropNaN64(a, b float64) (float64, bool) {
const quiet = uint64(1) << 51
ab, bb := math.Float64bits(a), math.Float64bits(b)
aNaN := a != a
bNaN := b != b
if !aNaN && !bNaN {
return 0, false
}
aSig := aNaN && ab&quiet == 0
bSig := bNaN && bb&quiet == 0
switch {
case aSig:
return math.Float64frombits(ab | quiet), true
case bSig:
return math.Float64frombits(bb | quiet), true
case aNaN:
return a, true
default:
return b, true
}
}
func simdPropNaN32(a, b float32) (float32, bool) {
const quiet = uint32(1) << 22
ab, bb := math.Float32bits(a), math.Float32bits(b)
aNaN := a != a
bNaN := b != b
if !aNaN && !bNaN {
return 0, false
}
aSig := aNaN && ab&quiet == 0
bSig := bNaN && bb&quiet == 0
switch {
case aSig:
return math.Float32frombits(ab | quiet), true
case bSig:
return math.Float32frombits(bb | quiet), true
case aNaN:
return a, true
default:
return b, true
}
}
func simdFMin64(a, b float64) float64 {
if n, ok := simdPropNaN64(a, b); ok {
return n
}
if a == b { // ±0: min is -0 if either is -0
if math.Signbit(a) {
return a
}
return b
}
if a < b {
return a
}
return b
}
func simdFMax64(a, b float64) float64 {
if n, ok := simdPropNaN64(a, b); ok {
return n
}
if a == b { // ±0: max is +0 if either is +0
if math.Signbit(a) {
return b
}
return a
}
if a > b {
return a
}
return b
}
func simdFMin32(a, b float32) float32 {
if n, ok := simdPropNaN32(a, b); ok {
return n
}
if a == b {
if math.Signbit(float64(a)) {
return a
}
return b
}
if a < b {
return a
}
return b
}
func simdFMax32(a, b float32) float32 {
if n, ok := simdPropNaN32(a, b); ok {
return n
}
if a == b {
if math.Signbit(float64(a)) {
return b
}
return a
}
if a > b {
return a
}
return b
}
func simd_i8x16_extract_lane_s_scalar(v [2]uint64, lane int32) int32 {
return int32(int8(simdToU8(v)[lane]))
}
func simd_i8x16_extract_lane_u_scalar(v [2]uint64, lane int32) int32 {
return int32(simdToU8(v)[lane])
}
func simd_i8x16_replace_lane_scalar(v [2]uint64, lane int32, x int32) [2]uint64 {
b := simdToU8(v)
b[lane] = uint8(x)
return simdFromU8(b)
}
func simd_i16x8_extract_lane_s_scalar(v [2]uint64, lane int32) int32 {
return int32(int16(simdToU16(v)[lane]))
}
func simd_i16x8_extract_lane_u_scalar(v [2]uint64, lane int32) int32 {
return int32(simdToU16(v)[lane])
}
func simd_i16x8_replace_lane_scalar(v [2]uint64, lane int32, x int32) [2]uint64 {
b := simdToU16(v)
b[lane] = uint16(x)
return simdFromU16(b)
}
func simd_i32x4_extract_lane_scalar(v [2]uint64, lane int32) int32 {
return int32(simdToU32(v)[lane])
}
func simd_i32x4_replace_lane_scalar(v [2]uint64, lane int32, x int32) [2]uint64 {
b := simdToU32(v)
b[lane] = uint32(x)
return simdFromU32(b)
}
func simd_i64x2_extract_lane_scalar(v [2]uint64, lane int32) int64 {
return int64(v[lane])
}
func simd_i64x2_replace_lane_scalar(v [2]uint64, lane int32, x int64) [2]uint64 {
v[lane] = uint64(x)
return v
}
func simd_f32x4_extract_lane_scalar(v [2]uint64, lane int32) float32 {
return simdToF32(v)[lane]
}
func simd_f32x4_replace_lane_scalar(v [2]uint64, lane int32, x float32) [2]uint64 {
b := simdToF32(v)
b[lane] = x
return simdFromF32(b)
}
func simd_f64x2_extract_lane_scalar(v [2]uint64, lane int32) float64 {
return simdToF64(v)[lane]
}
func simd_f64x2_replace_lane_scalar(v [2]uint64, lane int32, x float64) [2]uint64 {
v[lane] = math.Float64bits(x)
return v
}
func simd_f16x4_cvt_bits_scalar(a [2]uint64) int64 {
var out uint64
for i := 0; i < 4; i++ {
w := uint32(a[i/2] >> (32 * uint(i) % 64))
shl1w := w + w
sign := w & 0x80000000
var h uint32
if shl1w > 0xFF000000 { // NaN
h = (sign >> 16) | 0x7E00
} else {
bias := shl1w & 0xFF000000
if bias < 0x71000000 {
bias = 0x71000000
}
f := math.Float32frombits(w&0x7FFFFFFF) * 0x1p+112 * 0x1p-110
f += math.Float32frombits((bias >> 1) + 0x07800000)
fbits := math.Float32bits(f)
h = (sign >> 16) | (fbits>>13)&0x7C00 + fbits&0xFFF
}
out |= uint64(uint16(h)) << (16 * uint(i))
}
return int64(out)
}
func simd_i64x2_mul_scalar(a, b [2]uint64) [2]uint64 { return [2]uint64{a[0] * b[0], a[1] * b[1]} }
func simd_i64x2_shr_s_scalar(a [2]uint64, s int32) [2]uint64 {
sh := uint(s) % 64
return [2]uint64{uint64(int64(a[0]) >> sh), uint64(int64(a[1]) >> sh)}
}
func simdSatI16From32(x int32) int16 {
if x > 32767 {
return 32767
}
if x < -32768 {
return -32768
}
return int16(x)
}
func simdSatU16From32(x int32) uint16 {
if x > 65535 {
return 65535
}
if x < 0 {
return 0
}
return uint16(x)
}
func simdTruncSatI32(x float64) int32 {
if x != x {
return 0
}
x = math.Trunc(x)
if x >= 2147483647 {
return 2147483647
}
if x <= -2147483648 {
return -2147483648
}
return int32(x)
}
func simdTruncSatU32(x float64) uint32 {
if x != x {
return 0
}
x = math.Trunc(x)
if x >= 4294967295 {
return 4294967295
}
if x <= 0 {
return 0
}
return uint32(x)
}