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
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3431,6 +3431,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# Handlers that do not model a modifier they can receive refuse it (#1771).
add_test(NAME startup_gfx2hlsl_modifier_free COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_modifier_free_check.py")
# The src_scc scalar source (#1820).
add_test(NAME startup_gfx2hlsl_src_scc COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py")
# image_sample_c_lz with sampler word 2 bits 28-30 set (#1723).
add_test(NAME startup_gfx2hlsl_sample_c_lz_mip COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sample_c_lz_mip_check.py")
Expand Down
11 changes: 11 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -16692,3 +16692,14 @@ Linux controls, `form_coverage_check.check_sdwa_cvt_forms`, and Python reference
```powershell
ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_scalar_null_(controls|warp|hardware)$" -V
```
## `src_scc` as a scalar source

`s_mul_i32 s28, 1.0, src_scc` was refused as `operand 'src_scc'` (issue #1820), one of the refused shaders
in the loading-screen cache (#870). Scalar source code 253 reads the SCC bit as the integer value 0 or 1
(fitting in 16 bits, so `low16_only=True` returns the same expression), and the generated shader carries SCC
as a `bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC
on every reaching path in the current block (`s_cmp_*` / `s_and_b32` etc. via `set_scc()`, `set_exec_scc()`,
or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at shader entry, across
control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in
`SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run
`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`.
194 changes: 194 additions & 0 deletions tests/startup_gfx2hlsl_src_scc_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
"""The `src_scc` scalar source in tools/startup/gfx2hlsl.py (issue #1820).

usage: startup_gfx2hlsl_src_scc_check.py

The census contained `s_mul_i32 s28, 1.0, src_scc`, refused as `operand 'src_scc'` (#870, issue #1820).
Source code 253 reads the SCC bit as the integer value 0 or 1; the generated shader carries SCC as a
`bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC on
every reaching path in the current block, and refuses when the incoming SCC is unverified (at shader entry,
after an unmodeled SCC writer such as `s_add_u32`, after descriptor-elided SCC, or across control-flow
joins).

The instruction bytes are **constructed here** from the field layout the checked-in decoder reads
(`tools/disasm_rdna2.py`):
- SOP2 (`[31:30] == 0b10`, op in `w0[29:23]`, sdst in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`,
optional literal dword when a source is 255)
- SOPC (`[31:23] == 0b101111110`, op in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`)
- SOPP (`[31:23] == 0b101111111`, op in `w0[22:16]`, simm16 in `w0[15:0]`)
"""
import os
import struct
import sys

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

failures = []


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


SOP2_ADD_U32 = 0x00
SOP2_AND_B32 = 0x0E
SOP2_MUL_I32 = 0x26
SOPC_CMP_EQ_U32 = 0x06
SOPP_NOP = 0x00
SOPP_ENDPGM = 0x01
SOPP_CBRANCH_SCC0 = 0x04

S_ZERO = 128 # inline integer 0
S_ONE = 129 # inline integer 1
S_SCC = 253 # the src_scc scalar source code
S_1_0 = 242 # the inline float constant 1.0 (its raw bits are 0x3f800000)
LITERAL = 255
S1, S4, S5, S27, S28, S29 = 1, 4, 5, 27, 28, 29


def encode_sop2(op, sdst, ssrc0, ssrc1, literal=None):
w0 = ((0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16)
| ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF))
code = struct.pack('<I', w0)
if literal is not None:
code += struct.pack('<I', literal)
return code


def encode_sopc(op, ssrc0, ssrc1, literal=None):
w0 = (0xBF000000 | ((op & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF))
code = struct.pack('<I', w0)
if literal is not None:
code += struct.pack('<I', literal)
return code


def encode_sopp(op, simm=0):
w0 = 0xBF800000 | ((op & 0x7F) << 16) | (simm & 0xFFFF)
return struct.pack('<I', w0)


class Pipeline:
"""Just enough pipeline state for Stage.translate()."""

def __init__(self):
self.resources, self.notes, self.modified = {}, set(), set()


def translate_program(code):
"""Decode and run the full Stage.translate() CFG/block pass on synthetic bytes."""
decoded = G.decode(code)
stage = G.Stage.__new__(G.Stage)
stage.pipe = Pipeline()
stage.kind = 'ps'
stage.lines, stage.sym = [], {}
stage.used_s, stage.used_v, stage.masks = set(), set(), set()
stage.attrs = {}
stage.exec_known = True
stage.ins = decoded
stage.force_joined = {}
stage.translate()
body = ' '.join(line for _, lines, _ in stage.blocks for line in lines)
return [asm for _o, _s, _n, asm in decoded], body, stage


def refused_reason(code):
try:
translate_program(code)
except G.Unsupported as error:
return str(error)
return None


# 1. At shader entry, SCC is unverified: reading src_scc before any modeled writer must be refused.
check('entry src_scc in s_mul_i32 is refused',
refused_reason(encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + encode_sopp(SOPP_ENDPGM))
== 'src_scc with unverified SCC')
check('entry src_scc in s_and_b32 is refused',
refused_reason(encode_sop2(SOP2_AND_B32, S28, S_SCC, S5) + encode_sopp(SOPP_ENDPGM))
== 'src_scc with unverified SCC')

# 2. Modeled compare -> census s_mul_i32 s28, 1.0, src_scc: decodes and lowers using the SCC bit.
cmp_census = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO)
+ encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC)
+ encode_sopp(SOPP_ENDPGM))
asm, emitted, stage = translate_program(cmp_census)
check('encodes and decodes compare + census form',
asm[:2] == ['s_cmp_eq_u32 0, 0', 's_mul_i32 s28, 1.0, src_scc'], repr(asm))
check('compare + census form lowers to the SCC bit',
'scc = 0x00000000u == 0x00000000u;' in emitted and 's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted,
emitted)
check('low16_only=True returns the same 0/1 expression',
stage.u('src_scc', low16_only=True) == '(scc ? 1u : 0u)')

# 3. Modeled bitwise writer -> src_scc in the first source position -> next instruction reads updated SCC.
bitwise_seq = (encode_sop2(SOP2_AND_B32, S27, S4, S5)
+ encode_sop2(SOP2_AND_B32, S28, S_SCC, S5)
+ encode_sop2(SOP2_MUL_I32, S29, S_1_0, S_SCC)
+ encode_sopp(SOPP_ENDPGM))
asm, emitted, _stage = translate_program(bitwise_seq)
check('encodes and decodes bitwise sequence with src_scc in first position',
asm[:3] == ['s_and_b32 s27, s4, s5', 's_and_b32 s28, src_scc, s5', 's_mul_i32 s29, 1.0, src_scc'],
repr(asm))
check('bitwise sequence reads and updates SCC cleanly',
's28 = (scc ? 1u : 0u) & s5; scc = s28 != 0;' in emitted
and 's29 = 0x3f800000u * (scc ? 1u : 0u);' in emitted,
emitted)

# 4. Distinguishing carry case: compare sets SCC=0, then s_add_u32 0xffffffff + 1 wraps and sets hardware
# carry SCC=1 without an HLSL SCC update. Reading src_scc afterwards must refuse rather than read stale 0.
carry_seq = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ONE)
+ encode_sop2(SOP2_ADD_U32, S1, LITERAL, S_ONE, literal=0xFFFFFFFF)
+ encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC)
+ encode_sopp(SOPP_ENDPGM))
check('s_add_u32 carry after compare leaves SCC unverified and is refused',
refused_reason(carry_seq) == 'src_scc with unverified SCC',
repr(refused_reason(carry_seq)))

# 5. s_add_u32 reading src_scc as an input before overwriting SCC is accepted (input read precedes write),
# while a second src_scc after s_add_u32 is refused.
add_reads_scc = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO)
+ encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE)
+ encode_sopp(SOPP_ENDPGM))
asm, emitted, _stage = translate_program(add_reads_scc)
check('s_add_u32 reading incoming verified src_scc is accepted',
's1 = (scc ? 1u : 0u) + 0x00000001u;' in emitted, emitted)
check('reading src_scc after s_add_u32 is refused',
refused_reason(encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO)
+ encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE)
+ encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC)
+ encode_sopp(SOPP_ENDPGM)) == 'src_scc with unverified SCC')

# 6. Across a control-flow join: branch skips s_nop 0 to target 0x10; incoming SCC at the join is unverified,
# so src_scc there is refused unless a modeled writer runs inside the joined block first.
join_refused = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00
+ encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> label_0x0c (skip 1 dword at 0x08)
+ encode_sopp(SOPP_NOP, simm=0) # 0x08
+ encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x0c (branch target / join)
+ encode_sopp(SOPP_ENDPGM)) # 0x10
check('src_scc across a control-flow join is refused',
refused_reason(join_refused) == 'src_scc with unverified SCC',
repr(refused_reason(join_refused)))

