From 4824613b2dd7f82d2b51aa93772f5b8655fc7837 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 10:55:59 +0100 Subject: [PATCH 1/3] startup: keep or refuse non-constant scalar symbols at joins in gfx2hlsl Follow-up to #2279. Work out the joined registers over the basic blocks and dominators (a proven s_setpc_b64 is an edge). At a join, a register keeps a symbol every path agrees on, reads a constant at run time, and refuses a read when a path brings a descriptor word, pointer or unplaced register. A 64-bit copy assigns its high word at run time. Adds a pure-Python and dispatch check. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 14 + docs/experiments.md | 16 + tests/startup_gfx2hlsl_join_symbols_check.py | 313 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 243 ++++++++++++-- 6 files changed, 567 insertions(+), 22 deletions(-) create mode 100644 tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index c135fb974..028742754 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -105,6 +105,7 @@ jobs: (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), @@ -222,6 +223,7 @@ jobs: tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ + tests/startup_gfx2hlsl_join_symbols_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ diff --git a/AGENTS.md b/AGENTS.md index ff1293285..2a9e117ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,6 +177,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ba340aa9a..3d727eea7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3341,6 +3341,20 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: scalar constants are dropped at a branch join that another path writes (loop counters). add_test(NAME startup_gfx2hlsl_loop_constants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_loop_constants_check.py") + # Startup shader translator: symbols that are not constants (descriptors, pointers, pairs) at a branch join. + add_test(NAME startup_gfx2hlsl_join_symbols_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_join_symbols_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_join_symbols_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_join_symbols_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + add_test(NAME startup_gfx2hlsl_join_symbols_folded_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_join_symbols_check.py" control "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_join_symbols_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + set_tests_properties(startup_gfx2hlsl_join_symbols_folded_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control OUTSIDE: 3 in all four channels") + endforeach() # Startup shader translator: uniform sources of v_readfirstlane_b32 in straight-line code and entry blocks (#1723). add_test(NAME startup_gfx2hlsl_readfirstlane_uniform COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index f15612013..0be5153b5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14063,3 +14063,19 @@ ctest --preset dev --no-tests=error -R '^(cpu_aot_switch_sal|cpu_aot_switch_shif The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequences (because ML64 assembles the `sal` mnemonic as `/4` `SHL`) across 24 translated functions covering all 12 `SAL` `Code` encodings (`SAL_RM{8,16,32,64}_{1,CL,IMM8}`), register and memory destinations, count-`1` all-16 `SETcc` checks, count->1 10-condition `SETcc` checks, `Jcc`, `CMOVcc`, narrow returns, and nonvolatile/stack-frame operands, plus 11 negative exports. [The differential check](../tests/cpu/switch_sal_check.py) verifies 28,024 `dev` and 28,024 `/O2` comparisons against native execution and the Python reference, four `/O2` mutated-C++ controls (`shift_dir`, `cf_mask`, `of_mask`, `cl_mask`), 11 MASM, 4 unit, and 7 PE-patched rejection controls, and records decoded mnemonics via `iced_x86.Mnemonic` to `FORM_COVERAGE_RECORD`. Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. + +## Non-constant scalar symbols at branch targets in the startup translator + +Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between +a branch and its target. Two cases remained wrong in the emitted HLSL: +- A symbol that is not a constant (a descriptor word, a pointer, a 64-bit pair, an unplaced compute user SGPR) was + kept across the join, so a descriptor reloaded on one path was bound for both, and a word overwritten on one path + was read as a register nothing assigned. +- A path that leaves a loop's textual range and comes back changes a constant the textual range does not cover. + +The joined registers are now worked out over the basic blocks and their dominators (a proven `s_setpc_b64` is an +edge, and ends its block). A joined register keeps its symbol when every path that wrote it brings an equal symbol +that names one value, is read at run time when it holds a constant, and refuses a read before its next write when a +path brings a symbol with no run-time value. `startup_gfx2hlsl_join_symbols_check.py` pins the cases; the +`join_symbols_folded_*` tests run the old OUTSIDE statement and must give 3, not 11. Controls are pure Python plus +a pixel dispatch on WARP and hardware; `binary` reassembles the fixture words with LLVM 15. diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py new file mode 100644 index 000000000..d02f4bcc2 --- /dev/null +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -0,0 +1,313 @@ +"""Scalar symbols at branch targets in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + dispatch + run the translated pixel bodies in a compute wrapper and compare the words + control + the same with the old folded statement, which must give the folded value + +Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between +a branch and its target. This check covers what that leaves: symbols that are not constants (descriptor words, +pointers, pairs, unplaced entry registers), and a path that leaves the loop's textual range and comes back. + +At a branch target, a register whose program-order symbol may not hold on every path (worked out over the basic blocks +and their dominators) keeps a symbol only when every path into the target brings an equal one that names one value. +Otherwise it is read at run time: every constant is assigned when set, and an entry root constant is assigned at +entry. A register that holds, on some path into the target, a symbol with no run-time value (a descriptor word, a +pointer, an unplaced compute user SGPR) refuses any read before its next write. + +The fixtures are source-built gfx1013 pixel stages behind a fixed vertex stage: +- PAIR_*, DESC_*: a 64-bit copy and descriptor loads around a join (pure Python); OUTSIDE: a loop whose path leaves the + loop's textual range and comes back; CS_UNPLACED: a compute program writing an unplaced user SGPR on one path. +- JOIN_SAME, DESC_SAME: the same constant (read at run time since #2279), or the same descriptor, on both paths of a forward join (kept). +- CS_RELOAD: a compute loop that stores through its descriptor at the header and reloads it from the same table slot + before the back edge (kept, and dispatched); CS_RELOAD_OTHER reloads another slot (refused). +- CALC: s23 = 1, a proven s_setpc_b64 skips s23 = 2 and lands on the read (a calculated jump is a branch; 1). +- LOOP_RFL, JOIN_RFL: v_readfirstlane_b32 of a loop counter, and of a register written on one path of a join (both + refused as unproven, never recomputed with a folded constant). +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_flat_param_check import G, VS_WORDS, assemble, root_blob + +EXPORT = 'exp mrt0 v0, v0, v0, v0 done vm\ns_endpgm\n' +EXPORT_WORDS = '0f1800f800000000' '000081bf' +SOURCES = { + # A proven s_setpc_b64 jumps over s23 = 2 to the read: the target is a branch target, and the decoy never runs. + 'CALC': ('s_mov_b32 s23, 1\ns_getpc_b64 s[20:21]\ns_add_u32 s20, s20, 16\ns_addc_u32 s21, s21, 0\n' + 's_setpc_b64 s[20:21]\ns_mov_b32 s23, 2\nv_mov_b32 v0, s23\n' + EXPORT, + '810397be' '001f94be' '14901480' '15801582' '142080be' '820397be' '1702007e' + EXPORT_WORDS), + # The same through a calculated jump: the decoy's s16 = 3 sits between the s_setpc_b64 and its target, so the + # loaded descriptor word is joined there and refused, not read as the decoy's constant. + 'DESC_CALC': ('s_load_dwordx8 s[16:23], s[8:9], 0x0\ns_getpc_b64 s[12:13]\ns_add_u32 s12, s12, 16\n' + 's_addc_u32 s13, s13, 0\ns_setpc_b64 s[12:13]\ns_mov_b32 s16, 3\ns_waitcnt lgkmcnt(0)\n' + 'v_mov_b32 v0, s16\n' + EXPORT, + '04040cf4000000fa' '001f8cbe' '0c900c80' '0d800d82' '0c2080be' '830390be' '7fc08cbf' '1002007e' + + EXPORT_WORDS), + 'PAIR_READ': ('s_mov_b32 s30, 0\ns_mov_b32 s9, 5\ns_mov_b64 s[20:21], s[8:9]\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\n' + 's_add_u32 s31, s21, 1\nv_mov_b32 v0, s21\n' + EXPORT, + '80039ebe850389be080494be1e8006bf010085bf15811f801502007e0f1800f800000000000081bf'), + 'PAIR_ROOT': ('s_mov_b32 s30, 0\ns_mov_b32 s21, 7\ns_mov_b64 s[20:21], s[8:9]\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\n' + 's_add_u32 s31, s21, 1\nv_mov_b32 v0, s21\n' + EXPORT, + '80039ebe870395be080494be1e8006bf010085bf15811f801502007e0f1800f800000000000081bf'), + 'PAIR_WRITE': ('s_mov_b32 s30, 0\ns_mov_b32 s9, 5\ns_mov_b64 s[20:21], s[8:9]\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\n' + 's_mov_b32 s21, 7\nv_mov_b32 v0, s21\n' + EXPORT, + '80039ebe850389be080494be1e8006bf010085bf870395be1502007e0f1800f800000000000081bf'), + 'DESC_LOAD': ('s_load_dwordx8 s[16:23], s[8:9], 0x0\ns_mov_b32 s30, 0\nv_mov_b32 v0, 0\nv_mov_b32 v1, 0\n' + 's_cmp_eq_u32 s30, 0\ns_cbranch_scc1 2\ns_load_dwordx8 s[16:23], s[8:9], 0x20\ns_waitcnt lgkmcnt(0)\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '04040cf4000000fa80039ebe8002007e8002027e1e8006bf020085bf04040cf4200000fa7fc08cbf080f00f000040400' + '703f8cbf0f1800f804050607000081bf'), + 'DESC_WORD': ('s_load_dwordx8 s[16:23], s[8:9], 0x0\ns_mov_b32 s30, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\n' + 's_mov_b32 s16, 3\ns_waitcnt lgkmcnt(0)\nv_mov_b32 v0, s16\n' + EXPORT, + '04040cf4000000fa80039ebe1e8006bf010085bf830390be7fc08cbf1002007e0f1800f800000000000081bf'), + 'OUTSIDE': ('s_mov_b32 s23, 1\ns_mov_b32 s24, 0\ns_mov_b32 s25, 0\ns_add_u32 s25, s25, s23\ns_add_u32 s24, s24, 1\n' + 's_cmp_eq_u32 s24, 1\ns_cbranch_scc1 3\ns_cmp_lt_u32 s24, 3\ns_cbranch_scc1 65530\ns_branch 2\n' + 's_mov_b32 s23, 5\ns_branch 65531\nv_mov_b32 v0, s25\n' + EXPORT, + '810397be800398be800399be1917198018811880188106bf030085bf18830abffaff85bf020082bf850397befbff82bf' + '1902007e0f1800f800000000000081bf'), + 'CS_UNPLACED': ('s_mov_b32 s30, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\ns_mov_b32 s0, 5\nv_mov_b32 v1, s0\ns_endpgm\n', + '80039ebe1e8006bf010085bf850380be0002027e000081bf'), + 'JOIN_SAME': ('s_mov_b32 s23, 1\ns_cmp_eq_u32 s8, 0\ns_cbranch_scc1 1\ns_mov_b32 s23, 1\nv_mov_b32 v0, s23\n' + EXPORT, + '810397be' '088006bf' '010085bf' '810397be' '1702007e' + EXPORT_WORDS), + 'DESC_SAME': ('s_load_dwordx8 s[16:23], s[8:9], 0x0\ns_mov_b32 s30, 0\nv_mov_b32 v0, 0\nv_mov_b32 v1, 0\n' + 's_cmp_eq_u32 s30, 0\ns_cbranch_scc1 2\ns_load_dwordx8 s[16:23], s[8:9], 0x0\ns_waitcnt lgkmcnt(0)\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '04040cf4000000fa80039ebe8002007e8002027e1e8006bf020085bf04040cf4000000fa7fc08cbf080f00f000040400' + '703f8cbf0f1800f804050607000081bf'), + # Compute, with the root of startup_gfx2hlsl_compute_check.py: the table descriptor is loaded before the loop, the + # loop stores through it at its header and reloads it from the same place before the back edge. Each of 8 lanes + # stores the counter (1, then 2) to two consecutive words. + 'CS_RELOAD': ('s_mov_b32 s10, s6\ns_mov_b32 s11, 0\ns_load_dwordx8 s[12:19], s[10:11], 0x0\ns_mov_b32 s22, 0\n' + 'v_lshlrev_b32 v4, 3, v0\ns_waitcnt lgkmcnt(0)\ns_add_u32 s22, s22, 1\nv_mov_b32 v5, s22\n' + 'buffer_store_dword v5, v4, s[16:19], 0 offen\nv_add_nc_u32 v4, 4, v4\n' + 's_load_dwordx8 s[12:19], s[10:11], 0x0\ns_cmp_lt_u32 s22, 2\ns_cbranch_scc1 65526\ns_endpgm\n', + '06038abe80038bbe05030cf4000000fa800396be83000834' '7fc08cbf1681168016020a7e001070e004050480' + '8408084a05030cf4000000fa16820abff6ff85bf000081bf'), + # The same loop reloading from byte 32 of the table: the back edge brings another descriptor. + 'CS_RELOAD_OTHER': ('s_mov_b32 s10, s6\ns_mov_b32 s11, 0\ns_load_dwordx8 s[12:19], s[10:11], 0x0\ns_mov_b32 s22, 0\n' + 'v_lshlrev_b32 v4, 3, v0\ns_waitcnt lgkmcnt(0)\ns_add_u32 s22, s22, 1\nv_mov_b32 v5, s22\n' + 'buffer_store_dword v5, v4, s[16:19], 0 offen\nv_add_nc_u32 v4, 4, v4\n' + 's_load_dwordx8 s[12:19], s[10:11], 0x20\ns_cmp_lt_u32 s22, 2\ns_cbranch_scc1 65526\ns_endpgm\n', + '06038abe80038bbe05030cf4000000fa800396be83000834' '7fc08cbf1681168016020a7e001070e004050480' + '8408084a05030cf4200000fa16820abff6ff85bf000081bf'), + # v_readfirstlane_b32 of a VGPR copied from a loop counter (LOOP_RFL) or from a register written on one path of a + # forward join (JOIN_RFL): the recomputed uniform expression must not carry a constant folded across the join. + 'LOOP_RFL': ('s_mov_b32 s23, 0\ns_add_u32 s23, s23, 1\nv_mov_b32 v7, s23\nv_readfirstlane_b32 s24, v7\n' + 'v_mov_b32 v0, s24\ns_cmp_lt_u32 s23, 2\ns_cbranch_scc1 65530\n' + EXPORT, + '800397be' '17811780' '17020e7e' '0705307e' '1802007e' '17820abf' 'faff85bf' + EXPORT_WORDS), + 'JOIN_RFL': ('s_mov_b32 s23, 1\ns_cmp_eq_u32 s8, 0\ns_cbranch_scc1 1\ns_mov_b32 s23, 2\nv_mov_b32 v7, s23\n' + 'v_readfirstlane_b32 s24, v7\nv_mov_b32 v0, s24\n' + EXPORT, + '810397be' '088006bf' '010085bf' '820397be' '17020e7e' '0705307e' '1802007e' + EXPORT_WORDS), + # A path that never wrote the register brings no value to the join: the descriptor loaded on the other path is + # kept (DESC_ONE_PATH). A graphics user SGPR (s0-s15) counts as written at entry, so a constant written on one path + # into it is read at run time, not folded (USER_ONE_PATH). + 'DESC_ONE_PATH': ('s_mov_b32 s30, 0\nv_mov_b32 v0, 0\nv_mov_b32 v1, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 2\n' + 's_load_dwordx8 s[16:23], s[8:9], 0x0\ns_waitcnt lgkmcnt(0)\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '80039ebe8002007e8002027e1e8006bf020085bf04040cf4000000fa7fc08cbf080f00f000040400703f8cbf' + '0f1800f804050607000081bf'), + 'USER_ONE_PATH': ('s_mov_b32 s30, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\ns_mov_b32 s12, 2\nv_mov_b32 v0, s12\n' + + EXPORT, '80039ebe1e8006bf010085bf82038cbe0c02007e' + EXPORT_WORDS), +} +CS_RSRC2, CS_GROUP = 7 << 1 | 0 << 11, (8, 1, 1) # s0-s3, two root constants, one table; v0 = tid.x +# The results by instruction semantics (COUNT with a root constant of 3; OUTSIDE adds 1, then 5 twice). +EXPECTED = {'OUTSIDE': 11} +# The folded statements main emitted, and what they give: the folded loops run to the guard and export nothing. +OLD = {'OUTSIDE': (' s25 = s25 + s23;\n', ' s25 = s25 + 0x00000001u;\n', 3)} + + +def root(*params): + """RTS0 with the given parameters: 't' a descriptor table, an int n that many root constants (b0).""" + head = 24 + 12 * len(params) + blob, data = b'', b'' + for p in params: + if p == 't': + blob += struct.pack('<3I', 0, 0, head + len(data)) + data += struct.pack('<2I', 0, head + len(data) + 8) + else: + blob += struct.pack('<3I', 1, 0, head + len(data)) + data += struct.pack('<3I', 0, 0, p) + rts0 = struct.pack('<6I', 2, len(params), 24, 0, head + len(data), 0) + blob + data + part = b'RTS0' + struct.pack(' X -> Y -> T) writes s23 = 5: s23 is joined at + # the loop header T (+0xc), worked out over the blocks rather than the textual range, and read at run time there. + stage = G.Stage.__new__(G.Stage) + stage.ins = G.decode(bytes.fromhex(SOURCES['OUTSIDE'][1])) + assert 23 in stage.joined_registers()[0xc], stage.joined_registers() + assert ' s25 = s25 + s23;' in lines('OUTSIDE') + # Compute: an unplaced user SGPR (refused in straight-line code) written on one path only is refused at the join. + import startup_gfx2hlsl_compute_check as C + try: + G.ComputePipeline(bytes.fromhex(SOURCES['CS_UNPLACED'][1]), C.root_blob(), C.CASES['A'][2], (1, 1, 1)).hlsl_cs() + except G.Unsupported as reason: + assert 'numeric use of s0 holding joined at a branch target' in str(reason), str(reason) + else: + raise AssertionError('CS_UNPLACED accepted') + # Every path brings an equal symbol: kept. A constant equal on both paths still folds, and a descriptor reloaded + # from the same table slot on one path is still bound, in a forward join and across a loop's back edge. + assert ' v0 = s23;' in lines('JOIN_SAME') # #2279 drops the constant at any join another path writes + same = translate('DESC_SAME') + assert ' t = r0.Load(int3(v0, v1, 0));' in same.hlsl_ps().splitlines(), same.hlsl_ps() + reload = translate_cs('CS_RELOAD') + cs = reload.hlsl_cs().splitlines() + assert ' u0.Store(a, v5);' in cs and ' s22 = s22 + 0x00000001u;' in cs, cs + assert 'uav 0 table 1 16' in reload.manifest().splitlines(), reload.manifest() + # Another descriptor on the back edge: refused where the loop header reads it. + try: + translate_cs('CS_RELOAD_OTHER').hlsl_cs() + except G.Unsupported as reason: + assert "buffer store through s[16:19] holding ('joined at a branch target',)" in str(reason), str(reason) + else: + raise AssertionError('CS_RELOAD_OTHER accepted') + one = translate('DESC_ONE_PATH') + assert ' t = r0.Load(int3(v0, v1, 0));' in one.hlsl_ps().splitlines(), one.hlsl_ps() + user = lines('USER_ONE_PATH') + assert ' v0 = s12;' in user and not any('v0 = 0x00000002u' in l for l in user), user + # The readfirstlane recompute (uniform since the last join) gets no folded constant from across a join: both are + # refused as unproven. Main folded the loop counter to 0 + 1 at the header and read s24 = s23 from it. + refused('LOOP_RFL', 'v_readfirstlane_b32 requires a proven uniform source') + refused('JOIN_RFL', 'v_readfirstlane_b32 requires a proven uniform source') + # Equal tuples that do not name one value are not kept: a word modified on both paths (the written value is not + # in the symbol) and descnum. + assert not G.names_one_value(('desc', ('table', 0), 0, 0, 'modified')) and not G.names_one_value(('descnum',)) + assert G.names_one_value(('desc', ('table', 0), 0, 0)) and G.names_one_value(('const', 2)) + print('loop counters, forward joins, a root-constant loop, 64-bit copies and descriptor joins pass; equal symbols ' + 'on every path are kept; straight-line code still folds') + + +def check_binary(llvm_mc): + for name, (source, words) in SOURCES.items(): + built = assemble(llvm_mc, source).hex() + assert built == words, '%s: assembled %s, recorded %s' % (name, built, words) + print('fixture words match llvm-mc') + + +def run(dxc, runner, adapter, hlsl, directory, name): + source = hlsl.replace('PSOut main(PSIn i)', 'PSOut translated(PSIn i)') + ''' +RWByteAddressBuffer data : register(u0); +[numthreads(1, 1, 1)] +void main() { + PSIn i = (PSIn)0; + data.Store4(0, asuint(translated(i).mrt0)); +} +''' + src, cso, output = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'bin')) + src.write_text(source, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + result = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', '64', str(output)], + capture_output=True, text=True) + print(result.stdout, end='') + if result.returncode == 77: + sys.exit(77) + if result.returncode or result.stderr: + raise AssertionError(result.stderr or 'raw UAV dump exited with %d' % result.returncode) + return struct.unpack('<4I', output.read_bytes()[:16]) + + +def check_dispatch(dxc, runner, adapter, control=False): + runner = str(Path(runner).resolve()) + out = Path(__file__).resolve().parents[1] / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + for name, want in EXPECTED.items(): + hlsl = translate(name).hlsl_ps() + if control: + old, new, folded = OLD[name] + assert hlsl.count(old) == 1, (name, hlsl) + hlsl = hlsl.replace(old, new) + want = folded + got = run(dxc, runner, adapter, hlsl, Path(tmp), name) + assert got == (want,) * 4, (name, got, want) + print('%s%s: %d in all four channels' % ('control ' if control else '', name, want)) + if not control: + run_reload(dxc, runner, adapter, Path(tmp)) + + +def run_reload(dxc, runner, adapter, directory): + """CS_RELOAD through the compute-store runner of startup_gfx2hlsl_compute_check.py: root UAV u0 is the stored + buffer. Lane t writes 1 and 2 to words 2t and 2t + 1; every other word keeps the sentinel.""" + import startup_gfx2hlsl_compute_check as C + want = [C.SENTINEL] * C.WORDS + for t in range(CS_GROUP[0]): + want[2 * t:2 * t + 2] = [1, 2] + src, cso, case = (directory / ('CS_RELOAD.%s' % ext) for ext in ('hlsl', 'cso', 'case')) + src.write_text(translate_cs('CS_RELOAD').hlsl_cs(), encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + case.write_bytes(struct.pack(' 2) + + +def names_one_value(sym): + """True when two equal symbols stand for the same value, so a join where every path brings it can keep it. + A modified descriptor word, descnum, a fixed buffer word, a sampler-heap word and an unplaced entry register + compare equal for different values (what was written, or where it came from, is not in the tuple). An exec copy + is taken only while exec holds the entry mask, so equal copies hold the same mask.""" + if sym is None: + return False + if sym[0] == 'desc': + return len(sym) == 4 # ('desc', source, load offset, dword); the 'modified' mark drops the written value + # shortcut: equal 'ptr' symbols count as one value though s_add_u32 on a pointer keeps its symbol; not covered here (PR #2069) + return sym[0] in ('const', 'ud', 'ptr', 'ptrhi', 'execcopy') + + +def scalar_destinations(name, asm): + """The SGPRs (and 'm0') an instruction may write; 'any' for s_movrel*, whose register comes from m0.""" + if name.startswith(NO_SCALAR_DESTINATION) or '_store' in name: + return set() + if 'movrel' in name: + return {'any'} + ops = parse(asm)[1] + out = set() + for tok in ops[:2] if name.startswith(TWO_SCALAR_DESTINATIONS) else ops[:1]: + if tok == 'm0': + out.add('m0') + r = reg_range(tok) + if r and r[0] == 's': + out.update(range(r[1], r[2] + 1)) + return out + def desc_key(sym): """Resource key of the descriptor a ('desc', source, load offset, dword) word belongs to: the key descriptor() @@ -768,22 +813,38 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.ins = decode(strip_header(code)) else: self.ins = decode(strip_header(code), refusals) if decoded is None else decoded - self.lines = [] # body statements (per block) - self.sym = {} # scalar register -> symbolic value - self.used_s, self.used_v = set(), set() - self.exec_known = True # exec still equals the entry mask (the lane is active) - self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known - self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] - self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() - self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'f16' - self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) - self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export - self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export - self.uses_pos = False - self.masks = set() # scalar registers currently holding lane masks - self.fetched = False # vertex: the entry call into the fetch routine was translated as loads - self.setup_entry() - self.translate() + # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept + # there is known only afterwards: translate again with that register read at run time or refused there. A + # register only moves from kept to 'run' to 'refuse', so this ends. + self.force_joined = {} # branch target -> register -> 'run' | 'refuse' + first_refusal = len(refusals) if refusals is not None else 0 + while True: + self.lines = [] # body statements (per block) + self.sym = {} # scalar register -> symbolic value + self.used_s, self.used_v = set(), set() + self.exec_known = True # exec still equals the entry mask (the lane is active) + self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known + self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] + self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() + self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'f16' + self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) + self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export + self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export + self.uses_pos = False + self.masks = set() # scalar registers currently holding lane masks + self.fetched = False # vertex: the entry call into the fetch routine was translated as loads + self.setup_entry() + self.translate() + grown = False + for t, regs in self.back_force.items(): + have = self.force_joined.setdefault(t, {}) + for reg, kind in regs.items(): + if have.get(reg) not in (kind, 'refuse'): + have[reg], grown = kind, True + if not grown: + break + if refusals is not None: + del refusals[first_refusal:] # ---- entry state --------------------------------------------------------------------- def setup_entry(self): @@ -1077,6 +1138,77 @@ def const_words(self, tok): return None if any(w is None for w in words) else words # ---- instruction translation ------------------------------------------------------------- + def joined_registers(self): + """{branch target: registers whose program-order symbol may not hold on every path into it}. + + Program order carries the state after every instruction above the target into it. That state holds on every + path only for a register whose writes above the target are all in blocks that dominate it (in dominance + order), and which no block that reaches it from at or below it writes (a loop body, or a later block that + branches back). Computed over the basic blocks, so a path that leaves a loop's textual range and comes back + counts.""" + ins = self.ins + if not ins: + return {} + index = {off: i for i, (off, *_) in enumerate(ins)} + calculated = getattr(self, 'calculated_pc', {}) # unit probes build a Stage without translate() + branch = lambda name: name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64') + target_of = lambda off, name, asm: (calculated.get(off) if name == 's_setpc_b64' # None: no proven target + else int(parse(asm)[1][0].split('_')[1], 16)) + leaders = {0} | {target_of(off, name, asm) for off, _, name, asm in ins if branch(name)} - {None} + for i, (off, n, name, asm) in enumerate(ins[:-1]): + if branch(name) or name == 's_endpgm': + leaders.add(ins[i + 1][0]) + starts = sorted(index[o] for o in leaders if o in index) + bounds = list(zip(starts, starts[1:] + [len(ins)])) + block_of = {} + for b, (lo, hi) in enumerate(bounds): + for i in range(lo, hi): + block_of[i] = b + succ = [] + for lo, hi in bounds: + off, n, name, asm = ins[hi - 1] + out = [] if name in ('s_branch', 's_setpc_b64', 's_endpgm') or hi == len(ins) else [block_of[hi]] + if branch(name) and target_of(off, name, asm) in index: + out.append(block_of[index[target_of(off, name, asm)]]) + succ.append(out) + pred = [[a for a in range(len(bounds)) if b in succ[a]] for b in range(len(bounds))] + writes = [set().union(*(scalar_destinations(*ins[i][2:]) for i in range(lo, hi))) for lo, hi in bounds] + everything = set(range(106)) | {'m0'} + writes = [everything if 'any' in w else w for w in writes] + # Dominators of each block (iterative; the entry block is block 0). + dom = [set(range(len(bounds))) for _ in bounds] + dom[0] = {0} + changed = True + while changed: + changed = False + for b in range(1, len(bounds)): + new = ({b} | set.intersection(*(dom[p] for p in pred[b]))) if pred[b] else {b} + if new != dom[b]: + dom[b], changed = new, True + joined = {} + for target in leaders - {0} | ({0} if any(0 in s for s in succ) else set()): + if target not in index: + continue + t = block_of[index[target]] + reach, todo = set(), list(pred[t]) # blocks with a path of length >= 1 into the target + while todo: + b = todo.pop() + if b not in reach: + reach.add(b) + todo += pred[b] + regs = set() + above_dominators = sorted(b for b in dom[t] - {t} if b < t) + for b in range(len(bounds)): + if b < t and b not in dom[t]: + regs |= writes[b] # above the target but not on every path into it + if b in reach and b >= t: + regs |= writes[b] # a loop body or a later block that comes back + # Writes in dominating blocks hold on every path only if their textual order is their execution order. + if any(not (a in dom[c]) for a, c in zip(above_dominators, above_dominators[1:])): + regs |= set().union(*(writes[b] for b in above_dominators)) + joined[target] = regs + return joined + def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ try: @@ -1109,12 +1241,71 @@ def translate(self): self.has_branches = bool(targets) self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) + joined = self.joined_registers() + forced = getattr(self, 'force_joined', {}) # unit probes build a Stage without __init__ + entry_ud = {reg: sym for reg, sym in self.sym.items() if sym[0] == 'ud'} # never assigned at run time + materialize = {} # entry register -> its root-constant source, assigned at entry because a join reads it + incoming = {} # forward target -> (the joined registers' symbols, those written) at each branch to it + kept = {} # target -> joined register -> the symbol every path known so far brings (kept there) + self.back_force = {} # target -> register -> 'run' | 'refuse': a back edge disagrees with what was kept + # SGPRs written on the path being translated. A path that never wrote a register brings no value to a join + # (reading it there would read whatever the hardware left), so it does not constrain the meet. Every SGPR up + # to the last one the entry state names counts as written (hardware-initialized), and for graphics stages all + # user SGPRs s0-s15 too, so an entry value is never taken for an unwritten register. + # (unit probes build a Stage without __init__, so kind and used_s may be missing) + entry = [r for r in set(self.sym) | set(getattr(self, 'used_s', ())) if isinstance(r, int)] + written = set(range(max(entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} + every_sgpr = set(range(106)) | {'m0'} start = 0 + falls = True # the instruction above falls through (the entry path reaches the first one) for off, n, name, asm in self.ins: if off in targets and off != start: self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, None)) self.lines, start = [], off + if off in targets: + # A branch target joins paths, and the symbol tracked in program order holds on all of them only for + # a register outside the joined set. A joined register keeps its symbol when every path into the + # target brings an equal one that names one value (back edges are checked once the loop body is + # translated, see back_force). Otherwise it is read at run time from here on, which every constant + # allows (each is assigned when set; entry root constants are assigned at entry); one that holds, on + # some path, a symbol with no run-time value (a descriptor word, a pointer, an unplaced entry + # register) gets a symbol that refuses any read before the next write. + kept[off] = {} + here = joined.get(off, set()) + arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ + incoming.get(off, []) + written = (written - here) | set().union(*(w for _, w in arriving)) + for reg in here: + paths = [s[reg] for s, w in arriving if reg in w] # paths that never wrote it bring nothing + force = forced.get(off, {}).get(reg) + if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): + self.sym[reg] = kept[off][reg] = paths[0] + continue + if force == 'refuse' or any(p and not run_time_symbol(p) for p in paths): + self.sym[reg] = ('joined at a branch target',) + continue + if reg in entry_ud: + materialize[reg] = 'ud%d' % entry_ud[reg][1] + self.sym.pop(reg, None) + if reg != 'm0': + self.used_s.add(reg) + if name.startswith('s_cbranch') or name == 's_branch' or (name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): + target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) + there = joined.get(target, set()) + if target > off: + incoming.setdefault(target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) + else: + for reg in there & written: + back, sym = self.sym.get(reg), kept.get(target, {}).get(reg) + if back and not run_time_symbol(back) and back != sym: + self.back_force.setdefault(target, {})[reg] = 'refuse' + elif sym is not None and back != sym: + self.back_force.setdefault(target, {}).setdefault( + reg, 'run' if run_time_symbol(sym) else 'refuse') + falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') + dests = scalar_destinations(name, asm) + written |= every_sgpr if 'any' in dests else dests self.pc = off # 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 @@ -1155,6 +1346,7 @@ def translate(self): self.lines, start = [], off + n if self.lines: self.blocks.append((start, self.lines, None)) + self.materialized = materialize # declarations() assigns these before the body (and before any loop) self.pinned_low16_v.update(self.low16_only_v) leak = self.pinned_low16_v & self.whole_read_v if leak: @@ -1653,12 +1845,17 @@ def src_sym(t): if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] if pair: - hi = self.sym.get(reg_range(ops[1])[2]) - if hi and hi[0] in ('desc', 'descnum', 'ptr', 'ptrhi', 'const', 'ud'): - self.sym[d + 1] = hi + high = reg_range(ops[1])[2] + hi = self.sym.get(high) + if hi and not run_time_symbol(hi): + self.sym[d + 1] = hi # a descriptor word, a pointer or an unassigned constant: symbol only else: - self.sym.pop(d + 1, None) - if self.tracks_uniformity(): + # A value the high word holds at run time is copied at run time too, so a join that later + # reads the register at run time finds it (a constant keeps its symbol for folding). + self.set_s(d + 1, self.S(high)) + if hi and hi[0] in ('const', 'ud'): + self.sym[d + 1] = hi + elif self.tracks_uniformity(): self.varying_s.add(d + 1) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': @@ -1964,7 +2161,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load of %d dwords from %s' % (count, p[1])) # Shortcut (default unless X2W_SAMPLER_HEAP=1): a fixed default sampler. for i in range(count): - self.sym[dst[1] + i] = ('const', 0) + # Never assigned at run time (the third field says so): a join that reads it refuses (run_time_symbol). + self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return raise Unsupported('s_load with a register offset through %s' % (p[1],)) @@ -3495,6 +3693,7 @@ def declarations(self): if getattr(self, 'spill_slots', None): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') + lines += [' s%d = %s;' % kv for kv in sorted(getattr(self, 'materialized', {}).items())] return lines From 75053419664f739896d259fcab7a5e65664d07ee Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 12:25:54 +0100 Subject: [PATCH 2/3] startup: refuse joins with an undefined edge or different pointer offsets in gfx2hlsl A register that holds a non-run-time symbol on one edge into a branch target and has no definition on another is unproven there, so a later read is refused instead of using the symbol of the path that never ran. An add on a pointer now marks its symbol 'added', and only an untouched pointer names one value at a join. DESC_ONE_PATH becomes a refusal control; PTR_OFFSETS is new. Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 6 ++-- tests/startup_gfx2hlsl_join_symbols_check.py | 29 +++++++++++++++----- tools/startup/gfx2hlsl.py | 11 ++++++-- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 0be5153b5..21b993cd8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14074,8 +14074,8 @@ a branch and its target. Two cases remained wrong in the emitted HLSL: - A path that leaves a loop's textual range and comes back changes a constant the textual range does not cover. The joined registers are now worked out over the basic blocks and their dominators (a proven `s_setpc_b64` is an -edge, and ends its block). A joined register keeps its symbol when every path that wrote it brings an equal symbol -that names one value, is read at run time when it holds a constant, and refuses a read before its next write when a -path brings a symbol with no run-time value. `startup_gfx2hlsl_join_symbols_check.py` pins the cases; the +edge, and ends its block). A joined register keeps its symbol when every path into the target brings an equal symbol +that names one value (a pointer only if no add touched it), is read at run time when it holds a constant, and refuses a +read before its next write when a path brings a symbol with no run-time value or no definition at all. `startup_gfx2hlsl_join_symbols_check.py` pins the cases; the `join_symbols_folded_*` tests run the old OUTSIDE statement and must give 3, not 11. Controls are pure Python plus a pixel dispatch on WARP and hardware; `binary` reassembles the fixture words with LLVM 15. diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index d02f4bcc2..d7bd2d627 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -15,11 +15,14 @@ and their dominators) keeps a symbol only when every path into the target brings an equal one that names one value. Otherwise it is read at run time: every constant is assigned when set, and an entry root constant is assigned at entry. A register that holds, on some path into the target, a symbol with no run-time value (a descriptor word, a -pointer, an unplaced compute user SGPR) refuses any read before its next write. +pointer, an unplaced compute user SGPR) refuses any read before its next write, and so does one that such a symbol +reaches while another edge never defined it (DESC_ONE_PATH). The fixtures are source-built gfx1013 pixel stages behind a fixed vertex stage: - PAIR_*, DESC_*: a 64-bit copy and descriptor loads around a join (pure Python); OUTSIDE: a loop whose path leaves the loop's textual range and comes back; CS_UNPLACED: a compute program writing an unplaced user SGPR on one path. +- DESC_ONE_PATH, PTR_OFFSETS: refusal controls: the branch skips the only load of the descriptor, and two paths add + different offsets to one pointer. - JOIN_SAME, DESC_SAME: the same constant (read at run time since #2279), or the same descriptor, on both paths of a forward join (kept). - CS_RELOAD: a compute loop that stores through its descriptor at the header and reloads it from the same table slot before the back edge (kept, and dispatched); CS_RELOAD_OTHER reloads another slot (refused). @@ -106,15 +109,24 @@ 'JOIN_RFL': ('s_mov_b32 s23, 1\ns_cmp_eq_u32 s8, 0\ns_cbranch_scc1 1\ns_mov_b32 s23, 2\nv_mov_b32 v7, s23\n' 'v_readfirstlane_b32 s24, v7\nv_mov_b32 v0, s24\n' + EXPORT, '810397be' '088006bf' '010085bf' '820397be' '17020e7e' '0705307e' '1802007e' + EXPORT_WORDS), - # A path that never wrote the register brings no value to the join: the descriptor loaded on the other path is - # kept (DESC_ONE_PATH). A graphics user SGPR (s0-s15) counts as written at entry, so a constant written on one path - # into it is read at run time, not folded (USER_ONE_PATH). + # A descriptor loaded on only one path has no definition on the other edge: unproven at the join, refused when read + # (DESC_ONE_PATH: the branch skips the only load). A graphics user SGPR (s0-s15) counts as written at entry, so a + # constant written on one path into it is read at run time, not folded (USER_ONE_PATH). 'DESC_ONE_PATH': ('s_mov_b32 s30, 0\nv_mov_b32 v0, 0\nv_mov_b32 v1, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 2\n' 's_load_dwordx8 s[16:23], s[8:9], 0x0\ns_waitcnt lgkmcnt(0)\n' 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', '80039ebe8002007e8002027e1e8006bf020085bf04040cf4000000fa7fc08cbf080f00f000040400703f8cbf' '0f1800f804050607000081bf'), + # Two paths add different offsets to one pointer: the symbol keeps ('ptr', source) plus an 'added' mark, so the + # equal tuples must not be kept as one pointer (PTR_OFFSETS). + 'PTR_OFFSETS': ('s_mov_b32 s30, 0\nv_mov_b32 v0, 0\nv_mov_b32 v1, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 2\n' + 's_add_u32 s8, s8, 4\ns_branch 1\ns_add_u32 s8, s8, 8\n' + 's_load_dwordx8 s[16:23], s[8:9], 0x0\ns_waitcnt lgkmcnt(0)\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '80039ebe8002007e8002027e1e8006bf020085bf08840880010082bf08880880' + '04040cf4000000fa7fc08cbf080f00f000040400703f8cbf0f1800f804050607000081bf'), 'USER_ONE_PATH': ('s_mov_b32 s30, 0\ns_cmp_eq_u32 s30, 0\ns_cbranch_scc1 1\ns_mov_b32 s12, 2\nv_mov_b32 v0, s12\n' + EXPORT, '80039ebe1e8006bf010085bf82038cbe0c02007e' + EXPORT_WORDS), } @@ -142,7 +154,8 @@ def root(*params): ROOTS = {'DESC_CALC': ('t', 1), 'PAIR_READ': ('t', 1), 'PAIR_ROOT': ('t', 1), 'PAIR_WRITE': ('t', 1), 'DESC_LOAD': ('t', 1), - 'DESC_WORD': ('t', 1), 'DESC_SAME': ('t', 1), 'DESC_ONE_PATH': ('t', 1)} + 'DESC_WORD': ('t', 1), 'DESC_SAME': ('t', 1), 'DESC_ONE_PATH': ('t', 1), + 'PTR_OFFSETS': ('t', 1)} def translate(name): @@ -217,8 +230,9 @@ def check_controls(): assert "buffer store through s[16:19] holding ('joined at a branch target',)" in str(reason), str(reason) else: raise AssertionError('CS_RELOAD_OTHER accepted') - one = translate('DESC_ONE_PATH') - assert ' t = r0.Load(int3(v0, v1, 0));' in one.hlsl_ps().splitlines(), one.hlsl_ps() + # Refusal controls: no definition on the skipping edge, and different offsets added to one pointer. + refused('DESC_ONE_PATH', "descriptor operand s[16:23] holds ('joined at a branch target',)") + refused('PTR_OFFSETS', "s_load through s8 holding ('joined at a branch target',)") user = lines('USER_ONE_PATH') assert ' v0 = s12;' in user and not any('v0 = 0x00000002u' in l for l in user), user # The readfirstlane recompute (uniform since the last join) gets no folded constant from across a join: both are @@ -229,6 +243,7 @@ def check_controls(): # in the symbol) and descnum. assert not G.names_one_value(('desc', ('table', 0), 0, 0, 'modified')) and not G.names_one_value(('descnum',)) assert G.names_one_value(('desc', ('table', 0), 0, 0)) and G.names_one_value(('const', 2)) + assert G.names_one_value(('ptr', ('table', 0))) and not G.names_one_value(('ptr', ('table', 0), 'added')) print('loop counters, forward joins, a root-constant loop, 64-bit copies and descriptor joins pass; equal symbols ' 'on every path are kept; straight-line code still folds') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 715a93c5c..94c88a77a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -465,8 +465,9 @@ def names_one_value(sym): return False if sym[0] == 'desc': return len(sym) == 4 # ('desc', source, load offset, dword); the 'modified' mark drops the written value - # shortcut: equal 'ptr' symbols count as one value though s_add_u32 on a pointer keeps its symbol; not covered here (PR #2069) - return sym[0] in ('const', 'ud', 'ptr', 'ptrhi', 'execcopy') + # An add on a pointer keeps its symbol and marks it 'added' (the offset is not in the tuple), so only an + # untouched pointer, exactly (kind, source), names one value. + return sym[0] in ('const', 'ud', 'execcopy') or (sym[0] in ('ptr', 'ptrhi') and len(sym) == 2) def scalar_destinations(name, asm): @@ -1279,6 +1280,10 @@ def translate(self): for reg in here: paths = [s[reg] for s, w in arriving if reg in w] # paths that never wrote it bring nothing force = forced.get(off, {}).get(reg) + if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): + # An edge with no definition brings the hardware's leftover, not this symbol: unproven. + self.sym[reg] = ('joined at a branch target',) + continue if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): self.sym[reg] = kept[off][reg] = paths[0] continue @@ -1863,6 +1868,8 @@ def src_sym(t): # The word keeps its descriptor identity for loads; an exact-word check (unmodified_descriptor) # sees the mark. self.sym[d] = own[:4] + ('modified',) + else: + self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked else: self.sym[d] = ('descnum',) return None From aa17c95646683d3895f417e00264758a071c6429 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 12:26:19 +0100 Subject: [PATCH 3/3] startup: move the shader cache revision to x2w-startup-shader-10 The join-symbol lowering changes the generated HLSL for programs with joins, so translations cached under revision 9 are not reused. Co-Authored-By: Claude Fable 5.2 --- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_draw.inl | 4 ++-- tests/startup_compute_request_offline_check.py | 4 ++-- tests/startup_indirect_draw_indexed.cpp | 2 +- tools/startup/gfx2hlsl.py | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 7d3804bde..0727c2523 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -189,7 +189,7 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-9`, so translations paired by number are not reused. +The shader cache revision is `x2w-startup-shader-10`, so translations paired by number are not reused. The record layouts were checked offline against the signatures of one title's shader archive (local files only, not in the repository). The counts below apply the translator's own record checks. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index de85dc166..4a2cb4da4 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -232,7 +232,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-9"; + constexpr char revision[] = "x2w-startup-shader-10"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -352,7 +352,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-9cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-10cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index bb0e8ef1c..9825135f8 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0xc034b1a1c9e1d289 # compute_key of the parts above +KEY = 0xbc35a19da8443505 # compute_key of the parts above def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-9cs': + for b in b'x2w-startup-shader-10cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-9"; + constexpr char revision[] = "x2w-startup-shader-10"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 94c88a77a..9d4ec32ff 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4297,7 +4297,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-9')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-10')))) return fnv(layout, key) if layout else key @@ -4306,7 +4306,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-9cs') + key = fnv(b'x2w-startup-shader-10cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack('