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 .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ jobs:
(["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}),
(["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}),
(["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "decode", "libLLVM-15.so.1"], {}),
(["tests/startup_gfx2hlsl_sop2_complement_check.py", "binary", "llvm-mc-15"], {}),
(["tests/startup_gfx2hlsl_sop2_complement_check.py", "decode", "libLLVM-15.so.1"], {}),
(["tests/startup_inline_sampler_check.py", "binary", "llvm-mc-15"], {}),
(["tests/startup_smem_address_check.py", "binary", "llvm-mc-15"], {}),
(["tests/compute_entry_layout_check.py", "binary", "llvm-mc-15"], {}),
Expand Down Expand Up @@ -197,6 +199,7 @@ jobs:
tests/startup_gfx2hlsl_mad_check.py \
tests/startup_gfx2hlsl_shift64_check.py \
tests/startup_gfx2hlsl_vopc_sdwa_check.py \
tests/startup_gfx2hlsl_sop2_complement_check.py \
tests/startup_inline_sampler_check.py \
tests/startup_buffer_address_check.py \
tests/startup_smem_address_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_translator_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py
./out/pe-env/bin/python -B tests/startup_flat_param_check.py
./out/pe-env/bin/python -B tests/startup_inline_sampler_check.py
./out/pe-env/bin/python -B tests/startup_buffer_address_check.py
Expand Down
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2023,6 +2023,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# A typed buffer load of BUF_FMT_16_16_16_16_FLOAT reads four halves from one 8-byte element (#1695).
add_test(NAME startup_gfx2hlsl_tbuffer_16f COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_tbuffer_16f_check.py")
# 32-bit scalar complement logic: s_nand_b32, s_nor_b32 and s_xnor_b32 against an integer reference (#1919).
add_test(NAME startup_gfx2hlsl_sop2_complement COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sop2_complement_check.py")
# gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with
# DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with.
find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}")
Expand Down
13 changes: 13 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -6018,6 +6018,19 @@ the handler writes back in one statement. VGPR pairs, SGPR pairs and the integer
sources; the low word is always shifted unsigned and only the arithmetic form signs the high word.
Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_b64_shift$' -V`.

**The 32-bit scalar complement logic operations.** The scalar table had `s_nand_b64`, `s_nor_b64` and
`s_xnor_b64` and the 32-bit `s_andn2_b32` and `s_orn2_b32`, but not `s_nand_b32`, `s_nor_b32` or `s_xnor_b32`
(#870, issue #1919). They now lower as `~(S0 & S1)`, `~(S0 | S1)` and `~(S0 ^ S1)` on 32 bits, the text
`pixel_aot` uses, and set SCC when the result is nonzero like the other logic operations. The check decodes
SGPR, in-place, inline-constant, literal and m0-destination forms and evaluates the emitted lines against an
integer reference over 0, all ones, alternating bits, every single bit and mixed words. Lane-mask forms (a
vcc_lo/exec_lo operand or destination, or an SGPR holding a compare mask) are refused: guest SCC reads the whole
32-bit mask, which the per-lane projection cannot show. A table
entry without the complement or without the SCC write must fail, and SOP2 operations with no lowering stay
refused by name. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with
LLVM 15, `tests/startup_gfx2hlsl_sop2_complement_check.py binary <llvm-mc>` and `decode <libLLVM>` round-trip
the same words.

## Pixel color without a texture sample

For an unsampled pixel program, a matched P1/P2 interpolation in the entry mask can supply attr0.x/y/z/w from a four-component TEXCOORD0. The profile binds entry v0/v1 to the barycentric pair and the observed m0 source to the interpolation base. Each completed P2 produces a distinct value, including when the destination overwrites v0. The test vertex shader varies all four channels across a full-screen triangle. CPU references check all four output words at 1,024 pixel centers; an incorrect channel at an interior pixel must fail. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_attribute_'`.
Expand Down
318 changes: 318 additions & 0 deletions tests/startup_gfx2hlsl_sop2_complement_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,318 @@
"""32-bit scalar complement logic operations in tools/startup/gfx2hlsl.py: s_nand_b32, s_nor_b32, s_xnor_b32 (#1919).

(no arguments) translation controls, pure Python
binary <llvm-mc> assemble the decoded text of every form with llvm-mc and compare with the words built here
decode <libLLVM> disassemble the same words with LLVM's C API and compare with tools/disasm_rdna2.py

The instruction words are built here from the SOP2 layout that tools/disasm_rdna2.py reads: [31:30] = 0b10,
[29:23] opcode, [22:16] sdst, [15:8] ssrc1, [7:0] ssrc0, and one literal dword after the word when a source is 255.

Each form is decoded and translated, and the emitted lines (the result, then SCC) are run in order on the CPU by the
integer evaluator of startup_gfx2hlsl_bit_alu_check.py over edge values: 0, all ones, alternating bits, every single
bit and its complement, and mixed words. The reference is written here with plain integer arithmetic from the ISA
meaning: D = ~(S0 op S1) on 32 bits and SCC = (D != 0). SCC starts at a value neither 0 nor 1, so a form that does not
write it fails. The value set gives SCC = 0 and SCC = 1 for every operation.

The lowering text and SCC rule equal pixel_aot's SCALAR entries for the same operations (#561). Every numeric form
(SGPR, inline, literal or m0 operands) emits the lines of its non-complement sibling (s_and_b32, s_or_b32, s_xor_b32)
with the operation wrapped in ~( ). Lane-mask forms are refused: a vcc_lo or exec_lo operand or destination, or an
SGPR holding a compare mask, is the whole wave's mask, and SCC is set when any bit of the complemented 32-bit result
is; the translator's per-lane projection cannot show that, so no mask lowering is claimed.

Mutations: the table entry with the complement dropped, and the entry with the SCC write dropped, must each read a
wrong result or SCC. Refused: every SOP2 operation the decoder names that still has no lowering.
"""
import re
import struct
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'tools'))
sys.path.insert(0, str(HERE.parent / 'tools' / 'startup'))
sys.path.insert(0, str(HERE))
import disasm_rdna2 as D # noqa: E402
import gfx2hlsl as G # noqa: E402
import pixel_aot as P # noqa: E402
from startup_flat_param_check import assemble # noqa: E402
from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402

MASK = 0xffffffff
OPCODE = {name: op for op, (name, _) in D.SOP2_OPS.items()}
# operation -> (non-complement sibling, reference)
OPS = {
's_nand_b32': ('s_and_b32', lambda a, b: ~(a & b) & MASK),
's_nor_b32': ('s_or_b32', lambda a, b: ~(a | b) & MASK),
's_xnor_b32': ('s_xor_b32', lambda a, b: ~(a ^ b) & MASK),
}
SIBLING_OPERATOR = {'s_and_b32': '&', 's_or_b32': '|', 's_xor_b32': '^'}

SPECIAL = [0, MASK, 0xaaaaaaaa, 0x55555555, 0x80000000, 0x7fffffff, 1, 0xfffffffe, 0xffff0000, 0x0000ffff,
0x12345678, 0xedcba987, 0xdeadbeef, 0x0f0f0f0f]
VALUES = SPECIAL + [1 << k for k in range(32)] + [~(1 << k) & MASK for k in range(32)]
PAIRS = [(a, b) for a in SPECIAL for b in VALUES] + [(a, b) for a in VALUES for b in SPECIAL]
SCC_UNSET = 2 # not a value SCC can take: a form that leaves SCC alone keeps it

VCC_LO, M0, EXEC_LO, LITERAL = 106, 124, 126, 255
INLINE = {128: 0, 129: 1, 193: MASK} # ssrc codes: 0, 1, -1


def sop2(name, sdst, ssrc0, ssrc1, literal=None):
word = (0b10 << 30) | (OPCODE[name] << 23) | (sdst << 16) | (ssrc1 << 8) | ssrc0
return struct.pack('<I', word) + (b'' if literal is None else struct.pack('<I', literal))


# (sdst, ssrc0, ssrc1, literal): the forms with an SGPR or m0 destination and no mask source are checked against
# the integer reference; the others only against the sibling.
VALUE_FORMS = [
(3, 1, 2, None), # s3 = s1 op s2
(1, 1, 2, None), # in place, first source
(2, 1, 2, None), # in place, second source
(3, 1, 1, None), # one register on both sides
(3, 128, 2, None), # inline 0
(3, 193, 2, None), # inline -1
(3, 1, 129, None), # inline 1
(3, 1, 193, None), # inline -1 as the second source
(3, LITERAL, 2, 0xaaaaaaaa),
(3, 1, LITERAL, 0x55555555),
(M0, 1, 2, None),
]
MASK_FORMS = [
(3, VCC_LO, 2, None), # a lane-mask source marks the destination as a mask
(3, 1, EXEC_LO, None),
(VCC_LO, 1, 2, None),
(EXEC_LO, 1, 2, None),
]


def code(name, form):
return sop2(name, *form)


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

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


def decode_one(words):
decoded = G.decode(words)
assert len(decoded) == 1 and decoded[0][1] == len(words), decoded
return decoded[0][2], decoded[0][3]


def translate(words):
name, asm = decode_one(words)
stage = Probe()
stage.one(name, asm)
return asm, stage


def attempt(words):
"""translate(), with a refusal returned as a stage whose only line names it."""
try:
return translate(words)
except G.Unsupported as error:
stage = Probe()
stage.lines = ['refused: %s' % error]
return decode_one(words)[1], stage


def source_value(code_, literal, env):
if code_ == LITERAL:
return literal
if code_ in INLINE:
return INLINE[code_]
return env['s%d' % code_]


def run_lines(lines, env):
env = dict(env)
for line in lines:
m = re.fullmatch(r'(\w+) = (.*);', line)
assert m, line
env[m.group(1)] = Expr(m.group(2)).run(env)[0]
return env


failures = []


def check(label, ok, detail=''):
print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True)
if not ok:
failures.append(label)
if detail:
print(' ' + detail)


def first_mismatch(name):
"""The first (form, a, b, got, want) whose result or SCC differs from the reference, or None."""
reference = OPS[name][1]
for form in VALUE_FORMS:
sdst, ssrc0, ssrc1, literal = form
asm, stage = attempt(code(name, form))
if stage.lines[0].startswith('refused: '):
return asm, stage.lines[0]
destination = 'm0' if sdst == M0 else 's%d' % sdst
for a, b in PAIRS:
env = {'s1': a, 's2': b, 'scc': SCC_UNSET}
want = reference(source_value(ssrc0, literal, env), source_value(ssrc1, literal, env))
out = run_lines(stage.lines, env)
got = (out.get(destination), out['scc'])
if got != (want, int(want != 0)):
return asm, hex(a), hex(b), got, (want, int(want != 0))
return None


def controls():
# 1. The encoder writes what the decoder reads, checked on the LLVM 15 encodings in tests/rdna2_tools_check.py.
known = [(sop2('s_nand_b32', 0, 1, 2), '0102008c'), (sop2('s_nor_b32', 0, 1, 2), '0102008d'),
(sop2('s_xnor_b32', 0, 1, 2), '0102008e')]
check('encoder matches LLVM 15 encodings', all(w.hex() == want for w, want in known),
str([(w.hex(), want) for w, want in known]))
decoded = [decode_one(code(name, form))[1] for name in OPS for form in VALUE_FORMS + MASK_FORMS]
check('decoder names every form (%d)' % len(decoded), all(t.split(' ', 1)[0] in OPS for t in decoded), str(decoded))

# 2. The table entries are pixel_aot's lowering of the same operations, with the logic-op SCC rule.
for name in OPS:
text, scc = G.SCA.get(name, (None, None))
arity, aot_text, aot_scc = P.SCALAR[name[2:]]
sibling = G.SCA[OPS[name][0]]
check('%s: %r SCC %r equals pixel_aot %r SCC %r and the sibling SCC rule'
% (name, text, scc, aot_text, aot_scc),
arity == 2 and text == aot_text and aot_scc == P.NONZERO and scc == '$ != 0' and sibling[1] == scc)

# 3. The value set reaches SCC = 0 and SCC = 1 for every operation.
for name, (_, reference) in OPS.items():
results = {reference(a, b) for a, b in PAIRS}
check('%s: %d pairs give a zero and a nonzero result' % (name, len(PAIRS)), 0 in results and len(results) > 1)

# 4. Every value form evaluates to the reference: result and SCC.
for name in OPS:
found = first_mismatch(name)
check('%s: %d forms x %d pairs equal the reference (result and SCC)' % (name, len(VALUE_FORMS), len(PAIRS)),
found is None, str(found))

# 5. Every numeric form emits the sibling's lines with the operation complemented.
for name, (sibling, _) in OPS.items():
wrong = []
for form in VALUE_FORMS:
asm, stage = attempt(code(name, form))
plain_asm, plain = translate(code(sibling, form))
operands = plain_asm.split(' ', 1)[1].split(', ')
probe = Probe()
inner = '%s %s %s' % (probe.u(operands[1]), SIBLING_OPERATOR[sibling], probe.u(operands[2]))
expected = [line.replace(inner, '~(%s)' % inner, 1) for line in plain.lines]
if (asm != plain_asm.replace(sibling, name, 1) or stage.lines != expected or expected == plain.lines
or stage.masks != plain.masks or stage.exec_known != plain.exec_known):
wrong.append((asm, stage.lines, plain.lines, stage.masks, plain.masks))
check('%s: %d numeric forms emit the %s lines complemented, same mask and EXEC bookkeeping'
% (name, len(VALUE_FORMS), sibling), not wrong, str(wrong[:2]))

# 5b. Lane-mask forms are refused: vcc_lo/exec_lo operands and destinations, and an SGPR holding a compare mask.
for name in OPS:
accepted = []
for form in MASK_FORMS:
asm, stage = attempt(code(name, form))
if stage.lines != ['refused: %s on a lane mask' % name]:
accepted.append((asm, stage.lines))
stage = Probe()
stage.masks.add(1) # s1 holds a compare result
try:
stage.one(name, '%s s3, s1, s2' % name)
accepted.append(('%s s3, s1(mask), s2' % name, stage.lines))
except G.Unsupported as error:
if str(error) != '%s on a lane mask' % name:
accepted.append(('%s s3, s1(mask), s2' % name, [str(error)]))
check('%s: %d lane-mask forms refused' % (name, len(MASK_FORMS) + 1), not accepted, str(accepted[:2]))

# Symbolic descriptor sources cannot silently leave the previous SCC in place.
for name in OPS:
stage = Probe()
stage.sym[1] = ('ptr', 0, 0)
try:
stage.one(name, '%s s3, s1, s2' % name)
except G.Unsupported as error:
check('%s refuses a descriptor before writing SCC' % name,
str(error) == 'scc from descriptor data' and not stage.lines, str(error))
else:
check('%s refuses a descriptor before writing SCC' % name, False, str(stage.lines))

# 6. Mutated table entries, built from the sibling's, must read a wrong word or SCC.
saved = dict(G.SCA)
try:
for name, (sibling, _) in OPS.items():
G.SCA[name] = saved[sibling]
found = first_mismatch(name)
check('%s mutation without the complement fails: %s' % (name, found), found is not None)
G.SCA[name] = ('~(%s)' % saved[sibling][0], None)
found = first_mismatch(name)
check('%s mutation without the SCC write fails: %s' % (name, found), found is not None)
G.SCA.clear()
G.SCA.update(saved)
finally:
G.SCA.clear()
G.SCA.update(saved)

# 7. SOP2 operations that still have no lowering are refused by name.
missing = [name for _op, (name, _) in sorted(D.SOP2_OPS.items())
if name not in G.SCA and not hasattr(G.Stage, 'op_' + name)]
wrong = []
for name in missing:
asm = decode_one(sop2(name, 2, 4, 6))[1]
try:
Probe().one(name, asm)
wrong.append((asm, 'accepted'))
except G.Unsupported as error:
if str(error) != name:
wrong.append((asm, str(error)))
check('%d SOP2 operations without a lowering are refused by name (%s)' % (len(missing), ', '.join(missing)),
missing and not wrong and not set(OPS) & set(missing), str(wrong))


def all_codes():
return [code(name, form) for name in list(OPS) + [s for s, _ in OPS.values()] for form in VALUE_FORMS + MASK_FORMS]


def check_binary(llvm_mc):
codes = all_codes()
text = ''.join(decode_one(c)[1] + '\n' for c in codes)
check('llvm-mc assembles %d decoded SOP2 forms to the same words' % len(codes),
assemble(llvm_mc, text) == b''.join(codes))


def check_decode(library):
codes = all_codes()
texts = P.disassemble(b''.join(codes), library)
ours = [decode_one(c)[1] for c in codes]
wrong = [(a, b) for a, b in zip(texts, ours) if a != b]
check('LLVM disassembles %d SOP2 forms as tools/disasm_rdna2.py does' % len(codes),
len(texts) == len(codes) and not wrong, str(wrong[:3]))


def main():
if len(sys.argv) == 1:
controls()
else:
mode, *args = sys.argv[1:]
if mode == 'binary':
check_binary(*args)
elif mode == 'decode':
check_decode(*args)
else:
raise SystemExit(__doc__)
if failures:
print('FAIL')
for text in failures:
print(' ' + text)
sys.exit(1)
print('PASS')


if __name__ == '__main__':
main()
Loading
Loading