From d378c2d3e5bdc38ad48256493293a74de8c278db Mon Sep 17 00:00:00 2001 From: Buhe <41640988+xiaoqi72665@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:52:04 +0800 Subject: [PATCH] runtime: bind startup FP32 compute array UAV views Refs #2742. Depends on the translator-only #2744; preserves upstream author and maintainer changes. AI-assisted; synthetic fixtures only. --- README.md | 1 + docs/experiments.md | 3 +- docs/experiments/startup-compute-array-uav.md | 33 ++++++ src/startup_stubs/d3d12_compute_dispatch.inl | 25 ++++- .../startup_compute_dispatch_array.cmake | 8 ++ tests/startup_compute_dispatch_array_check.py | 105 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 36 ++++-- 7 files changed, 198 insertions(+), 13 deletions(-) create mode 100644 docs/experiments/startup-compute-array-uav.md create mode 100644 tests/cmake/startup_compute_dispatch_array.cmake create mode 100644 tests/startup_compute_dispatch_array_check.py diff --git a/README.md b/README.md index d9cc29cde6..a24bec923b 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1013 image atomics | Lower [2D `R32_UINT` `image_atomic_add`, `umax` and `cmpswap`](docs/experiments.md#gfx1013-2d-image-atomics) with the gfx1030 lowering and compare every texel of a three-mip texture, including contended adds. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_atomics_'` | | gfx1013 image gathers | Lower [one 2D `image_gather4_l` with a constant sampler and a known integer LOD](docs/experiments.md#gfx1013-2d-explicit-lod-image-gathers) on an RGBA32 FLOAT view. Compare all four taps at three mips and on a view that starts at mip 1. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_gather4_l_'` | | Startup compute mip-zero gather | Dispatch a [gfx1013 `image_gather4_lz`](docs/experiments.md#compute-mip-zero-gather) and compare four texels from the first visible mip against a CPU reference. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_lz'` | +| Startup compute FP32 array image store | Bind a [2D-array UAV](docs/experiments/startup-compute-array-uav.md) through the startup runtime, verify the nonzero first slice and per-lane EXEC, and compare every texel after the fence. | `ctest --preset dev --no-tests=error -R '^startup_compute_dispatch_array_'` | | Startup compute D16 image store | Write [four packed half-floats](docs/experiments.md#startup-compute-d16-image-store) per active thread and check all three mips. | `ctest --preset dev --no-tests=error -R '^startup_compute_image_store_d16'` | | Startup explicit-LOD 2D gather | Dispatch and draw [gfx1013 `image_gather4_l`](docs/experiments.md#explicit-lod-2d-gather) across explicit mips, view offsets, clamped edges, and dynamic per-lane LOD against CPU references. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_l'` | | Startup compute buffer atomics | Dispatch [gfx1013 32-bit MUBUF raw buffer atomics](docs/experiments.md#startup-compute-raw-buffer-atomics) with thread contention, `glc` old-value returns, `cmpswap` order, and `EXEC` masking. | `ctest --preset dev --no-tests=error -R '^startup_compute_buffer_atomics'` | diff --git a/docs/experiments.md b/docs/experiments.md index 64b9d75ff9..7495165aa3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15174,7 +15174,8 @@ The startup compute translator accepts the full-mask FP32 image_store on dim:SQ_RSRC_IMG_2D_ARRAY with three full-width address VGPRs for x, y and layer. It emits an RWTexture2DArray store under the lane EXEC bit and records uav N tex2da float table P O channels 4 in the version 2 manifest. -The startup runtime still needs the array UAV binding in #2742. Pixel arrays, +The [startup runtime array UAV binding](experiments/startup-compute-array-uav.md) +consumes this manifest. Pixel arrays, packed D16 arrays and the 1D, 3D and cube store forms remain refused. The standalone GPU fixture writes the same four words into mip zero of layer 1 diff --git a/docs/experiments/startup-compute-array-uav.md b/docs/experiments/startup-compute-array-uav.md new file mode 100644 index 0000000000..6a52449004 --- /dev/null +++ b/docs/experiments/startup-compute-array-uav.md @@ -0,0 +1,33 @@ +# Startup compute FP32 array UAV binding + +Refs [#2742](https://github.com/R0Y00/Xbox2Windows/issues/2742). +Depends on the full-mask FP32 compute array image store lowering in +[#2744](https://github.com/R0Y00/Xbox2Windows/pull/2744). Pixel and packed-half +array stores remain refused. + +The production startup compute manifest consumer accepts +`uav N tex2da float table P O channels 4`. It requires an explicitly described +2D array UAV with a valid single-plane mip and slice range, retains the caller's +FirstArraySlice and ArraySize and refuses a plain 2D UAV before Dispatch. +The existing 2D and raw buffer paths are unchanged. Shader layer indices are +view-relative and are not clamped. + +The fixture publishes the encoded program through slot 67, translates it with +DXC, and binds a 32x8 RGBA32_FLOAT resource through slot 19. Its six physical +slices have distinct sentinels; the UAV selects four slices starting at +FirstArraySlice=1. Relative layers 1 and 3 write physical slices 2 and 4. +The actual translated dispatch goes through slot 14. After the fence, compare +all 6,144 words, including every adjacent and out-of-view slice. Full and +partial EXEC are checked for both layers. The wrong-layer and dropped-EXEC +controls must differ by 128 and 32 words respectively. A mismatched 2D view +must be refused with all 1,024 words untouched. + +Reproduce on Windows (source-built fixtures only): + +```powershell +cmake --build --preset dev --target startup_stream_consumer offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^startup_compute_dispatch_array_(warp|hardware)$' -V +``` + +No game input, retail program coverage, title execution or guest +out-of-bounds behavior is established. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 3024222bd0..3e3bc51b0b 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -2,7 +2,7 @@ // 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: raw buffers (`srv buf table ` // inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures -// (`srv tex2d table ` inputs, `uav tex2d float table channels 4` outputs) named +// (`srv tex2d table ` inputs, `uav tex2d/tex2da 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 @@ -23,6 +23,7 @@ struct ComputeTranslation { int word_param = -1, word_byte = 0; std::uint32_t at = 0, times = 0; Source source = root_constant; + bool array = false; }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable @@ -125,6 +126,11 @@ const char* load_compute_translation(ComputeTranslation& tr) 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()) { + tr.uavs.push_back({a, b, true}); + tr.uavs.back().array = true; + } 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}); // A static sampler, plain (smp) or with the descriptor's LOD clamp (smpl), decoded as the draw path does. @@ -136,7 +142,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 float texture" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D/2D-array 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"; } @@ -299,11 +305,20 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& 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)) reason = "an output texture view was not created on the desktop"; - else if (described ? desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc.Texture2D.PlaneSlice + else if (slot.array) { + // 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) + reason = "an output texture view is not a 2D array"; + else if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.SampleDesc.Count != 1 || + a.PlaneSlice || a.MipSlice >= resource.MipLevels || a.FirstArraySlice >= resource.DepthOrArraySize || + !a.ArraySize || a.ArraySize > resource.DepthOrArraySize - a.FirstArraySlice) + reason = "an output texture array view is outside the resource"; + } else if (described ? desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc.Texture2D.PlaneSlice : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) reason = "an output texture view is not 2D"; - else if (x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; - else if (!float_output_format(format)) reason = "an output texture format is not a float or normalized one"; + if (!reason && x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; + if (!reason && !float_output_format(format)) reason = "an output texture format is not a float or normalized one"; // One state per resource here: a texture read and written by the same call is refused. Two outputs // of one texture (two mips) share the unordered access state. for (std::size_t input = 0; input < inputs && !reason; ++input) diff --git a/tests/cmake/startup_compute_dispatch_array.cmake b/tests/cmake/startup_compute_dispatch_array.cmake new file mode 100644 index 0000000000..e601ef99d1 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_array.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_array_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_array_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_array_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_compute_dispatch_array_check.py b/tests/startup_compute_dispatch_array_check.py new file mode 100644 index 0000000000..37ae6e9b60 --- /dev/null +++ b/tests/startup_compute_dispatch_array_check.py @@ -0,0 +1,105 @@ +"""Startup FP32 array UAV binding through the production slot-67 / slot-14 path (#2742).""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_compute_image_store_check as A +import startup_compute_dispatch_texture_check as T +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a + +WIDTH, HEIGHT, LAYERS, FIRST = 32, 8, 6, 1 +WORDS = WIDTH * HEIGHT * 4 + + +def reference(layer=None, rows=2, layers=LAYERS): + result = [0xbf000000 | (z << 12) | i for z in range(layers) for i in range(WORDS)] + if layer is not None: + for y in range(rows): + for x in range(4 * A.fixture.GROUPS): + at = (FIRST + layer) * WORDS + (y * WIDTH + x) * 4 + result[at:at + 4] = A.ARRAY_VALUES + return result + + +def check(directory, consumer, dxc, adapter, layer, masked): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1") + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(T.C.root_blob(3, table_range=True)) + env["X2W_TEST_COMPUTE_ROOT"] = str(directory / "compute_root") + program = A.array_program(layer) + if masked: + assert program.count(A.ARRAY_STORE) == 1 + program = program.replace(A.ARRAY_STORE, A.MASK + A.ARRAY_STORE) + (directory / "program").write_bytes(program) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a(A.fixture.GROUP, A.RSRC2)) + layout = "<%dI" % (WORDS * LAYERS) + mode = "texture-array" + got, result = T.run(directory, consumer, env, mode, layout) + print(result.stdout, end="") + assert got == reference(), "untranslated dispatch wrote the texture" + assert len(T.lines(result, "Dispatch(2, 1, 1) refused: no translation")) == 1, result.stderr[-3000:] + key = int(T.lines(result, "x2w-draw compute request")[0].split()[3], 16) + T.translate(cache, dxc, key) + manifest = (cache / f"{key:016x}.txt").read_text() + assert "uav 0 tex2da float table 1 64 channels 4" in manifest.splitlines(), manifest + hlsl = cache / f"{key:016x}.cs.hlsl" + cso = cache / f"{key:016x}.cs.cso" + source = hlsl.read_text() + assert "RWTexture2DArray w0 : register(u0);" in source + expected = reference(layer, 1 if masked else 2) + got, result = T.run(directory, consumer, env, mode, layout) + assert len(T.lines(result, "Dispatch(2, 1, 1) translated")) == 1, result.stderr[-3000:] + debug = T.clean(result) + wrong = sum(a != b for a, b in zip(got, expected)) + assert wrong == 0, (layer, masked, wrong) + print(f"{adapter}: relative layer {layer}, physical layer {FIRST + layer}, partial EXEC={masked}: " + f"{len(got)} words, mismatches={wrong}; debug layer: {debug}", flush=True) + + # The actual runtime must refuse a plain 2D view of the same format before dispatch. + got, result = T.run(directory, consumer, env, "texture-array-2d", "<%dI" % WORDS) + assert got == reference(layers=1) + refusal = T.lines(result, "Dispatch(2, 1, 1) refused:") + assert len(refusal) == 1 and refusal[0].endswith("an output texture view is not a 2D array"), result.stderr[-3000:] + assert not T.lines(result, "Dispatch(2, 1, 1) translated") + print(f"{adapter}: incompatible 2D UAV refused; {len(got)} words unchanged", flush=True) + + # Negative controls run through the same production binding, not the offscreen shortcut. + guard = "if (exec & 1) " + A.ARRAY_LINE + if masked: + assert source.count(guard) == 1 + mutant = source.replace(guard, A.ARRAY_LINE) + label, count = "dropped EXEC", 32 + else: + index = "uint3(v8, v9, v10)" + assert source.count(index) == 1 + delta = "+ 1u" if layer == 1 else "- 1u" + mutant = source.replace(index, f"uint3(v8, v9, v10 {delta})") + label, count = "wrong layer", 128 + hlsl.write_text(mutant, encoding="ascii") + subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) + got, result = T.run(directory, consumer, env, mode, layout) + assert len(T.lines(result, "Dispatch(2, 1, 1) translated")) == 1, result.stderr[-3000:] + T.clean(result) + wrong = sum(a != b for a, b in zip(got, expected)) + assert wrong == count, (layer, label, wrong, count) + print(f"{adapter}: {label} control: {len(got)} words, mismatches={wrong} (expected {count})", flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temp: + for layer in (1, 3): + for masked in (False, True): + check(Path(temp) / f"layer-{layer}-{masked}", consumer, dxc, adapter, layer, masked) + print(f"startup_compute_dispatch_array: PASS on {adapter}") + + +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_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index ee78b1d5e0..34840c464b 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -401,13 +401,17 @@ 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, pitch = width * 8, bytes = pitch * height; + constexpr UINT width = 32, height = 8; + const bool fp32 = mode == "texture-array" || mode == "texture-array-2d"; + const UINT layers = mode == "texture-array" ? 6 : 1; + 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) { return make_committed(device, type, desc, state); }; - const DXGI_FORMAT format = 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, 1, 1, format, + 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, {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}, @@ -417,7 +421,13 @@ static int texture_slot67(void* device, const std::string& mode) void* const readback = make(D3D12_HEAP_TYPE_READBACK, buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST); void* memory = nullptr; if (!texture || !upload || !readback || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; - for (UINT i = 0; i < bytes / 2; ++i) static_cast(memory)[i] = static_cast(0x5000 + i); + if (fp32) { + for (UINT layer = 0; layer < layers; ++layer) + for (UINT i = 0; i < slice_bytes / 4; ++i) + static_cast(memory)[layer * slice_bytes / 4 + i] = 0xbf000000u | (layer << 12) | i; + } else { + for (UINT i = 0; i < bytes / 2; ++i) static_cast(memory)[i] = static_cast(0x5000 + i); + } invoke(upload, 9, 0, 0); const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; @@ -433,7 +443,11 @@ static int texture_slot67(void* device, const std::string& mode) FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); if (!cpu || !gpu) return 73; - const D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; + if (layers > 1) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray = {0, 1, 4, 0}; // four selected slices, with untouched neighbors on both sides + } if (mode != "texture-store-copied") invoke(device, 19, word(texture), 0, word(&view), cpu + 64); if (mode == "texture-store-copied") { // The view is created at another handle and its token copied into this slot by memcpy, as a title does; a @@ -464,13 +478,21 @@ static int texture_slot67(void* device, const std::string& mode) const UINT constants[3] = {1, 2, 3}; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; invoke(list, 32, 1, word(&heap)); - invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + for (UINT layer = 0; layer < layers; ++layer) { + image.SubresourceIndex = layer; + source.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + } invoke(list, 25, word(slot67_pipeline)); invoke(list, 33, word(slot67_root)); invoke(list, 39, 0, 3, word(constants), 0); invoke(list, 35, 1, gpu); if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); - invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); + for (UINT layer = 0; layer < layers; ++layer) { + image.SubresourceIndex = layer; + result.PlacedFootprint.Offset = UINT64{layer} * slice_bytes; + invoke(list, 16, word(&result), 0, 0, 0, word(&image), 0); + } if (FAILED(static_cast(invoke(list, 9)))) return 75; invoke(queue, 10, 1, word(&list)); if (FAILED(static_cast(invoke(queue, 14, word(fence), 1)))) return 76;