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
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2157,6 +2157,10 @@ if(EXISTS "${INTAKE_PYTHON}")
# The 64-bit vector shifts (#1815).
add_test(NAME startup_gfx2hlsl_b64_shift COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_b64_shift_check.py")
# The SOPK arithmetic forms s_mulk_i32 and s_addk_i32 (#1723).
add_test(NAME startup_gfx2hlsl_s_mulk_addk COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_mulk_addk_check.py")
Comment on lines +2161 to +2162

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the new startup SOPK capability and reproduction check

The patch introduces startup-translator support and a new CTest, but updates neither README.md nor docs/experiments.md. AGENTS.md requires documentation updates when public capabilities or reproduction commands change; the existing SOPK paragraph documents pixel_aot, not this startup lowering. Add the new startup check and its measured scope to the public experiment documentation, distinguishing the Linux emitted-statement evaluation from Windows/DXIL or GPU validation.

AGENTS.md reference: AGENTS.md:L209-L210

Useful? React with 👍 / 👎.

set_tests_properties(startup_gfx2hlsl_s_mulk_addk PROPERTIES TIMEOUT 60)
# SDWA forms of the float-result conversions (#1727).
add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py")
Expand Down
121 changes: 121 additions & 0 deletions tests/startup_gfx2hlsl_s_mulk_addk_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""s_mulk_i32 and s_addk_i32 in tools/startup/gfx2hlsl.py (issue #1723, Run 20 census #5).

usage: startup_gfx2hlsl_s_mulk_addk_check.py

The two SOPK arithmetic forms `s_mulk_i32 sN, simm16` and `s_addk_i32 sN, simm16` were refused. Both read and write
SDST and take a 16-bit immediate that is sign-extended; s_addk_i32 also sets SCC to the signed overflow of the add.

The instruction words are constructed here from the layout the checked-in decoder reads (`tools/disasm_rdna2.py`,
SOPK branch): 0xb0000000, opcode in bits 27:23 (0x0f add, 0x10 mul), SDST in bits 22:16, SIMM16 in bits 15:0.
The emitted statements are executed on 32-bit values and compared with the architectural result.
"""
import os
import re
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)


SOPK_ADDK, SOPK_MULK = 0x0F, 0x10
MASK = 0xFFFFFFFF


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


class Stage(G.Stage):
"""A Stage with no pipeline: enough state for a decoded instruction to be translated."""

def __init__(self):
self.lines, self.sym, self.masks = [], {}, set()
self.used_s, self.used_v, self.uniform_v = set(), set(), set()
self.exec_known = True
self.exports = {}
self.pipe = Pipeline()


def encode(op, sdst, simm):
return struct.pack('<I', 0xB0000000 | (op << 23) | (sdst << 16) | simm)


def translate(code):
stage = Stage()
decoded = G.decode(code)
for _offset, _size, name, asm in decoded:
stage.one(name, asm)
return decoded[0][3], stage


def run(lines, s4, scc=0):
"""Execute the emitted statements on 32-bit unsigned values (HLSL uint wraps)."""
env = {'s4': s4, 'scc': bool(scc)}
for line in lines:
text = re.sub(r'0x([0-9a-f]{8})u', r'0x\1', line.rstrip(';'))
text = re.sub(r'\b0u\b', '0', text).replace('&&', ' and ')
name, _, expr = text.partition(' = ')
value = eval(expr, {}, env)
env[name] = value if name == 'scc' else value & MASK
return env['s4'], env['scc']


def signed(value):
return value - (1 << 32) if value & 0x80000000 else value


def expected_add(a, imm):
total = signed(a) + imm
return total & MASK, not -(1 << 31) <= total < (1 << 31)


for simm in (0x0000, 0x0001, 0x7FFF, 0x8000, 0xFFFE, 0xFFFF):
imm = simm - 0x10000 if simm >= 0x8000 else simm
asm, stage = translate(encode(SOPK_MULK, 4, simm))
check('decodes s_mulk_i32 0x%x' % simm, asm == 's_mulk_i32 s4, 0x%x' % simm, asm)
ok = all(run(stage.lines, a)[0] == (signed(a) * imm) & MASK
for a in (0, 1, 3, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x12345678))
check('s_mulk_i32 0x%x multiplies by the sign-extended immediate' % simm, ok, ' '.join(stage.lines))
check('s_mulk_i32 0x%x leaves SCC alone' % simm, all('scc' not in line for line in stage.lines), ' '.join(stage.lines))

asm, stage = translate(encode(SOPK_ADDK, 4, simm))
check('decodes s_addk_i32 0x%x' % simm, asm == 's_addk_i32 s4, 0x%x' % simm, asm)
ok = all(run(stage.lines, a) == expected_add(a, imm)
for a in (0, 1, 3, 0x7FFF, 0x7FFFFFFF, 0x7FFFFFF0, 0x80000000, 0x80000001, 0xFFFFFFFF, 0x12345678))
check('s_addk_i32 0x%x adds and sets SCC to the signed overflow' % simm, ok, ' '.join(stage.lines))

# SCC is written from the old value, so the result write must come after it.
_asm, stage = translate(encode(SOPK_ADDK, 4, 1))
check('s_addk_i32 reads the old destination for SCC', stage.lines[0].startswith('scc =') and stage.lines[1].startswith('s4 ='),
' '.join(stage.lines))

# A destination that is not a plain SGPR is refused rather than lowered wrongly.
refused = True
try:
translate(encode(SOPK_MULK, 106, 2))
except G.Unsupported:
pass
else:
refused = False
check('a non-SGPR destination is refused', refused)

if failures:
print('FAIL')
for text in failures:
print(' ' + text)
sys.exit(1)
print('PASS')
32 changes: 32 additions & 0 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1750,6 +1750,38 @@ def handler(self, ops, mods):
setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make())


def _sopk_arith(self, base, scalar_op, ops, mods):
"""s_mulk_i32 / s_addk_i32: SDST = SDST op sign_extend(SIMM16), through the two-source scalar lowering.

The decoder prints the 16-bit immediate as unsigned hex; it is sign-extended here. s_addk_i32 also sets SCC
to the signed overflow of the add, which the plain add lowering does not model."""
if mods or len(ops) != 2:
raise Unsupported('%s with %d operands' % (base, len(ops)))
reg = reg_range(ops[0])
if not reg or reg[0] != 's' or reg[1] != reg[2] or reg[1] > 105:
raise Unsupported('%s destination %s' % (base, ops[0]))
Comment on lines +1761 to +1762

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject SOPK arithmetic on projected lane-mask SGPRs

When SDST holds a comparison mask, this validation accepts it even though Stage.compare() stores only the current lane's 0/1 projection and records that fact in self.masks. For example, after v_cmp_lt_i32_e64 s4, v0, v1 produces a guest low mask of 0x7fffffff, s_addk_i32 s4, 1 must set SCC, but the emitted expression computes on 0/1 and sets SCC false in every invocation; a following scalar select or SCC branch therefore takes the wrong path. Reject mask-tagged SGPRs before either SOPK lowering, as the complement/pack handlers already do, or model the full mask instead of treating its projection as a numeric word.

Useful? React with 👍 / 👎.

try:
imm = int(ops[1], 0)
except ValueError:
raise Unsupported('%s immediate %s' % (base, ops[1]))
if not -0x8000 <= imm <= 0xffff:
raise Unsupported('%s immediate %s outside 16 bits' % (base, ops[1]))
if imm >= 0x8000:
imm -= 0x10000
word = imm & 0xffffffff
if base == 's_addk_i32':
if self.sym.get(reg[1]):
raise Unsupported('scc from descriptor data')
Comment on lines +1773 to +1774

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow numeric symbolic SGPRs through the addk guard

When SDST is initialized by an immediate move or supplied as a root constant, self.sym contains a numeric const or ud entry, not descriptor data. Consequently, the ordinary sequence s_mov_b32 s4, 1; s_addk_i32 s4, 1 raises Unsupported('scc from descriptor data') through the production Stage constructor instead of lowering the addition. Numeric fixed_buffer_word entries are rejected too. Restrict this guard to genuinely non-numeric symbols so the new instruction works on initialized scalar values; the added test misses this because it starts with an empty symbol table.

Useful? React with 👍 / 👎.

old = self.u(ops[0])
self.emit('scc = ((%s ^ 0x%08xu) & 0x80000000u) == 0u && ((%s ^ (%s + 0x%08xu)) & 0x80000000u) != 0u;'
% (old, word, old, old, word))
return self.scalar(scalar_op, [ops[0], ops[0], '0x%08x' % word])


Stage.op_s_mulk_i32 = lambda self, ops, mods: _sopk_arith(self, 's_mulk_i32', 's_mul_i32', ops, mods)
Stage.op_s_addk_i32 = lambda self, ops, mods: _sopk_arith(self, 's_addk_i32', 's_add_i32', ops, mods)


def parse_root(blob):
if not blob or blob[:4] != b'DXBC':
raise Unsupported('root signature blob missing')
Expand Down
Loading