diff --git a/AGENTS.md b/AGENTS.md index ea635125cf..8b5b46c435 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,6 +174,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_pixel_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_store_3d1d_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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 95609be3ef..50679e005f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3351,6 +3351,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_image_store_3d1d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_store_3d1d_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 diff --git a/docs/experiments/startup-compute-volume-line-uav.md b/docs/experiments/startup-compute-volume-line-uav.md new file mode 100644 index 0000000000..0a3d4560e0 --- /dev/null +++ b/docs/experiments/startup-compute-volume-line-uav.md @@ -0,0 +1,14 @@ +# Startup compute stores to 3D and 1D UAVs + +The startup translator lowers full-channel compute `image_store` to +`RWTexture3D` with an integer XYZ address or `RWTexture1D` +with a scalar integer address. A 3D address can be a VGPR tuple or an NSA list. +Both forms use the fixed table descriptor and emit a `tex3d` or `tex1d` UAV +entry. Requests refused before this change are retried by `--pending`, so +the compute cache revision is unchanged. + +Dispatch uses the title's view at its selected mip. For 3D the shader's Z +coordinate is relative to `FirstWSlice`, and a W size of all ones selects +the remaining slices. The Dispatch fixture compares all mip-one texels +against a CPU reference and checks that a 2D view or an out-of-range W +selection leaves the texels unchanged. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 7aca74bd22..4fd8bdb1bc 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2392,6 +2392,10 @@ These are measured on one executable; treat them as hypotheses for others. z must fail. The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. +- **Compute stores to 3D and 1D images.** A compute `image_store` with `dmask:0xf` on a 3D or 1D image + becomes a store to `RWTexture3D` or `RWTexture1D`, and Dispatch binds the title's + 3D or 1D view after checking its mip and, for 3D, its W range. See + [Startup compute stores to 3D and 1D UAVs](experiments/startup-compute-volume-line-uav.md). - **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d|tex2da table P O` line as a UAV range `u0..` placed after the SRVs in the translated root signature's view table. The view is made from the unordered-access view the title created at that table entry (`resolve_pixel_uavs` in `d3d12_draw.inl`), on diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 1dd08c68cc..5060aecaa6 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -2,8 +2,8 @@ // the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and // .cs.cso. Bound from the compute tables recorded by slot 35 and compute root SRVs recorded by slot 43: raw // buffers (`srv buf table ` and `srv buf root ` inputs, `uav table ` -// outputs) named by hardware buffer descriptors or 64-bit root SRV addresses, and 2D textures -// (`srv tex2d table ` inputs, `uav tex2d/tex2da float table channels 4` outputs) named +// outputs) named by hardware buffer descriptors or 64-bit root SRV addresses, and textures +// (`srv tex2d table ` inputs, `uav tex1d/tex2d/tex2da/tex3d float table channels 4` outputs) named // by the token of a view the title created (device slots 18 and 19). `smp` lines become static samplers. Entry // values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is // bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record @@ -12,6 +12,15 @@ // binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only // syncs content). +const char* volume_uav_range_error(const D3D12_RESOURCE_DESC& resource, const D3D12_TEX3D_UAV& view) +{ + if (view.MipSlice >= resource.MipLevels) return "an output 3D texture mip is outside the resource"; + const UINT depth = (std::max)(1u, UINT{resource.DepthOrArraySize} >> (std::min)(view.MipSlice, 15u)); + if (view.FirstWSlice >= depth || !view.WSize || (view.WSize != ~0u && view.WSize > depth - view.FirstWSlice)) + return "an output 3D texture W range is outside the mip"; + return nullptr; +} + 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, or, with word_param @@ -24,7 +33,7 @@ struct ComputeTranslation { int word_param = -1, word_byte = 0; std::uint32_t at = 0, times = 0; Source source = root_constant; - bool array = false; + D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; bool root = false; }; u64 key = 0; @@ -105,6 +114,13 @@ const char* load_compute_translation(ComputeTranslation& tr) if (!std::strcmp(name, names[s])) return static_cast(s + 1); return ComputeTranslation::root_constant; }; + const auto uav_dimension = [&] { + if (!std::strcmp(name, "tex1d")) return D3D12_UAV_DIMENSION_TEXTURE1D; + if (!std::strcmp(name, "tex2d")) return D3D12_UAV_DIMENSION_TEXTURE2D; + if (!std::strcmp(name, "tex2da")) return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + if (!std::strcmp(name, "tex3d")) return D3D12_UAV_DIMENSION_TEXTURE3D; + return D3D12_UAV_DIMENSION_UNKNOWN; + }; 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; if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) @@ -130,13 +146,10 @@ const char* load_compute_translation(ComputeTranslation& tr) 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() && - i == tr.uavs.size()) - tr.uavs.push_back({a, b, true}); - else if (std::sscanf(line.c_str(), "uav %u tex2da float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && - i == tr.uavs.size()) { + else if (std::sscanf(line.c_str(), "uav %u %15s float table %d %d channels 4%n", &i, name, &a, &b, &used) == 4 && whole() && + i == tr.uavs.size() && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN) { tr.uavs.push_back({a, b, true}); - tr.uavs.back().array = true; + tr.uavs.back().uav_dimension = uav_dimension(); } else if (std::sscanf(line.c_str(), "srv %u tex2d table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, true}); @@ -149,7 +162,7 @@ const char* load_compute_translation(ComputeTranslation& tr) i == tr.samplers.statics.size()) tr.samplers.read_manifest_line(line.c_str()); else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 2D texture" - : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D/2D-array float texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 1D/2D/2D-array/3D float texture" : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant or a buffer descriptor word" : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; } @@ -388,9 +401,28 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; words[3] = static_cast(format) | static_cast(desc.ViewDimension) << 16; if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; - else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const auto& view = desc.Texture3D; + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) + reason = "an output texture view or resource is not 3D"; + else { + // Slot 19 can retain a rejected range as an unmaterialized view. + reason = volume_uav_range_error(resource, view); + if (!reason && !created) reason = "an output texture view was not created on the desktop"; + } + } else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + // Checked before `created`, as for 3D: slot 19 records a 1D view with an out-of-range mip as refused. + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D) + reason = "an output texture view or resource is not 1D"; + else if (desc.Texture1D.MipSlice >= resource.MipLevels) + reason = "an output 1D texture mip is outside the resource"; + else if (!created) + reason = "an output texture view was not created on the desktop"; + } else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) reason = "an output texture view was not created on the desktop"; - else if (slot.array) { + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) { // The layer in HLSL is relative to FirstArraySlice: retain the caller's complete view. const auto& a = desc.Texture2DArray; if (!described || desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 909352f100..726c103a45 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4741,14 +4741,14 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) }; const char* skip = nullptr; bool default_view = false; - bool uav_denied = false; // a UAV of a resource without unordered access: recorded as not created, as before #2649 + bool record_refused_uav = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { skip = "resource lacks unordered access"; - uav_denied = true; + record_refused_uav = true; } if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; @@ -4783,6 +4783,20 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if (first_calls(mismatched, 6)) log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, x2w_view_dimension::needed(N, view_dimension), dimension); + } else if constexpr (N == 19) { + if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + skip = volume_uav_range_error(resource_desc, view.Texture3D); + record_refused_uav = skip != nullptr; + } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + x2w_local::readable(reinterpret_cast(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast(described), sizeof(view)); + if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource"; + record_refused_uav = skip != nullptr; + } } } } @@ -4801,7 +4815,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) } else if constexpr (N == 19) { // A translated compute Dispatch tells this refusal from a descriptor that holds no view by the record. // A refused creation leaves a descriptor that still holds a live view as it is. - if (uav_denied && !descriptor_has_live_view(args[D], title_dest)) record_view(false); + if (record_refused_uav && !descriptor_has_live_view(args[D], title_dest)) record_view(false); } }; if (skip) { diff --git a/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..195cfc4b28 --- /dev/null +++ b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py --llvm-mc llvm-mc-15 diff --git a/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..156f018870 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index fd09c48dec..54a6dce2b4 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -13,6 +13,7 @@ 4. texture-store-denied (a texture without unordered access, whose view the stand-in does not create): refused with one logged reason, every half keeps its sentinel. A fifth run binds the same program under a manifest edited to declare no entry values. +The 1D and 3D float texture cases check mip-one readback, a mismatched view, and an invalid 3D W range. Texture input: case A of startup_gfx2hlsl_compute_check.py with a level-zero sample of a 2D texture XORed into the stored word (a static sampler, a texture view at table byte 64). The consumer adds a 1x1 RGBA8 texture whose red @@ -34,6 +35,7 @@ import startup_compute_image_store_d16_check as S import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_image_store_3d1d_check as V from startup_compute_dispatch_check import lines from startup_compute_request_check import DATA, prepare from startup_compute_translate_check import state_a @@ -148,6 +150,54 @@ def store(directory, consumer, dxc, env): f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') +def store_3d1d(directory, consumer, dxc, env, form): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(V.program(form)) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(V.group(form), V.A.RSRC2)) + + volume = form != 'line' + mode = 'texture-volume' if volume else 'texture-line' + width, height, depth = 32, 8 if volume else 1, 6 if volume else 1 + plane_words = width * height * 4 + initial = [0xbf000000 | (z << 12) | i for z in range(depth) for i in range(plane_words)] + expected = initial.copy() + for y in range(V.group(form)[1]): + # The 3D view starts at W slice 1 and the shader writes relative z=1. + start = (2 * plane_words if volume else 0) + y * width * 4 + expected[start:start + 32] = V.VALUES * 8 + layout = '<%dI' % len(initial) + got, result = run(directory, consumer, env, mode, layout) + assert got == initial and len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1 + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + manifest = (cache / f'{key:016x}.txt').read_text().splitlines() + dim = '3d' if volume else '1d' + assert f'uav 0 tex{dim} float table 1 64 channels 4' in manifest, manifest + got, result = run(directory, consumer, env, mode, layout) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + assert got == expected, (form, sum(a != b for a, b in zip(got, expected, strict=True))) + clean(result) + + mismatch = initial[:32 * 8 * 4] if volume else [0xbf000000 | i for i in range(32 * 8 * 4)] + cases = [('texture-array-2d', mismatch, f'an output texture view or resource is not {dim.upper()}')] + if volume: + # Manual mutant: skipping the mip-relative W-range check must fail the required refusal. + cases.append(('texture-volume-bad-w', initial, 'an output 3D texture W range is outside the mip')) + else: + # Manual mutant: dropping the 1D mip check before `created` must fail this required refusal. + cases.append(('texture-line-bad-mip', initial, 'an output 1D texture mip is outside the resource')) + for bad_mode, untouched, reason in cases: + got, result = run(directory, consumer, env, bad_mode, '<%dI' % len(untouched)) + refusal = lines(result, 'Dispatch(2, 1, 1) refused:') + assert len(refusal) == 1 and refusal[0].endswith(reason), result.stderr[-3000:] + assert got == untouched and not lines(result, 'Dispatch(2, 1, 1) translated') + print(f'{form}: {len(expected)} mip-one words match; incompatible views refused with sentinels intact') + + # v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed # (not assembled by llvm-mc here; the translation below is checked to read it as written). XOR = 'v_xor_b32 v5, v5, v12' @@ -269,6 +319,8 @@ def main(consumer, dxc, adapter): env['X2W_TEST_DISPATCH_HARDWARE'] = '1' with tempfile.TemporaryDirectory() as temporary: store(Path(temporary) / 'store', consumer, dxc, env) + for form in V.FORMS: + store_3d1d(Path(temporary) / form, consumer, dxc, env, form) sample(Path(temporary) / 'sample', consumer, dxc, env) filtered(Path(temporary) / 'filtered', consumer, dxc, env) print(f'startup_compute_dispatch_texture: PASS on {adapter}') diff --git a/tests/startup_compute_image_store_check.py b/tests/startup_compute_image_store_check.py index 1623afee8e..d4831af416 100644 --- a/tests/startup_compute_image_store_check.py +++ b/tests/startup_compute_image_store_check.py @@ -150,17 +150,13 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:17]', 'v[14:15]').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0600', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8') + ' a16', '080f20f0080e0640', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0600', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) - # 1D, 3D and cube keep the same refusal with the address count their form would take. - for dim, address in (('SQ_RSRC_IMG_1D', 'v8'), ('SQ_RSRC_IMG_3D', 'v[8:10]'), - ('SQ_RSRC_IMG_CUBE', 'v[8:10]')): - refused('only 2D images', - lambda: pipe.cs.op_image_store(['v[14:17]', address, 's[24:31]'], ['dmask:0xf', 'dim:' + dim])) + refused('only 1D, 2D, 2D-array and 3D images', + lambda: pipe.cs.op_image_store(['v[14:17]', 'v[8:10]', 's[24:31]'], + ['dmask:0xf', 'dim:SQ_RSRC_IMG_CUBE'])) wait = encoded('s_waitcnt lgkmcnt(0)', '7fc08cbf') changed = encoded('s_mov_b32 s26, 0', '80039abe') diff --git a/tests/startup_compute_image_store_d16_check.py b/tests/startup_compute_image_store_d16_check.py index 9c7fd55160..310e26be39 100644 --- a/tests/startup_compute_image_store_d16_check.py +++ b/tests/startup_compute_image_store_d16_check.py @@ -89,8 +89,6 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:15]', 'v14').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0680', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8').replace(' d16', ' a16 d16'), '080f20f0080e06c0', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0680', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) diff --git a/tests/startup_gfx2hlsl_image_store_3d1d_check.py b/tests/startup_gfx2hlsl_image_store_3d1d_check.py new file mode 100644 index 0000000000..9d892e749a --- /dev/null +++ b/tests/startup_gfx2hlsl_image_store_3d1d_check.py @@ -0,0 +1,88 @@ +"""Check full compute image stores to 1D and 3D texture UAVs.""" +import argparse + +import startup_compute_image_store_check as A +from startup_gfx2hlsl_compute_check import G, assemble, refused, root_blob +from startup_pixel_image_store_check import WORDS as PIXEL_WORDS, translate as pixel_pipeline + + +FORMS = { + 'volume': ('3D', 'v[2:4]', 's[16:23]', '101f20f002080400', 'uint3(v2, v3, v4)'), + 'volume-nsa': ('3D', '[v2, v3, v5]', 's[16:23]', '121f20f00208040003050000', 'uint3(v2, v3, v5)'), + 'line': ('1D', 'v0', 's[8:15]', '001f20f000080200', 'uint(v0)'), +} +VALUES = A.ARRAY_VALUES +DATA = bytes.fromhex( + 'ff02107e0000403f' # v_mov_b32_e32 v8, 0x3f400000 + 'ff02127e0000803e' # v_mov_b32_e32 v9, 0x3e800000 + 'ff02147e00008140' # v_mov_b32_e32 v10, 0x40810000 + 'ff02167e010081bf' # v_mov_b32_e32 v11, 0xbf810001 +) + + +def group(form): + return (4, 1, 1) if form == 'line' else A.fixture.GROUP + + +def program(form, store=None): + # s[12:13] is the fixed table pointer. Compute the global X before the 1D descriptor overwrites s10. + prefix = bytes.fromhex('07038cbe80038dbe') # s_mov_b32 s12, s7; s_mov_b32 s13, 0 + if form == 'line': + address = bytes.fromhex( + '000046d70a040104' # v_lshl_add_u32 v0, s10, 2, v0 + '06020cf4400000fa' # s_load_dwordx8 s[8:15], s[12:13], 0x40 + ) + else: + address = bytes.fromhex( + '06040cf4400000fa' # s_load_dwordx8 s[16:23], s[12:13], 0x40 + '020046d70a040104' # v_lshl_add_u32 v2, s10, 2, v0 + '030046d70b020504' # v_lshl_add_u32 v3, s11, 1, v1 + ) + address += bytes.fromhex('81020a7e' if form == 'volume-nsa' else '8102087e') # z = 1 + instruction = bytes.fromhex(FORMS[form][3]) if store is None else store + return prefix + address + bytes.fromhex('7fc08cbf') + DATA + instruction + A.ARRAY_END + + +def pipeline(form, store=None): + return G.ComputePipeline(program(form, store), root_blob(3), A.RSRC2, group(form)) + + +def controls(llvm_mc): + ps = pixel_pipeline(PIXEL_WORDS).ps + for form, (dim, address, descriptor, words, index) in FORMS.items(): + dim_mod = f'dim:SQ_RSRC_IMG_{dim}' + asm = f'image_store v[8:11], {address}, {descriptor} dmask:0xf {dim_mod} unorm' + store = bytes.fromhex(words) + assert G.D.decode_instruction(store, 0)[2] == asm + if llvm_mc: + assert assemble(llvm_mc, asm + '\n') == store, asm + pipe = pipeline(form) + hlsl, manifest = pipe.hlsl_cs(), pipe.manifest() + # Manual mutants: dropping the third coordinate or mapping 1D to 2D must fail these assertions. + assert f'RWTexture{dim} w0 : register(u0);' in hlsl, hlsl + assert f'w0[{index}] = asfloat(uint4(v8, v9, v10, v11));' in hlsl, hlsl + assert f'uav 0 tex{dim.lower()} float table 1 64 channels 4' in manifest.splitlines(), manifest + mods = ['dmask:0xf', dim_mod, 'unorm'] + refused('only 2D images', lambda: ps.op_image_store(['v[8:11]', address, descriptor], mods)) + wrong_width = 'v[0:1]' + refused('with 2 address registers', lambda: pipe.cs.op_image_store(['v[8:11]', wrong_width, descriptor], mods)) + for d16 in (False, True): + partial = bytearray(store) + partial[1] = (partial[1] & 0xf0) | 0x3 + if d16: + partial[7] |= 0x80 + refused('typed UAV store writes all four channels', lambda: pipeline(form, bytes(partial))) + # d16 with the full mask takes the same packed-half path as 2D: two data VGPRs unpacked low half first. + # Manual mutant: dropping the f16tof32 unpack for these kinds must fail this assertion. + packed = bytearray(store) + packed[7] |= 0x80 + d16_hlsl = pipeline(form, bytes(packed)).hlsl_cs() + d16_store = f'w0[{index}] = float4(f16tof32(v8 & 0xffffu), f16tof32(v8 >> 16), f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16));' + assert d16_store in d16_hlsl, d16_hlsl + print('Compute 1D, 3D and 3D NSA stores, d16 full-mask stores, manifest and refusal checks passed') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + controls(parser.parse_args().llvm_mc) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index c100a274f7..7e2a84d506 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -449,9 +449,14 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin // handle, which keeps the first view; texture-store-self also creates a shader resource view of the texture at table byte 0. static int texture_slot67(void* device, const std::string& mode) { - constexpr UINT width = 32, height = 8; - const bool fp32 = mode == "texture-array" || mode == "texture-array-2d"; - const UINT layers = mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + constexpr UINT width = 32; + const bool volume = mode == "texture-volume" || mode == "texture-volume-bad-w"; + const bool line = mode == "texture-line" || mode == "texture-line-bad-mip"; + const UINT mip = volume || line ? 1 : 0; + const UINT height = line ? 1 : 8; + const bool fp32 = volume || line || mode == "texture-array" || mode == "texture-array-2d"; + const UINT layers = volume || mode == "texture-array" || mode == "texture-array-d16" ? 6 : 1; + const UINT subresources = volume ? 1 : layers; const UINT pitch = width * (fp32 ? 16 : 8), slice_bytes = pitch * height, bytes = slice_bytes * layers; const auto word = [](const void* value) { return reinterpret_cast(value); }; const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { @@ -459,7 +464,10 @@ static int texture_slot67(void* device, const std::string& mode) }; const DXGI_FORMAT format = fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; - const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, static_cast(layers), 1, format, + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + D3D12_RESOURCE_DIMENSION_TEXTURE2D; + const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width << mip, line ? 1 : height << mip, + static_cast(volume ? layers << mip : layers), static_cast(mip + 1), format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, mode == "texture-store-denied" ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, @@ -492,7 +500,14 @@ static int texture_slot67(void* device, const std::string& mode) const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); if (!cpu || !gpu) return 73; D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; - if (layers > 1) { + if (volume) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + // At mip 1 the depth is six. The bad count fits only if the binder uses the base mip's depth. + view.Texture3D = {mip, 1, mode == "texture-volume-bad-w" ? layers : ~0u}; + } else if (line) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + view.Texture1D.MipSlice = mode == "texture-line-bad-mip" ? mip + 1 : mip; // bad-mip: one past the last mip + } else if (layers > 1) { view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; view.Texture2DArray = {0, 1, 4, 0}; // four selected slices, with untouched neighbors on both sides } @@ -520,15 +535,15 @@ static int texture_slot67(void* device, const std::string& mode) if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); D3D12_TEXTURE_COPY_LOCATION image{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; D3D12_TEXTURE_COPY_LOCATION source{static_cast(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; + source.PlacedFootprint = {0, {format, width, height, volume ? layers : 1, pitch}}; D3D12_TEXTURE_COPY_LOCATION result = source; result.pResource = static_cast(readback); const UINT constants[3] = {1, 2, 3}; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; invoke(list, 32, 1, word(&heap)); - for (UINT layer = 0; layer < layers; ++layer) { - image.SubresourceIndex = layer; - source.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + image.SubresourceIndex = subresource + mip; + source.PlacedFootprint.Offset = UINT64{subresource} * slice_bytes; invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); } invoke(list, 25, word(slot67_pipeline)); @@ -536,9 +551,9 @@ static int texture_slot67(void* device, const std::string& mode) invoke(list, 39, 0, 3, word(constants), 0); invoke(list, 35, 1, gpu); if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); - for (UINT layer = 0; layer < layers; ++layer) { - image.SubresourceIndex = layer; - result.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + image.SubresourceIndex = subresource + mip; + result.PlacedFootprint.Offset = UINT64{subresource} * slice_bytes; invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); } if (FAILED(static_cast(invoke(list, 9)))) return 75; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 0d7630b52d..75dcbf4b46 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7738,10 +7738,10 @@ def fixed_table_image(self, operand, name): return self.descriptor(operand) def op_image_store(self, ops, mods): - """Write a 2D texel, or a full 2D-array texel. + """Write a texel to a 2D or 2D-array image, or to a 1D or 3D compute image. MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE via MIMG_Store): VDATA is the - source, VADDR the integer texel address (x, y for dim 2D, x, y, layer for dim 2D-array) and SRSRC + source, VADDR the integer texel address (x; x, y; x, y, z; or x, y, layer) and SRSRC the image descriptor; the channels selected by DMASK are written in order from consecutive VDATA registers. A full DMASK 0xf is a direct float4 assignment. A partial pixel-stage mask writes only those components (a swizzle store). It does not read the texel: a float4 read-modify-write would @@ -7767,9 +7767,20 @@ def op_image_store(self, ops, mods): masks = [m[6:] for m in mods if m.startswith('dmask:')] if len(dims) != 1 or len(masks) != 1: raise Unsupported('%s without exactly one dim and dmask' % name) - array = dims[0] == 'SQ_RSRC_IMG_2D_ARRAY' - if dims[0] not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_2D_ARRAY'): - raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) + shapes = { + 'SQ_RSRC_IMG_2D': ('tex2d', 2, 'x and y'), + 'SQ_RSRC_IMG_2D_ARRAY': ('tex2da', 3, 'x, y and layer'), + } + if self.kind == 'cs': + shapes.update({ + 'SQ_RSRC_IMG_1D': ('tex1d', 1, 'x'), + 'SQ_RSRC_IMG_3D': ('tex3d', 3, 'x, y and z'), + }) + if dims[0] not in shapes: + supported = '1D, 2D, 2D-array and 3D' if self.kind == 'cs' else '2D' + raise Unsupported('%s on %s: only %s images are lowered' % (name, dims[0], supported)) + kind, address, axes = shapes[dims[0]] + array = kind == 'tex2da' try: mask = int(masks[0], 0) except ValueError: @@ -7789,10 +7800,9 @@ def op_image_store(self, ops, mods): else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] - address = 3 if array else 2 if len(cs) != address: raise Unsupported('%s with %d address registers: %s expected' - % (name, len(cs), 'x, y and layer' if array else 'x and y')) + % (name, len(cs), axes)) words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] if self.kind == 'cs': if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): @@ -7800,8 +7810,9 @@ def op_image_store(self, ops, mods): key = self.fixed_table_image(ops[2], name) else: key = self.descriptor(ops[2]) - image = self.pipe.uav(key, 'tex2da' if array else 'tex2d') - index = 'uint%d(%s)' % (address, ', '.join(self.u(c) for c in cs)) + image = self.pipe.uav(key, kind) + index_type = 'uint' if address == 1 else 'uint%d' % address + index = '%s(%s)' % (index_type, ', '.join(self.u(c) for c in cs)) if d16: # RDNA 2 ISA ยง8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] @@ -10820,7 +10831,7 @@ def common(self): for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) + out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D', 'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'tex3d': 'RWTexture3D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: