Skip to content
Closed
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
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2371,6 +2371,9 @@ if(EXISTS "${INTAKE_PYTHON}")
set_tests_properties(startup_live_view PROPERTIES TIMEOUT 60)
add_test(NAME startup_uniform_lane COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py")
# v_readfirstlane_b32 in a program with branches: proven inside one basic block, refused across a join or exec write.
add_test(NAME startup_readfirstlane_branch COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_readfirstlane_branch_check.py")
# NGG primitive-shader cases (#1723): identity triangle against single-change contrasts, reference model.
add_test(NAME startup_ngg_slice COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_ngg_slice_check.py")
Expand Down
6 changes: 4 additions & 2 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -12144,12 +12144,14 @@ In straight-line code with a known `exec`, the proof follows `v_cvt_u32_f32`, `v

Uniform sources include inline constants and literals, SGPRs holding constants, user data or fixed buffer words, other SGPRs tracked as uniform, and VGPRs with an existing proof. A scalar result is tracked as varying when its expression depends on `vcc`, `exec`, `m0`, a varying scalar register, a VGPR without a proof, or a varying `scc`. Descriptor, pointer, and sampler symbols, and SGPRs holding a lane mask (a compare result, even from uniform operands), are treated as non-uniform sources. A 64-bit move proves its high word only from the source high word as it was before the move, never when the destination overlaps it, and a descriptor-path move carries a high-word symbol only when that symbol does not depend on the register's run-time contents. SCC follows the same dependency tracking, with saveexec and wrexec marking it varying. A scalar write to `m0` that also sets SCC judges SCC from the write's sources, so `s_and_b32 m0, vcc_lo, -1` makes it varying while a write from uniform scalars makes it uniform. Instructions whose SCC result is not modelled (`s_add`, `s_sub`, `s_min` and `s_max`, `s_wqm`, and scalar ops on symbolic descriptor words, which emit nothing) mark SCC varying. Scalar buffer loads track the original offset across every destination word, including when the emitted code saves it in a temporary.

An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the proof and the read are accepted only in the entry block: before the first branch target and before the first terminator. Every path reaches those instructions through the same instructions, so the program-order tracking is exact there. A branch back to the first instruction makes the whole program refuse, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source.
An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the entry block (before the first branch target and the first terminator) is always exact in program order, because every path reaches it through the same instructions. Later blocks are accepted only when the proof is made inside one basic block: every branch target clears all VGPR proofs, and no instruction anywhere in the program writes `exec` (`exec` moves, `saveexec`, `wrexec` and `v_cmpx` all count). A whole-program scan also marks every scalar register, and `m0`, that can hold a per-lane value (compare results, `exec`/`vcc` copies, and selects on a per-lane SCC) as non-uniform, even when the write sits in a later block that loops back. A scalar register written in any later block is trusted in a later block only if that same block redefines it, because a join carries a different value per incoming path (two arms that set `s7` to 1 and 2 leave no single value at the join). A branch back to the first instruction refuses every proof, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source.

`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, 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, after the first terminator, or in an entry block re-entered by a loop), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse.

`tests/startup_readfirstlane_branch_check.py` covers the branch case: a block-local read is accepted, while a join point, an `exec` write, `wrexec`, a per-lane SCC and `m0` taint are refused.

```powershell
ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_readfirstlane_uniform$' -V
ctest --preset dev --no-tests=error -R '^startup_(gfx2hlsl_readfirstlane_uniform|readfirstlane_branch)$' -V
```

## Desktop audio render sink
Expand Down
66 changes: 66 additions & 0 deletions tests/startup_readfirstlane_branch_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""v_readfirstlane_b32 in a program with branches: the entry block is proven in program order (#2183); a later block is
proven only inside itself, with no exec write anywhere and no loop back to the entry."""
from pathlib import Path
import struct
import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/startup"))
import gfx2hlsl as gfx


class TestPipeline:
root = {"params": [{"type": 2}], "flags": 0}

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


S_BRANCH_NEXT = 0xbf820000 # s_branch +0: the next instruction becomes a block start
S_BRANCH_ENTRY = 0xbf820000 | 0xfffb # s_branch back to offset 0 when placed at word 4 (after S_LOAD, CVT, READ)
S_EXEC_LO_ZERO = 0xbe800300 | 126 << 16 | 128 # s_mov_b32 exec_lo, 0
S_LOAD = [0xf4000000 | 8 << 18 | 7 << 6 | 4, 125 << 25 | 12] # s_buffer_load_dword s7, s[8:11], 12
CVT_V4 = 0x7e000000 | 4 << 17 | 8 << 9 | 7 # v_cvt_i32_f32 v4, s7
READ_V4 = 0x7e000000 | 6 << 17 | 2 << 9 | 256 + 4 # v_readfirstlane_b32 s6, v4
END = 0xbf810000
CMP_V0 = 0x7c000000 | 0x82 << 17 | 128 # v_cmp_eq_i32 vcc, 0, v0 (per-lane)
BRANCH_VCCZ_2 = 0xbf860000 | 2 # s_cbranch_vccz +2
BRANCH_OVER_1 = 0xbf820000 | 1 # s_branch +1
MOV_V4_S7 = 0x7e000000 | 4 << 17 | 1 << 9 | 7 # v_mov_b32 v4, s7


def mov_s7(value): # s_mov_b32 s7, <inline constant>
return 0xbe800300 | 7 << 16 | 128 + value


def translate(*words):
words = [*S_LOAD, *words]
return gfx.Stage(TestPipeline(), "ps", struct.pack(f"<{len(words)}I", *words))


def body(*words):
return "\n".join(line for block in translate(*words).blocks for line in block[1])


# Accepted, one per rule: the entry block, and a later block whose proof is made inside that block.
assert "s6 = v4;" in body(CVT_V4, READ_V4, S_BRANCH_NEXT, END), "entry block read refused"
assert "s6 = v4;" in body(S_BRANCH_NEXT, CVT_V4, READ_V4, END), "later block read refused"

# Accepted: the join block redefines s7 itself, so the proof does not lean on the two arms.
DIAMOND = [CMP_V0, BRANCH_VCCZ_2, mov_s7(1), BRANCH_OVER_1, mov_s7(2)]
assert "s6 = v4;" in body(*DIAMOND, mov_s7(3), MOV_V4_S7, READ_V4, END), "same-block redefinition refused"

# Refused: a join between proof and read, an exec write before the read (even in a later block), an exec write
# in a later block when the read sits in a later block, and a loop back to the entry block.
for words in ([CVT_V4, S_BRANCH_NEXT, READ_V4, END],
[S_EXEC_LO_ZERO, CVT_V4, READ_V4, S_BRANCH_NEXT, END],
[S_BRANCH_NEXT, CVT_V4, READ_V4, S_EXEC_LO_ZERO, END],
[CVT_V4, READ_V4, S_BRANCH_ENTRY, END],
# a varying branch picks s7 = 1 or s7 = 2; the join reads whichever arm ran last in program order
[*DIAMOND, MOV_V4_S7, READ_V4, END]):
try:
translate(*words)
except gfx.Unsupported as error:
assert "requires a proven uniform source" in str(error), str(error)
else:
raise AssertionError("accepted an unproven readfirstlane: %r" % (words,))
print("readfirstlane with branches: entry and later-block proofs accepted; five unproven reads rejected")
95 changes: 92 additions & 3 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,12 +700,18 @@ def translate(self):
self.varying_s = set()
self.scc_uniform = True
self.has_branches = bool(targets)
self.entry_loop = 0 in targets
self.branch_proof, self.tainted_s = self.scan_branch_safety() if targets else (False, set())
self.later_written = self.scan_later_writes(targets) if targets else set()
self.block_sdef = set() # scalar registers written so far in the current block
start = 0
refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__
for off, n, name, asm in self.ins:
if off in targets and off != start:
self.blocks.append((start, self.lines, None))
self.lines, start = [], off
self.uniform_v.clear() # a join point: no VGPR proof survives from the code above it
self.block_sdef = set()
self.pc = off
# Before the first branch target or terminator every path has run exactly the instructions above, so
# the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a
Expand All @@ -723,12 +729,91 @@ def translate(self):
raise
refusals.append((handler_error(name, error, refusals), self.kind))
continue
self.block_sdef.update(self.scalar_dst(name, parse(asm)[1]))
if term:
self.blocks.append((start, self.lines, term))
self.lines, start = [], off + n
self.uniform_v.clear()
self.block_sdef = set()
if self.lines:
self.blocks.append((start, self.lines, None))

def scan_branch_safety(self):
"""-> (proof_ok, tainted_s) for a program with branches. VGPR uniformity is proven inside one basic block
only (see translate), and only when no instruction anywhere writes exec (including the implicit writes of
saveexec, wrexec and v_cmpx), so exec_known holds on every path. tainted_s holds each scalar register
(and 'm0') that can carry a per-lane value: a compare, an exec-derived mask, or a select on a per-lane SCC.
It is found over the whole program because a loop can bring a later write back to an earlier read."""
lane_names = ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi', 'vccz', 'execz')
parsed = []
proof_ok = True
for _, _, name, asm in self.ins:
_, ops, _ = parse(asm)
parsed.append((name, ops))
if (ops and ops[0] in ('exec', 'exec_lo', 'exec_hi')) or 'saveexec' in name or 'wrexec' in name or \
name.startswith('v_cmpx'):
proof_ok = False

def keys(tok):
if tok == 'm0':
return ['m0']
r = reg_range(tok)
return list(range(r[1], r[2] + 1)) if r and r[0] == 's' else []

tainted = set()
scc_tainted = False
changed = True
while changed:
changed = False
for name, ops in parsed:
if not ops or name.startswith('v_readfirstlane'):
continue
no_dst = re.match(r's_(cmp|bitcmp|cbranch)', name) is not None
srcs = ops if no_dst else ops[1:]
src_hot = any(tok in lane_names or any(k in tainted for k in keys(tok)) for tok in srcs)
# Any scalar op fed by a per-lane value may leave a per-lane SCC (compare, and/or, shifts, ...).
if name.startswith('s_') and src_hot and not scc_tainted:
scc_tainted = changed = True
dst = [] if no_dst else keys(ops[0])
if not dst:
continue
hot = name.startswith('v_cmp') or src_hot or (
scc_tainted and re.match(r's_(cselect|cmov|addc|subb)', name) is not None)
if hot and not all(k in tainted for k in dst):
tainted.update(dst)
changed = True
return proof_ok, tainted

@staticmethod
def scalar_dst(name, ops):
"""Scalar registers (and 'm0') an instruction may write: its first operand when that is scalar."""
if not ops or re.match(r's_(cmp|bitcmp|cbranch)', name):
return []
if ops[0] == 'm0':
return ['m0']
r = reg_range(ops[0])
return list(range(r[1], r[2] + 1)) if r and r[0] == 's' else []

def scan_later_writes(self, targets):
"""Scalar registers written anywhere after the first block boundary. Such a register holds a different
value per incoming path at a join, so the value last seen in program order proves nothing there."""
ends = ('s_branch', 's_cbranch', 's_endpgm', 's_setpc', 's_swappc')
boundary = min([t for t in targets if t > 0] + [off + n for off, n, name, _ in self.ins
if name.startswith(ends)])
written = set()
for off, _, name, asm in self.ins:
if off >= boundary:
written.update(self.scalar_dst(name, parse(asm)[1]))
return written

def proof_allowed(self):
"""Entry-block code is exact in program order (merged entry proof). Later blocks need the branch scan to
pass and no branch back to offset 0, so an entry loop keeps refusing."""
if not getattr(self, 'past_entry', True):
return True
return (not getattr(self, 'entry_loop', True) and
(not getattr(self, 'has_branches', True) or getattr(self, 'branch_proof', False)))

def tracks_uniformity(self):
return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform'))

Expand All @@ -740,8 +825,12 @@ def uniform_source(self, tok):
return False
if kind == 'v':
return lo in self.uniform_v
if lo in getattr(self, 'masks', ()):
if lo in getattr(self, 'masks', ()) or (getattr(self, 'has_branches', False) and
lo in getattr(self, 'tainted_s', ())):
return False
if (getattr(self, 'has_branches', False) and getattr(self, 'past_entry', False) and
lo in getattr(self, 'later_written', ()) and lo not in getattr(self, 'block_sdef', ())):
return False # per-path value at a join: redefine it in this block to prove it
sym = self.sym.get(lo)
if sym:
return sym[0] in ('const', 'ud', 'fixed_buffer_word')
Expand All @@ -761,7 +850,7 @@ def one(self, name, asm):
dst = None
# Unit probes build a Stage without __init__: without the tracking state, prove nothing.
if (base in UNIFORM_VALU and ops and self.tracks_uniformity() and
not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False) and
self.proof_allowed() and getattr(self, 'exec_known', False) and
(not mods or (base in VEC_F or base in VEC_U_TO_F) and
all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods))):
candidate = reg_range(ops[0])
Expand Down Expand Up @@ -1855,7 +1944,7 @@ def op_v_cvt_i32_f32(self, ops, mods):

def op_v_readfirstlane_b32(self, ops, mods):
src, dst = reg_range(ops[1]), reg_range(ops[0])
if (mods or not self.tracks_uniformity() or getattr(self, 'past_entry', True) or
if (mods or not self.tracks_uniformity() or not self.proof_allowed() or
not getattr(self, 'exec_known', False) or not dst or dst[0] != 's' or dst[1] != dst[2] or
not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v):
raise Unsupported('v_readfirstlane_b32 requires a proven uniform source')
Expand Down
Loading