Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -17331,7 +17331,7 @@ In a local census, 7 compute programs (about 135 thousand Dispatch calls) had an

### An input named by a resource heap record

A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, <root constant word>, 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv <i> buf heap rootconst <parameter> <word>`. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing.
A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, <root constant word>, 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv <i> buf heap rootconst <parameter> <word>`. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. A bounded per-lane waterfall index is lowered onto `resheap` in space 2 by copying the index SGPR into a temporary when the index is marked; the load reads that temporary, and a write of the SGPR that the copy does not capture is refused.

Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer in any form other than the one below (`s_load of a resource heap record whose index is read from a buffer other than a table buffer at a dispatch-constant offset`). A formatted load or a store through such a record, and the graphics stages, are refused as before.

Expand Down
62 changes: 57 additions & 5 deletions tests/startup_compute_waterfall_heap_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
waterfall loops, including both direct heap offsets (s_lshl_b32 + s_load_dwordx4 s[...], s[8:9], sI)
and the adjacent 64-bit pointer-add carry form (s_add_u32 + s_add_u32 0, src_scc / s_addc_u32, with
either in-body s_lshl_b32 or pre-loop v_lshlrev_b32 ..., 5), plus v_min_u32 and v_bfe_u32 bounds.
2. Soundness negative controls: unbounded keys, oversized masks, one-arm diamond bounds, bounded writes under
narrowed EXEC, missing/wrong shift, missing resheap root flag, non-zero high word, broken carry, descriptor
mutation, exit-live scalars, and forbidden store/formatted/idxen uses.
2. Soundness negative controls: unbounded keys (including an unbounded `v_mov_b32` copy), oversized masks,
one-arm diamond bounds, bounded writes under narrowed EXEC, missing/wrong shift, missing resheap root flag,
non-zero high word, broken carry, descriptor mutation, exit-live scalars, forbidden store/formatted/idxen uses,
and a per-lane index expression that still names an SGPR. An index SGPR overwritten after its mark keeps the
mark-time key. `v_lshrrev_b32` bounds declare an exact `rh[N]`.
3. Independent DXIL handle metadata assertions via DXC cs_6_0: confirms the resource handle selects SRV space 2
[0..3] with nonUniformIndex=true, and that stripping NonUniformResourceIndex changes it to false.
4. Four-record GPU oracle (--oracle): reference, static switch, no-marker, and first-active (asserting the
Expand Down Expand Up @@ -108,6 +110,11 @@
's_nop 0': '000080bf',
's_or_b32 s31, s31, 0': '1f801f88',
's_mov_b32 s22, 0': '800396be',
's_mov_b32 s24, 0': '800398be',
's_lshl_b32 s23, s24, 5': '1885178f',
'v_mov_b32_e32 v5, v9': '09030a7e',
'v_lshrrev_b32_e32 v5, 1, v5': '810a0a2c',
'v_lshrrev_b32_e32 v5, 22, v5': '960a0a2c',
'v_mov_b32_e32 v7, s22': '16020e7e',
'v_mov_b32_e32 v7, s28': '1c020e7e',
'buffer_load_dword v7, v4, s[28:31], 0 idxen': '002030e004070780',
Expand Down Expand Up @@ -161,6 +168,18 @@ def row_pair(asm):
return (asm, ENCODINGS[asm])


def assert_pinned_index(hlsl, manifest, assignment, clobber=None, records='resheap 4 2'):
"""The load reads the index copied at the mark, not an SGPR written later."""
lines = [ln.strip() for ln in hlsl.splitlines()]
assert assignment in lines, hlsl
assert 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl
assert manifest.endswith(records + '\n'), manifest
if clobber is not None:
assert clobber in lines, hlsl
assert lines.index(assignment) < lines.index(clobber)
assert not any(ln.startswith('h0 =') for ln in lines[lines.index(clobber) + 1:]), lines


def build_program(*, bound=(MASK_AND3,), init=INIT_AND_GUARD, body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, BODY_LOAD, WAIT_VM),
after_restore=()):
loop = (HEAD, COMPARE, *body, CLOSE)
Expand Down Expand Up @@ -265,7 +284,8 @@ def check_translator(llvm_mc=None):
hlsl_inp, _ = translate(build_program(body=(row_pair('s_lshl_b32 s22, s22, 5'),
row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'),
WAIT_LGKM, BODY_LOAD, WAIT_VM)))
assert 'h0 = (s22 >> 5);' in hlsl_inp
# The key is copied at v_readfirstlane, before the in-place shift replaces s22.
assert 'h0 = s22;' in hlsl_inp and hlsl_inp.index('h0 = s22;') < hlsl_inp.index('s22 = s22 <<')
hlsl_reused, _ = translate(build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, row_pair('s_mov_b32 s22, 0'),
BODY_LOAD, WAIT_VM)))
assert 'h0 = s22;' in hlsl_reused and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_reused
Expand All @@ -274,9 +294,36 @@ def check_translator(llvm_mc=None):
WAIT_LGKM, BODY_LOAD, WAIT_VM)))
assert 'h0 = s22;' in hlsl_ocpy

