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
8 changes: 8 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -15484,6 +15484,14 @@ ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(unifor
python -B tests/startup_compute_readfirstlane_check.py --llvm-mc llvm-mc-15
```

The same checks exercise a [four-thread resource-index waterfall](../tests/startup_compute_waterfall.py) for #2644.
`v_readfirstlane_b32` selects a key and the following `v_cmpx_eq_i32` enables the lanes sharing that key. A saved
copy of `exec_lo`, `s_andn2_wrexec_b32` and a backward `s_cbranch_scc1` serve the remaining lanes. Each participating
lane can execute one visit with its own key when the body performs proven lane-local operations and its temporary
scalars are dead at exit. The fixtures vary the active count from zero to four, restore EXEC, and check both an
arithmetic result and a key-dependent byte offset in one fixed raw buffer. A read of the group's active mask,
a store inside the loop, a live scalar or a key-selected descriptor keeps an instruction-specific refusal.

## Desktop audio render sink

`startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes.
Expand Down
19 changes: 14 additions & 5 deletions tests/startup_compute_readfirstlane_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
reads it through ``v_readfirstlane_b32`` at the join, runs a four-iteration uniform loop whose counter ``s22`` is
incremented uniformly and read back via ``v_readfirstlane_b32`` both inside the loop and after loop exit, and stores
one combined word per thread across two four-thread groups ``(4, 1, 1) x (2, 1, 1)`` so both arms of the branch
run on the GPU.
run on the GPU. The waterfall fixtures also exercise a lane-varying key. They restore the incoming threads
after selecting zero to four lanes, then read back per-key arithmetic and a load from one fixed raw buffer.
"""
import argparse
from pathlib import Path
Expand All @@ -23,6 +24,7 @@
sys.path.insert(0, str(HERE.parent / 'tools' / 'startup'))

import disasm_rdna2 as D # noqa: E402
import startup_compute_waterfall as waterfall
from startup_gfx2hlsl_compute_check import ( # noqa: E402
CASES, G, KEY, MASK, SENTINEL, STRIDE, WORDS, patch, refused, root_blob,
)
Expand Down Expand Up @@ -194,7 +196,8 @@ def controls(llvm_mc=None):

if llvm_mc:
check_binary(llvm_mc)
print('Compute readfirstlane one-path, loop-counter and refusal checks passed')
waterfall.controls(llvm_mc)
print('Compute readfirstlane one-path, loop-counter, waterfall and refusal checks passed')


CONTROLS = {
Expand Down Expand Up @@ -231,18 +234,24 @@ def dispatch(dxc, runner, adapter):
print(proc.stdout, end='')
if proc.returncode == 77:
return 77
diagnostics = []
for line in proc.stderr.splitlines():
if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '):
print(line, file=sys.stderr)
else:
diagnostics.append(line)
if mutation:
want = CONTROLS[mutation][2]
first = proc.stderr.strip().splitlines()[:1]
first = diagnostics[:1]
if proc.returncode != 1 or first != [want]:
raise AssertionError('control %s: expected exit 1 with %r, got exit %d %r'
% (mutation, want, proc.returncode, proc.stderr))
print('control %s (%s): rejected at %s' % (mutation, adapter, first[0]))
elif proc.returncode or proc.stderr:
elif proc.returncode or diagnostics:
raise AssertionError('baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode))
else:
print('baseline (%s): all %d words match' % (adapter, WORDS))
return 0
return waterfall.dispatch(td, dxc, runner, adapter)


def main(argv):
Expand Down
107 changes: 107 additions & 0 deletions tests/startup_compute_waterfall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Source-built four-lane numeric waterfall for the compute readfirstlane fixture (#2644)."""
import struct
import subprocess

from compute_load_format_check import check_references
from startup_gfx2hlsl_compute_check import G, MASK, SENTINEL, USER7, WORDS, assemble, refused, root_blob


# The input buffer contains the keys. Root constant s4 selects how many lanes enter the loop.
# Every lane writes its result after the original EXEC is restored, including the initial 13 for inactive lanes.
PREFIX = (
('s_mov_b32 s10, s6', '06038abe'), ('s_mov_b32 s11, 0', '80038bbe'),
('s_load_dwordx8 s[12:19], s[10:11], 0', '05030cf4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'),
('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), ('buffer_load_dword v5, v4, s[12:15], 0 offen', '001030e004050380'),
('s_waitcnt vmcnt(0)', '703f8cbf'), ('v_mov_b32_e32 v7, 13', '8d020e7e'),
('s_mov_b32 s26, exec_lo', '7e039abe'), ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'),
)
SAVE = ('s_mov_b32 s21, exec_lo', '7e0395be')
HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e')
COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d')
ADD = ('s_add_u32 s23, s22, 17', '16911780')
XOR = ('v_xor_b32_e32 v7, s23, v0', '17000e3a')
CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be')
RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe')
STORE = ('buffer_store_dword v7, v4, s[16:19], 0 offen', '001070e004070480')
END = ('s_endpgm', '000081bf')
FIXED_LOAD = (('s_load_dwordx4 s[28:31], s[10:11], 0', '050708f4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'),
('v_mov_b32_e32 v8, s22', '1602107e'), ('buffer_load_dword v7, v8, s[28:31], 0 offen', '001030e008070780'),
('s_waitcnt vmcnt(0)', '703f8cbf'))


def program(*, before_save=(), after_save=(), compare=COMPARE, body=(ADD, XOR), after_restore=()):
loop = (HEAD, compare, *body, CLOSE)
offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1)
branch = ('s_cbranch_scc1 %d' % offset, struct.pack('<I', 0xbf850000 | (offset & 0xffff)).hex())
return (*PREFIX, *before_save, SAVE, *after_save, *loop, branch, RESTORE, *after_restore, STORE, END)


def translate(rows, group=(4, 1, 1)):
code = bytes.fromhex(''.join(word for _, word in rows))
return G.ComputePipeline(code, root_blob(), USER7, group).hlsl_cs()


def controls(llvm_mc=None):
live = ('v_mov_b32_e32 v7, s23', '17020e7e')
copy = ('s_mov_b32 s24, s21', '150398be')
reset = ('s_mov_b32 s23, 0', '800397be')
conditional = ('s_cbranch_scc0 1', '010084bf')
cases = (
(program(), None),
(program(after_save=(('s_nop 0', '000080bf'),)), None),
(program(body=FIXED_LOAD), None),
(program(after_restore=(reset, live)), None),
(program(body=(('s_mov_b32 s23, s22', '160397be'), ('s_lshl_b32 s23, s23, 1', '1781178f'),
('s_or_b32 s23, s23, 1', '17811788'), ('s_and_b32 s23, s23, 31', '179f1787'),
('v_add_nc_u32_e32 v7, s23, v0', '17000e4a'))), None),
(program(body=(STORE,)), 'body instruction buffer_store_dword'),
(program(body=(('v_mbcnt_lo_u32_b32 v7, exec_lo, 0', '070065d77e000100'),)), 'body instruction v_mbcnt'),
(program(after_restore=(live,)), 'body scalar is live'),
(program(after_restore=(conditional, reset, live)), 'body scalar is live'),
(program(after_save=(('s_mov_b32 s21, 1', '810395be'),)), 'unchanged copy of EXEC'),
(program(body=(('s_add_u32 s23, s23, 1', '17811780'), XOR)), 'loop-carried scalar'),
(program(body=(('s_add_u32 s23, 0, src_scc', '80fd1780'), XOR)), 'loop-carried scalar'),
(program(body=(copy, XOR)), 'reads or changes a lane mask'),
(program(compare=('v_cmpx_eq_i32_e32 s22, v4', '1608247d')), 'same key'),
(program(before_save=(conditional,)), 'another branch enters'),
(program(body=(('s_load_dwordx4 s[28:31], s[22:23], 0', '0b0708f4000000fa'), *FIXED_LOAD[1:])),
'per-lane descriptor selection'),
)
for rows, reason in cases:
if llvm_mc:
source = '\n'.join(asm for asm, _ in rows) + '\n'
assert assemble(llvm_mc, source) == bytes.fromhex(''.join(word for _, word in rows)), source
if reason:
refused(reason, lambda: translate(rows))
else:
assert 's22 = v5;' in translate(rows)
refused('at most 32 threads', lambda: translate(program(), (33, 1, 1)))


def dispatch(directory, dxc, runner, adapter):
for label, body in (('arithmetic', (ADD, XOR)), ('fixed-buffer', FIXED_LOAD)):
src, shader = directory / 'waterfall.hlsl', directory / 'waterfall.cso'
src.write_text(translate(program(body=body)), encoding='ascii')
subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', shader, src], check=True)
cases = []
inputs = [(n, (64, 32, 64, 96)) for n in range(5)]
if label == 'arithmetic':
inputs.append((4, (MASK, MASK, 0, 0)))
for active, keys in inputs:
source = [17 * i + 9 for i in range(WORDS)]
source[:4] = keys
output = [13] * 4
for lane, key in enumerate(keys[:active]):
output[lane] = (((key + 17) & MASK) ^ lane) if label == 'arithmetic' else source[key // 4]
case = directory / ('waterfall-%d.case' % len(cases))
words = [1, *output, *([SENTINEL] * (WORDS - 4)), active, *([0] * 15), *source]
case.write_bytes(struct.pack('<%dI' % len(words), *words))
cases.append((case, 'keys %s, %d active' % (keys, active), None))
if active == 4 and keys[0] != keys[1]:
wrong = (output[0] ^ 1) if label == 'arithmetic' else output[0]
words[2] = wrong # lane 1 using lane 0's key
case = directory / 'waterfall-wrong.case'
case.write_bytes(struct.pack('<%dI' % len(words), *words))
cases.append((case, 'uniform key', 'word=1 expected=%08x actual=%08x' % (wrong, output[1])))
check_references(label + ' waterfall', runner, adapter, shader, cases)
return 0
97 changes: 97 additions & 0 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2349,6 +2349,13 @@ def execz_refusals(self):
value = reads | (out - writes)
if value != live_in[i]:
live_in[i], changed = value, True
self.waterfall_reads = {}
for close, target in jumps:
head = index.get(target)
if (head is not None and head + 3 < close and self.ins[close][2] == 's_cbranch_scc1'
and self.ins[head][2] == 'v_readfirstlane_b32'
and self.ins[close - 1][2] == 's_andn2_wrexec_b32'):
self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps)
refused = {}
for b, (off, n, name, asm) in enumerate(self.ins):
if name != 's_cbranch_execz':
Expand Down Expand Up @@ -2395,6 +2402,89 @@ def execz_refusals(self):
refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason))
return refused

