cultmath map: Pass 9c (-Od temporaries, by-value lowering, HLSL-equal gate); od-temporaries probes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-17 12:45:42 +02:00
commit 774bebb0d3
3 changed files with 203 additions and 16 deletions

View file

@ -2299,6 +2299,47 @@ and 16:50 UTC (18:30 to 18:50 CEST). Logs are in the Imagination scratchpad
combinations as ES 3.00. The source has 13 `static const` lines, all of the form
`static const float CULTMATH_X = <literal>;`. None of them reaches the output, and today's GLSL
holds 13.
- **What `-Od` leaves, and what cleans it (Pass 9c).** Imagination `imagination-ag4-od-temps`,
2026-10-17, on e626bf26 (188 wrappers, 140 names, 117 families), ubuntu:24.04 on Yggdrasil, 10:05 to
10:35 UTC (12:05 to 12:35 CEST), dxc v1.9.2607, SPIRV-Cross and SPIRV-Tools both built from
`vulkan-sdk-1.4.363.0` (spirv-opt v2026.4), log `od-temps/imag-od7.log` in the session scratchpad,
probe in `docs/research/native-shader-probes/od-temporaries/`. Pass 9b's route as ruled, with no
further step, emits:
- 2824 lines, 86129 bytes, 188 `cultmath_` definitions, 140 names, no suffixed names. The
committed files are 1663 lines of one-line bodies, so line counts do not compare; SPIRV-Cross
prints every body in Allman style.
- Named locals survive, so most functions read like the source. Two things do not. First, 472
`param_var_*` copies: dxc passes every parameter as a pointer and the caller copies in. Second,
11 functions assign to a parameter in their body (`smootherstep`, `integral_clamp_linear`,
`fbm_grad`, `ridged_grad`, both Bezier pairs, `span_stage`, `iv_fbm_ball`, `af_fbm`) and come out
`inout`. The HLSL has no `out` or `inout` anywhere.
- That `inout` is a defect in the route, not a blemish. glslang refuses a consumer call with a
value, `cultmath_smootherstep(x + 1.0)` ("l-value required"), and a call with a variable
rewrites the caller's variable. Pass 9b's bit-identical result held because the families call
through their own copies. Overloads that look native must also take values like native ones.
- NaN-safe `min` and `max` expansions (`mix(mix(max(a, b), b, isnan(a)), a, isnan(b))`) from
`NMin` and `NMax`.
- Six `spirv-opt` pass lists on the edited module alone (`--convert-local-access-chains`,
`--ssa-rewrite`, `--eliminate-local-single-block`, `--eliminate-local-single-store`,
`--eliminate-local-multi-store`, `--simplify-instructions`, `--eliminate-dead-branches`,
`--merge-blocks`, `--vector-dce`, `--redundancy-elimination`, `--scalar-replacement`,
`--copy-propagate-arrays`, each with `--eliminate-dead-code-aggressive`) are valid and keep 188
functions, but make the text bigger (2870 to 2930 lines) and swap named locals for `_N` ids (218
tokens become 2155 to 2517). `param_var_` and `inout` stay. They are not a cleanup.
- A by-value lowering of the SPIR-V (`od-temporaries/byvalue.py`, 50 lines) makes each Function
pointer parameter a value parameter, with the old id kept as an entry-block local stored from
it, and each call loads what it passed. It changed 187 functions and 456 parameters, validates,
and leaves `inout` at 0. On lavapipe all 117 families stay bit-identical to the committed GLSL.
- Then `spirv-opt --eliminate-local-single-store --eliminate-dead-code-aggressive` removes every
`param_var_` copy (472 to 0): 2604 lines, 79782 bytes, 188 functions, 316 distinct `_N` ids, valid.
Adding SPIRV-Cross `--relax-nan-checks` drops the `isnan` expansions: 2556 lines, 74263 bytes,
268 `_N` ids. glslang accepts both as ES 3.00, `cultmath_smootherstep(p.x + 1.0)` included.
- That cleaned module is bit-identical to the lavapipe HLSL result on 117 of 117 families, where
the committed GLSL is on 97. It differs from the committed GLSL in 20 families. Against the C#
fixture the exact, at most 4 ulp, at most 64 ulp and over 64 buckets are 80, 11, 9, 17, where
the committed GLSL is 80, 9, 10, 18. `--relax-nan-checks` changes no lavapipe bit. So the
cleaned route is closer to the HLSL than today's GLSL is, and "bit-identical to today's
lowering" cannot be its gate. With apt's spirv-tools 2025.1~rc1 the figures for this route are the same.
- **Capability strip.** `spirv-opt --trim-capabilities` (spirv-tools 2025.1~rc1) leaves all 14
capabilities and both extensions in place, and SPIRV-Cross still refuses ("RayQuery requires Vulkan
GLSL 460"). Stripping every capability except Shader and Linkage and every OpExtension in the
@ -2350,35 +2391,44 @@ and 16:50 UTC (18:30 to 18:50 CEST). Logs are in the Imagination scratchpad
`static const` line of another form. The wrappers are text in the build's temp directory and are
never committed. The source gains no `export` keyword and no `CULTMATH_EXPORT` macro.
- The compile mode. The library compiles at `-Od`, because the default optimiser's inlining is
what erases the overloads. glslang and the drivers optimise downstream, and on lavapipe the
result is bit-identical to today's output.
what erases the overloads. The text it leaves is cleaned by the next two items (Pass 9c), not
shipped as is: `-Od` alone emits `inout` parameters, which native overloads must not have.
- One SPIR-V edit. A single instruction-level pass over the binary, never a regex over text,
strips capabilities and extensions, deletes the wrappers and moves their exports onto the
callees. It replaces the disassembly grep that the capability-strip probe used. It refuses a
wrapper that is not exactly one call. SPIRV-Cross then emits the overloaded names as they are,
so the build has no rename step and no name map.
- By-value parameters. The same pass makes every Function-pointer parameter a value parameter
(`byvalue.py` in the probe), so no emitted function can be `inout`. The build then runs exactly
`spirv-opt --eliminate-local-single-store --eliminate-dead-code-aggressive`, never an inliner
and never `--simplify-instructions` or `--ssa-rewrite`, which turn named locals into `_N` ids,
and SPIRV-Cross runs with `--relax-nan-checks`, so `min` and `max` are the plain intrinsics.
- The gate is the HLSL, not the old text. A cleaned route's lavapipe-glsl result must equal the
lavapipe-hlsl result bit for bit in every family (117 of 117 measured), and the C# judge's
bounds are re-recorded only where a family moved and equals its HLSL result.
### Cut sequence (Pass 9; one line each, mapped when about to run)
1. `shader-conforming-run`: spec admitted. The lavapipe job with the C# device judge, run against
today's committed HLSL and GLSL, so the next cut is verified against a running check.
2. `glsl-build-dxc`: the switch. `tools/build-glsl.sh` pins dxc v1.9.2607 (the sha above) and SPIRV-Cross
`vulkan-sdk-1.4.363.0`. Its first step generates the export wrappers, one per non-texture definition,
into the build's temp directory; they are never committed (Pass 9b). It compiles source plus
wrappers with `-T lib_6_3 -spirv -Od`. One SPIR-V edit then strips capabilities and extensions,
deletes the wrappers and moves their exports onto the callees, and `spirv-val` runs on the result.
The build emits ES 3.10 with the guarded `#version` and no placeholder `main`, and partitions the
output by origin file into the three committed files with their licence lines and guards. It emits
the 13 constants from their source lines. The HLSL source is not edited, and every overload keeps
its name in the HLSL and the GLSL. `GlslLowering.cs` and its lowering contract tests are deleted.
The lavapipe job checks that the committed files are the build's output, and that every family's
`lavapipe-glsl` result is bit-identical to the old lowering's. A miss is a defect in the cut, not
something to re-record. `get-spirv-cross.ps1` is pinned to the same tag. Waits on 1. If
`trophic-nodes` merges first, the build covers its four new overloads with nothing extra.
2. `glsl-build-dxc` (spec admitted): the build, not yet the switch. `packages/cultmath/tools/glsl/`
holds `build-glsl.sh`, which pins dxc v1.9.2607 (the sha above), SPIRV-Cross and SPIRV-Tools
`vulkan-sdk-1.4.363.0`, plus one SPIR-V tool in Python. The build generates the export wrappers into
its temp directory (never committed), compiles source plus wrappers with `-T lib_6_3 -spirv -Od`,
and runs the one SPIR-V edit (strip, wrapper delete, export move, by-value parameters; Pass 9c).
It runs the pinned `spirv-opt` pair, `spirv-val`, and SPIRV-Cross ES 3.10 with `--relax-nan-checks`,
then partitions by origin file and emits the 13 constants. Output goes to a directory the caller
names. The committed GLSL, `GlslLowering.cs` and its tests are untouched, and the lavapipe job gains
one switch to run a built directory in place of `shaders/*.glsl`. Waits on 1, which is merged.
2b. `glsl-switch` (mapped when 2 is verified): commits the build's output with the licence lines and
guards, deletes `GlslLowering.cs` and the lowering contract tests, makes the lavapipe job check
the committed files against the build, re-records the lavapipe bounds for moved families
(Pass 9c's gate), and pins `get-spirv-cross.ps1`. If `trophic-nodes` merges first, the build
covers its four new overloads with nothing extra.
3. `angle-capture` (stage-shaders-device part 2): the Starfire native-ANGLE tool on the shared work
list (ES 3.00 fragment flavour, RGBA32UI readback), loading a pinned ANGLE build rather than Docker
Desktop's copy. Captures carry the renderer, ANGLE version and revision, the shader sha and per-family
argument hashes and bits, and the ordinary test run judges them. A shader-sha change marks them stale.
It settles `span-allowance-gpu-margin`'s six CPU survivors, `iv-exp-gpu-widening`'s measurement and
`device-p2-pin-notes`, and closes `glsl-browser-parity-run` and `affine-device-runner-seed`. It waits
on 2, because a capture of the old lowering goes stale at the switch.
on 2b, because a capture of the old lowering goes stale at the switch.

View file

@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Probe: by-value parameter lowering on a SPIR-V module. dxc -Od passes every parameter as a Function pointer and the
caller copies in; a callee that assigns its parameter then comes out of SPIRV-Cross as `inout`. This pass makes each
Function-pointer parameter a value parameter: the old param id becomes a local variable in the entry block, stored from the
new value parameter; each call loads the pointer it passed. usage: byvalue.py <in.spv> <out.spv>"""
import struct, sys
def load(p):
b = open(p, 'rb').read(); w = list(struct.unpack('<%dI' % (len(b) // 4), b)); ins = []; i = 5
while i < len(w): n = w[i] >> 16; ins.append(w[i:i + n]); i += n
return w[:5], ins
def op(x): return x[0] & 0xffff
def mk(o, *ws): return [((len(ws) + 1) << 16) | o, *ws]
h, ins = load(sys.argv[1]); bound = h[3]
ptr = {x[1]: (x[2], x[3]) for x in ins if op(x) == 32} # id -> (storage, pointee)
ftype = {x[1]: x for x in ins if op(x) == 33}
fnparams = {}; cur = None; fntype = {}
for x in ins: # analysis: per function, which params are Function pointers
if op(x) == 54: cur = x[2]; fnparams[cur] = []; fntype[cur] = x[4]
elif op(x) == 55 and cur is not None:
t = x[1]; conv = t in ptr and ptr[t][0] == 7
fnparams[cur].append((x[2], t, ptr[t][1] if conv else None, bound if conv else None)); bound += conv
newtype = {}; typeins = []; sig = {tuple(x[2:]): x[1] for x in ins if op(x) == 33}
for f, ps in fnparams.items():
if any(p[2] for p in ps):
ft = ftype[fntype[f]]; key = (ft[2], *[p[2] if p[2] else p[1] for p in ps])
if key not in sig: bound += 1; sig[key] = bound; typeins.append(mk(33, bound, *key))
newtype[f] = sig[key]
names = {x[1]: x for x in ins if op(x) == 5}
out = []; cur = None; pend = []; need_stores = False; first = True; pc = 0
for x in ins:
o = op(x)
if o == 54 and first: out += typeins; first = False
if need_stores and o != 59:
out += [mk(62, p, q) for p, _, q in pend]; pend = []; need_stores = False
if o == 54:
cur = x[2]; pc = 0
if cur in newtype: x = x[:4] + [newtype[cur]] + x[5:]
elif o == 55:
_, t, pointee, q = fnparams[cur][pc]; pc += 1
if pointee: out.append(mk(55, pointee, q)); pend.append((x[2], t, q)); continue
elif o == 248 and pend:
out.append(x); out += [mk(59, t, p, 7) for p, t, _ in pend]; need_stores = True; continue
elif o == 57:
callee = x[3]; args = x[4:]; new = []
for a, (_, _, pointee, _) in zip(args, fnparams[callee]):
if pointee: bound += 1; out.append(mk(61, pointee, bound, a)); new.append(bound)
else: new.append(a)
x = x[:4] + new; x[0] = (len(x) << 16) | 57
out.append(x)
if o == 5 and x[1] in [p[0] for ps in fnparams.values() for p in ps if p[2]]:
q = next(p[3] for ps in fnparams.values() for p in ps if p[0] == x[1]); out.append([x[0], q] + x[2:])
h[3] = bound + 1; w = h + [v for x in out for v in x]; open(sys.argv[2], 'wb').write(struct.pack('<%dI' % len(w), *w))
print('byvalue: %d functions changed, %d params' % (len(newtype), sum(1 for ps in fnparams.values() for p in ps if p[2])))

View file

@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Imagination probe: what dxc -Od leaves in the SPIRV-Cross GLSL and what cleans it. ubuntu:24.04, /src = CultLib, /cache persists tools.
set -u; P=/src/docs/research/native-shader-probes; O=$P/overload-wrappers; W=/tmp/w; mkdir -p $W /cache; cd $W
step() { echo; echo "=== $*"; }
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq >/dev/null && apt-get install -y -qq --no-install-recommends ca-certificates curl git cmake g++ make python3 gcc \
mesa-vulkan-drivers libvulkan-dev glslang-tools spirv-tools >/dev/null 2>&1; echo "apt exit $?"
dpkg-query -W -f='${Package} ${Version}\n' spirv-tools glslang-tools mesa-vulkan-drivers
if [ ! -x /cache/sc/spirv-cross ]; then
git clone -q --depth 1 --branch vulkan-sdk-1.4.363.0 https://github.com/KhronosGroup/SPIRV-Cross.git /cache/scsrc
cmake -S /cache/scsrc -B /cache/scb -DCMAKE_BUILD_TYPE=Release -DSPIRV_CROSS_ENABLE_TESTS=OFF -DSPIRV_CROSS_CLI=ON >/dev/null && cmake --build /cache/scb --target spirv-cross -j8 >/dev/null 2>&1
mkdir -p /cache/sc; cp /cache/scb/spirv-cross /cache/sc/
fi
if [ ! -x /cache/dxc/bin/dxc ]; then
curl -sL --fail -o /cache/dxc.tgz https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2607/linux_dxc_2026_07_29.x86_x64.tar.gz
mkdir -p /cache/dxc && tar xzf /cache/dxc.tgz -C /cache/dxc
fi
DXC=$(find /cache/dxc -name dxc -type f | head -1); SC=/cache/sc/spirv-cross; export LD_LIBRARY_PATH=$(dirname $DXC)/../lib:${LD_LIBRARY_PATH:-}
if [ ! -x /cache/st/spirv-opt ]; then
git clone -q --depth 1 --branch vulkan-sdk-1.4.363.0 https://github.com/KhronosGroup/SPIRV-Tools.git /cache/stsrc
git clone -q --depth 1 --branch vulkan-sdk-1.4.363.0 https://github.com/KhronosGroup/SPIRV-Headers.git /cache/stsrc/external/spirv-headers
cmake -S /cache/stsrc -B /cache/stb -DCMAKE_BUILD_TYPE=Release -DSPIRV_SKIP_TESTS=ON -DSPIRV_WERROR=OFF >/dev/null && cmake --build /cache/stb --target spirv-opt spirv-val spirv-dis spirv-as -j8 >/dev/null 2>&1
mkdir -p /cache/st; cp /cache/stb/tools/spirv-* /cache/st/
fi
export PATH=/cache/st:$PATH; echo "spirv-opt from $(which spirv-opt)"
echo "dxc $DXC"; $DXC --version 2>&1|head -2; spirv-opt --version | head -1
SH=/src/packages/cultmath/shaders; FX=/src/packages/cultmath/tests/CultMath.Tests/fixtures/glsl-parity.json
step "1 build the -Od library as in Pass 9b"
python3 $O/wrapgen.py $SH shw
$DXC -T lib_6_3 -HV 2021 -spirv -fspv-target-env=universal1.5 -Od -I shw shw/cm_wrappers.hlsl -Fo w.spv 2>&1 | head -3
python3 $O/spvedit.py edit w.spv e.spv shw/wrappers.tsv export; spirv-val --target-env spv1.5 e.spv && echo "val ok"
nf() { spirv-dis "$1" | grep -c ' = OpFunction '; }; echo "functions in e.spv: $(nf e.spv)"
step "2 variants: by-value lowering, then spirv-opt (never an inliner)"
cp e.spv v0.spv
python3 $P/od-temporaries/byvalue.py e.spv b0.spv; spirv-val --target-env spv1.5 b0.spv && echo "b0 val ok"
spirv-opt --target-env=spv1.5 --ssa-rewrite --eliminate-dead-code-aggressive --simplify-instructions e.spv -o v2.spv
SSA="--ssa-rewrite --eliminate-dead-code-aggressive"
declare -A VP=([b1]="--eliminate-local-single-store --eliminate-dead-code-aggressive" [b2]="$SSA" [b3]="$SSA --simplify-instructions" [b4]="--eliminate-local-single-block --eliminate-local-single-store --eliminate-local-multi-store --eliminate-dead-code-aggressive --merge-blocks")
for v in b1 b2 b3 b4; do spirv-opt --target-env=spv1.5 ${VP[$v]} b0.spv -o $v.spv 2>$v.err; echo "$v opt exit $? functions $(nf $v.spv 2>/dev/null) $(head -c 160 $v.err)"; done
cp b1.spv b1r.spv; VS="v0 b0 b1 b1r b3"
for v in $VS; do [ -s $v.spv ] || continue
spirv-val --target-env spv1.5 $v.spv >$v.val 2>&1; vx=$?
$SC $v.spv --es --version 310 $([ $v = b1r ] && echo --relax-nan-checks) --output $v.glsl >$v.sc 2>&1; sx=$?
[ -s $v.glsl ] || { echo "$v val $vx sc exit $sx"; head -3 $v.val $v.sc; continue; }
python3 - $v $vx $sx <<'PY'
import re,sys
v,vx,sx=sys.argv[1:4]; g=open(f'/tmp/w/{v}.glsl').read()
defs=re.findall(r'(?m)^(?:\w+ )*?(\w+) (cultmath_\w+)\(([^)]*)\)\n\{',g)
ids=re.findall(r'\b_\d+\b',g)
print(f'{v}: val={vx} sc={sx} lines={g.count(chr(10))} bytes={len(g)} cultmath_defs={len(defs)} distinct={len(set(d[1] for d in defs))} id_tokens={len(ids)} distinct_ids={len(set(ids))} param_var={g.count("param_var_")} inout={len(re.findall(r"inout",g))} suffixed={len(re.findall(r"cultmath_\w+_\d+\(",g))}')
PY
done
mkdir -p /cache/out; cp *.glsl *.spv /cache/out/ 2>/dev/null
step "3 SPIRV-Cross options"
for opt in "--remove-unused-variables"; do for v in v0 b2; do $SC $v.spv --es --version 310 $opt --output $v.o.glsl >/dev/null 2>&1; echo "$v + $opt: lines $(wc -l < $v.o.glsl)"; done; done
step "4 lerp(vec3) as emitted: v0 vs b2, vs committed"
for v in v0 b2; do echo "--- $v lerp(vec3)"; awk '/^(highp )?vec3 cultmath_lerp\((highp )?vec3/{p=1} p{print} p&&/^}/{exit}' $v.glsl; done
echo "--- committed lerp(vec3)"; grep -n -A3 -E '^(highp )?vec3 cultmath_lerp\(' $SH/CultMath.glsl | head -6
for v in v0 b2; do echo "--- $v snoise(vec3) head"; awk '/^(highp )?float cultmath_snoise\((highp )?vec3/{p=1} p{print; if(++n>=40) exit}' $v.glsl; done
step "5 conformance on lavapipe, every family, per variant vs committed GLSL and HLSL"
mkdir -p fam; gcc -O2 -o vkrun $P/vkrun.c -lvulkan && python3 $P/fam.py gen $FX fam >/dev/null
cat $SH/CultMath.glsl $SH/CultMath.Cycles.glsl $SH/CultMath.Phacelle.glsl > all.glsl
body() { sed -E '/^#version/d; /^#ifdef SPIRV_CROSS/d; /^#endif/d; /^layout\(local_size/d' $1 | awk 'BEGIN{s=0} /^void main\(\)/{s=1} s==0{print} s==1&&/^\}/{s=0}'; }
for v in $VS; do [ -s $v.glsl ] && body $v.glsl > $v.body; done
run() { local t=fam/$1 n; n=$(python3 -c "import json;m={x['tag']:x for x in json.load(open('fam/manifest.json'))}['$1'];print(m['n'],m['nout'])")
{ printf '#version 310 es\nprecision highp float;\nprecision highp int;\n'; cat $3 $t.body.glsl; } > $t.$2.comp
glslangValidator -V --target-env vulkan1.2 -o $t.$2.spv $t.$2.comp >$t.$2.log 2>&1 && ./vkrun $t.$2.spv $t.in $t.$2.out $n; }
for b in fam/*.body.glsl; do tag=$(basename ${b%.body.glsl})
n=$(python3 -c "import json;m={x['tag']:x for x in json.load(open('fam/manifest.json'))}['$tag'];print(m['n'],m['nout'])")
$DXC -T cs_6_0 -E main -HV 2021 -spirv -fspv-target-env=vulkan1.2 -I $SH fam/$tag.hlsl -Fo fam/$tag.h.spv >/dev/null 2>&1 && ./vkrun fam/$tag.h.spv fam/$tag.in fam/$tag.h.out $n
run $tag g all.glsl; for v in $VS; do [ -s $v.body ] && run $tag $v $v.body; done; done
export VS; python3 - <<'PY'
import os,filecmp
d='/tmp/w/fam'; tags=sorted(f[:-10] for f in os.listdir(d) if f.endswith('.body.glsl'))
def same(a,b): return [t for t in tags if os.path.exists(f'{d}/{t}.{a}.out') and os.path.exists(f'{d}/{t}.{b}.out') and filecmp.cmp(f'{d}/{t}.{a}.out',f'{d}/{t}.{b}.out',shallow=False)]
print('families',len(tags),'hlsl ran',len([t for t in tags if os.path.exists(f'{d}/{t}.h.out')]),'committed glsl ran',len([t for t in tags if os.path.exists(f'{d}/{t}.g.out')]))
for v in os.environ['VS'].split():
ran=[t for t in tags if os.path.exists(f'{d}/{t}.{v}.out')]
sg=same(v,'g'); print(v,'ran',len(ran),'bit-identical to committed glsl',len(sg),'to hlsl',len(same(v,'h')),'| differs from g:',[t for t in ran if t not in sg][:8])
print('committed vs hlsl',len(same('g','h')),'of',len(tags))
PY
for v in v0 b2; do { printf '#version 300 es\nprecision highp float;\nprecision highp int;\n'; cat $v.body; printf 'out highp vec4 c;\nvoid main() { vec3 p = gl_FragCoord.xyz; c = vec4(cultmath_lerp(p, p.yzx, vec3(0.5)), cultmath_lerp(1.0, 2.0, p.x)) + cultmath_saturate(vec4(p, 1.0)) + vec4(cultmath_snoise(p)); }\n'; } > $v.es300.frag; glslangValidator $v.es300.frag >$v.es300.txt 2>&1; echo "$v ES 3.00 glslang exit $? $(grep -m2 ERROR $v.es300.txt | tr '\n' ' ' | cut -c1-200)"; done
for t in g $VS; do echo "--- cmp vs C# fixture: $t"; CMP_TOP=3 python3 $P/fam.py cmp $FX fam $t 2>&1 | grep -v "^ *$" | head -8; done
echo PROBE-DONE