diff --git a/CMakeLists.txt b/CMakeLists.txt index 34d462b6eb..11e458dbfd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3188,7 +3188,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control mbcnt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap) + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap + j-scalar-dropped h-inner-unpredicated k-block-entered) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index b6f48c49e5..a7a6258cfa 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13737,9 +13737,41 @@ root placement. The only in-repo evidence is the local compute-record scan above used s4 or s5. A numeric read of a user SGPR that the root signature does not place, including s0-s3, is refused because its value is unknown. -Inside a block that `s_cbranch_execz` skips, a scalar instruction is refused. The wave runs that block -when any lane is active, while the one-lane model would skip it for an inactive lane. An image sample -with implicit LOD is also refused, because a compute lane has no derivatives. +A block that `s_cbranch_execz` skips needs a liveness check. The wave runs the block when any lane is +active, so its scalar results are the same for every lane. The one-lane model skips the block for an +inactive lane. That lane can only differ from the wave by reading scalar state the block defines after the +join. When no lane is active, the wave skips the block too. The block is therefore translated unchanged +when every SGPR, `vcc`, `m0` and SCC it may define is dead where it joins. A backward liveness pass over +the program's instructions checks this. `m0` is always treated as live. + +Exec writes inside the block are accepted when the block is straight-line (no branch in it and none into +it) and the write cannot set the exec bit of a lane whose bit is clear, because that lane's bit is clear on +entry. Accepted forms: +- `s_and_saveexec` and `v_cmpx`; +- `s_and` or `s_andn2` that keeps exec; +- `s_or`, `s_xor` or a move whose other source only ever holds a copy of exec made earlier in the same block. + +That covers a nested `if` without its own branch. The copies are tracked in program order, which is every path +only in a straight-line block. + +Each instruction's reads and writes come from its printed operands, checked against the repository +decoder's spelling: +- `v_cmpx` prints no destination (its e64 form prints an unused SDST field), so all of its operands are reads; +- `s_setpc` and `s_movrel*` do not write their printed operand; +- `v_div_fmas` reads `vcc`; +- the high half of a mask is tracked apart from the low half. + +The block is still refused in these cases: +- a definition that is live at the join; +- any other exec write: exec set from a compare alone, restored from a mask saved before the block, or written + in a block with a branch or entered by one (a proven calculated `s_setpc_b64` jump counts), or restored through a 64-bit move, `s_or` or `s_xor` (the tracked copies name + registers, not which exec half they hold); +- an effect outside scalar registers, such as a scalar store or atomic, a barrier, `s_endpgm` or `v_writelane`; +- a branch out of the block; +- a backward `s_cbranch_execz`. + +Graphics stages keep today's per-lane behaviour. An image sample with implicit LOD is refused, because a +compute lane has no derivatives. The output is a `cs` HLSL main with `[numthreads]` and a version 2 manifest. The manifest has `stage cs` and `group` lines, plus one `uav table ` line for each store @@ -13774,14 +13806,28 @@ The runtime has no slot-67 path yet, so no translated compute program runs in th immediate offset. - Case C enables Y only, with group size 8x1x1 and 1x5x1 groups. It stores four words from every lane, then three words under an exec mask set from a compare. +- Case J leaves three of eight lanes active, then enters a block that `s_cbranch_execz` skips for the other + lanes. Inside the block it loads the store descriptor and computes a scalar from the group ID and the root + constants, which the active lanes store. The block's scalars are dead at the join. A control that drops one + of the block's scalar statements must mismatch. +- Case H nests an `s_and_saveexec`/`s_or` if inside such a block. Three lanes store two words, three more lanes + store one word, and the rest store nothing. A control that drops the inner exec predicate must mismatch. +- Case K enters such a block only in group 1; in the other three groups the whole wave skips it. A control that + runs the block for the skipped waves must mismatch. Each thread reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL for `cs_6_0`, and a plain D3D12 device dispatches it. The root signature is the test runner's (a root SRV, a root UAV and the root constants), so the manifest's table lines and the descriptor fetch are not exercised on the GPU. All 320 words are compared, including the sentinels. Four controls must each mismatch: swapping the X and Y group IDs, dropping the store, dropping case B's immediate offset, and dropping case C's exec -predicate. The pure-Python controls refuse every reviewed input that was previously accepted: a modified -descriptor word, an execz-skipped scalar write, an implicit-LOD sample and a misaligned immediate offset. +predicate. Three more cover the execz cases: dropping a scalar statement in case J's block, dropping case H's +inner exec predicate, and running case K's block for the skipped waves. + +The pure-Python controls cover: +- accepted and refused execz blocks: a dead definition is accepted; a live scalar definition, SCC consumed + after the join, a nested block and a backward branch are refused; +- a modified descriptor word, an implicit-LOD sample and a misaligned immediate offset, all refused; +- a store past the descriptor's range, which today translates with no range check. Translating every cached graphics request before and after the descriptor-tracking change gave identical output and refusals. The local check covered 925 requests, 123 of which translate. diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index a1d74c902d..ac460cb05a 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -23,14 +23,19 @@ - case E runs five SAVEEXEC forms with overlapping and distinct source registers. Four single-thread groups cover both input bits for EXEC and S0; each stores the saved EXEC, resulting SCC and new EXEC. - case F exchanges LDS dwords across the two halves of each 64-thread group and broadcasts lane 37. +- case J enables X only, v0, group size 8x1x1 and 4x1x1 groups, leaves lanes tid.x < 3 active and branches over + a block with s_cbranch_execz; the block loads the store descriptor and computes a scalar from the group ID and + the root constants that the active lanes store, and its scalars are dead where it joins; +- case H is case J's shape with a nested if inside the skipped block (s_and_saveexec, restored with s_or of the + saved mask): lanes tid.x < 3 store two words, lanes 3-5 one word, the rest none. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's r0, u0 and entry cbuffer. The manifest's table lines and the descriptor fetch are therefore not exercised on the GPU. All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the X -and Y group IDs at entry, drop the store, drop case B's immediate offset, or drop case C's exec predicate; each must -change the readback. +and Y group IDs at entry, drop the store, drop case B's immediate offset, drop case C's exec predicate, or drop a +scalar statement inside case J's block; each must change the readback. """ import struct import subprocess @@ -167,6 +172,66 @@ def tidig(components): # A known SGPR base of UINT_MAX wraps to zero when the first mask bit is counted. SOURCE_D_WRAP = SOURCE_D.replace('v_mov_b32 v6, 7', 's_mov_b32 s22, -1').replace('v8, s20, v6', 'v8, s20, s22') WORDS_D_WRAP = WORDS_D.replace(bytes.fromhex('87020c7e080065d7140c0200'), bytes.fromhex('c10396be080065d7142c0000')) +SOURCE_J = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 3, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 10 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) lgkmcnt(0) +v_xor_b32 v5, s22, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_J = bytes.fromhex( + '06038abe' '80038bbe' '050308f4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8300887d' + '6a03febe' '0a0088bf' '050408f4100000fa' '07051693' '16041680' '001030e004050380' '70008cbf' '160a0a3a' + '001070e004050480' '1503febe' '000081bf') + +SOURCE_H = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 3, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 11 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +v_xor_b32 v5, s22, v3 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_saveexec_b32 s0, vcc_lo +buffer_store_dword v5, v4, s[16:19], 0 offen +s_or_b32 exec_lo, exec_lo, s0 +v_not_b32 v6, v5 +buffer_store_dword v6, v4, s[16:19], 0 offen offset:4 +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_H = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '83060834' '7e0395be' '8600887d' + '6a03febe' '0b0088bf' '07051693' '16041680' '16060a3a' '8300887d' '6a3c80be' '001070e004050480' '7e007e88' + '056f0c7e' '041070e004060480' '1503febe' '000081bf') + +# Case K is case J with the condition on the group ID: only group 1 enters the block, and in groups 0, 2 and 3 the +# whole wave skips it. +SOURCE_K = SOURCE_J.replace('v_cmp_gt_u32 vcc_lo, 3, v0\n', 'v_mov_b32 v6, s7\nv_cmp_eq_u32_e32 vcc_lo, 1, v6\n') +WORDS_K = WORDS_J.replace(bytes.fromhex('8300887d'), bytes.fromhex('07020c7e' '810c847d')) def saveexec_fixture(): # RDNA 2 ISA, SOP1: D takes old EXEC, then EXEC takes the bitwise result and SCC reports nonzero. @@ -275,6 +340,9 @@ def saveexec_fixture(): 'D-wrap': (SOURCE_D_WRAP, WORDS_D_WRAP, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), 'E': (*saveexec_fixture(), USER7 | TGID_X | tidig(1), (1, 1, 1), (4, 1, 1)), 'F': (SOURCE_F, WORDS_F, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), } @@ -320,6 +388,13 @@ def saveexec_fixture(): 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:6': '061070e004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:4092': 'fc1f70e004050480', + 's_add_u32 s23, s7, 1': '07811780', + 's_cselect_b32 s23, 1, 0': '81801785', + 'v_cmp_gt_u32 vcc_lo, 3, v0': '8300887d', + 's_cbranch_execz 0': '000088bf', + 's_cbranch_execz 3': '030088bf', + 's_cbranch_execz 65534': 'feff88bf', + 's_or_b32 exec_lo, exec_lo, s21': '7e157e88', 's_and_b32 s17, s17, 0xc000ffff': '11ff1187ffff00c0', 's_and_b32 s17, s17, 0xc000fff0': '11ff1187f0ff00c0', 's_and_b32 s18, s18, 0xc000ffff': '12ff1287ffff00c0', @@ -404,6 +479,21 @@ def expected(name): if name == 'A': i = (gx + 3 * gy + 6 * gz) * 24 + tx + 2 * ty + 6 * tz out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * STRIDE) & MASK) + elif name == 'K': + i = gx * 8 + tx + if gx == 1: # only group 1's wave enters the block + out[i] = input_word(i) ^ ((gx * STRIDE + KEY) & MASK) + elif name == 'H': + i = gx * 8 + tx + value = i ^ ((KEY + gx * STRIDE) & MASK) + if tx < 3: # the nested if inside the skipped block + out[2 * i] = value + if tx < 6: # the skipped block + out[2 * i + 1] = ~value & MASK + elif name == 'J': + i = gx * 8 + tx + if tx < 3: # the lanes the compare leaves active; the others skip the block + out[i] = input_word(i) ^ ((gx * STRIDE + KEY) & MASK) elif name == 'C': i = gy * 8 + tx record = [input_word(i), i, (KEY + i * STRIDE) & MASK] @@ -680,17 +770,84 @@ def check_controls(): pipe = G.ComputePipeline(splice('s_and_b32 s18, s18, 0xffff'), root_blob(), CASES['A'][2], (2, 3, 4), refusals=refusals) assert pipe.modified == {(('table', 1), 16)}, pipe.modified assert [G.normalize_refusal(r) for r, _ in refusals] == ['buffer store through a modified descriptor'], refusals - # A scalar write in a block s_cbranch_execz skips: the wave runs it when any lane is active, so a per-lane skip - # would store 0 for inactive lanes. Refused with exec from a plain move and in the saveexec form. - for lines in (['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', - 's_cbranch_execz 1', 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20'], + # Scalar instructions in a block s_cbranch_execz skips. The wave runs the block when any lane is active, so an + # inactive lane that skips it can differ only by reading, after the join, scalar state the block defines. + # Live after the join: the block's s20 is read by v_mov_b32 v5, s20, so the hardware stores gid.x + 1 for every + # lane while a per-lane skip would store 0. Still refused, with exec from a plain move and in the saveexec form. + enter = ['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo'] + leave = ['s_mov_b32 exec_lo, s21'] + for lines in (enter + ['s_cbranch_execz 1', 's_add_u32 s20, s7, 1'] + leave + ['v_mov_b32 v5, s20'], ['v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo', 's_cbranch_execz 1', 's_add_u32 s20, s7, 1', 's_or_b32 exec_lo, exec_lo, s0', 'v_mov_b32 v5, s20']): - refused('s_add_u32 inside a block s_cbranch_execz skips', lambda lines=lines: translate( - 'A', code=splice(*lines)).hlsl_cs()) - # The same block without the branch translates: the scalar write then runs for every lane. - translate('A', code=splice('s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', - 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20')).hlsl_cs() + refused('s_add_u32 inside a block s_cbranch_execz skips per lane: definition of s20', + lambda lines=lines: translate('A', code=splice(*lines)).hlsl_cs()) + # Dead after the join (s23 and SCC are not read again): accepted, and case J runs such a block on the GPU. + translate('A', code=splice(*enter, 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', *leave)).hlsl_cs() + translate('J').hlsl_cs() + # SCC set in the block and consumed after the join by s_cselect: refused. + refused('definition of scc', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', *leave, 's_cselect_b32 s23, 1, 0')).hlsl_cs()) + # Exec writes inside the block. For a lane whose exec bit is clear on entry, the wave's writes must keep it clear, + # so its exec at the join is what the model has. Exec set from a compare alone can set it: refused. + refused('exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_mov_b32 exec_lo, vcc_lo', 's_cbranch_execz 0', + *leave)).hlsl_cs()) + # A nested if (s_and_saveexec, restored with s_or of the mask saved in the block) keeps it clear: accepted, and + # case H runs one on the GPU. Restoring with a mask saved before the block (s21) could set it: refused. + translate('A', code=splice(*enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', + 's_and_saveexec_b32 s0, vcc_lo', 's_or_b32 exec_lo, exec_lo, s0', *leave)).hlsl_cs() + translate('H').hlsl_cs() + refused('exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_saveexec_b32 s0, vcc_lo', + 's_or_b32 exec_lo, exec_lo, s21', *leave)).hlsl_cs()) + # A backward s_cbranch_execz: refused. + refused('s_cbranch_execz to a block before it', lambda: translate('A', code=splice( + 's_add_u32 s23, s7, 1', 's_cbranch_execz 65534')).hlsl_cs()) + # The same live-out block without the branch translates: the scalar write then runs for every lane. + translate('A', code=splice(*enter, 's_add_u32 s20, s7, 1', *leave, 'v_mov_b32 v5, s20')).hlsl_cs() + # Review inputs that were accepted. v_cmpx prints no destination: in `v_cmpx_gt_u32_e32 s23, v0` after the join, + # s23 is read (the wave compares against gid.x + 1 in every lane), so the block's s23 is live: refused. + prologue = '06038abe' '80038bbe' '050308f4000000fa' '7fc08cbf' # s[12:15] = the table's first descriptor + for cmpx in ('1700a87d', '0000d4d417000200'): # v_cmpx_gt_u32 s23, v0 in the e32 and e64 forms + program = bytes.fromhex(prologue + '800397be' '7e0395be' '8300887d' '6a03febe' '010088bf' '07811780' '1503febe' + + cmpx + '82000834' '001070e004000380' '000081bf') + refused('s_add_u32 inside a block s_cbranch_execz skips per lane: definition of s23', + lambda program=program: translate('A', code=program).hlsl_cs()) + # A branch inside the block: on the path that skips `s_mov_b32 s21, exec_lo` the restore reads the mask saved + # before the block, which can set inactive lanes. Exec writes are accepted in straight-line blocks only: refused. + program = bytes.fromhex(prologue + '82000834' '7e0395be' '8300887d' '6a03febe' '040088bf' '048007bf' '010085bf' + '7e0395be' '1503febe' '001070e004000380' '000081bf') + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', + lambda: translate('A', code=program).hlsl_cs()) + # saved tracks register names, not which exec half was copied: two 32-bit copies restored through a 64-bit move + # would set exec_hi from exec_lo. Refused; the 32-bit restore above stays accepted. + SPLICE.update({'s_mov_b32 s22, exec_lo': '7e0396be', 's_mov_b32 s23, exec_lo': '7e0397be', + 's_mov_b64 exec, s[22:23]': '1604febe'}) + refused('s_mov_b64 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 's_mov_b32 s22, exec_lo', 's_mov_b32 s23, exec_lo', 's_mov_b64 exec, s[22:23]', + *leave)).hlsl_cs()) + # Refusals of the block scan with short programs: a branch leaving the block, a vcc definition that a vcc branch + # reads after the join, and a proven s_setpc_b64 (GETPC, ADD, ADDC, SETPC) inside the block. + SPLICE['s_branch 2'] = '020082bf' + refused('s_branch inside a block s_cbranch_execz skips per lane: branch out of the block', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 1', 's_branch 2', *leave)).hlsl_cs()) + refused('v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 1', 'v_cmp_gt_u32 vcc_lo, 1, v0', *leave, + 's_cbranch_vccz 1', 'v_mov_b32 v5, s20')).hlsl_cs()) + SPLICE.update({'s_cbranch_execz 4': '040088bf', 's_getpc_b64 s[22:23]': '001f96be', 's_add_u32 s22, s22, 12': '168c1680', + 's_addc_u32 s23, s23, 0': '17801782', 's_setpc_b64 s[22:23]': '162080be'}) + refused('s_setpc_b64 inside a block s_cbranch_execz skips per lane: effect outside scalar registers', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 4', 's_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 12', + 's_addc_u32 s23, s23, 0', 's_setpc_b64 s[22:23]', *leave)).hlsl_cs()) + # A proven calculated jump into the block bypasses the copy like a direct branch does: the restore at the target + # reads a mask the block did not save. GETPC / ADD 20 / ADDC / SETPC lands on the restore; both are refused. + SPLICE.update({'s_add_u32 s22, s22, 20': '16941680', 's_cbranch_execz 2': '020088bf'}) + block = ['s_cbranch_execz 2', 's_mov_b32 s21, exec_lo', *leave] + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( + 'A', code=splice('s_branch 2', *block)).hlsl_cs()) + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( + 'A', code=splice('s_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 20', 's_addc_u32 s23, s23, 0', + 's_setpc_b64 s[22:23]', *block)).hlsl_cs()) # An implicit-LOD sample has no derivatives in a compute lane; the level-zero form translates. load = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40') sample = 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D' @@ -738,6 +895,9 @@ def check_binary(llvm_mc): 'd-exec': ('D', 'if (exec & 1) v10 =', 'v10 ='), 'f-peer': ('F', '0x00000080u ^ v4', 'v4'), 'f-broadcast': ('F', 'lds[(v8 + 164u) >> 2]', 'lds[(v8 + 160u) >> 2]'), + 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), + 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), + 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), 'g-overlap': ('G', 'v7 = lds[(a + 144u)', 'v7 = lds[(v6 + 144u)'), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6d48308b49..7b67482df4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -440,8 +440,111 @@ def reg_range(tok): return None -# Scalar instructions with no scalar or exec effect, allowed inside a compute block s_cbranch_execz skips. -SKIPPABLE_SCALAR = ('s_waitcnt', 's_nop', 's_inst_prefetch', 's_clause', 's_cbranch_', 's_branch') +# Scalar state for the compute execz-block check (Stage.execz_refusals): registers as 's', 'vcc', 'exec', 'm0' +# and 'scc'. Reads may be over-approximated and must-writes under-approximated; both only add refusals. +# The low half of a mask (vcc_lo, exec_lo) is 'vcc' / 'exec', the high half 'vcc_hi' / 'exec_hi', and a 64-bit +# operand both, so a write of one half never counts as writing the other. +SCALAR_TOKEN = re.compile(r'\bs\[(\d+):(\d+)\]|\bs(\d+)\b|\b(vcc|exec)(_lo|_hi)?\b|\b(m0)\b|\bsrc_(scc)\b') +EXEC_KEYS = {'exec', 'exec_hi'} +NO_SCALAR_EFFECT = ('s_waitcnt', 's_nop', 's_inst_prefetch', 's_clause', 's_cbranch_', 's_branch') +# Forms that print no destination: every printed scalar operand is read. v_cmpx writes EXEC implicitly; its e32 and +# SDWA forms print only sources, and the repository decoder prints the e64 form's unused SDST field first. +# s_setpc reads its address; s_movrel* address a register through m0, so their printed operand is not a plain write. +NO_DESTINATION = ('v_cmpx', 's_setpc', 's_movrel', 'v_movrel') +IMPLICIT_VCC_READ = ('v_div_fmas',) +SCC_READERS = ('s_cselect', 's_cmov', 's_addc', 's_subb', 's_cbranch_scc') +READ_MODIFY_WRITE = ('s_addk_i32', 's_mulk_i32', 's_cmov', 's_bitset', 'v_mac', 'v_fmac') +TWO_DESTINATIONS = ('v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', 'v_mad_u64_u32', 'v_mad_i64_i32') +# Effects outside scalar registers, or control flow the wave takes as a whole: refused inside such a block. +EXECZ_REFUSED = ('s_endpgm', 's_store', 's_atomic', 's_buffer_store', 's_buffer_atomic', 's_barrier', 's_sendmsg', + 's_setreg', 's_setpc', 's_swappc', 's_dcache', 's_icache', 's_gl1', 's_memtime', 's_memrealtime', + 's_trap', 's_sleep', 'v_writelane', 's_movrel', 'v_movrel') + + +def scalar_tokens(text): + out = set() + for lo, hi, single, mask, half, m0, scc in SCALAR_TOKEN.findall(text): + if lo: + out.update('s%d' % n for n in range(int(lo), int(hi) + 1)) + elif mask: + out.update({'_lo': {mask}, '_hi': {mask + '_hi'}}.get(half, {mask, mask + '_hi'})) + else: + out.add('s' + single if single else m0 or scc) + return out + + +def is_exec(regs): + return regs in ({'exec'}, EXEC_KEYS) + + +def exec_stays_clear(name, asm, saved): + """True when an exec write cannot set the bit of a lane whose bit is clear: exec & x (s_and_saveexec, v_cmpx, + s_and or s_andn2 with exec as the kept operand), or exec | x, exec ^ x or a move of x where x is only ever a copy + of exec made inside the same skipped block (so x's bit is clear for that lane too).""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(('s_and_saveexec', 'v_cmpx')): + return True + if not ops or not is_exec(scalar_tokens(ops[0])): + return False + srcs = [scalar_tokens(op) for op in ops[1:]] + # saved tracks register names, not which exec half was copied, so only a 32-bit restore is trusted + copies = lambda regs: bool(regs) and regs <= saved and base.endswith('32') + if base in ('s_and_b32', 's_and_b64'): + return any(is_exec(regs) for regs in srcs) + if base in ('s_andn2_b32', 's_andn2_b64'): + return bool(srcs) and is_exec(srcs[0]) + if base in ('s_or_b32', 's_or_b64', 's_xor_b32', 's_xor_b64') and len(srcs) == 2: + return all(is_exec(regs) or copies(regs) for regs in srcs) + if base in ('s_mov_b32', 's_mov_b64') and len(srcs) == 1: + return copies(srcs[0]) + return False + + +def exec_copies_after(name, asm, saved, may): + """The registers that hold only copies of exec made in the block, after this instruction.""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + dests = scalar_tokens(ops[0]) - EXEC_KEYS - {'scc'} if ops else set() + saved = saved - (may - EXEC_KEYS - {'scc'}) + if base.startswith('s_and_saveexec') or (base in ('s_mov_b32', 's_mov_b64') and len(ops) == 2 + and is_exec(scalar_tokens(ops[1]))): + saved |= dests + return saved + + +def scalar_effects(name, asm): + """(reads, must-writes, may-writes) of scalar state for one decoded instruction.""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(NO_SCALAR_EFFECT) or base == 's_endpgm': + reads = {'scc'} if base.startswith('s_cbranch_scc') else {'vcc'} if base.startswith('s_cbranch_vcc') else \ + {'exec'} if base.startswith('s_cbranch_exec') else set() + return reads, set(), set() + if base.startswith('v_cmpx'): + return scalar_tokens(' '.join(ops)) | {'exec'}, {'exec'}, set(EXEC_KEYS) + if '_store' in base or base.startswith(('ds_write', 'exp') + NO_DESTINATION) or not ops: + return scalar_tokens(' '.join(ops)) | ({'m0'} if 'movrel' in base else set()), set(), set() + if base.startswith(('s_cmp', 's_bitcmp')): + return scalar_tokens(' '.join(ops)), {'scc'}, {'scc'} + two = base.startswith(TWO_DESTINATIONS) + dests, srcs = ops[:2] if two else ops[:1], ops[2:] if two else ops[1:] + writes = scalar_tokens(' '.join(dests)) + reads = scalar_tokens(' '.join(srcs)) + if base.startswith(READ_MODIFY_WRITE): + reads |= writes + if base.startswith(SCC_READERS) or (base in SCA and 'scc' in SCA[base][0]): + reads.add('scc') + if base.startswith(IMPLICIT_VCC_READ): + reads.add('vcc') + may = set() + if 'saveexec' in base or 'wrexec' in base: + reads.add('exec') + writes.add('exec') + may |= EXEC_KEYS + if (base in SCA and SCA[base][1]) or 'saveexec' in base or 'wrexec' in base: + writes.add('scc') + return reads, writes, writes | may | ({'scc'} if base.startswith('s_') else set()) # Forms with no scalar destination: their printed operands are all sources (v_cmpx writes only EXEC, which the # symbolic tracking does not hold). @@ -1253,6 +1356,73 @@ def const_words(self, tok): words = [self.is_const(n) for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words + def execz_refusals(self): + """{offset: reason} for compute blocks that s_cbranch_execz skips and the one-lane model cannot run. + + The wave runs such a block when any lane is active, so its scalar results are the same for every lane; the + model skips the block for an inactive lane. That lane can differ from the wave only by reading, after the + join, scalar state the block defines (no lane active means the wave skipped the block too). The block is + therefore accepted unchanged when every scalar register, mask and SCC it may define is dead where it joins, + and it has no effect outside scalar registers and no branch out of it. An exec write is accepted in a + straight-line block (no branch in it, none into it) when it cannot set the bit of a lane whose bit is clear + (exec_stays_clear): such a lane's bit is clear on entry, so the wave leaves it clear and its exec at the + join is the model's. A live definition, another exec write, a refused effect, a branch leaving the block + or a backward s_cbranch_execz is refused.""" + offsets = [ins[0] for ins in self.ins] + index = {off: i for i, off in enumerate(offsets)} + effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] + succ = [] + targets = [] # every branch target, the proven calculated s_setpc_b64 ones included + for i, (off, n, name, asm) in enumerate(self.ins): + to = int(parse(asm)[1][0].split('_')[1], 16) if name.startswith(('s_cbranch', 's_branch')) else None + if name == 's_setpc_b64': # a proven calculated jump reaches its target + to = getattr(self, 'calculated_pc', {}).get(off) + nxt = [i + 1] if i + 1 < len(self.ins) and name not in ('s_branch', 's_endpgm') else [] + if to is not None: + targets.append(to) + succ.append(nxt + ([index[to]] if to in index else [])) + live_in = [set() for _ in self.ins] + changed = True + while changed: + changed = False + for i in reversed(range(len(self.ins))): + out = set().union(*(live_in[s] for s in succ[i])) if succ[i] else set() + reads, writes, _ = effects[i] + value = reads | (out - writes) + if value != live_in[i]: + live_in[i], changed = value, True + refused = {} + for b, (off, n, name, asm) in enumerate(self.ins): + if name != 's_cbranch_execz': + continue + t = index.get(int(parse(asm)[1][0].split('_')[1], 16)) + if t is None or t <= b: + refused.setdefault(off, 's_cbranch_execz to a block before it') + continue + live = live_in[t] | {'m0'} # m0 is also read implicitly; treat it as live + saved = set() # registers whose every write in the block so far is a copy of exec + # The copies are tracked in program order, which is every path only in a straight-line block: no branch + # in it and no branch into it. Elsewhere an exec write is refused. + straight = not any(self.ins[k][2].startswith(('s_cbranch', 's_branch')) for k in range(b + 1, t)) and \ + not any(index.get(target) in range(b + 1, t) for target in targets) + for i in range(b + 1, t): + at, _, inner, inner_asm = self.ins[i] + may = effects[i][2] + reason = None + if inner.startswith(EXECZ_REFUSED): + reason = 'effect outside scalar registers' + elif inner.startswith(('s_cbranch', 's_branch')) and not ( + b < index.get(int(parse(inner_asm)[1][0].split('_')[1], 16), -1) <= t): + reason = 'branch out of the block' + elif may & EXEC_KEYS and not (straight and exec_stays_clear(inner, inner_asm, saved)): + reason = 'exec write' + elif (may - EXEC_KEYS) & live: + reason = 'definition of %s, live where the block joins' % ', '.join(sorted((may - EXEC_KEYS) & live)) + saved = exec_copies_after(inner, inner_asm, saved, may) + if reason: + refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) + return refused + # ---- instruction translation ------------------------------------------------------------- def joined_registers(self, with_cfg=False): """{branch target: registers whose program-order symbol may not hold on every path into it}. @@ -1393,7 +1563,6 @@ def translate(self): refusals.append((str(reason), self.kind)) self.calculated_pc = {} targets = set() - skipped = [] # compute: (branch, target) of each s_cbranch_execz targets.update(target for target in self.calculated_pc.values() if target is not None) # (branch, target) of every branch, the proven s_setpc_b64 jumps included branches = [(pc, target) for pc, target in self.calculated_pc.items() if target is not None] @@ -1402,9 +1571,8 @@ def translate(self): target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) branches.append((off, target)) - if name == 's_cbranch_execz' and self.kind == 'cs': - skipped.append((off, target)) join_writes = self.join_writes(branches) + refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) init_sym = dict(self.sym) init_exec_known = getattr(self, 'exec_known', True) @@ -1545,13 +1713,8 @@ def translate(self): dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests try: - if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( - name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) - and not name.startswith(SKIPPABLE_SCALAR) - and not (name == 's_setpc_b64' and off in self.calculated_pc)): - # The wave runs this block when any lane is active, so its scalar state changes for every - # lane; the one-lane model would skip it for an inactive lane. - raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) + if off in refused: + raise Unsupported(refused[off]) base = re.sub(r'_e(32|64)$', '', name) if base.startswith('s_cbranch_'): cond = base[10:]