def waterfall_refusal(self, head, close, effects, live_in, jumps):
"""Return None when the lane can pick its own key at the head of the waterfall.

CMPX selects all remaining lanes with the first lane's key. WREXEC removes those lanes,
so each incoming lane participates exactly once. A lane-local body computes its value on
that visit. Other visits can only affect it through shared state or an escaping scalar.
"""
ins = self.ins
_, key_ops, mods = parse(ins[head][3])
if (mods or len(key_ops) != 2 or not re.fullmatch(r's\d+', key_ops[0])
or not re.fullmatch(r'v\d+', key_ops[1])):
return 'unsupported key operands'
key = key_ops[0]
name, ops, mods = parse(ins[head + 1][3])
if re.sub(r'_e(32|64)$', '', name) != 'v_cmpx_eq_i32' or mods or ops != key_ops:
return 'the next instruction does not select lanes with the same key'
_, ops, mods = parse(ins[close - 1][3])
if mods or len(ops) != 2 or ops[0] != ops[1] or not re.fullmatch(r's\d+', ops[0]) or ops[0] == key:
return 'the closing mask is not a distinct remaining-lanes register'
remaining = ops[0]
# The b32 close covers only the low 32 lanes when the hardware uses wave64.
x, y, z = self.pipe.group
if x * y * z > 32:
return 'b32 remaining mask requires at most 32 threads per group'
copy = None
for i in reversed(range(head)):
_, _, op, asm = ins[i]
if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_endpgm', 's_movrel')):
break
if remaining in effects[i][2] or effects[i][2] & EXEC_KEYS:
if op == 's_mov_b32' and parse(asm)[1] == [remaining, 'exec_lo']:
copy = i
break
if copy is None:
return 'remaining mask is not an unchanged copy of EXEC'
if any(ins[copy][0] < target <= ins[close][0] for branch, target in jumps if branch != close):
return 'another branch enters the saved mask or loop'
# Only ordinary lane-local operations and reads of a bound raw buffer. An instruction
# that observes the other lanes sharing this key cannot use this scalarization (e.g. mbcnt of EXEC).
body_writes = {key, 'scc'} # WREXEC supplies SCC for the next iteration.
numeric_writes = {key}
descriptor_inputs, buffer_descriptors = set(), set()
reads_before_write = set()
defined = {key}
for j in range(head + 2, close - 1):
base, ops, mods = parse(ins[j][3])
base = re.sub(r'_e(32|64)$', '', base)
if base not in ('s_add_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt',
'v_mov_b32', 'v_xor_b32', 'v_add_nc_u32', 's_load_dwordx4', 'buffer_load_dword'):
return 'body instruction %s is not proven lane-local' % base
if mods and not (base == 'buffer_load_dword' and mods == ['offen']):
return 'body instruction %s has unproved modifiers' % base
reads, writes, may_write = effects[j]
if (reads | may_write) & (EXEC_KEYS | {'vcc', 'vcc_hi', 'm0', remaining}):
return 'body reads or changes a lane mask or special register'
if base == 's_load_dwordx4':
dst = reg_range(ops[0]) if len(ops) == 3 else None
if not dst or dst[0] != 's' or dst[2] > 105:
return 'descriptor load overlaps a special register'
descriptor_inputs.update(reads)
else:
numeric_writes.update(may_write)
if base == 'buffer_load_dword':
if len(ops) < 3:
return 'buffer load has no descriptor'
buffer_descriptors.update(scalar_tokens(ops[2]))
reads_before_write.update(reads - defined)
defined.update(writes)
body_writes.update(may_write)
if reads_before_write & body_writes:
return 'body reads loop-carried scalar state'
# The data byte offset can use the key. Loading or modifying the resource descriptor
# with the key needs a separate proof that the runtime binds the whole range.
if descriptor_inputs & body_writes or buffer_descriptors & numeric_writes:
return 'per-lane descriptor selection requires a proven bound heap range'
# The close leaves EXEC and SCC zero. The last physical pass's other scalar
# values can differ per lane in this model and must be dead on every successor.
if close + 1 < len(ins) and (body_writes - {'scc'}) & live_in[close + 1]:
return 'body scalar is live at the loop exit'
if any(name.startswith('s_movrel') for _, _, name, _ in ins):
return 'relative scalar indexing can observe a loop register'
return None

def phi_mask_ok(self, key, b, t, effects, succ, targets, index):
"""True when lane mask `key` ('vcc' for vcc_lo, or 'sN'), live at the join t of the s_cbranch_execz at b, is
the zeroed-then-set-from-exec shape execz_refusals accepts (see its docstring): every write of it in the
Expand Down Expand Up @@ -6119,6 +6209,13 @@ def proven_uniform_v(self, n):
def op_v_readfirstlane_b32(self, ops, mods):
src, dst = reg_range(ops[1]), reg_range(ops[0])
past_entry = getattr(self, 'past_entry', True)
waterfalls = getattr(self, 'waterfall_reads', {})
if getattr(self, 'pc', None) in waterfalls and not (src and self.proven_uniform_v(src[1])):
reason = waterfalls[self.pc]
if reason:
raise Unsupported('compute readfirstlane waterfall: ' + reason)
self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes
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])):
raise Unsupported('v_readfirstlane_b32 requires a proven uniform source')
Expand Down
Loading