diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index bcec8358c9..aef1f5d722 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -110,6 +110,7 @@ jobs: (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_word_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), @@ -305,6 +306,7 @@ jobs: tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ tests/startup_gfx2hlsl_heap_record_check.py \ + tests/startup_gfx2hlsl_heap_word_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 402377e163..bf2d228982 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_word_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index be634595a2..044219bf75 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3290,6 +3290,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") + add_test(NAME startup_gfx2hlsl_heap_word COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_word_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -4457,11 +4459,15 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) add_test(NAME startup_compute_live_retry_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_live_retry_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} - startup_compute_dispatch_heap_${adapter} startup_compute_live_retry_${adapter} + startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} + startup_compute_live_retry_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 3831d690bf..e69fadc8fb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16654,7 +16654,7 @@ ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. -Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer in any form other than the one below (`s_load of a resource heap record whose index is read from a buffer other than a table buffer at a dispatch-constant offset`). A formatted load or a store through such a record, and the graphics stages, are refused as before. `tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). @@ -16686,6 +16686,19 @@ python -B tests/startup_compute_lds_dual_atomics_check.py binary llvm-mc-15 Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), signed 32-bit (`ds_min_i32`/`ds_max_i32`), `ds_xor_b32`, `ds_sub_u32`/`ds_rsub_u32`, float LDS atomics, and 64-bit LDS dual/atomic forms. +#### A heap record index read from a table buffer + +The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_load_dword(xN)` from a table buffer descriptor that no instruction modified, at a literal byte offset or at ` * k + c` built with `s_mul_i32`, `s_mulk_i32`, `s_add_u32`, `s_add_i32` or `s_addk_i32` and literals (plus any `offset:` modifier), dword-aligned, with no branch target between the arithmetic and the load or between the load and the shift. The manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the stand-in reads the table record, computes the byte offset in 32-bit arithmetic, reads the index word from the buffer's memory and binds the heap record it names as above. The read is made at record time, so it is sound only when the GPU does not write the word: the stand-in reads it only when the buffer lies in the recording's upload memory (list slot 148), which no GPU command writes. A buffer elsewhere refuses the dispatch (`a heap index word is not in the list's upload memory`), and so does a word past the buffer's `stride * num_records` bytes (`a heap index word is outside its table buffer`). An index from a per-thread value, a group ID, another buffer word, a register sum or a modified descriptor keeps the refusal. + +`tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. + +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index. All 153 change their first refusal and none translates fully yet: 145 now stop at a later instruction (82 at a per-lane `vcc` live at an `s_cbranch_execz` join, 24 at `v_fma_mix_f32`, 14 at `src_scc` in `s_mul_i32`, 25 at others), 6 at a buffer read in another form and 2 at an 8-dword record. 145 programs hold a heap load that now lowers, but 120 of the 158 still hold a refused heap-record load somewhere: 101 a buffer read in another form, 32 an offset that is not a root constant shifted by 5, 2 an 8-dword record (this counts every refusal site, including sites after an earlier refusal). Most of the buffer-form sites compute the offset or read the word before a branch target, which ends the marks because another path into the join may hold a different word; in about 97 programs an 8-dword (image) heap record would stay refused even past that. + +```powershell +python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_word_" -V +``` + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index dffee39960..618ad9976a 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -11,8 +11,15 @@ struct ComputeTranslation { // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root - // constant (parameter and word) that indexes its 32-byte record in the list's view heap. - struct Slot { int a, b; bool texture, heap; }; + // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param + // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: + // at alone) is the index. + struct Slot { + int a, b; + bool texture, heap; + int word_param = -1, word_byte = 0; + std::uint32_t at = 0, times = 0; + }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later @@ -81,7 +88,7 @@ const char* load_compute_translation(ComputeTranslation& tr) continue; } unsigned i = 0, x = 0, y = 0, z = 0, w = 0; - int a = 0, b = 0, used = 0; + int a = 0, b = 0, c = 0, d = 0, used = 0; const auto whole = [&] { return used == static_cast(line.size()); }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; @@ -92,6 +99,12 @@ const char* load_compute_translation(ComputeTranslation& tr) else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u%n", &i, &a, &b, &x, &used) == 4 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({-1, 0, false, true, a, b, x}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u rootconst %d %d times %u%n", &i, &a, &b, &x, + &c, &d, &y, &used) == 7 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({c, d, false, true, a, b, x, y}); else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) tr.uavs.push_back({a, b}); else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && @@ -174,12 +187,34 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; - // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by - // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. - const u64 entry = slot.a < 0 || slot.b < 0 ? 0 - : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) - : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); + std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); + if (slot.word_param >= 0) { + // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command + // writes there), at the dword-aligned 32-bit byte offset the program reads it at. + const u64 table_entry = pass.compute_tables.table(slot.word_param).record(static_cast(slot.word_byte), 16); + if (!table_entry || !x2w_local::readable(reinterpret_cast(table_entry), 16)) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(table_entry), 16); + const std::uint32_t at = slot.at + index * slot.times; + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + if (words[0] == view_token_magic || !list_upload_range(self, address + at, 4).resource) { + reason = "a heap index word is not in the list's upload memory"; + break; + } + if (u64{at} + 4 > u64{stride ? stride : 1} * words[2]) { + reason = "a heap index word is outside its table buffer"; + break; + } + std::memcpy(&index, reinterpret_cast(address + at), 4); + } + // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the + // title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.heap ? (slot.word_param >= 0 || slot.a >= 0 ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); const std::size_t entry_bytes = slot.texture ? 32 : 16; if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; diff --git a/tests/startup_compute_dispatch_heap_word_check.py b/tests/startup_compute_dispatch_heap_word_check.py new file mode 100644 index 0000000000..4ddb8ad31f --- /dev/null +++ b/tests/startup_compute_dispatch_heap_word_check.py @@ -0,0 +1,94 @@ +"""A translated compute program whose input is the resource heap record a word of a table buffer indexes (slot 14). + +usage: startup_compute_dispatch_heap_word_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_word_check.py as a device slot 67 pipeline and records it +as startup_compute_dispatch_heap_check.py does, with root constant word 2 set to 1 and a buffer in the recording's +upload memory (list slot 148) at table byte 96. Word 288 + 336 * 1 of that buffer is 2, the heap record of the +input. Heap records 0 and 1 hold the output's descriptor and every other word of the buffer names one of them, so +a dispatch that ignores the word, the root constant, its scale or the byte offset is refused instead of passing. +Runs sharing one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the word and all 320 words equal the expectation of + case A of startup_gfx2hlsl_compute_check.py; +3. dispatch-heap-word-outside (the word is 0x07ffffff, a record past the heap), dispatch-heap-word-past (the + buffer ends at the word) and dispatch-heap-word-placed (the buffer is the placed input, not upload memory): + each refused with one logged reason, every output word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +import startup_gfx2hlsl_heap_word_check as W +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +CONTROLS = ( + ('dispatch-heap-word-outside', "a heap record is outside the list's view heap"), + ('dispatch-heap-word-past', 'a heap index word is outside its table buffer'), + ('dispatch-heap-word-placed', "a heap index word is not in the list's upload memory"), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and W.FORM == '288 rootconst 0 2 times 336', 'the consumer hard-codes these' + (directory / 'program').write_bytes(W.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == W.MANIFEST % W.FORM + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + for mode, reason in CONTROLS: + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, '%s: a refused Dispatch wrote the output' % mode + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and reason in refused[0], '%s:\n%s' % (mode, result.stderr[-3000:]) + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (mode, census) + print(f'startup_compute_dispatch_heap_word: PASS on {adapter} (all {C.WORDS} words match through the index word; ' + f'untouched before translation and for {len(CONTROLS)} refused controls)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py index 0ea8575862..ff517ffc80 100644 --- a/tests/startup_gfx2hlsl_heap_record_check.py +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -13,8 +13,9 @@ dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are compared whole. Every other form keeps a refusal: another shift, another index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an offset -modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the -record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +modifier, eight dwords, an index read from a buffer at an offset that differs between groups (named as such; +startup_gfx2hlsl_heap_word_check.py covers the buffer forms that are accepted), a formatted load or a store through +the record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. """ import argparse import struct @@ -52,7 +53,8 @@ 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', - 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_buffer_load_dword s26, s[28:31], s14': '8e0620f40000001c', 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', @@ -166,10 +168,10 @@ def check_refusals(): ('index register loaded from a buffer after the shift', {SHIFT: (SHIFT, TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0')}, not_shifted), ('branch target between the shift and the load', {SHIFT: (SHIFT,) + JUMP}, not_shifted), - ('index read from a buffer', {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], 0x0', 's_lshl_b32 s6, s26, 5')}, - from_buffer), - ('index read from a buffer into the shifted register', - {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0', SHIFT)}, from_buffer), + ('index read from a buffer at a group-ID offset', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], s14', 's_lshl_b32 s6, s26, 5')}, from_buffer), + ('index read from a buffer at a group-ID offset into the shifted register', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], s14', SHIFT)}, from_buffer), ('high word 1', {CLEAR: ('s_mov_b32 s9, 1',)}, high), ('high word a root constant', {CLEAR: ('s_mov_b32 s9, s5',)}, high), ('high word left as the group ID', {CLEAR: ()}, high), diff --git a/tests/startup_gfx2hlsl_heap_word_check.py b/tests/startup_gfx2hlsl_heap_word_check.py new file mode 100644 index 0000000000..68578488d4 --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_word_check.py @@ -0,0 +1,160 @@ +"""A compute program whose resource heap record index is a word it reads from a table buffer. + +usage: startup_gfx2hlsl_heap_word_check.py [--llvm-mc ] + +The program of startup_gfx2hlsl_heap_record_check.py with its index no longer the root constant itself: root constant +word 2 picks the byte offset of a word in the buffer of table byte 96, and that word is the index: + + s_load_dwordx4 s[28:31], s[12:13], 0x60 + s_mulk_i32 s6, 0x150 + s_add_u32 s6, s6, 0x120 + s_buffer_load_dword s6, s[28:31], s6 + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +gfx2hlsl.py names that input `srv 1 buf heap word table 1 96 at 288 rootconst 0 2 times 336`: the dispatch reads the +word at byte 288 + 336 * (root constant word 2) of that buffer, then the 32-byte heap record it indexes. The byte +offset is the same for every thread of the dispatch. A literal byte offset, an offset modifier, s_mul_i32 and +s_addk_i32 and a later word of a wider load give the same line with their own numbers; the HLSL and the manifest of +the first form are compared whole. Every other form keeps a refusal: an offset from the group ID, an offset read +from a buffer, a scale or a byte offset that is not a multiple of 4, a register added after the arithmetic, a +modified descriptor, and a branch target between the arithmetic and the load. --llvm-mc reassembles every +instruction used here and compares the words. +""" +import argparse + +import startup_gfx2hlsl_heap_record_check as H +from startup_gfx2hlsl_compute_check import G, assemble, refused + +TABLE = 's_load_dwordx4 s[28:31], s[12:13], 0x60' +SCALE, ADD = 's_mulk_i32 s6, 0x150', 's_add_u32 s6, s6, 0x120' +READ_INDEX = 's_buffer_load_dword s6, s[28:31], s6' +WAIT = 's_waitcnt lgkmcnt(0)' +INDEX = (TABLE, SCALE, ADD, WAIT, READ_INDEX, WAIT, H.SHIFT) +# Every instruction added here, recorded from llvm-mc 15. +ENCODED = { + TABLE: '060708f4600000fa', SCALE: '500106b8', ADD: '06ff068020010000', READ_INDEX: '8e0120f40000000c', + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6': '8e0624f40000000c', 's_lshl_b32 s6, s27, 5': '1b85068f', + 's_buffer_load_dword s6, s[28:31], 0x40': '8e0120f4400000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_mulk_i32 s6, 0x152': '520106b8', 's_add_u32 s6, s6, 0x122': '06ff068022010000', + 's_and_b32 s29, s29, 0xffff': '1dff1d87ffff0000', 's_add_u32 s6, s6, s14': '060e0680', + 's_mul_i32 s6, s6, s5': '06050693', 's_mul_i32 s6, s6, 0x150': '06ff069350010000', 's_addk_i32 s6, 0x120': '200186b7', + 's_buffer_load_dword s6, s[28:31], s6 offset:0x10': '8e0120f41000000c', +} +ALL = {**H.ENCODED, **ENCODED} + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf table 1 96 +srv 1 buf heap word table 1 96 at %s +uav 0 table 1 16 +""" +FORM = '288 rootconst 0 2 times 336' +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +ByteAddressBuffer r1 : register(t1); +RWByteAddressBuffer u0 : register(u0); +""" +# The heap record program's body with the index read through r0 (the table buffer) and the input through r1. +MAIN = H.MAIN.replace(' s6 = ud2 << (0x00000005u & 31);\n', """\ + s6 = ud2 * 0x00000150u; + s6 = s6 + 0x00000120u; + s6 = r0.Load(s6 + 0); + s6 = s6 << (0x00000005u & 31); +""").replace('v5 = r0.Load(a + 0);', 'v5 = r1.Load(a + 0);') +assert MAIN.count('r0.Load') == 1 and MAIN.count('r1.Load') == 1 + + +def words(index=INDEX): + """The heap record program with the index lines in place of its shift.""" + return b''.join(bytes.fromhex(ALL[line]) for original in H.PROGRAM + for line in (index if original == H.SHIFT else (original,))) + + +WORDS = words() + + +def pipeline(index=INDEX): + return G.ComputePipeline(words(index), H.root_blob(), H.RSRC2, H.GROUP) + + +def replace(old, *new): + assert old in INDEX + return tuple(line for original in INDEX for line in (new if original == old else (original,))) + + +def check_lowering(): + pipe = pipeline() + hlsl = pipe.hlsl_cs() + assert pipe.manifest() == MANIFEST % FORM, pipe.manifest() + assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] + forms = ( + ('literal byte offset', (TABLE, WAIT, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, H.SHIFT), '64'), + ('offset modifier', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s6 offset:0x10'), + '304 rootconst 0 2 times 336'), + ('s_mul_i32 and s_addk_i32', replace(ADD, 's_addk_i32 s6, 0x120'), FORM), + ('s_mul_i32 by a literal', replace(SCALE, 's_mul_i32 s6, s6, 0x150'), FORM), + ('second word of a wider load', replace(H.SHIFT, 's_lshl_b32 s6, s27, 5')[:4] + ( + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6', WAIT, 's_lshl_b32 s6, s27, 5'), '292 rootconst 0 2 times 336'), + # A branch target before the arithmetic changes nothing. + ('branch target before the arithmetic', (TABLE,) + H.JUMP + INDEX[1:], FORM), + ) + for name, index, form in forms: + got = pipeline(index).manifest() + assert got == MANIFEST % form, '%s:\n%s' % (name, got) + return len(forms) + + +def check_refusals(): + other = ('s_load of a resource heap record whose index is read from a buffer other than a table buffer at a ' + 'dispatch-constant offset') + controls = ( + ('offset from the group ID', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s14')), + ('offset read from a buffer', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, READ_INDEX)), + ('scale not a multiple of 4', replace(SCALE, 's_mulk_i32 s6, 0x152')), + ('byte offset not a multiple of 4', replace(ADD, 's_add_u32 s6, s6, 0x122')), + ('a register added after the arithmetic', replace(ADD, ADD, 's_add_u32 s6, s6, s14')), + ('scaled by a register', replace(SCALE, 's_mul_i32 s6, s6, s5')), + ('modified descriptor', replace(TABLE, TABLE, WAIT, 's_and_b32 s29, s29, 0xffff')), + ('branch target between the arithmetic and the load', replace(ADD, ADD, *H.JUMP)), + ) + for name, index in controls: + try: + refused(other, lambda: pipeline(index).manifest()) + except AssertionError as error: + raise AssertionError('%s: %s' % (name, error)) from None + # A branch target between the load and the shift ends the word's mark, as for a root constant. + refused('whose offset is not a root constant shifted left by 5', + lambda: pipeline(replace(READ_INDEX, READ_INDEX, *H.JUMP)).manifest()) + # Only a buffer read is named in the manifest; another kind through such a record is refused there. + pipe = pipeline() + key = next(k for k in pipe.resources if k[0][:2] == ('resheap', 'word')) + pipe.resources[key]['kind'] = 'tex2d' + refused("resource through ('resheap', 'word'", pipe.manifest) + return len(controls) + 2 + + +def check_binary(llvm_mc): + for line, encoded in ENCODED.items(): + assert assemble(llvm_mc, line + '\n') == bytes.fromhex(encoded), line + text = [line for original in H.PROGRAM for line in (INDEX if original == H.SHIFT else (original,))] + assert assemble(llvm_mc, '\n'.join(text) + '\n') == WORDS + print('heap word fixture: %d instructions reassembled to the recorded words' % len(ENCODED)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + args = parser.parse_args() + if args.llvm_mc: + check_binary(args.llvm_mc) + forms = check_lowering() + count = check_refusals() + print('startup_gfx2hlsl_heap_word: PASS (manifest and HLSL exact; %d more forms; %d refused controls)' % (forms, count)) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 1d7afbf743..fa1d9a2b21 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -163,7 +163,7 @@ static void* desktop_pipeline(void* device) // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable // dispatch, dispatch-swapped, dispatch-none, dispatch-sampled, dispatch-sampled-unbound, dispatch-heap, -// dispatch-heap-outside: one creation, then dispatch_slot67 below +// dispatch-heap-outside, dispatch-heap-word*: one creation, then dispatch_slot67 below // texture-store, texture-store-none, texture-store-denied, texture-store-occupied, texture-store-copied: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; @@ -196,6 +196,10 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's // descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. // dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// dispatch-heap-word runs the program of startup_gfx2hlsl_heap_word_check.py: the constant is 1 and picks the word +// of the upload buffer at table byte 96 that holds the index, 2. dispatch-heap-word-outside makes that word +// 0x07ffffff, dispatch-heap-word-past ends the buffer at that word, and dispatch-heap-word-placed names the placed +// input buffer instead of upload memory. // Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets // another compute root and the first one again after the constants, dispatch-same-root sets the same root again; // dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other @@ -243,7 +247,8 @@ static int dispatch_slot67(void* device, const std::string& mode) if (heap_record) for (const UINT at : {0u, 32u, 64u}) std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); - const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; + const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; const auto bind = [&] { invoke(list, 32, 1, word(&heap)); @@ -281,6 +286,20 @@ static int dispatch_slot67(void* device, const std::string& mode) bind(); } if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_word) { + // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 + // holds the index, 2; every other word names record 0 or 1, the output's descriptor. + constexpr UINT bytes = 0x400, at = 0x270; + auto* const index = static_cast(reinterpret_cast(invoke(list, 148, bytes, 256))); + if (!index) return 81; + std::memset(index, 0, bytes); + index[0x120 / 4] = index[0x150 / 4] = 1; + index[at / 4] = mode == "dispatch-heap-word-outside" ? 0x07ffffffu : 2u; + const UINT64 address = reinterpret_cast(mode == "dispatch-heap-word-placed" ? buffers[0] : index); + const UINT view[4] = {static_cast(address), static_cast(address >> 32), + mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; + std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); + } invoke(list, 35, 1, gpu); if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); if (FAILED(static_cast(invoke(list, 9)))) return 75; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 529c03a3a5..b9bdc54b59 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4646,15 +4646,8 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False - if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) - and int(srcs[1], 0) == 5): - # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a - # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). - r = reg_range(srcs[0]) - if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': - self.heap_index[d] = self.pipe.uds[syms[0][1]] - elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): - self.heap_index[d] = ('buffer',) + if hasattr(self, 'heap_index'): + self.mark_heap_index(base, d, srcs, syms) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -4663,6 +4656,38 @@ def known(tok): self.set_s(d + 1, self.S(high) if high is not None else '0u', uniform=high_uniform) return None + def heap_word_offset(self, tok, sym): + """(param, word, scale, add) when tok, whose symbol before this instruction is sym, holds root constant word + (param, word) times scale plus add, modulo 2^32 (see mark_heap_index); else None.""" + if sym and sym[0] == 'ud' and self.pipe.uds[sym[1]][0] == 'rootconst': + return self.pipe.uds[sym[1]][1:] + (1, 0) + r = reg_range(tok) + mark = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + return mark[1:] if mark and mark[0] == 'rc' else None + + def mark_heap_index(self, base, d, srcs, syms): + """Marks of SGPR d for heap_record. index << 5 is the byte offset of a 32-byte resource-heap record; the index + is named when it is a root constant word (the dispatch knows it) or a word an s_buffer_load wrote (see + op_s_buffer_load_dword). A root constant word times a literal plus a literal ('rc') is the byte offset such a + load may read the index word at: the same for every thread of the dispatch.""" + lit = [int(t, 0) & 0xffffffff if re.fullmatch(r'0x[0-9a-f]+|[0-9]+', t) else None for t in srcs] + r = reg_range(srcs[0]) + if base == 's_lshl_b32' and lit[1:] == [5]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif word and word[0] == 'bufword': + self.heap_index[d] = ('buffer',) + word[1:] + elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: + for i in (0, 1): + k = lit[1 - i] + offset = self.heap_word_offset(srcs[i], syms[i]) if k is not None else None + if offset: + p, w, scale, add = offset + self.heap_index[d] = (('rc', p, w, scale * k & 0xffffffff, add * k & 0xffffffff) if base == 's_mul_i32' + else ('rc', p, w, scale, add + k & 0xffffffff)) + break + def set_exec_scc(self, expr): self.exec_known = False self.scc_effect = 'emitted' @@ -4757,6 +4782,11 @@ def scalar_accumulate(self, base, ops, mods): self.set_s(d, '0x%08xu' % value, ('const', value)) else: self.set_s(d, result) + offset = self.heap_word_offset(ops[0], sym) if hasattr(self, 'heap_index') else None + if offset: + p, w, scale, plus = offset + self.heap_index[d] = ('rc', p, w, scale, plus + imm & 0xffffffff) if add else ( + 'rc', p, w, scale * imm & 0xffffffff, plus * imm & 0xffffffff) self.masks.discard(d) return None @@ -5020,16 +5050,19 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load with a register offset through %s' % (p[1],)) def heap_record(self, dst, base, token, imm, count): - """s_load_dwordx4 D, , R in a compute program, where R is a root constant word - shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in - the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch - reads the record. Only this exact form is modelled.""" + """s_load_dwordx4 D, , R in a compute program, where R is an index shifted left by 5 + with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap + record that the index names. The index is a root constant word, or a word an s_buffer_load read from an + unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal + (the marks, see mark_heap_index, end at a branch target). The manifest names the root constant or where the + word is; the dispatch reads the word and the record. Only these exact forms are modelled.""" what = 's_load of a resource heap record' r = reg_range(token) index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None if index == ('buffer',): - raise Unsupported('%s whose index is read from a buffer' % what) - if not index or index[0] != 'rootconst': + raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' + 'offset' % what) + if not index or index[0] not in ('rootconst', 'buffer'): raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) if count != 4: raise Unsupported('%s of %d dwords' % (what, count)) @@ -5037,8 +5070,9 @@ def heap_record(self, dst, base, token, imm, count): raise Unsupported('%s with offset:%#x' % (what, imm)) if self.sym.get(base[2]) != ('const', 0): raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] for i in range(count): - self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + self.sym[dst[1] + i] = ('desc', source, 0, i) def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" @@ -5262,6 +5296,19 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: self.emit('a = %s;' % offset) offset = 'a' + # A word read from an unmodified table buffer at a literal offset or at a root constant word times a literal + # plus a literal is the same for the whole dispatch: heap_record names it by (table parameter, table byte, + # root constant parameter and word or None, scale, byte offset). Any other buffer word is only marked. + where = () + if hasattr(self, 'heap_index'): + key, r, sreg = self.descriptor(ops[1]), reg_range(ops[1]), reg_range(token) + first = self.sym.get(r[1]) + at = (None, None, 0, val) if is_lit else self.heap_word_offset( + token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) + if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant + and first[0] == 'desc' and key[0][0] == 'table' and key not in getattr(self.pipe, 'modified', ()) # probes build a bare pipe + and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) + first[4:] for n in range(4))): + where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. uniform = self.tracks_uniformity() and self.uniform_source(token) for i in range(count): @@ -5269,7 +5316,7 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) if hasattr(self, 'heap_index'): - self.heap_index[dst[1] + i] = ('bufword',) + self.heap_index[dst[1] + i] = ('bufword',) + (where[:5] + ((where[5] + 4 * i) & 0xffffffff,) if where else ()) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -9185,6 +9232,11 @@ def manifest(self): where = 'root %d' % source[1] elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes + elif source[0] == 'resheap' and source[1] == 'word' and r['kind'] == 'buf': + # The record the word at byte `at` (+ root constant word * `times`) of table buffer indexes. + table, byte, param, word, scale, at = source[2:] + where = 'heap word table %d %d at %d' % (table, byte, at) + ( + '' if param is None else ' rootconst %d %d times %d' % (param, word, scale)) else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where))