# An emitted write of the index SGPR between the mark and the load keeps the mark-time key.
zero22 = 's22 = 0x00000000u;'
assert_pinned_index(*translate(build_program(body=(SHIFT5, row_pair('s_mov_b32 s22, 0'), HEAP_LOAD,
WAIT_LGKM, BODY_LOAD, WAIT_VM))),
'h0 = s22;', zero22)
assert_pinned_index(*translate(build_program(
bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 5, v5')),
body=(*CARRY_ADD_S22[:2], row_pair('s_mov_b32 s22, 0'), CARRY_ADD_S22[2], WAIT_LGKM, BODY_LOAD, WAIT_VM))),
'h0 = (s22 >> 5);', zero22)
assert_pinned_index(*translate(build_program(body=(
row_pair('s_lshl_b32 s22, s22, 5'), row_pair('s_mov_b32 s24, s22'), row_pair('s_mov_b32 s22, 0'),
row_pair('s_load_dwordx4 s[28:31], s[8:9], s24'), WAIT_LGKM, BODY_LOAD, WAIT_VM))),
'h0 = s22;', zero22)
assert_pinned_index(*translate(build_program(body=(
row_pair('s_mov_b32 s24, s22'), row_pair('s_lshl_b32 s23, s24, 5'), row_pair('s_mov_b32 s24, 0'),
HEAP_LOAD, WAIT_LGKM, BODY_LOAD, WAIT_VM))),
'h0 = s22;', 's24 = 0x00000000u;')

# v_lshrrev bounds: a bounded source shifts the max index, and a wide source is 0xffffffff >> shift.
hlsl_shr, man_shr = translate(build_program(bound=(MASK_AND3, row_pair('v_lshrrev_b32_e32 v5, 1, v5'))))
assert 'ByteAddressBuffer rh[2] : register(t0, space2);' in hlsl_shr and man_shr.endswith('resheap 2 2\n')
hlsl_wide, man_wide = translate(build_program(bound=(row_pair('v_lshrrev_b32_e32 v5, 22, v5'),)))
assert 'ByteAddressBuffer rh[1024] : register(t0, space2);' in hlsl_wide
assert man_wide.endswith('resheap 1024 2\n'), man_wide

# Negative controls: every missing proof or forbidden extension stays refused.
controls = (
('unbounded key', build_program(bound=()), 'per-lane descriptor selection requires a proven bound heap range'),
('unbounded v_mov copy', build_program(bound=(row_pair('v_mov_b32_e32 v5, v9'),)),
'per-lane descriptor selection requires a proven bound heap range'),
('oversized mask', build_program(bound=(row_pair('v_and_b32_e32 v5, 0x7ff, v5'),)),
'per-lane descriptor selection requires a proven bound heap range'),
('only one diamond arm bounds key',
Expand Down Expand Up @@ -336,6 +383,11 @@ def check_translator(llvm_mc=None):
raise AssertionError(f'{label}: {err}') from None
refused('per-lane descriptor selection requires a proven bound heap range',
lambda: translate(build_program(), root=H.root_blob(flags=0)))
# The load must not fall back to a raw SGPR name: that reads whatever the register holds now.
def stale_capture():
stage = G.ComputePipeline(assemble_rows(build_program()), H.root_blob(), H.RSRC2, GROUP).cs
stage._capture_resheap_desc(('s', 28, 31), 's22', 3)
refused('per-lane resource heap index overwritten before the load', stale_capture)

# Check binary reassembly against llvm-mc if provided.
checked_asm = 0
Expand All @@ -349,7 +401,7 @@ def check_translator(llvm_mc=None):
got = assemble(llvm_mc, asm + '\n')
assert got == bytes.fromhex(hexcode), f'{asm}: {got.hex()} != {hexcode}'
checked_asm += 1
print(f'startup_compute_waterfall_heap: PASS (translator + {len(controls) + 1} refused controls'
print(f'startup_compute_waterfall_heap: PASS (translator + {len(controls) + 2} refused controls'
+ (f' + {checked_asm} llvm-mc encodings' if checked_asm else '') + ')')


Expand Down
63 changes: 56 additions & 7 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4878,6 +4878,7 @@ def one(self, name, asm):
self.uniform_vaddr = '(%s)' % exprs[vaddr[1]] if vaddr and vaddr[1] in exprs else None
self.uniform_temps = {}
self.last_v = None
wrote = ()
if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state
# Any write ends a register's mark; the lowering below sets the new one, if any.
wrote = scalar_destinations(name, asm)
Expand All @@ -4891,6 +4892,8 @@ def one(self, name, asm):
finally:
temps = getattr(self, 'uniform_temps', None)
self.uniform_vaddr = self.uniform_temps = None
if wrote:
self._refuse_overwritten_per_lane(wrote)
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)
Expand Down Expand Up @@ -6284,14 +6287,28 @@ def mark_heap_index(self, base, d, srcs, syms):
self.heap_index[d] = ('buffer',) + word[1:]
elif per_lane is not None:
expr, bound = per_lane
self.heap_index[d] = ('per_lane', ('(s%d >> 5)' % d) if d == r[1] else expr, bound)
# An in-place shift has already replaced sD. The index is that word shifted back, unless a
# temporary already holds the mark-time key.
if not re.fullmatch(r'h\d+', expr) and d == r[1]:
if expr != 's%d' % d:
raise Unsupported('per-lane resource heap index overwritten before the load')
expr = '(s%d >> 5)' % d
self.heap_index[d] = ('per_lane', self._pin_resheap_index(expr), bound)
elif base == 's_mov_b32' and len(srcs) == 1 and r and r[0] == 's' and r[1] == r[2]:
word = {**self.heap_index, **self.heap_index_was}.get(r[1])
per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1])
if word and word[0] == 'per_lane':
self.heap_index[d] = word
expr = word[1]
if not re.fullmatch(r'h\d+', expr) and re.search(r'\bs%d\b' % d, expr):
raise Unsupported('per-lane resource heap index overwritten before the load')
self.heap_index[d] = ('per_lane', self._pin_resheap_index(expr), word[2])
elif per_lane is not None:
self.per_lane_index[d] = ('s%d' % d, per_lane[1])
expr, bound = per_lane
if not re.fullmatch(r'h\d+', expr):
if re.search(r'\bs%d\b' % d, expr) and r[1] != d:
raise Unsupported('per-lane resource heap index overwritten before the load')
expr = self._pin_resheap_index('s%d' % d)
self.per_lane_index[d] = (expr, bound)
elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2:
for i in (0, 1):
k = lit[1 - i]
Expand Down Expand Up @@ -6914,13 +6931,43 @@ def op_s_load_dwordx4(self, ops, mods, count=4):
return self.heap_record(dst, base, token, imm, count)
raise Unsupported('s_load with a register offset through %s' % (p[1],))