join_rewritten = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00
+ encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> 0x0c
+ encode_sopp(SOPP_NOP, simm=0) # 0x08
+ encode_sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x0c (modeled writer after join)
+ encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x10
+ encode_sopp(SOPP_ENDPGM))
asm, emitted, _stage = translate_program(join_rewritten)
check('src_scc after a modeled writer in the joined block is accepted',
's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, emitted)

if failures:
print('FAIL')
for text in failures:
print(' ' + text)
sys.exit(1)
print('PASS')
20 changes: 20 additions & 0 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2159,6 +2159,12 @@ def note_whole_read(self, reg):

def u(self, tok, *, low16_only=False):
"""uint expression for a 32-bit operand."""
if tok == 'src_scc':
# Source code 253 reads SCC as 0 or 1 (fits in 16 bits, so low16_only=True needs no mask).
# Refuse unless a modeled writer set SCC on the reaching path in this block.
if not getattr(self, 'scc_verified', False):
raise Unsupported('src_scc with unverified SCC')
return '(scc ? 1u : 0u)'
if tok in ('vcc_lo', 'vcc'):
self.read_vcc()
return 'vcc'
Expand Down Expand Up @@ -2395,6 +2401,7 @@ def set_scc(self, expr, proof=None):
"""Emit an SCC assignment and track its uniformity from `proof` (an expression over the
sources) when the emitted text names a register, such as m0, that the proof cannot judge."""
self.scc_effect = 'emitted'
self.scc_verified = True
if self.tracks_uniformity():
self.scc_uniform = self.scalar_expr_uniform(expr if proof is None else proof)
self.emit('scc = %s;' % expr)
Expand Down Expand Up @@ -2983,6 +2990,7 @@ def translate(self):
self.uniform_v = set()
self.varying_s = set()
self.scc_uniform = True
self.scc_verified = False
self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load
self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries
self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer
Expand Down Expand Up @@ -3023,6 +3031,8 @@ def translate(self):
self.pc = off
self.descriptor_instruction_index = instruction_index
self.scc_effect = None
if not falls:
self.scc_verified = False
# 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
# branch-free program is past it too (dead code).
Expand Down Expand Up @@ -3072,6 +3082,7 @@ def translate(self):
tentative_kept.update((kept_u & clobber) - blocked)
self.uniform_v.clear()
self.since_join, self.scc_uniform = kept_u, False
self.scc_verified = False
# A constant is only known here if no other path into the join writes the register: a loop counter
# set before the loop and incremented in it reaches the loop head with a new value on every pass.
# set_s also assigns constants at run time, so the register reads its real value once it is dropped.
Expand Down Expand Up @@ -3528,6 +3539,7 @@ def lower(self, base, asm, ops, mods):
self.varying_s.add(reg)
if base in ('s_add_u32', 's_addc_u32'):
self.scc_uniform = False
self.scc_verified = False
return None
if getattr(self, 'fetched', False): # unit probes build a Stage without __init__
# Behind a fetch call the definite-assignment guard relies on exec_known: every exec write must clear it.
Expand All @@ -3546,6 +3558,7 @@ def lower(self, base, asm, ops, mods):
self.uniform_v.clear()
if hasattr(self, 'scc_uniform'):
self.scc_uniform = False # the hardware SCC result is not modelled
self.scc_verified = False
return None
if base == 's_setreg_imm32_b32':
# The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode):
Expand Down Expand Up @@ -4160,8 +4173,11 @@ def src_sym(t):
return None
raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % tg_srcs[0])
if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms):
if 'src_scc' in srcs and not getattr(self, 'scc_verified', False):
raise Unsupported('src_scc with unverified SCC')
if scc or base in SCC_UNMODELLED:
self.scc_effect = 'descriptor'
self.scc_verified = False
if self.tracks_uniformity():
self.scc_uniform = False
if shift_add or word_complement or word_absdiff:
Expand Down Expand Up @@ -4249,6 +4265,8 @@ def src_sym(t):
# Compute carry before writing the low register, which can also be an addend.
self.set_scc('(%s) < %s' % (expr, values[0]))
self.address_carry_reader = self.address_carry_pairs[self.pc]
elif base in SCC_UNMODELLED:
self.scc_verified = False
if shift_add:
# carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written
n = SHIFT_ADD[base]
Expand Down Expand Up @@ -4362,6 +4380,7 @@ def known(tok):
def set_exec_scc(self, expr):
self.exec_known = False
self.scc_effect = 'emitted'
self.scc_verified = True
self.emit('exec = (%s) & 1; scc = exec != 0;' % expr)
if hasattr(self, 'scc_uniform'):
self.scc_uniform = False
Expand Down Expand Up @@ -4847,6 +4866,7 @@ def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=Non
if self.tracks_uniformity():
(self.varying_s.discard if uniform else self.varying_s.add)(r)
self.scc_effect = 'emitted'
self.scc_verified = True
if self.tracks_uniformity():
self.scc_uniform = uniform
return None
Expand Down
Loading