Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ jobs:
tests/startup_gfx2hlsl_join_symbols_check.py \
tests/startup_joined_table_pointer_check.py \
tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \
tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py \
tests/startup_compute_readfirstlane_check.py \
tests/startup_gfx2hlsl_heap_record_check.py \
tests/startup_gfx2hlsl_calculated_target_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_absdiff_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py
Expand Down
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4724,6 +4724,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# v_readfirstlane_b32 past the entry block of a branched program: recomputed definition, joins and EXEC refused.
add_test(NAME startup_gfx2hlsl_readfirstlane_recompute COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py")
# A uniform compute buffer load past the entry block: per-lane temporary, joins, EXEC and per-lane addresses refused.
add_test(NAME startup_gfx2hlsl_readfirstlane_load_recompute COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py")
add_test(NAME startup_gfx2hlsl_calculated_target COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_calculated_target_check.py")
# Startup shader translator: read-only census of every refusal site (--refusals).
Expand Down
4 changes: 3 additions & 1 deletion docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -15860,12 +15860,14 @@ Past the entry block of a program with branches, the read does not copy the VGPR

A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms (including one-path scalars and uniform loop counters both inside and after loops) and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge, a divergent `else`-arm write before a join, a non-uniform loop back-edge and a join where two definitions reach.

A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC.

[`tests/startup_compute_readfirstlane_check.py`](../tests/startup_compute_readfirstlane_check.py) pairs that unit coverage with a source-built gfx1013 compute fixture (`(4, 1, 1)` local threads x `(2, 1, 1)` groups) containing both a one-path SGPR across a uniform forward branch join and a four-iteration uniform loop counter read via `v_readfirstlane_b32` inside the loop and after exit, machine-code refusal patches (non-uniform `s_cbranch_vccnz` back-edge, divergent `else`/`then` write before a join, lane-mask loop update) and 320-word GPU readback with pinned `dropped-one-path`, `dropped-loop-read` and `dropped-post-loop` negative controls. Verified with zero mismatches and zero D3D12 debug-layer errors or warnings on Windows 11 25H2 (build 26200.9974) across WARP 10.0.26100.9818 and an AMD Radeon RX 7900 XTX (driver 32.0.32029.2010).

`tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` translates short sequences through the stage's dispatch without shader machine code. It checks emitted assignments for the listed operations, supported modifiers, and in-place and cross-register chains, the median of three that clamps a scalar to `[0, 0.5]`, including the unsigned-division reciprocal estimate (`v_cvt_f32_u32`, `v_rcp_f32`, `v_mul_f32` by `0x4f7ffffe`, `v_cvt_u32_f32`) that compiled shaders read back with `v_readfirstlane_b32`. That chain stays refused from a lane-varying source or a lane mask, across an `exec` write or an overwrite, and from a definition in another block. Refusal cases cover varying sources and offsets, overwrites that invalidate a proof, WQM, a restored `exec` copy and other exec writes, lane masks, overlapping and descriptor-path 64-bit moves, branch and operand restrictions (a read at the first branch target, in a loop whose header is in the entry block, at a backward branch target, in an entry block re-entered by a loop, or after `s_endpgm` in a branch-free program; a read after the first terminator is recomputed), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse.

```powershell
ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(uniform|recompute)|startup_compute_readfirstlane(_(warp|hardware))?)$' -V
ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(uniform|recompute|load_recompute)|startup_compute_readfirstlane(_(warp|hardware))?)$' -V
python -B tests/startup_compute_readfirstlane_check.py --llvm-mc llvm-mc-15
```

Expand Down
142 changes: 142 additions & 0 deletions tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""Check v_readfirstlane_b32 of a uniform compute buffer load past the entry block, without shader machine code.

A lane the load skipped keeps an older VGPR, so every lane loads the words again into a temporary from an address
every lane computes alike (the uniform expression of the address VGPR, or its copy while EXEC is still the entry
mask), and the read copies that temporary. A branch target, an EXEC write or an overwrite between the load and
the read still refuses, as do a per-lane address, a graphics stage and a destination of the wrong width.
"""
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup'))
import gfx2hlsl as G # noqa: E402

failures = []


def check(label, condition, detail=''):
print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}")
if not condition:
failures.append(label)


class Pipe:
resources = {(('table', 0), 0): {'index': 0}} # the formatted load reads the stride and FORMAT words by index
modified = set()

def resource(self, key, kind):
return 'r0'

def ud(self, key):
return 0


def run(*instructions, kind='cs', descriptor_proven=False):
"""Translate disassembly text through the same dispatch and block split as a real stage."""
s = G.Stage.__new__(G.Stage)
if descriptor_proven:
# The past-entry descriptor proof of a formatted load is checked in startup_gfx2hlsl_compute_check.py.
s.formatted_descriptor_from_block = lambda reg, first: True
s.pipe, s.lines, s.attrs = Pipe(), [], {}
s.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)}
s.used_s, s.used_v, s.masks = set(), set(), set()
s.exec_known, s.kind = True, kind
s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)]
try:
s.translate()
except G.Unsupported as error:
return str(error)
return [line for _, lines, _ in s.blocks for line in lines]


REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source'
READ = 'v_readfirstlane_b32 s9, v7'
# Offset 0x8 is a join: the branch at 0x0 skips the instruction at 0x4, so everything after it is past the entry.
JOIN = ('s_cbranch_scc0 label_0008', 's_nop 0')
SCALAR = 's_buffer_load_dword s3, s[4:7], 0x10' # a uniform scalar written after the join
LOAD = 'buffer_load_dword v7, off, s[4:7], s3' # at 0xc after JOIN + (SCALAR,)
NARROW = 's_and_saveexec_b32 s8, s2'

# (label, instructions, the lines from the load on)
ACCEPTED = [
('scalar offset load', JOIN + (SCALAR, LOAD, READ),
['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 's9 = ulc_7;']),
# The temporary already holds the words, so a later write of the offset scalar does not matter.
('offset scalar rewritten after the load', JOIN + (SCALAR, LOAD, 's_mov_b32 s3, 0', READ),
['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 's3 = 0x00000000u;', 's9 = ulc_7;']),
# While EXEC is the entry mask every lane ran the address definition, so its copy serves even after the
# scalar it read is rewritten.
('address copy under the entry exec',
JOIN + (SCALAR, 'v_mov_b32_e32 v6, s3', 's_mov_b32 s3, 0', 'buffer_load_dword v7, v6, s[4:7], 0 offen', READ),
['a = v6 + 0;', 'v7 = r0.Load(a + 0);', 'ul14_7 = r0.Load(a + 0);', 's9 = ul14_7;']),
('second word of a two-dword load',
JOIN + (SCALAR, 'buffer_load_dwordx2 v[7:8], off, s[4:7], s3', 'v_readfirstlane_b32 s9, v8'),
['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 'v8 = r0.Load(a + 4);',
'ulc_8 = r0.Load(a + 4);', 's9 = ulc_8;']),
('conversion of the loaded word',
JOIN + (SCALAR, LOAD, 'v_cvt_f32_u32_e32 v8, v7', 'v_readfirstlane_b32 s9, v8'),
['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 'v8 = U(float(v7));',
's9 = U(float((ulc_7)));']),
]
for label, instructions, lines in ACCEPTED:
got = run(*instructions)
check(f'{label} accepted', isinstance(got, list) and got[-len(lines):] == lines, repr(got))

# A formatted load keeps the selected component; the address and the selection are the ones the guarded write uses.
got = run(*JOIN, SCALAR, 'buffer_load_format_x v7, off, s[4:7], s3', READ, descriptor_proven=True)
pick = '((ud0 >> 0) & 7u) == 4u ? c0 : ((ud0 >> 0) & 7u) == 5u ? c1 : ((ud0 >> 0) & 7u) == 6u ? c2 : ' \
'((ud0 >> 0) & 7u) == 7u ? c3 : ((ud0 >> 0) & 7u) == 1u ? one : 0u'
check('formatted load accepted', isinstance(got, list) and 'a = s3 + 0;' in got and
got[-3:] == ['ulc_7 = %s;' % pick, '}', 's9 = ulc_7;'] and got[-4] == 'v7 = %s;' % pick, repr(got))
# The temporary is declared once at function scope, next to the registers.
s = G.Stage.__new__(G.Stage)
s.uniform_load_temps, s.used_s, s.used_v, s.kind, s.pipe = {'ulc_7'}, set(), set(), 'cs', Pipe()
s.pipe.packed_position_vgpr = None
check('temporary declared', ' uint ulc_7 = 0;' in s.declarations(), repr(s.declarations()))

REFUSED = [
# Two definitions reach the read at a join.
('join of a load and another definition', ('s_cbranch_scc0 label_0014', SCALAR, LOAD, 's_branch label_0014',
'v_mov_b32_e32 v7, 0', READ, 's_endpgm')),
('per-lane address', JOIN + ('buffer_load_dword v7, v0, s[4:7], 0 offen', READ)),
('per-lane offset scalar', JOIN + ('v_cmp_lt_f32_e64 s3, v0, v1', LOAD, READ)),
# A loop head between the load and the read: a later iteration reaches the read without the load.
('back-edge target between load and read', JOIN + (SCALAR, LOAD, 's_nop 0', READ, 's_cbranch_scc0 label_0014',
's_endpgm')),
# The load runs inside a block lanes with clear EXEC skip, and the read is past the block's join.
('load inside a block one lane skips', JOIN + (SCALAR, 's_and_saveexec_b32 s8, vcc_lo', 's_cbranch_execz label_0018',
LOAD, 's_mov_b32 exec_lo, s8', READ, 's_endpgm')),
('EXEC narrowed between load and read', JOIN + (SCALAR, LOAD, NARROW, READ)),
# On empty EXEC, RDNA 2 reads the old lane-0 VGPR, not an unguarded reload.
('empty EXEC keeps the old lane-zero VGPR', JOIN + ('v_mov_b32_e32 v7, 17', 's_mov_b32 exec_lo, 0',
SCALAR, LOAD, READ)),
('address expression with potentially empty EXEC',
JOIN + (NARROW, SCALAR, 'v_mov_b32_e32 v7, s3', 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ)),
# Under a narrowed EXEC a lane that skipped the address definition holds an older copy, and the expression
# is gone once its scalar is rewritten.
('stale address copy under a narrowed exec',
JOIN + (NARROW, SCALAR, 'v_mov_b32_e32 v6, s3', 's_mov_b32 s3, 0', 'buffer_load_dword v7, v6, s[4:7], 0 offen',
READ)),
('loaded register overwritten before the read', JOIN + (SCALAR, LOAD, 'v_mov_b32_e32 v7, v0', READ)),
('two-dword load into three registers', JOIN + (SCALAR, 'v_mov_b32_e32 v9, v0',
'buffer_load_dwordx2 v[7:9], off, s[4:7], s3',
'v_readfirstlane_b32 s9, v9')),
]
for label, instructions in REFUSED:
got = run(*instructions)
check(f'{label} refused', got == REFUSAL, repr(got))
got = run(*JOIN, SCALAR, LOAD, READ, kind='ps')
check('graphics stage refused', got == REFUSAL, repr(got))

# Without the load allowlist the accepted programs refuse again.
original = G.UNIFORM_LOADS
G.UNIFORM_LOADS = frozenset()
try:
for label, instructions, _ in ACCEPTED:
got = run(*instructions)
check(f'control: {label} refused without the load proof', got == REFUSAL, repr(got))
finally:
G.UNIFORM_LOADS = original

print('Readfirstlane load recompute checks: %d failed' % len(failures))
sys.exit(1 if failures else 0)
Loading
Loading