def _capture_resheap_desc(self, dst, expr, bound):
def _pin_resheap_index(self, expr):
"""Copy a per-lane heap index where its mark is made, not at the s_load.

The load used to read the SGPR name, so a write of that SGPR before the load selected record 0.
A temporary already captured (hN) is kept. The load refuses an expression that still names an SGPR.
"""
if re.fullmatch(r'h\d+', expr or ''):
return expr
if not hasattr(self, 'resheap_index_temps'):
self.resheap_index_temps = []
temp = 'h%d' % len(self.resheap_index_temps)
self.resheap_index_temps.append(temp)
self.emit('%s = %s;' % (temp, expr))
source = ('resheap', 'per_lane', temp, bound)
return temp

def _refuse_overwritten_per_lane(self, wrote):
"""Refuse a per-lane index expression that still names an SGPR this instruction wrote."""
def stale(expr):
if not isinstance(expr, str) or re.fullmatch(r'h\d+', expr):
return False
if 'any' in wrote:
return re.search(r'\bs\d+\b', expr) is not None
return any(isinstance(n, int) and re.search(r'\bs%d\b' % n, expr) for n in wrote)

for mark in self.heap_index.values():
if isinstance(mark, tuple) and mark and mark[0] == 'per_lane' and len(mark) > 1 and stale(mark[1]):
raise Unsupported('per-lane resource heap index overwritten before the load')
for item in getattr(self, 'per_lane_index', {}).values():
if item and stale(item[0]):
raise Unsupported('per-lane resource heap index overwritten before the load')

def _capture_resheap_desc(self, dst, expr, bound):
if not re.fullmatch(r'h\d+', expr or ''):
if re.search(r'\bs\d+\b', expr or ''):
raise Unsupported('per-lane resource heap index overwritten before the load')
expr = self._pin_resheap_index(expr)
source = ('resheap', 'per_lane', expr, bound)
for i in range(4):
self.sym[dst[1] + i] = ('desc', source, 0, i)

Expand Down Expand Up @@ -9321,10 +9368,12 @@ def op_v_readfirstlane_b32(self, ops, mods):
self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes
bound = getattr(self, 'waterfall_heap_bounds', {}).get(self.pc)
if bound:
# Snapshot the key now. A later write of this SGPR must not change the record the load reads.
if bound[0] == 'idx':
self.per_lane_index[dst[1]] = ('s%d' % dst[1], bound[1])
self.per_lane_index[dst[1]] = (self._pin_resheap_index('s%d' % dst[1]), bound[1])
elif bound[0] == 'off5':
self.heap_index[dst[1]] = ('per_lane', '(s%d >> 5)' % dst[1], bound[1])
pinned = self._pin_resheap_index('(s%d >> 5)' % dst[1])
self.heap_index[dst[1]] = ('per_lane', pinned, bound[1])
return
if (mods 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 not self.proven_uniform_v(src[1])):
Expand Down
Loading