From 8a69d81cb29e29751b03e7c82c03bc73247273b2 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 17:58:41 +0100 Subject: [PATCH 1/3] gfx2hlsl: prove a compute buffer load with a uniform address uniform v_readfirstlane_b32 needs a vector source with the same value in every active lane. A buffer_load_dword or buffer_load_format_x in a compute program reads a read-only descriptor (a descriptor used for a load and a store is already refused), so with a uniform VGPR index or offset, a uniform scalar offset and exec known in the entry block, every lane reads the same dword. Mark the destination uniform there. The value has no recomputable expression, so reads past the entry block still refuse. Tests: positive cases plus negative controls for a varying VGPR offset, a varying scalar offset, a graphics stage, no stage kind, unknown exec, a read after the entry block and a varying overwrite. Co-Authored-By: Claude Sonnet 5.5 --- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 32 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 18 ++++++++++- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index eef9354837..cbf2fd3af6 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -28,7 +28,7 @@ def resource(self, key, kind): ALIAS_LOAD = 's_buffer_load_dwordx2 s[2:3], s[4:7], s2' -def run(*instructions, exec_known=True): +def run(*instructions, exec_known=True, kind=None): """Translate disassembly text using the same dispatch and branch scan as a real stage.""" s = G.Stage.__new__(G.Stage) s.pipe, s.lines = Pipe(), [] @@ -37,6 +37,8 @@ def run(*instructions, exec_known=True): s.sym[3] = ('fixed_buffer_word',) s.used_s, s.used_v, s.masks = set(), set(), set() s.exec_known = exec_known + if kind: + s.kind = kind s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] try: s.translate() @@ -200,6 +202,34 @@ def run(*instructions, exec_known=True): got = run('v_mov_b32_e32 v7, s2', READ, exec_known=False) check('unknown exec refused', got == REFUSAL, repr(got)) +# A compute load through a read-only descriptor with a uniform address is uniform; the value has no recomputable +# expression, so only the entry block reads it. +LOAD_OFF = 'buffer_load_dword v7, off, s[4:7], s2' +LOAD_OFFEN = 'buffer_load_dword v8, v7, s[4:7], 0 offen' +got = run(LOAD_OFF, READ, kind='cs') +check('uniform scalar offset load accepted', got[-2:] == ['v7 = r0.Load(a + 0);', 's9 = v7;'], repr(got)) +got = run(MOVE, LOAD_OFFEN, 'v_readfirstlane_b32 s9, v8', kind='cs') +check('uniform vgpr offset load accepted', got[-1] == 's9 = v8;' and len(got) == 4, repr(got)) +got = run(MOVE, 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ, kind='cs') +check('load overwriting its uniform address accepted', got[-1] == 's9 = v7;', repr(got)) +for label, instructions, kind, known in ( + ('load with a varying vgpr offset', ('buffer_load_dword v8, v0, s[4:7], 0 offen', 'v_readfirstlane_b32 s9, v8'), 'cs', True), + ('load with a varying scalar offset', (COMPARE, 'buffer_load_dword v7, off, s[4:7], s2', READ), 'cs', True), + ('load in a graphics stage', (LOAD_OFF, READ), 'ps', True), + ('load without a stage kind', (LOAD_OFF, READ), None, True), + ('load with unknown exec', (LOAD_OFF, READ), 'cs', False), + ('load after the entry block', (LOAD_OFF, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm'), 'cs', True), + ('load then a varying overwrite', (LOAD_OFF, 'v_mov_b32_e32 v7, v0', READ), 'cs', True)): + got = run(*instructions, kind=kind, exec_known=known) + check(f'{label} refused', got == REFUSAL, repr(got)) +original = G.UNIFORM_LOADS +G.UNIFORM_LOADS = frozenset() +try: + got = run(LOAD_OFF, READ, kind='cs') + check('control: load refused without tracking', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_LOADS = original + # Older probes may provide either no tracker or only part of the tracking state. for present in ((), ('uniform_v',), ('uniform_v', 'varying_s')): s = G.Stage.__new__(G.Stage) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 221cedb43b..e3d9a9605a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -654,6 +654,8 @@ def smem_mods(mods): 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) +UNIFORM_LOADS = frozenset(('buffer_load_dword', 'buffer_load_format_x')) + # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} @@ -1941,6 +1943,20 @@ def one(self, name, asm): sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] + # A compute load through a read-only descriptor (a descriptor is never both loaded and stored) with a uniform + # address reads the same dword in every lane. Entry block only: the value has no recomputable expression. + loaded = (dst is None and base in UNIFORM_LOADS and len(ops) == 4 and self.tracks_uniformity() and + getattr(self, 'kind', None) == 'cs' and not getattr(self, 'past_entry', True) and + getattr(self, 'exec_known', False) and + all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and + not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and + (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + if loaded: + candidate = reg_range(ops[0]) + if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: + dst = candidate[1] + else: + loaded = False self.last_v = None term = self.lower(base, asm, ops, mods) uniform_written = self._uniform_written @@ -1961,7 +1977,7 @@ def one(self, name, asm): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or any(n not in self.uniform_expr for n in vs): + if expr is None or loaded or any(n not in self.uniform_expr for n in vs): self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], From a485968486f867c1af7a7efce3c9c01490c5878e Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 18:13:06 +0100 Subject: [PATCH 2/3] gfx2hlsl: extend the uniform compute load proof to multi-register loads The entry-block rule for a compute buffer load with a uniform address covered one destination register. Accept buffer_load_dwordx2/x3/x4 and buffer_load_format_xy/xyz/xyzw too: every destination register of such a load holds the same dword in every lane. The destination range must be exactly as long as the opcode writes, so no register the load leaves alone is marked uniform. None of them records a recomputable expression. Co-Authored-By: Claude Sonnet 5.5 --- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 22 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 16 ++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index cbf2fd3af6..e51cd4e08e 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -17,9 +17,14 @@ def check(label, condition, detail=''): class Pipe: """The single resource needed by the buffer-load probe.""" + resources = {(('table', 0), 0): {'index': 0}} # the formatted load reads the stride and FORMAT words by index + def resource(self, key, kind): return 'r0' + def ud(self, key): + return 0 + REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' READ = 'v_readfirstlane_b32 s9, v7' @@ -230,6 +235,23 @@ def run(*instructions, exec_known=True, kind=None): finally: G.UNIFORM_LOADS = original +# Every destination register of a multi-register load is uniform, and only the registers the opcode writes. +for label, instructions, read in ( + ('two-dword load, first word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 7), + ('two-dword load, second word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 8), + ('four-dword load, last word', ('buffer_load_dwordx4 v[6:9], off, s[4:7], s2',), 9), + ('load over a varying register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 8), + ('formatted two-component load', ('buffer_load_format_xy v[7:8], off, s[4:7], s2',), 8)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} accepted', got[-1] == 's9 = v%d;' % read, repr(got)) +for label, instructions, read in ( + ('two-dword load into three registers', ('v_mov_b32_e32 v9, v0', 'buffer_load_dwordx2 v[7:9], off, s[4:7], s2'), 9), + ('two-dword load into one register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v7, off, s[4:7], s2'), 8), + ('two-dword load with a varying offset', ('buffer_load_dwordx2 v[7:8], v0, s[4:7], 0 offen',), 8), + ('other register after a load', ('v_mov_b32_e32 v6, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 6)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} refused', got == REFUSAL, repr(got)) + # Older probes may provide either no tracker or only part of the tracking state. for present in ((), ('uniform_v',), ('uniform_v', 'varying_s')): s = G.Stage.__new__(G.Stage) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e3d9a9605a..2c1fa7b10b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -654,7 +654,10 @@ def smem_mods(mods): 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) -UNIFORM_LOADS = frozenset(('buffer_load_dword', 'buffer_load_format_x')) +UNIFORM_LOAD_WORDS = {'buffer_load_dword': 1, 'buffer_load_dwordx2': 2, 'buffer_load_dwordx3': 3, 'buffer_load_dwordx4': 4, + 'buffer_load_format_x': 1, 'buffer_load_format_xy': 2, 'buffer_load_format_xyz': 3, + 'buffer_load_format_xyzw': 4} +UNIFORM_LOADS = frozenset(UNIFORM_LOAD_WORDS) # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. @@ -1951,10 +1954,13 @@ def one(self, name, asm): all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + loaded_regs = () if loaded: candidate = reg_range(ops[0]) - if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: - dst = candidate[1] + # Exactly the registers the opcode writes, as many as its name says. + count = UNIFORM_LOAD_WORDS[base] + if candidate and candidate[0] == 'v' and candidate[2] <= 255 and candidate[2] - candidate[1] + 1 == count: + dst, loaded_regs = candidate[1], range(candidate[1], candidate[2] + 1) else: loaded = False self.last_v = None @@ -1972,7 +1978,9 @@ def one(self, name, asm): self.defined_uniform_s.discard(r) self.bad_sgprs.add(r) if dst is not None: - self.uniform_v.add(dst) + self.uniform_v.update(loaded_regs or (dst,)) + for reg in loaded_regs: + getattr(self, 'uniform_expr', {}).pop(reg, None) if hasattr(self, 'uniform_expr'): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None From 06718301355edcbb6eeffa40d989d12babc86457 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 23:39:08 +0100 Subject: [PATCH 3/3] startup: read a uniform compute buffer load past the entry block Past the entry block a lane the load skipped keeps an older VGPR, so every lane loads the same words again into a function-scope temporary from an address every lane computes alike, and v_readfirstlane_b32 copies that temporary. Branch targets, EXEC writes and overwrites between the load and the read still refuse, as do per-lane addresses and graphics stages. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 4 +- ...hlsl_readfirstlane_load_recompute_check.py | 141 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 51 +++++-- 6 files changed, 187 insertions(+), 14 deletions(-) create mode 100644 tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 1837fd4118..f876de1756 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -264,6 +264,7 @@ jobs: tests/startup_gfx2hlsl_loop_constants_check.py \ tests/startup_gfx2hlsl_join_symbols_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_calculated_target_check.py \ tests/startup_triage_run_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 6bcd9cd284..d09b462836 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -193,6 +193,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 diff --git a/CMakeLists.txt b/CMakeLists.txt index eb977a69d6..08cf0da652 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4036,6 +4036,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). diff --git a/docs/experiments.md b/docs/experiments.md index 7c81370a70..40733bf839 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14903,12 +14903,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 with a uniform address (the entry-block load proof) is also read past the entry block. A lane the load skipped keeps an older VGPR, so the lowering has every lane load the same words again into a function-scope temporary `ul_`, and the read copies that temporary, for example `ulc_7 = r0.Load(a + 0);` then `s9 = ulc_7;`. The address is the uniform expression of the address VGPR, read before the load can overwrite it, or the VGPR itself while `exec` is still the entry mask (every lane then ran its definition). The branch-target, `exec`-write and overwrite conditions above apply between the load and the read; a later write of the offset scalar does not, because the temporary already holds the words. A per-lane address or offset, a graphics stage and a destination of the wrong width still refuse. `tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py` checks the exact HLSL of the accepted forms (scalar offset, address expression under a narrowed `exec`, address copy under the entry `exec`, the second word of a two-dword load, a conversion of the loaded word and a formatted load) and refuses a join of two definitions, a per-lane address or offset scalar, a back-edge target between load and read, a load inside a block one lane skips, an `exec` narrowing between load and read, a stale address copy, an overwrite and a wrong-width destination; its negative control empties the load allowlist and requires every accepted form to refuse. + [`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 ``` diff --git a/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py new file mode 100644 index 0000000000..640e9b17f8 --- /dev/null +++ b/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py @@ -0,0 +1,141 @@ +"""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;']), + # Under a narrowed EXEC the address is the expression of the VGPR, read before the load overwrites it. + ('address from the expression under a narrowed exec', + JOIN + (NARROW, SCALAR, 'v_mov_b32_e32 v7, s3', 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ), + ['a = (s3) + 0;', 'if (exec & 1) v7 = r0.Load(a + 0);', 'ul14_7 = r0.Load(a + 0);', 's9 = ul14_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)), + # 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) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5f9cfc8fad..388ea02fa4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1871,6 +1871,11 @@ def set_v(self, n, expr, *, low16_only=False): self.clear_low16(n) self.used_v.add(n) self.emit('v%d = %s;' % (n, expr) if self.exec_known else 'if (exec & 1) v%d = %s;' % (n, expr)) + temps = getattr(self, 'uniform_temps', None) + if temps is not None: # a uniform load past the entry block (one()): every lane keeps the words + temps[n] = 'ul%x_%d' % (self.pc, n) + self.uniform_load_temps.add(temps[n]) + self.emit('%s = %s;' % (temps[n], expr)) def f_mods(self, expr, mods=()): # The hardware applies the output modifier before the clamp, but the disassembler prints `clamp` @@ -2395,6 +2400,7 @@ def translate(self): } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.uniform_load_temps = set() # temporaries of uniform loads past the entry block (set_v) self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -2684,24 +2690,39 @@ def one(self, name, asm): if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] # A compute load through a read-only descriptor (a descriptor is never both loaded and stored) with a uniform - # address reads the same dword in every lane. Entry block only: the value has no recomputable expression. - loaded = (dst is None and base in UNIFORM_LOADS and len(ops) == 4 and self.tracks_uniformity() and - getattr(self, 'kind', None) == 'cs' and not getattr(self, 'past_entry', True) and - getattr(self, 'exec_known', False) and - all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and - not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and - (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + # address reads the same dword in every lane. In the entry block with known exec every lane ran it. + load_form = (dst is None and base in UNIFORM_LOADS and len(ops) == 4 and self.tracks_uniformity() and + getattr(self, 'kind', None) == 'cs' and + all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and + not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and + (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + loaded = load_form and not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False) + # Past the entry block a lane the load skipped keeps an older VGPR, so every lane loads the words again into a + # temporary (set_v), and the read copies that temporary. The address comes from the uniform expression of the + # VGPR, or from its copy while exec is still the entry mask (every lane then ran its definition). + vaddr = reg_range(ops[1]) if load_form and ops[1] != 'off' else None + exprs = getattr(self, 'uniform_expr', None) + recomputed = (load_form and not loaded and getattr(self, 'past_entry', False) and exprs is not None and + (vaddr is None or vaddr[1] in exprs or getattr(self, 'exec_known', False))) loaded_regs = () - if loaded: + if loaded or recomputed: candidate = reg_range(ops[0]) # Exactly the registers the opcode writes, as many as its name says. count = UNIFORM_LOAD_WORDS[base] if candidate and candidate[0] == 'v' and candidate[2] <= 255 and candidate[2] - candidate[1] + 1 == count: dst, loaded_regs = candidate[1], range(candidate[1], candidate[2] + 1) else: - loaded = False + loaded = recomputed = False + if recomputed: + # Read before the load can overwrite its own address register. + self.uniform_vaddr = '(%s)' % exprs[vaddr[1]] if vaddr and vaddr[1] in exprs else None + self.uniform_temps = {} self.last_v = None - term = self.lower(base, asm, ops, mods) + try: + term = self.lower(base, asm, ops, mods) + finally: + temps = getattr(self, 'uniform_temps', None) + self.uniform_vaddr = self.uniform_temps = None uniform_written = self._uniform_written if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: self.since_join -= (wrote_s - uniform_written) @@ -2722,11 +2743,13 @@ def one(self, name, asm): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or loaded or any(n not in self.uniform_expr for n in vs): + if expr is None or loaded_regs or any(n not in self.uniform_expr for n in vs): self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], expr) + if recomputed: + self.uniform_expr.update(temps) return term def dpp_pair(self, base, asm, ops, mods): @@ -3918,12 +3941,12 @@ def buffer_address(self, ops, mods): if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: raise Unsupported('buffer vaddr %s for idxen' % ops[1]) stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u(ops[1]), stride)) + terms.append('%s * ud%d' % (getattr(self, 'uniform_vaddr', None) or self.u(ops[1]), stride)) elif offen: r = reg_range(ops[1]) if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: raise Unsupported('buffer vaddr %s for offen' % ops[1]) - terms.append(self.u(ops[1])) + terms.append(getattr(self, 'uniform_vaddr', None) or self.u(ops[1])) elif ops[1] != 'off': raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) if soffset is not None: @@ -6108,6 +6131,8 @@ def declarations(self): lines.append(' v%d = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' % packed) if getattr(self, 'spill_slots', None): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) + if getattr(self, 'uniform_load_temps', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in sorted(self.uniform_load_temps))) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') if getattr(self, 'used_atomic', None): if 'uint' in self.used_atomic: