From 0192a5ed9904a952106e3e1b1f90a78eb9e4ae5f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 19:53:44 +0100 Subject: [PATCH 01/25] feat: record the compute root signature and descriptor tables (slots 33 and 35) Header-only state in list_compute_root.h with a Linux-testable check. Dispatch (slot 14) is not handled here; the state is exposed through ready() and table() for it. Refs #870. --- CMakeLists.txt | 6 +++ src/startup_stubs/d3d12_xs_device.cpp | 19 +++++++ src/startup_stubs/list_compute_root.h | 65 +++++++++++++++++++++++ tests/startup_compute_root.cpp | 75 +++++++++++++++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 src/startup_stubs/list_compute_root.h create mode 100644 tests/startup_compute_root.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e42aadcf71..efb59d3e26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -975,6 +975,12 @@ target_sources(offscreen_check PRIVATE tests/startup_cb_blend.cpp "${startup_cb_ # The same decoder without a device (#1149): each factor value in each of the four factor slots, # colour and alpha combine functions apart, refusal reasons, MIN / MAX per slot, the write mask and # control_word. The mutated run (destination alpha left in its colour form) is the negative control. +# Compute root state (command-list slots 33 and 35): signature, descriptor tables, clear on a different signature, +# range limit, closed list. Checked against real mutations of list_compute_root.h before submission. +add_executable(startup_compute_root tests/startup_compute_root.cpp) +target_include_directories(startup_compute_root PRIVATE src) +target_compile_features(startup_compute_root PRIVATE cxx_std_17) +add_test(NAME startup_compute_root COMMAND startup_compute_root) add_executable(startup_cb_blend_check tests/startup_cb_blend_check.cpp) target_include_directories(startup_cb_blend_check PRIVATE src) target_compile_features(startup_cb_blend_check PRIVATE cxx_std_17) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 8c96001c34..b87e39f3bb 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -15,6 +15,7 @@ #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" #include "startup_stubs/logical_view_table.h" +#include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" @@ -1678,6 +1679,7 @@ struct Pass { Wrapper* pipeline = nullptr; UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; + x2w_startup::ComputeRootState compute_root; // slots 33 and 35, read by a Dispatch handler u64 source_view_heap = 0; u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; @@ -1800,6 +1802,21 @@ void __stdcall list_graphics_root(Wrapper* self, void* root) log("x2w-render root signature %p with heap flags 0x%x not set on the desktop list (title heaps are not forwarded)", static_cast(w), pass.root_heap_flags); } +// List slot 33 (desktop 29 + 4), SetComputeRootSignature. Recorded only; nothing is forwarded to the desktop list yet. +void __stdcall list_compute_root_signature(Wrapper* self, void* root) +{ + Wrapper* w = as_wrapper(root); + pass_of(self).compute_root.set_signature(self->own().list_open, w ? root_info(w) : nullptr); +} +// List slot 35 (desktop 31 + 4), SetComputeRootDescriptorTable(parameter, gpu_handle). Recorded only. +void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + static LONG dropped; + if (pass_of(self).compute_root.set_table(self->own().list_open, parameter, gpu_handle) == x2w_startup::ComputeRootState::Result::out_of_range && + first_calls(dropped, 4)) + log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, + x2w_startup::ComputeRootState::max_parameters); +} DXGI_FORMAT view_format_of(u64 desktop_handle, ID3D12Resource* target) { DXGI_FORMAT format = target->GetDesc().Format; @@ -3428,6 +3445,8 @@ void build_tables() list_typed[25] = reinterpret_cast(&list_pipeline); list_typed[32] = reinterpret_cast(&list_set_descriptor_heaps); list_typed[34] = reinterpret_cast(&list_graphics_root); + list_typed[33] = reinterpret_cast(&list_compute_root_signature); + list_typed[35] = reinterpret_cast(&list_compute_table); list_typed[44] = reinterpret_cast(&list_root_srv); list_typed[42] = reinterpret_cast(&list_root_cbv); list_typed[50] = reinterpret_cast(&list_targets); diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h new file mode 100644 index 0000000000..4580ae9303 --- /dev/null +++ b/src/startup_stubs/list_compute_root.h @@ -0,0 +1,65 @@ +#pragma once + +// Compute root state of one command list: command-list slot 33 (desktop 29 + 4, SetComputeRootSignature) and +// slot 35 (desktop 31 + 4, SetComputeRootDescriptorTable). Both are seen in real logs next to Dispatch (slot 14). +// Only the state is recorded here and nothing is forwarded to the desktop list. A Dispatch handler reads it through +// ready() and table(): without a compute root signature set, the desktop list rejects the dispatch. +// +// The rules follow the graphics side (slot 34): setting the root signature that is already set keeps the descriptor +// tables, setting a different one (or none) leaves no table bound. A parameter index past the kept range is +// refused and counted, and a list that is not recording ignores both calls. + +#include + +namespace x2w_startup { + +class ComputeRootState { +public: + static constexpr unsigned max_parameters = 16; // same range as the graphics tables + + // What a call did, so the caller can log it and tests can check it. + enum class Result { recorded, ignored_closed, out_of_range }; + + // The root signature is identified by any stable pointer (the title wrapper's parameter list); null clears it. + Result set_signature(bool recording, const void* signature) + { + if (!recording) { + ++closed_ignored_; + return Result::ignored_closed; + } + if (signature != signature_) + for (auto& handle : tables_) handle = 0; + signature_ = signature; + return Result::recorded; + } + + // gpu_handle is the title's GPU descriptor handle of the table, kept as given (0 = nothing bound). + Result set_table(bool recording, unsigned parameter, std::uint64_t gpu_handle) + { + if (!recording) { + ++closed_ignored_; + return Result::ignored_closed; + } + if (parameter >= max_parameters) { + ++out_of_range_; + return Result::out_of_range; + } + tables_[parameter] = gpu_handle; + return Result::recorded; + } + + // Accessors for a Dispatch handler. + bool ready() const { return signature_ != nullptr; } + const void* signature() const { return signature_; } + std::uint64_t table(unsigned parameter) const { return parameter < max_parameters ? tables_[parameter] : 0; } + std::uint32_t out_of_range_count() const { return out_of_range_; } + std::uint32_t closed_ignored_count() const { return closed_ignored_; } + +private: + const void* signature_ = nullptr; + std::uint64_t tables_[max_parameters] = {}; + std::uint32_t out_of_range_ = 0; + std::uint32_t closed_ignored_ = 0; +}; + +} // namespace x2w_startup diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp new file mode 100644 index 0000000000..6cfb00cb85 --- /dev/null +++ b/tests/startup_compute_root.cpp @@ -0,0 +1,75 @@ +// Checks src/startup_stubs/list_compute_root.h without a device: the compute root signature and descriptor +// tables a command list records for a later Dispatch. +#include "startup_stubs/list_compute_root.h" + +#include +#include +#include + +namespace { +using x2w_startup::ComputeRootState; +int failures; + +void check(bool ok, const char* name) +{ + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +} // namespace + +int main() +{ + int root_a = 0, root_b = 0; + + { + ComputeRootState s; + check(!s.ready(), "a fresh list has no compute root"); + check(s.set_signature(true, &root_a) == ComputeRootState::Result::recorded && s.ready() && s.signature() == &root_a, "signature set"); + check(s.set_table(true, 2, 0x1000) == ComputeRootState::Result::recorded && s.table(2) == 0x1000, "table set"); + check(s.table(3) == 0, "an unset parameter has no table"); + } + { + ComputeRootState s; + s.set_signature(true, &root_a); + s.set_table(true, 0, 0x2000); + s.set_table(true, 5, 0x3000); + s.set_signature(true, &root_a); + check(s.table(0) == 0x2000 && s.table(5) == 0x3000, "the same signature keeps the tables"); + } + { + ComputeRootState s; + s.set_signature(true, &root_a); + s.set_table(true, 0, 0x2000); + s.set_table(true, 5, 0x3000); + s.set_signature(true, &root_b); + check(s.signature() == &root_b && s.table(0) == 0 && s.table(5) == 0, "a different signature leaves no table bound"); + s.set_signature(true, nullptr); + check(!s.ready(), "a null signature clears the compute root"); + } + { + ComputeRootState s; + s.set_signature(true, &root_a); + s.set_table(true, 1, 0x4000); + const auto at_limit = s.set_table(true, ComputeRootState::max_parameters - 1, 0x5000); + const auto past = s.set_table(true, ComputeRootState::max_parameters, 0x6000); + check(at_limit == ComputeRootState::Result::recorded && s.table(ComputeRootState::max_parameters - 1) == 0x5000, "the last parameter is kept"); + check(past == ComputeRootState::Result::out_of_range && s.out_of_range_count() == 1 && s.table(ComputeRootState::max_parameters) == 0, + "a parameter out of range is refused and counted"); + s.set_table(true, 1000, 1); + check(s.out_of_range_count() == 2 && s.table(1) == 0x4000, "a refused call leaves the other tables alone"); + } + { + ComputeRootState s; + const auto closed_sig = s.set_signature(false, &root_a); + check(closed_sig == ComputeRootState::Result::ignored_closed && !s.ready(), "a closed list ignores the signature"); + s.set_signature(true, &root_a); + const auto closed_table = s.set_table(false, 0, 0x7000); + check(closed_table == ComputeRootState::Result::ignored_closed && s.table(0) == 0, "a closed list ignores the table"); + check(s.closed_ignored_count() >= 1, "ignored calls are counted"); + } + std::printf("startup_compute_root: %s\n", failures ? "FAILED" : "ok"); + return failures ? 1 : 0; +} From 682b0e0de7c1d33fef54a3eec1df41a0fd35a095 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:40:20 +0100 Subject: [PATCH 02/25] feat: record compute descriptor tables (slot 35) and clear them on a root or heap change --- CMakeLists.txt | 6 ++ src/startup_stubs/d3d12_draw.inl | 32 +++++++++-- src/startup_stubs/d3d12_xs_device.cpp | 4 ++ src/startup_stubs/list_compute_root.h | 55 ++++++++++++++++++ tests/startup_compute_root.cpp | 82 +++++++++++++++++++++++++++ 5 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 src/startup_stubs/list_compute_root.h create mode 100644 tests/startup_compute_root.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c67aa831e3..c88e23cf0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1315,6 +1315,12 @@ add_executable(startup_logical_view_table_check tests/startup_logical_view_table target_include_directories(startup_logical_view_table_check PRIVATE src) target_compile_features(startup_logical_view_table_check PRIVATE cxx_std_17) add_test(NAME startup_logical_view_table COMMAND startup_logical_view_table_check) +# Compute descriptor tables (command-list slot 35, src/startup_stubs/list_compute_root.h): a table at a nonzero +# descriptor offset, a wrong handle, clear on a different signature or a view heap change, range limit. +add_executable(startup_compute_root tests/startup_compute_root.cpp) +target_include_directories(startup_compute_root PRIVATE src) +target_compile_features(startup_compute_root PRIVATE cxx_std_17) +add_test(NAME startup_compute_root COMMAND startup_compute_root) # Local switch, logging, and page-probe helpers (src/startup_stubs/local_log.h, #1149). add_executable(startup_local_log_check tests/startup_local_log_check.cpp) target_include_directories(startup_local_log_check PRIVATE src) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f12dd8038b..c715727a79 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1222,17 +1222,17 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* } auto& pass = pass_of(self); if (pass.source_view_heap != view_heap) + { for (auto& table : pass.view_tables) table = {}; + pass.compute_tables.clear(); + } pass.source_view_heap = view_heap; pass.title_samplers = source; } -// List slot 36 (desktop 32 + 4), SetGraphicsRootDescriptorTable(parameter, GPU handle): the table's -// address in the title's descriptor memory is kept for the draw. -void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) +// The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). +x2w_startup::ViewTable resolve_title_table(const Pass& pass, u64 gpu_handle) { - if (parameter >= 16) return; - auto& pass = pass_of(self); x2w_startup::ViewTable table; AcquireSRWLockShared(¬e_lock); for (const HeapInfo& heap : heap_infos()) { @@ -1243,7 +1243,27 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) if (table.address) break; } ReleaseSRWLockShared(¬e_lock); - pass.view_tables[parameter] = table; + return table; +} + +// List slot 36 (desktop 32 + 4), SetGraphicsRootDescriptorTable(parameter, GPU handle): the table's +// address in the title's descriptor memory is kept for the draw. +void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + if (parameter >= 16) return; + auto& pass = pass_of(self); + pass.view_tables[parameter] = resolve_title_table(pass, gpu_handle); +} +// List slot 35 (desktop 31 + 4), SetComputeRootDescriptorTable(parameter, GPU handle). Recorded only for a later +// Dispatch; slot 33 keeps the desktop compute root bind. +void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + static LONG dropped; + if (!self->own().list_open) return; + auto& pass = pass_of(self); + if (!pass.compute_tables.set_table(parameter, resolve_title_table(pass, gpu_handle)) && first_calls(dropped, 4)) + log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, + x2w_startup::ComputeTables::max_parameters); } // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 105d7b93f1..954c13f8bc 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -15,6 +15,7 @@ #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" #include "startup_stubs/logical_view_table.h" +#include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" @@ -1872,6 +1873,7 @@ struct Pass { Wrapper* pipeline = nullptr; UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; + x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; @@ -1979,6 +1981,7 @@ void __stdcall list_compute_root(Wrapper* self, void* root) Pass& pass = pass_of(self); const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; + pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound if (pass.compute_root) list->SetComputeRootSignature(pass.compute_root); } @@ -3793,6 +3796,7 @@ void build_tables() list_typed[42] = reinterpret_cast(&list_root_cbv); list_typed[50] = reinterpret_cast(&list_targets); list_typed[13] = reinterpret_cast(&list_draw_indexed); + list_typed[35] = reinterpret_cast(&list_compute_table); list_typed[36] = reinterpret_cast(&list_table); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h new file mode 100644 index 0000000000..6e5d89c469 --- /dev/null +++ b/src/startup_stubs/list_compute_root.h @@ -0,0 +1,55 @@ +#pragma once + +// Descriptor tables of the compute root of one command list: command-list slot 35 (desktop 31 + 4, +// SetComputeRootDescriptorTable). Slot 33 (SetComputeRootSignature) keeps its own desktop bind; it only tells this +// state which root signature is current. Tables are recorded for a later Dispatch handler and are not forwarded. +// +// The rules follow the graphics side (slots 34 and 36): setting the root signature that is already set keeps the +// tables, setting a different one (or none) leaves no table bound, and so does a change of the title's view heap. +// A parameter past the kept range is refused and counted. + +#include + +#include "startup_stubs/logical_view_table.h" + +namespace x2w_startup { + +class ComputeTables { +public: + static constexpr unsigned max_parameters = 16; // same range as the graphics tables + + // The root signature is identified by any stable pointer (the title wrapper's parameter list); null clears it. + void set_signature(const void* signature) + { + if (signature != signature_) clear(); + signature_ = signature; + } + + // Slot 32 with another view heap: the recorded addresses belong to the old one. + void clear() + { + for (auto& table : tables_) table = {}; + } + + // False when the parameter is out of range (counted). + bool set_table(unsigned parameter, const ViewTable& table) + { + if (parameter >= max_parameters) { + ++out_of_range_; + return false; + } + tables_[parameter] = table; + return true; + } + + const void* signature() const { return signature_; } + ViewTable table(unsigned parameter) const { return parameter < max_parameters ? tables_[parameter] : ViewTable{}; } + std::uint32_t out_of_range_count() const { return out_of_range_; } + +private: + const void* signature_ = nullptr; + ViewTable tables_[max_parameters] = {}; + std::uint32_t out_of_range_ = 0; +}; + +} // namespace x2w_startup diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp new file mode 100644 index 0000000000..b31cd9bcce --- /dev/null +++ b/tests/startup_compute_root.cpp @@ -0,0 +1,82 @@ +// Checks src/startup_stubs/list_compute_root.h without a device: the descriptor tables slot 35 records for a +// compute Dispatch, resolved against a title view heap the way the graphics tables are (slot 36). +#include "startup_stubs/list_compute_root.h" + +#include +#include + +namespace { +using x2w_startup::ComputeTables; +using x2w_startup::ViewTable; +using x2w_startup::resolve_view_table; +int failures; + +void check(bool ok, const char* name) +{ + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +// A title heap of 8 descriptors of 32 bytes: GPU base 0x10000, CPU base 0x7000. +constexpr std::uint64_t gpu_base = 0x10000, cpu_base = 0x7000; +constexpr unsigned count = 8, stride = 32; +ViewTable at(unsigned descriptor) { return resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + std::uint64_t{descriptor} * stride); } +} // namespace + +int main() +{ + int root_a = 0, root_b = 0; + + { + // A UAV table at a nonzero descriptor offset resolves to that offset, not to the heap start. + ComputeTables s; + s.set_signature(&root_a); + check(s.set_table(2, at(3)), "table set"); + check(s.table(2).address == cpu_base + 3 * stride && s.table(2).bytes == 5 * stride, "slot 35 keeps the offset table"); + check(s.table(2).address != at(0).address, "a nonzero offset is not the default table"); + check(s.table(3).address == 0, "an unset parameter has no table"); + } + { + // A handle that is not in the heap resolves to nothing: the wrong binding is not turned into a default. + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + count * stride).address == 0, "past the heap"); + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + 5).address == 0, "inside a descriptor"); + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base - stride).address == 0, "before the heap"); + ComputeTables s; + s.set_signature(&root_a); + s.set_table(0, at(1)); + s.set_table(0, resolve_view_table(gpu_base, cpu_base, count, stride, 0xdead0000)); + check(s.table(0).address == 0, "a wrong handle replaces the earlier binding with nothing"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(0, at(1)); + s.set_table(5, at(4)); + s.set_signature(&root_a); + check(s.table(0).address == cpu_base + stride && s.table(5).address == cpu_base + 4 * stride, "the same signature keeps the tables"); + s.set_signature(&root_b); + check(s.signature() == &root_b && s.table(0).address == 0 && s.table(5).address == 0, "a different signature clears the tables"); + s.set_table(1, at(2)); + s.set_signature(nullptr); + check(s.signature() == nullptr && s.table(1).address == 0, "a null signature clears the tables"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(7, at(6)); + s.clear(); + check(s.table(7).address == 0 && s.signature() == &root_a, "a view heap change clears the tables and keeps the signature"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(1, at(1)); + check(s.set_table(ComputeTables::max_parameters - 1, at(2)) && s.table(ComputeTables::max_parameters - 1).address, "the last parameter is kept"); + check(!s.set_table(ComputeTables::max_parameters, at(3)) && s.out_of_range_count() == 1, "a parameter out of range is refused and counted"); + check(s.table(ComputeTables::max_parameters).address == 0 && s.table(1).address == cpu_base + stride, "a refused call leaves the other tables alone"); + } + std::printf("startup_compute_root: %s\n", failures ? "FAILED" : "ok"); + return failures ? 1 : 0; +} From 033f40cdf7446ea1f26a4673910b4545fef6d90d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 23:10:47 +0100 Subject: [PATCH 03/25] startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. --- CMakeLists.txt | 4 ++ src/startup_stubs/d3d12_draw.inl | 30 +++++++++++---- src/startup_stubs/d3d12_xs_device.cpp | 12 +++++- src/startup_stubs/root_constant_store.h | 50 ++++++++++++++++++++++++ tests/startup_root_constant_store.cpp | 51 +++++++++++++++++++++++++ 5 files changed, 138 insertions(+), 9 deletions(-) create mode 100644 src/startup_stubs/root_constant_store.h create mode 100644 tests/startup_root_constant_store.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d301b2b72..aa6f5861b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -731,6 +731,10 @@ endforeach() add_executable(startup_command_list_slot_names tests/startup_command_list_slot_names.cpp) target_compile_features(startup_command_list_slot_names PRIVATE cxx_std_17) add_test(NAME startup_command_list_slot_names COMMAND startup_command_list_slot_names) +# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, list slots 37, 39 and 40, #870). +add_executable(startup_root_constant_store tests/startup_root_constant_store.cpp) +target_compile_features(startup_root_constant_store PRIVATE cxx_std_17) +add_test(NAME startup_root_constant_store COMMAND startup_root_constant_store) # Game-save stand-in storage (src/startup_stubs/save_store.h): a blob written by one process is read by a second. add_executable(startup_gamesave_persist tests/startup_gamesave_persist.cpp) target_compile_features(startup_gamesave_persist PRIVATE cxx_std_17) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f16c0110e1..309edbe992 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1402,7 +1402,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI values[i] = ud.kind == Translation::rect ? (rect ? 1u : 0u) : ud.kind == Translation::base_vertex ? static_cast((indexed ? base_vertex : static_cast(start)) - vertex_first) : ud.kind == Translation::start_instance ? start_instance - : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) + : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants.words[ud.a][ud.b] : 0) : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] : 0; } @@ -1518,15 +1518,31 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) ReleaseSRWLockShared(¬e_lock); pass.view_tables[parameter] = table; } +// Keeps the words of a root constants call; a call outside the 16 x 8 words kept is logged and cut or dropped. +static void store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, + const std::uint32_t* data, UINT offset) +{ + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; + const auto result = store.set(parameter, count, data, offset); + static LONG refused; + if (result != x2w_root_constants::Result::stored && first_calls(refused, 4)) + log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", kind, + result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count); +} // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) { - static LONG dropped; - if (count && (parameter >= 16 || offset >= 8 || count > 8 - offset) && first_calls(dropped, 4)) - log("x2w-render root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", - parameter >= 16 || offset >= 8 ? "dropped" : "truncated", parameter, offset, count); - if (parameter >= 16 || offset >= 8 || !count || !x2w_local::readable(data, std::size_t{count} * 4)) return; - for (UINT i = 0; i < count && offset + i < 8; ++i) pass_of(self).constants[parameter][offset + i] = data[i]; + store_root_constants(pass_of(self).constants, "graphics", parameter, count, data, offset); +} +// List slot 37 (desktop 33 + 4), SetComputeRoot32BitConstant(parameter, value, offset). +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, 1, &value, offset); +} +// List slot 39 (desktop 35 + 4), SetComputeRoot32BitConstants(parameter, count, data, offset). +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, count, data, offset); } // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0450fd8b4c..9dc1bc8beb 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -42,6 +42,7 @@ #include "console_plane_size.h" #include "descriptor_heap_type.h" #include "null_binding_cause.h" +#include "root_constant_store.h" #include "null_texture_view.h" #include "packed_target_format.h" #include "present_view_format.h" @@ -1882,7 +1883,9 @@ struct Pass { x2w_startup::ViewTable view_tables[16]{}; u64 source_view_heap = 0; u64 root_address[16] = {}; // title address of each root descriptor - std::uint32_t constants[16][8] = {}; + x2w_root_constants::Store constants; // graphics root constants (slot 40) + x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; D3D12_INDEX_BUFFER_VIEW ib = {}; @@ -1994,6 +1997,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); + // A different root signature invalidates the title's cached compute root arguments. + if (pass.compute_root_wrapper != w) pass.compute_constants.clear(); + pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; if (pass.compute_root) list->SetComputeRootSignature(pass.compute_root); @@ -2267,7 +2273,7 @@ void __stdcall list_graphics_root(Wrapper* self, void* root) if (pass.root != params) { for (auto& table : pass.view_tables) table = {}; std::fill_n(pass.root_address, 16, 0); - std::memset(pass.constants, 0, sizeof(pass.constants)); + pass.constants.clear(); } pass.root = params; pass.srv_bound = 0; @@ -4001,6 +4007,8 @@ void build_tables() list_typed[50] = reinterpret_cast(&list_targets); list_typed[13] = reinterpret_cast(&list_draw_indexed); list_typed[36] = reinterpret_cast(&list_table); + list_typed[37] = reinterpret_cast(&list_compute_constant); + list_typed[39] = reinterpret_cast(&list_compute_constants); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h new file mode 100644 index 0000000000..7059b1a378 --- /dev/null +++ b/src/startup_stubs/root_constant_store.h @@ -0,0 +1,50 @@ +// Experimental (docs/startup-runtime.md, #870): the 32-bit root arguments a recorded command list keeps for +// translated draws and dispatches. Plain standard C++ with no Windows types, so it can be tested on its own. +// +// A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one +// that runs past them is cut off at the end of the parameter, so the caller can log either case. +#pragma once + +#include +#include + +namespace x2w_root_constants { + +inline constexpr unsigned parameter_count = 16; +inline constexpr unsigned words_per_parameter = 8; + +enum class Result { stored, truncated, dropped }; + +struct Store { + std::uint32_t words[parameter_count][words_per_parameter] = {}; + + void clear() noexcept + { + for (auto& row : words) + for (auto& word : row) word = 0; + } + + // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. + Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset) noexcept + { + if (!count || !data || parameter >= parameter_count || offset >= words_per_parameter) return Result::dropped; + const bool cut = count > words_per_parameter - offset; + const unsigned n = cut ? words_per_parameter - offset : count; + for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; + return cut ? Result::truncated : Result::stored; + } + + // SetXxxRoot32BitConstant(parameter, value, offset). + Result set_one(unsigned parameter, std::uint32_t value, unsigned offset) noexcept { return set(parameter, 1, &value, offset); } + + // The word a shader reads; 0 outside the kept range. + std::uint32_t word(int parameter, int offset) const noexcept + { + return parameter >= 0 && parameter < static_cast(parameter_count) && offset >= 0 && + offset < static_cast(words_per_parameter) + ? words[parameter][offset] + : 0; + } +}; + +} // namespace x2w_root_constants diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp new file mode 100644 index 0000000000..30dad50fc1 --- /dev/null +++ b/tests/startup_root_constant_store.cpp @@ -0,0 +1,51 @@ +// Experimental (docs/startup-runtime.md, #870): the root constants a command list keeps for compute +// (list slots 37 and 39) and graphics (slot 40). Plain standard C++; synthetic values, no title data. +#include "../src/startup_stubs/root_constant_store.h" + +#include +#include + +namespace { +using x2w_root_constants::Result; +using x2w_root_constants::Store; +int failures; + +void expect(bool ok, const std::string& what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; + } +} +} // namespace + +int main() +{ + Store store; + const std::uint32_t data[4] = {11, 22, 33, 44}; + + expect(store.set(3, 4, data, 2) == Result::stored, "four words at offset 2 are stored"); + expect(store.word(3, 2) == 11 && store.word(3, 5) == 44, "stored words read back at their offsets"); + expect(store.word(3, 1) == 0 && store.word(3, 6) == 0, "neighbouring words stay zero"); + + expect(store.set_one(5, 77, 7) == Result::stored, "a single word at the last offset is stored"); + expect(store.word(5, 7) == 77, "the single word reads back"); + + expect(store.set(6, 4, data, 6) == Result::truncated, "a write past the end of the parameter is cut off"); + expect(store.word(6, 6) == 11 && store.word(6, 7) == 22, "the words that fit are kept"); + expect(store.word(7, 0) == 0, "a cut-off write does not spill into the next parameter"); + + expect(store.set(16, 1, data, 0) == Result::dropped, "parameter 16 is refused"); + expect(store.set(0, 1, data, 8) == Result::dropped, "offset 8 is refused"); + expect(store.set(0, 0, data, 0) == Result::dropped, "an empty write is refused"); + expect(store.set(0, 1, nullptr, 0) == Result::dropped, "a null source is refused"); + expect(store.set_one(15, 5, 0) == Result::stored && store.word(15, 0) == 5, "parameter 15 is the last one kept"); + expect(store.word(16, 0) == 0 && store.word(-1, 0) == 0 && store.word(0, 8) == 0, "reads outside the range give 0"); + + store.clear(); + expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); + + if (failures) return 1; + std::puts("root constant store ok"); + return 0; +} From d8cc1ac18e7a44d8b1a31a23339bbcdc841683ae Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 23:11:05 +0100 Subject: [PATCH 04/25] feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. --- CMakeLists.txt | 9 ++++ src/startup_stubs/d3d12_xs_device.cpp | 22 +++++++++ src/startup_stubs/list_dispatch.h | 47 ++++++++++++++++++ tests/startup_list_dispatch_check.cpp | 71 +++++++++++++++++++++++++++ 4 files changed, 149 insertions(+) create mode 100644 src/startup_stubs/list_dispatch.h create mode 100644 tests/startup_list_dispatch_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3dd1df9c96..5defec9823 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1377,6 +1377,15 @@ foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) set_tests_properties(startup_heap_indexed_root_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Slot 14 (Dispatch) forward-or-refuse decision (src/startup_stubs/list_dispatch.h), without a device. +add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp) +target_include_directories(startup_list_dispatch_check PRIVATE src) +target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) +add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) +foreach(mutation IN ITEMS no-limit no-state) + add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) + set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) # The storage root handed to the executable ends in a separator and is never cut off diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 44561dbb94..2bc95b6c0a 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/heap_indexed_root.h" +#include "startup_stubs/list_dispatch.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" #include "startup_stubs/address_texture.h" @@ -2658,6 +2659,26 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) } pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } +// List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + x2w_startup::ListDispatch request; + request.list_open = list != nullptr; + if (list) request.type = list->GetType(); + const Pass& pass = pass_of(self); + request.compute_pipeline = pass.compute_pipeline; + request.compute_root = pass.compute_root; + request.x = x, request.y = y, request.z = z; + const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); + if (decision != x2w_startup::DispatchDecision::forward) { + static LONG refusals; + if (first_calls(refusals, 16)) + log("x2w-render Dispatch(%u, %u, %u) refused: %s", x, y, z, x2w_startup::dispatch_reason(decision)); + return; + } + list->Dispatch(x, y, z); +} extern LONG translated_draws, untranslated_draws, frame_number; bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); // List slot 12, DrawInstanced. @@ -4100,6 +4121,7 @@ void build_tables() list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[14] = reinterpret_cast(&list_dispatch); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); list_typed[22] = reinterpret_cast(&list_scissors); diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h new file mode 100644 index 0000000000..093de094d2 --- /dev/null +++ b/src/startup_stubs/list_dispatch.h @@ -0,0 +1,47 @@ +#pragma once + +// Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, and every group count +// is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. + +#include + +namespace x2w_startup { + +constexpr UINT max_dispatch_groups = 65535; + +struct ListDispatch { + bool list_open = false; + D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; + bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline + bool compute_root = false; // the bound compute root signature is a desktop root signature + UINT x = 0, y = 0, z = 0; +}; + +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, group_count_over_limit }; +constexpr int dispatch_decision_count = 5; + +inline const char* dispatch_reason(DispatchDecision decision) +{ + switch (decision) { + case DispatchDecision::forward: return "forward"; + case DispatchDecision::list_closed: return "list is closed"; + case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; + case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::group_count_over_limit: return "group count is over 65535"; + } + return "unknown"; +} + +inline DispatchDecision decide_dispatch(const ListDispatch& d) +{ + if (!d.list_open) return DispatchDecision::list_closed; + if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) + return DispatchDecision::wrong_list_type; + if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) + return DispatchDecision::group_count_over_limit; + return DispatchDecision::forward; +} + +} // namespace x2w_startup diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp new file mode 100644 index 0000000000..79ecc298d8 --- /dev/null +++ b/tests/startup_list_dispatch_check.cpp @@ -0,0 +1,71 @@ +// Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the +// desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. +// +// startup_list_dispatch_check [--mutate no-limit|no-state] +// +// The mutations change the expectations to those of a wrong decision (no group-count limit, or a forward without a +// compute pipeline and root); each must make the check fail. +#include "startup_stubs/list_dispatch.h" + +#include +#include + +namespace { +using namespace x2w_startup; +using D = DispatchDecision; +int failures, cases; +bool no_limit, no_state; + +void expect(const char* label, const ListDispatch& in, D expected) +{ + ++cases; + const D got = decide_dispatch(in); + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, dispatch_reason(expected), dispatch_reason(got)); +} + +ListDispatch ready(UINT x, UINT y, UINT z) +{ + ListDispatch d; + d.list_open = true; + d.compute_pipeline = d.compute_root = true; + d.x = x, d.y = y, d.z = z; + return d; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + no_limit = !std::strcmp(argv[2], "no-limit"); + no_state = !std::strcmp(argv[2], "no-state"); + if (!no_limit && !no_state) return 2; + } + expect("one group", ready(1, 1, 1), D::forward); + expect("limit on every axis", ready(65535, 65535, 65535), D::forward); + expect("zero groups", ready(0, 5, 5), D::forward); + expect("x over limit", ready(65536, 1, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("y over limit", ready(1, 65536, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("z over limit", ready(1, 1, 0xffffffffu), no_limit ? D::forward : D::group_count_over_limit); + ListDispatch d = ready(8, 1, 1); + d.compute_pipeline = false; + expect("graphics pipeline bound", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root = false; + expect("no compute root", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.list_open = false; + expect("closed list", d, D::list_closed); + d = ready(8, 1, 1); + d.type = D3D12_COMMAND_LIST_TYPE_COPY; + expect("copy list", d, D::wrong_list_type); + d.type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + expect("compute list", d, D::forward); + if (failures) { + std::printf("%d of %d cases failed\n", failures, cases); + return 1; + } + std::printf("%d cases passed\n", cases); + return 0; +} From 48635ddc3e04fac05bb29a4e3d55c751be82dfae Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 02:15:24 +0100 Subject: [PATCH 05/25] startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 --- CMakeLists.txt | 2 +- docs/experiments.md | 11 +++++++++++ src/startup_stubs/d3d12_xs_device.cpp | 9 ++++++++- src/startup_stubs/list_dispatch.h | 13 +++++++++---- tests/startup_list_dispatch_check.cpp | 16 +++++++++++----- 5 files changed, 40 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5defec9823..0dc60bd539 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1382,7 +1382,7 @@ add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp target_include_directories(startup_list_dispatch_check PRIVATE src) target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) -foreach(mutation IN ITEMS no-limit no-state) +foreach(mutation IN ITEMS no-limit no-state no-root-args) add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/docs/experiments.md b/docs/experiments.md index 3d9a4194f7..d3cb57c2ba 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13079,3 +13079,14 @@ ctest --preset dev --no-tests=error -R '^(cpu_aot_switch_sal|cpu_aot_switch_shif The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequences (because ML64 assembles the `sal` mnemonic as `/4` `SHL`) across 24 translated functions covering all 12 `SAL` `Code` encodings (`SAL_RM{8,16,32,64}_{1,CL,IMM8}`), register and memory destinations, count-`1` all-16 `SETcc` checks, count->1 10-condition `SETcc` checks, `Jcc`, `CMOVcc`, narrow returns, and nonvolatile/stack-frame operands, plus 11 negative exports. [The differential check](../tests/cpu/switch_sal_check.py) verifies 28,024 `dev` and 28,024 `/O2` comparisons against native execution and the Python reference, four `/O2` mutated-C++ controls (`shift_dir`, `cf_mask`, `of_mask`, `cl_mask`), 11 MASM, 4 unit, and 7 PE-patched rejection controls, and records decoded mnemonics via `iced_x86.Mnemonic` to `FORM_COVERAGE_RECORD`. Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. + +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no parameters or static samplers, and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A compute root with parameters is refused with `compute root arguments are not forwarded`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. + +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its three mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 2bc95b6c0a..3c7bdc751a 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -126,6 +126,7 @@ struct alignas(16) WrapperOwn { bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) Wrapper* list_device; // CommandList: wrapper that created this list. @@ -1687,8 +1688,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (SUCCEEDED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc) { heap_flags = static_cast(desc->Desc_1_1.Flags) & x2w_startup::root_flags_heap_indexed; w->own().root_without_bindings = !heap_flags && !desc->Desc_1_1.NumParameters && !desc->Desc_1_1.NumStaticSamplers; + w->own().root_srv_only = !heap_flags && !desc->Desc_1_1.NumStaticSamplers && desc->Desc_1_1.NumParameters; for (UINT i = 0; i < desc->Desc_1_1.NumParameters; ++i) { const auto& parameter = desc->Desc_1_1.pParameters[i]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) w->own().root_srv_only = false; RootParameter info{parameter.ParameterType, 0, 0}; if (parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) { @@ -1956,6 +1959,7 @@ struct Pass { bool compute_pipeline = false; ID3D12RootSignature* compute_root = nullptr; // desktop compute root set by slot 33 const std::vector* compute_params = nullptr; + bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; @@ -2089,6 +2093,8 @@ void __stdcall list_compute_root(Wrapper* self, void* root) const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_params = real ? root_info(w) : nullptr; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) list->SetComputeRootSignature(pass.compute_root); } @@ -2668,7 +2674,8 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) if (list) request.type = list->GetType(); const Pass& pass = pass_of(self); request.compute_pipeline = pass.compute_pipeline; - request.compute_root = pass.compute_root; + request.compute_root = pass.compute_root != nullptr; + request.compute_root_has_arguments = pass.compute_root_has_arguments; request.x = x, request.y = y, request.z = z; const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); if (decision != x2w_startup::DispatchDecision::forward) { diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h index 093de094d2..b2fb73a64b 100644 --- a/src/startup_stubs/list_dispatch.h +++ b/src/startup_stubs/list_dispatch.h @@ -1,8 +1,9 @@ #pragma once // Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, -// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, and every group count -// is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares +// no parameters (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs +// arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. #include @@ -15,11 +16,13 @@ struct ListDispatch { D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline bool compute_root = false; // the bound compute root signature is a desktop root signature + bool compute_root_has_arguments = false; // that root declares parameters or static samplers UINT x = 0, y = 0, z = 0; }; -enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, group_count_over_limit }; -constexpr int dispatch_decision_count = 5; +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, + group_count_over_limit }; +constexpr int dispatch_decision_count = 6; inline const char* dispatch_reason(DispatchDecision decision) { @@ -28,6 +31,7 @@ inline const char* dispatch_reason(DispatchDecision decision) case DispatchDecision::list_closed: return "list is closed"; case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; case DispatchDecision::group_count_over_limit: return "group count is over 65535"; } return "unknown"; @@ -39,6 +43,7 @@ inline DispatchDecision decide_dispatch(const ListDispatch& d) if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return DispatchDecision::wrong_list_type; if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) return DispatchDecision::group_count_over_limit; return DispatchDecision::forward; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp index 79ecc298d8..ab83b5cc20 100644 --- a/tests/startup_list_dispatch_check.cpp +++ b/tests/startup_list_dispatch_check.cpp @@ -1,10 +1,10 @@ // Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the // desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. // -// startup_list_dispatch_check [--mutate no-limit|no-state] +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args] // -// The mutations change the expectations to those of a wrong decision (no group-count limit, or a forward without a -// compute pipeline and root); each must make the check fail. +// The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a +// compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. #include "startup_stubs/list_dispatch.h" #include @@ -14,7 +14,7 @@ namespace { using namespace x2w_startup; using D = DispatchDecision; int failures, cases; -bool no_limit, no_state; +bool no_limit, no_state, no_root_args; void expect(const char* label, const ListDispatch& in, D expected) { @@ -40,7 +40,8 @@ int main(int argc, char** argv) if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { no_limit = !std::strcmp(argv[2], "no-limit"); no_state = !std::strcmp(argv[2], "no-state"); - if (!no_limit && !no_state) return 2; + no_root_args = !std::strcmp(argv[2], "no-root-args"); + if (!no_limit && !no_state && !no_root_args) return 2; } expect("one group", ready(1, 1, 1), D::forward); expect("limit on every axis", ready(65535, 65535, 65535), D::forward); @@ -55,6 +56,11 @@ int main(int argc, char** argv) d.compute_root = false; expect("no compute root", d, no_state ? D::forward : D::no_compute_state); d = ready(8, 1, 1); + d.compute_root_has_arguments = true; // e.g. a root UAV set through slot 45, which is not forwarded + expect("root with arguments", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d.x = 0; + expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d = ready(8, 1, 1); d.list_open = false; expect("closed list", d, D::list_closed); d = ready(8, 1, 1); From 7307c2f16381ef5031ff0b5718204426931792a3 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 07:20:02 +0100 Subject: [PATCH 06/25] startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. --- CMakeLists.txt | 2 +- docs/experiments.md | 4 ++-- src/startup_stubs/d3d12_xs_device.cpp | 23 ++++++++++++++++++++--- src/startup_stubs/list_dispatch.h | 12 +++++++++--- tests/startup_list_dispatch_check.cpp | 19 ++++++++++++++++--- 5 files changed, 48 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0dc60bd539..5e54698a36 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1382,7 +1382,7 @@ add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp target_include_directories(startup_list_dispatch_check PRIVATE src) target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) -foreach(mutation IN ITEMS no-limit no-state no-root-args) +foreach(mutation IN ITEMS no-limit no-state no-root-args no-pairing no-bound) add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/docs/experiments.md b/docs/experiments.md index d3cb57c2ba..c0c907586e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13082,9 +13082,9 @@ Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and ## Startup list Dispatch -Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no parameters or static samplers, and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A compute root with parameters is refused with `compute root arguments are not forwarded`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. -Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its three mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its five mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. ```powershell cmake --build --preset dev --target startup_list_dispatch_check diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 3c7bdc751a..3cc5c126d0 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -126,6 +126,7 @@ struct alignas(16) WrapperOwn { bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) @@ -1774,7 +1775,7 @@ std::size_t desktop_stream_size(UINT type) // Converts a console pipeline stream to desktop form and creates the pipeline. The subobject type // numbers and sizes are the desktop ones; only the pointers and formats inside need converting. ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, char* why, std::size_t why_size, - bool& compute, IndirectGraphicsPipeline& graphics) + bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root) { const std::size_t bytes = desc->SizeInBytes; if (bytes < 16 || bytes > 0x2000 || (bytes & 7) || !x2w_local::readable(desc->pPipelineStateSubobjectStream, bytes)) { @@ -1888,6 +1889,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES } check_device("Device CreatePipelineState", 86); } + if (pipeline && compute && root && root->own().kind == root_signature_kind) + pipeline_root = static_cast(root->own().real); if (pipeline && (vertex || mesh) && pixel) graphics = {static_cast(root->own().real), targets.RTFormats[0], mesh}; return pipeline; @@ -1957,6 +1960,8 @@ std::size_t readable_window(u64 address, std::size_t wanted) struct Pass { bool pipeline_real = false; // the bound pipeline has a desktop pipeline bool compute_pipeline = false; + ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against + UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 ID3D12RootSignature* compute_root = nullptr; // desktop compute root set by slot 33 const std::vector* compute_params = nullptr; bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers @@ -2079,6 +2084,7 @@ void __stdcall list_pipeline(Wrapper* self, void* pipeline) // a recognized desktop graphics pipeline just before it records the draw. pass.pipeline_real = available && !pass.indirect_graphics.root; pass.compute_pipeline = pass.pipeline_real && w->own().compute_pipeline; + pass.compute_pipeline_root = pass.compute_pipeline ? w->own().pipeline_root : nullptr; pass.pipeline = w && w->own().kind == pipeline_kind ? w : nullptr; InterlockedIncrement(pass.pipeline_real ? &render_pipelines_real : &render_pipelines_missing); if (auto* list = recording(self); list && pass.pipeline_real) list->SetPipelineState(static_cast(w->own().real)); @@ -2093,6 +2099,7 @@ void __stdcall list_compute_root(Wrapper* self, void* root) const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_params = real ? root_info(w) : nullptr; + pass.compute_srv_bound = 0; // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) list->SetComputeRootSignature(pass.compute_root); @@ -2615,7 +2622,12 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add if (!list || !params || parameter >= params->size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; const auto gpu = list_upload_gpu(self, address, 1); - if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) list->SetComputeRootShaderResourceView(parameter, gpu); + // A rejected replacement leaves no valid binding: the desktop list may still hold the previous address. + if (parameter < 32) pass_of(self).compute_srv_bound &= ~(1u << parameter); + if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { + list->SetComputeRootShaderResourceView(parameter, gpu); + if (parameter < 32) pass_of(self).compute_srv_bound |= 1u << parameter; + } } // List slot 44 (desktop 40 + 4), SetGraphicsRootShaderResourceView(parameter, title GPU address). @@ -2676,6 +2688,9 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) request.compute_pipeline = pass.compute_pipeline; request.compute_root = pass.compute_root != nullptr; request.compute_root_has_arguments = pass.compute_root_has_arguments; + request.root_matches_pipeline = pass.compute_pipeline_root && pass.compute_pipeline_root == pass.compute_root; + const UINT count = pass.compute_params ? static_cast(pass.compute_params->size()) : 0; + request.root_arguments_bound = count <= 32 && (pass.compute_srv_bound & (count >= 32 ? ~0u : (1u << count) - 1)) == (count >= 32 ? ~0u : (1u << count) - 1); request.x = x, request.y = y, request.z = z; const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); if (decision != x2w_startup::DispatchDecision::forward) { @@ -3625,12 +3640,13 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE bool has_depth_stencil = false; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; bool compute = false; + ID3D12RootSignature* pipeline_root = nullptr; IndirectGraphicsPipeline graphics; if (render_mode()) { char why[256] = ""; // Recognized desktop stages must reach the native path before the // guest cache creates a pending translation for any DXBC container. - real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); + real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics, pipeline_root); if (!real_pipeline || graphics.root) translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format); static LONG built; @@ -3639,6 +3655,7 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE } *out = wrap(real_pipeline, pipeline_kind); static_cast(*out)->own().compute_pipeline = real_pipeline && compute; + static_cast(*out)->own().pipeline_root = pipeline_root; static_cast(*out)->own().indirect_graphics = graphics; note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, translation, translation && has_blend ? &blend : nullptr, diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h index b2fb73a64b..cc00bdc8a0 100644 --- a/src/startup_stubs/list_dispatch.h +++ b/src/startup_stubs/list_dispatch.h @@ -2,7 +2,7 @@ // Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, // can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares -// no parameters (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs +// no parameters other than root SRVs (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs // arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. #include @@ -17,12 +17,14 @@ struct ListDispatch { bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline bool compute_root = false; // the bound compute root signature is a desktop root signature bool compute_root_has_arguments = false; // that root declares parameters or static samplers + bool root_matches_pipeline = true; // the compute pipeline was built against the bound compute root + bool root_arguments_bound = true; // every root SRV the root declares reached the desktop list (a rejected set clears it) UINT x = 0, y = 0, z = 0; }; enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, - group_count_over_limit }; -constexpr int dispatch_decision_count = 6; + root_pipeline_mismatch, unbound_root_argument, group_count_over_limit }; +constexpr int dispatch_decision_count = 8; inline const char* dispatch_reason(DispatchDecision decision) { @@ -32,6 +34,8 @@ inline const char* dispatch_reason(DispatchDecision decision) case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; + case DispatchDecision::root_pipeline_mismatch: return "compute pipeline was built against another root signature"; + case DispatchDecision::unbound_root_argument: return "a compute root SRV is not bound"; case DispatchDecision::group_count_over_limit: return "group count is over 65535"; } return "unknown"; @@ -44,6 +48,8 @@ inline DispatchDecision decide_dispatch(const ListDispatch& d) return DispatchDecision::wrong_list_type; if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; + if (!d.root_matches_pipeline) return DispatchDecision::root_pipeline_mismatch; + if (!d.root_arguments_bound) return DispatchDecision::unbound_root_argument; if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) return DispatchDecision::group_count_over_limit; return DispatchDecision::forward; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp index ab83b5cc20..17abf36480 100644 --- a/tests/startup_list_dispatch_check.cpp +++ b/tests/startup_list_dispatch_check.cpp @@ -1,7 +1,7 @@ // Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the // desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. // -// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args] +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args|no-pairing|no-bound] // // The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a // compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. @@ -14,7 +14,7 @@ namespace { using namespace x2w_startup; using D = DispatchDecision; int failures, cases; -bool no_limit, no_state, no_root_args; +bool no_limit, no_state, no_root_args, no_pairing, no_bound; void expect(const char* label, const ListDispatch& in, D expected) { @@ -41,7 +41,9 @@ int main(int argc, char** argv) no_limit = !std::strcmp(argv[2], "no-limit"); no_state = !std::strcmp(argv[2], "no-state"); no_root_args = !std::strcmp(argv[2], "no-root-args"); - if (!no_limit && !no_state && !no_root_args) return 2; + no_pairing = !std::strcmp(argv[2], "no-pairing"); + no_bound = !std::strcmp(argv[2], "no-bound"); + if (!no_limit && !no_state && !no_root_args && !no_pairing && !no_bound) return 2; } expect("one group", ready(1, 1, 1), D::forward); expect("limit on every axis", ready(65535, 65535, 65535), D::forward); @@ -61,6 +63,17 @@ int main(int argc, char** argv) d.x = 0; expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); d = ready(8, 1, 1); + d.root_matches_pipeline = false; // pipeline built against a different root signature + expect("root and pipeline differ", d, no_pairing ? D::forward : D::root_pipeline_mismatch); + d = ready(8, 1, 1); + d.root_arguments_bound = false; // a root SRV was never set, or a replacement was rejected + expect("unbound root SRV", d, no_bound ? D::forward : D::unbound_root_argument); + d.x = 0; + expect("unbound root SRV, zero groups", d, no_bound ? D::forward : D::unbound_root_argument); + d = ready(8, 1, 1); + d.root_matches_pipeline = d.root_arguments_bound = true; + expect("paired root with every SRV bound", d, D::forward); + d = ready(8, 1, 1); d.list_open = false; expect("closed list", d, D::list_closed); d = ready(8, 1, 1); From cffe8cea08cf93dc9b55c31c5e975a0f56a02e44 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 23:10:47 +0100 Subject: [PATCH 07/25] startup: record SetComputeRoot32BitConstant(s) (list slots 37, 39) Compute root constants are kept per list next to the graphics ones, in a shared 16 x 8 word store that refuses parameter >= 16 and offset >= 8. A new compute root signature clears them. --- CMakeLists.txt | 4 ++ src/startup_stubs/d3d12_draw.inl | 21 ++++++++++ src/startup_stubs/d3d12_xs_device.cpp | 8 ++++ src/startup_stubs/root_constant_store.h | 50 ++++++++++++++++++++++++ tests/startup_root_constant_store.cpp | 51 +++++++++++++++++++++++++ 5 files changed, 134 insertions(+) create mode 100644 src/startup_stubs/root_constant_store.h create mode 100644 tests/startup_root_constant_store.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 884ff147f5..2209538acb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -811,6 +811,10 @@ endforeach() add_executable(startup_command_list_slot_names tests/startup_command_list_slot_names.cpp) target_compile_features(startup_command_list_slot_names PRIVATE cxx_std_17) add_test(NAME startup_command_list_slot_names COMMAND startup_command_list_slot_names) +# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, list slots 37, 39 and 40, #870). +add_executable(startup_root_constant_store tests/startup_root_constant_store.cpp) +target_compile_features(startup_root_constant_store PRIVATE cxx_std_17) +add_test(NAME startup_root_constant_store COMMAND startup_root_constant_store) # Game-save stand-in storage (src/startup_stubs/save_store.h): a blob written by one process is read by a second. add_executable(startup_gamesave_persist tests/startup_gamesave_persist.cpp) target_compile_features(startup_gamesave_persist PRIVATE cxx_std_17) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 4493342ded..114fe4a96b 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2188,6 +2188,17 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) ReleaseSRWLockShared(¬e_lock); pass.view_tables[parameter] = table; } +// Keeps the words of a root constants call; a call outside the 16 x 8 words kept is logged and cut or dropped. +static void store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, + const std::uint32_t* data, UINT offset) +{ + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; + const auto result = store.set(parameter, count, data, offset); + static LONG refused; + if (result != x2w_root_constants::Result::stored && first_calls(refused, 4)) + log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", kind, + result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count); +} // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) { @@ -2203,6 +2214,16 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co count <= 8 - offset && offset + count <= (*pass.root)[parameter].constants_count) pass.constant_words_bound[parameter] |= static_cast(((1u << count) - 1) << offset); } +// List slot 37 (desktop 33 + 4), SetComputeRoot32BitConstant(parameter, value, offset). +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, 1, &value, offset); +} +// List slot 39 (desktop 35 + 4), SetComputeRoot32BitConstants(parameter, count, data, offset). +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, count, data, offset); +} // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 42b4bbebda..6cbd9a06c9 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -52,6 +52,7 @@ #include "descriptor_heap_type.h" #include "small_texture_4k.h" #include "null_binding_cause.h" +#include "root_constant_store.h" #include "null_texture_view.h" #include "packed_target_format.h" #include "present_view_format.h" @@ -2169,6 +2170,8 @@ struct Pass { u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; + x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; D3D12_INDEX_BUFFER_VIEW ib = {}; @@ -2320,6 +2323,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); + // A different root signature invalidates the title's cached compute root arguments. + if (pass.compute_root_wrapper != w) pass.compute_constants.clear(); + pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast(w->own().real) : nullptr; pass.compute_params = real ? root_info(w) : nullptr; @@ -4640,6 +4646,8 @@ void build_tables() list_typed[50] = reinterpret_cast(&list_targets); list_typed[13] = reinterpret_cast(&list_draw_indexed); list_typed[36] = reinterpret_cast(&list_table); + list_typed[37] = reinterpret_cast(&list_compute_constant); + list_typed[39] = reinterpret_cast(&list_compute_constants); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h new file mode 100644 index 0000000000..7059b1a378 --- /dev/null +++ b/src/startup_stubs/root_constant_store.h @@ -0,0 +1,50 @@ +// Experimental (docs/startup-runtime.md, #870): the 32-bit root arguments a recorded command list keeps for +// translated draws and dispatches. Plain standard C++ with no Windows types, so it can be tested on its own. +// +// A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one +// that runs past them is cut off at the end of the parameter, so the caller can log either case. +#pragma once + +#include +#include + +namespace x2w_root_constants { + +inline constexpr unsigned parameter_count = 16; +inline constexpr unsigned words_per_parameter = 8; + +enum class Result { stored, truncated, dropped }; + +struct Store { + std::uint32_t words[parameter_count][words_per_parameter] = {}; + + void clear() noexcept + { + for (auto& row : words) + for (auto& word : row) word = 0; + } + + // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. + Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset) noexcept + { + if (!count || !data || parameter >= parameter_count || offset >= words_per_parameter) return Result::dropped; + const bool cut = count > words_per_parameter - offset; + const unsigned n = cut ? words_per_parameter - offset : count; + for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; + return cut ? Result::truncated : Result::stored; + } + + // SetXxxRoot32BitConstant(parameter, value, offset). + Result set_one(unsigned parameter, std::uint32_t value, unsigned offset) noexcept { return set(parameter, 1, &value, offset); } + + // The word a shader reads; 0 outside the kept range. + std::uint32_t word(int parameter, int offset) const noexcept + { + return parameter >= 0 && parameter < static_cast(parameter_count) && offset >= 0 && + offset < static_cast(words_per_parameter) + ? words[parameter][offset] + : 0; + } +}; + +} // namespace x2w_root_constants diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp new file mode 100644 index 0000000000..30dad50fc1 --- /dev/null +++ b/tests/startup_root_constant_store.cpp @@ -0,0 +1,51 @@ +// Experimental (docs/startup-runtime.md, #870): the root constants a command list keeps for compute +// (list slots 37 and 39) and graphics (slot 40). Plain standard C++; synthetic values, no title data. +#include "../src/startup_stubs/root_constant_store.h" + +#include +#include + +namespace { +using x2w_root_constants::Result; +using x2w_root_constants::Store; +int failures; + +void expect(bool ok, const std::string& what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; + } +} +} // namespace + +int main() +{ + Store store; + const std::uint32_t data[4] = {11, 22, 33, 44}; + + expect(store.set(3, 4, data, 2) == Result::stored, "four words at offset 2 are stored"); + expect(store.word(3, 2) == 11 && store.word(3, 5) == 44, "stored words read back at their offsets"); + expect(store.word(3, 1) == 0 && store.word(3, 6) == 0, "neighbouring words stay zero"); + + expect(store.set_one(5, 77, 7) == Result::stored, "a single word at the last offset is stored"); + expect(store.word(5, 7) == 77, "the single word reads back"); + + expect(store.set(6, 4, data, 6) == Result::truncated, "a write past the end of the parameter is cut off"); + expect(store.word(6, 6) == 11 && store.word(6, 7) == 22, "the words that fit are kept"); + expect(store.word(7, 0) == 0, "a cut-off write does not spill into the next parameter"); + + expect(store.set(16, 1, data, 0) == Result::dropped, "parameter 16 is refused"); + expect(store.set(0, 1, data, 8) == Result::dropped, "offset 8 is refused"); + expect(store.set(0, 0, data, 0) == Result::dropped, "an empty write is refused"); + expect(store.set(0, 1, nullptr, 0) == Result::dropped, "a null source is refused"); + expect(store.set_one(15, 5, 0) == Result::stored && store.word(15, 0) == 5, "parameter 15 is the last one kept"); + expect(store.word(16, 0) == 0 && store.word(-1, 0) == 0 && store.word(0, 8) == 0, "reads outside the range give 0"); + + store.clear(); + expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); + + if (failures) return 1; + std::puts("root constant store ok"); + return 0; +} From e0966b9a955b3d83877f2ae4d7339e265b0e15c9 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 23:11:05 +0100 Subject: [PATCH 08/25] feat: record command-list slot 14 Dispatch on the desktop list Part of #870. Forward Dispatch only with a desktop compute pipeline and root bound and group counts within 65535 per axis; refuse otherwise. --- CMakeLists.txt | 9 ++++ src/startup_stubs/d3d12_xs_device.cpp | 22 +++++++++ src/startup_stubs/list_dispatch.h | 47 ++++++++++++++++++ tests/startup_list_dispatch_check.cpp | 71 +++++++++++++++++++++++++++ 4 files changed, 149 insertions(+) create mode 100644 src/startup_stubs/list_dispatch.h create mode 100644 tests/startup_list_dispatch_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 05927f896a..72b169900e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1522,6 +1522,15 @@ foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) set_tests_properties(startup_heap_indexed_root_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Slot 14 (Dispatch) forward-or-refuse decision (src/startup_stubs/list_dispatch.h), without a device. +add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp) +target_include_directories(startup_list_dispatch_check PRIVATE src) +target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) +add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) +foreach(mutation IN ITEMS no-limit no-state) + add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) + set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 2d4ab5d612..f87ad79558 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -26,6 +26,7 @@ #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" +#include "startup_stubs/list_dispatch.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" #include "startup_stubs/address_texture.h" @@ -3007,6 +3008,26 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) } pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } +// List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + x2w_startup::ListDispatch request; + request.list_open = list != nullptr; + if (list) request.type = list->GetType(); + const Pass& pass = pass_of(self); + request.compute_pipeline = pass.compute_pipeline; + request.compute_root = pass.compute_root; + request.x = x, request.y = y, request.z = z; + const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); + if (decision != x2w_startup::DispatchDecision::forward) { + static LONG refusals; + if (first_calls(refusals, 16)) + log("x2w-render Dispatch(%u, %u, %u) refused: %s", x, y, z, x2w_startup::dispatch_reason(decision)); + return; + } + list->Dispatch(x, y, z); +} extern LONG translated_draws, untranslated_draws, frame_number; bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); // List slot 12, DrawInstanced. @@ -4636,6 +4657,7 @@ void build_tables() list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[14] = reinterpret_cast(&list_dispatch); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); list_typed[22] = reinterpret_cast(&list_scissors); diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h new file mode 100644 index 0000000000..093de094d2 --- /dev/null +++ b/src/startup_stubs/list_dispatch.h @@ -0,0 +1,47 @@ +#pragma once + +// Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, and every group count +// is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. + +#include + +namespace x2w_startup { + +constexpr UINT max_dispatch_groups = 65535; + +struct ListDispatch { + bool list_open = false; + D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; + bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline + bool compute_root = false; // the bound compute root signature is a desktop root signature + UINT x = 0, y = 0, z = 0; +}; + +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, group_count_over_limit }; +constexpr int dispatch_decision_count = 5; + +inline const char* dispatch_reason(DispatchDecision decision) +{ + switch (decision) { + case DispatchDecision::forward: return "forward"; + case DispatchDecision::list_closed: return "list is closed"; + case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; + case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::group_count_over_limit: return "group count is over 65535"; + } + return "unknown"; +} + +inline DispatchDecision decide_dispatch(const ListDispatch& d) +{ + if (!d.list_open) return DispatchDecision::list_closed; + if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) + return DispatchDecision::wrong_list_type; + if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) + return DispatchDecision::group_count_over_limit; + return DispatchDecision::forward; +} + +} // namespace x2w_startup diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp new file mode 100644 index 0000000000..79ecc298d8 --- /dev/null +++ b/tests/startup_list_dispatch_check.cpp @@ -0,0 +1,71 @@ +// Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the +// desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. +// +// startup_list_dispatch_check [--mutate no-limit|no-state] +// +// The mutations change the expectations to those of a wrong decision (no group-count limit, or a forward without a +// compute pipeline and root); each must make the check fail. +#include "startup_stubs/list_dispatch.h" + +#include +#include + +namespace { +using namespace x2w_startup; +using D = DispatchDecision; +int failures, cases; +bool no_limit, no_state; + +void expect(const char* label, const ListDispatch& in, D expected) +{ + ++cases; + const D got = decide_dispatch(in); + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, dispatch_reason(expected), dispatch_reason(got)); +} + +ListDispatch ready(UINT x, UINT y, UINT z) +{ + ListDispatch d; + d.list_open = true; + d.compute_pipeline = d.compute_root = true; + d.x = x, d.y = y, d.z = z; + return d; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + no_limit = !std::strcmp(argv[2], "no-limit"); + no_state = !std::strcmp(argv[2], "no-state"); + if (!no_limit && !no_state) return 2; + } + expect("one group", ready(1, 1, 1), D::forward); + expect("limit on every axis", ready(65535, 65535, 65535), D::forward); + expect("zero groups", ready(0, 5, 5), D::forward); + expect("x over limit", ready(65536, 1, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("y over limit", ready(1, 65536, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("z over limit", ready(1, 1, 0xffffffffu), no_limit ? D::forward : D::group_count_over_limit); + ListDispatch d = ready(8, 1, 1); + d.compute_pipeline = false; + expect("graphics pipeline bound", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root = false; + expect("no compute root", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.list_open = false; + expect("closed list", d, D::list_closed); + d = ready(8, 1, 1); + d.type = D3D12_COMMAND_LIST_TYPE_COPY; + expect("copy list", d, D::wrong_list_type); + d.type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + expect("compute list", d, D::forward); + if (failures) { + std::printf("%d of %d cases failed\n", failures, cases); + return 1; + } + std::printf("%d cases passed\n", cases); + return 0; +} From f3b91dd49f277ad5b07c4672bf690c45373db0f7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 02:15:24 +0100 Subject: [PATCH 09/25] startup: refuse Dispatch under a compute root with unforwarded arguments, document slot 14 --- CMakeLists.txt | 2 +- docs/experiments.md | 11 +++++++++++ src/startup_stubs/d3d12_xs_device.cpp | 9 ++++++++- src/startup_stubs/list_dispatch.h | 13 +++++++++---- tests/startup_list_dispatch_check.cpp | 16 +++++++++++----- 5 files changed, 40 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 72b169900e..33f135bea1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1527,7 +1527,7 @@ add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp target_include_directories(startup_list_dispatch_check PRIVATE src) target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) -foreach(mutation IN ITEMS no-limit no-state) +foreach(mutation IN ITEMS no-limit no-state no-root-args) add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/docs/experiments.md b/docs/experiments.md index 093385c934..b68af0d8ec 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13947,3 +13947,14 @@ ctest --preset dev --no-tests=error -R '^(cpu_aot_switch_sal|cpu_aot_switch_shif The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequences (because ML64 assembles the `sal` mnemonic as `/4` `SHL`) across 24 translated functions covering all 12 `SAL` `Code` encodings (`SAL_RM{8,16,32,64}_{1,CL,IMM8}`), register and memory destinations, count-`1` all-16 `SETcc` checks, count->1 10-condition `SETcc` checks, `Jcc`, `CMOVcc`, narrow returns, and nonvolatile/stack-frame operands, plus 11 negative exports. [The differential check](../tests/cpu/switch_sal_check.py) verifies 28,024 `dev` and 28,024 `/O2` comparisons against native execution and the Python reference, four `/O2` mutated-C++ controls (`shift_dir`, `cf_mask`, `of_mask`, `cl_mask`), 11 MASM, 4 unit, and 7 PE-patched rejection controls, and records decoded mnemonics via `iced_x86.Mnemonic` to `FORM_COVERAGE_RECORD`. Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. + +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no parameters or static samplers, and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A compute root with parameters is refused with `compute root arguments are not forwarded`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. + +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its three mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f87ad79558..ae5165ec72 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -148,6 +148,7 @@ struct alignas(16) WrapperOwn { const void* compute_trace_root; LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) Wrapper* list_device; // CommandList: wrapper that created this list. @@ -1759,8 +1760,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (SUCCEEDED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc) { heap_flags = static_cast(desc->Desc_1_1.Flags) & x2w_startup::root_flags_heap_indexed; w->own().root_without_bindings = !heap_flags && !desc->Desc_1_1.NumParameters && !desc->Desc_1_1.NumStaticSamplers; + w->own().root_srv_only = !heap_flags && !desc->Desc_1_1.NumStaticSamplers && desc->Desc_1_1.NumParameters; for (UINT i = 0; i < desc->Desc_1_1.NumParameters; ++i) { const auto& parameter = desc->Desc_1_1.pParameters[i]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) w->own().root_srv_only = false; RootParameter info{parameter.ParameterType, 0, 0}; if (parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) { @@ -2150,6 +2153,7 @@ struct Pass { std::array desktop_compute_upload_srvs{}; const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; + bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; @@ -2330,6 +2334,8 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { if (pass.desktop_compute_root.Get() != pass.compute_root) pass.desktop_compute_upload_srvs.fill(0); @@ -3017,7 +3023,8 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) if (list) request.type = list->GetType(); const Pass& pass = pass_of(self); request.compute_pipeline = pass.compute_pipeline; - request.compute_root = pass.compute_root; + request.compute_root = pass.compute_root != nullptr; + request.compute_root_has_arguments = pass.compute_root_has_arguments; request.x = x, request.y = y, request.z = z; const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); if (decision != x2w_startup::DispatchDecision::forward) { diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h index 093de094d2..b2fb73a64b 100644 --- a/src/startup_stubs/list_dispatch.h +++ b/src/startup_stubs/list_dispatch.h @@ -1,8 +1,9 @@ #pragma once // Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, -// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, and every group count -// is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares +// no parameters (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs +// arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. #include @@ -15,11 +16,13 @@ struct ListDispatch { D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline bool compute_root = false; // the bound compute root signature is a desktop root signature + bool compute_root_has_arguments = false; // that root declares parameters or static samplers UINT x = 0, y = 0, z = 0; }; -enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, group_count_over_limit }; -constexpr int dispatch_decision_count = 5; +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, + group_count_over_limit }; +constexpr int dispatch_decision_count = 6; inline const char* dispatch_reason(DispatchDecision decision) { @@ -28,6 +31,7 @@ inline const char* dispatch_reason(DispatchDecision decision) case DispatchDecision::list_closed: return "list is closed"; case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; case DispatchDecision::group_count_over_limit: return "group count is over 65535"; } return "unknown"; @@ -39,6 +43,7 @@ inline DispatchDecision decide_dispatch(const ListDispatch& d) if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return DispatchDecision::wrong_list_type; if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) return DispatchDecision::group_count_over_limit; return DispatchDecision::forward; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp index 79ecc298d8..ab83b5cc20 100644 --- a/tests/startup_list_dispatch_check.cpp +++ b/tests/startup_list_dispatch_check.cpp @@ -1,10 +1,10 @@ // Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the // desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. // -// startup_list_dispatch_check [--mutate no-limit|no-state] +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args] // -// The mutations change the expectations to those of a wrong decision (no group-count limit, or a forward without a -// compute pipeline and root); each must make the check fail. +// The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a +// compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. #include "startup_stubs/list_dispatch.h" #include @@ -14,7 +14,7 @@ namespace { using namespace x2w_startup; using D = DispatchDecision; int failures, cases; -bool no_limit, no_state; +bool no_limit, no_state, no_root_args; void expect(const char* label, const ListDispatch& in, D expected) { @@ -40,7 +40,8 @@ int main(int argc, char** argv) if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { no_limit = !std::strcmp(argv[2], "no-limit"); no_state = !std::strcmp(argv[2], "no-state"); - if (!no_limit && !no_state) return 2; + no_root_args = !std::strcmp(argv[2], "no-root-args"); + if (!no_limit && !no_state && !no_root_args) return 2; } expect("one group", ready(1, 1, 1), D::forward); expect("limit on every axis", ready(65535, 65535, 65535), D::forward); @@ -55,6 +56,11 @@ int main(int argc, char** argv) d.compute_root = false; expect("no compute root", d, no_state ? D::forward : D::no_compute_state); d = ready(8, 1, 1); + d.compute_root_has_arguments = true; // e.g. a root UAV set through slot 45, which is not forwarded + expect("root with arguments", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d.x = 0; + expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d = ready(8, 1, 1); d.list_open = false; expect("closed list", d, D::list_closed); d = ready(8, 1, 1); From c18cacb80a0fcf1b35a4ac7f7d4af6f879b2cee8 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 07:20:02 +0100 Subject: [PATCH 10/25] startup: gate Dispatch on bound compute root SRVs and a pipeline built against the bound root Slot 43 clears a parameter's binding when a replacement is rejected, slot 33 clears all bindings, and the compute pipeline records its root so a mismatched pair is refused. --- CMakeLists.txt | 2 +- docs/experiments.md | 4 ++-- src/startup_stubs/d3d12_xs_device.cpp | 19 +++++++++++++++++-- src/startup_stubs/list_dispatch.h | 12 +++++++++--- tests/startup_list_dispatch_check.cpp | 19 ++++++++++++++++--- 5 files changed, 45 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 33f135bea1..5f87ac1b26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1527,7 +1527,7 @@ add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp target_include_directories(startup_list_dispatch_check PRIVATE src) target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) -foreach(mutation IN ITEMS no-limit no-state no-root-args) +foreach(mutation IN ITEMS no-limit no-state no-root-args no-pairing no-bound) add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/docs/experiments.md b/docs/experiments.md index b68af0d8ec..c2811f6451 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13950,9 +13950,9 @@ Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and ## Startup list Dispatch -Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no parameters or static samplers, and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A compute root with parameters is refused with `compute root arguments are not forwarded`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`, because the compute root-argument slots (35, 37, 39, 41, 43, 45) have no handler yet and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. -Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its three mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its five mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. ```powershell cmake --build --preset dev --target startup_list_dispatch_check diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ae5165ec72..ae89485099 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -148,6 +148,7 @@ struct alignas(16) WrapperOwn { const void* compute_trace_root; LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) @@ -1889,7 +1890,7 @@ std::size_t desktop_stream_size(UINT type) // Converts the supported stream layout to desktop form and creates the pipeline. ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, char* why, std::size_t why_size, - bool& compute, IndirectGraphicsPipeline& graphics, + bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root, ID3D12RootSignature* cached_root = nullptr) { const bool cached_mesh = cached_root != nullptr; @@ -2051,6 +2052,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES } check_device("Device CreatePipelineState", 86); } + if (pipeline && compute && root && root->own().kind == root_signature_kind) + pipeline_root = static_cast(root->own().real); if (pipeline && (vertex || mesh) && (pixel || cached_mesh)) { graphics = {cached_mesh ? cached_root : static_cast(root->own().real), targets.RTFormats[0], mesh, cached_mesh}; @@ -2151,6 +2154,8 @@ struct Pass { ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded x2w_startup::ComPtr desktop_compute_root; // last root actually set on this recording std::array desktop_compute_upload_srvs{}; + ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against + UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers @@ -2316,6 +2321,7 @@ void __stdcall list_pipeline(Wrapper* self, void* pipeline) // a recognized desktop graphics pipeline just before it records the draw. pass.pipeline_real = available && !pass.indirect_graphics.root; pass.compute_pipeline = pass.pipeline_real && w->own().compute_pipeline; + pass.compute_pipeline_root = pass.compute_pipeline ? w->own().pipeline_root : nullptr; pass.pipeline = w && w->own().kind == pipeline_kind ? w : nullptr; InterlockedIncrement(pass.pipeline_real ? &render_pipelines_real : &render_pipelines_missing); if (auto* list = recording(self); list && pass.pipeline_real) list->SetPipelineState(static_cast(w->own().real)); @@ -2334,6 +2340,7 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } + pass.compute_srv_bound = 0; // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { @@ -2961,9 +2968,12 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add if (!list || !params || parameter >= params->size() || parameter >= pass.desktop_compute_upload_srvs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; const auto gpu = list_upload_gpu(self, address, 1); + // A rejected replacement leaves no valid binding: the desktop list may still hold the previous address. + if (parameter < 32) pass.compute_srv_bound &= ~(1u << parameter); if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { pass.desktop_compute_upload_srvs[parameter] = gpu; list->SetComputeRootShaderResourceView(parameter, gpu); + if (parameter < 32) pass.compute_srv_bound |= 1u << parameter; } } @@ -3025,6 +3035,9 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) request.compute_pipeline = pass.compute_pipeline; request.compute_root = pass.compute_root != nullptr; request.compute_root_has_arguments = pass.compute_root_has_arguments; + request.root_matches_pipeline = pass.compute_pipeline_root && pass.compute_pipeline_root == pass.compute_root; + const UINT count = pass.compute_params ? static_cast(pass.compute_params->size()) : 0; + request.root_arguments_bound = count <= 32 && (pass.compute_srv_bound & (count >= 32 ? ~0u : (1u << count) - 1)) == (count >= 32 ? ~0u : (1u << count) - 1); request.x = x, request.y = y, request.z = z; const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); if (decision != x2w_startup::DispatchDecision::forward) { @@ -4053,13 +4066,14 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE bool has_depth_stencil = false; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; bool compute = false; + ID3D12RootSignature* pipeline_root = nullptr; IndirectGraphicsPipeline graphics; u64 mesh86_key = 0; if (render_mode()) { char why[256] = ""; // Recognized desktop stages must reach the native path before the // guest cache creates a pending translation for any DXBC container. - real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); + real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics, pipeline_root); bool mesh_cache_request = false; if (!real_pipeline) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); @@ -4071,6 +4085,7 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE } *out = wrap(real_pipeline, pipeline_kind); static_cast(*out)->own().compute_pipeline = real_pipeline && compute; + static_cast(*out)->own().pipeline_root = pipeline_root; static_cast(*out)->own().indirect_graphics = graphics; static_cast(*out)->own().mesh86_key = mesh86_key; note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h index b2fb73a64b..cc00bdc8a0 100644 --- a/src/startup_stubs/list_dispatch.h +++ b/src/startup_stubs/list_dispatch.h @@ -2,7 +2,7 @@ // Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, // can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares -// no parameters (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs +// no parameters other than root SRVs (the compute root-argument slots 35, 37, 39, 41, 43 and 45 are not forwarded yet, so a root that needs // arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. #include @@ -17,12 +17,14 @@ struct ListDispatch { bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline bool compute_root = false; // the bound compute root signature is a desktop root signature bool compute_root_has_arguments = false; // that root declares parameters or static samplers + bool root_matches_pipeline = true; // the compute pipeline was built against the bound compute root + bool root_arguments_bound = true; // every root SRV the root declares reached the desktop list (a rejected set clears it) UINT x = 0, y = 0, z = 0; }; enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, - group_count_over_limit }; -constexpr int dispatch_decision_count = 6; + root_pipeline_mismatch, unbound_root_argument, group_count_over_limit }; +constexpr int dispatch_decision_count = 8; inline const char* dispatch_reason(DispatchDecision decision) { @@ -32,6 +34,8 @@ inline const char* dispatch_reason(DispatchDecision decision) case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; + case DispatchDecision::root_pipeline_mismatch: return "compute pipeline was built against another root signature"; + case DispatchDecision::unbound_root_argument: return "a compute root SRV is not bound"; case DispatchDecision::group_count_over_limit: return "group count is over 65535"; } return "unknown"; @@ -44,6 +48,8 @@ inline DispatchDecision decide_dispatch(const ListDispatch& d) return DispatchDecision::wrong_list_type; if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; + if (!d.root_matches_pipeline) return DispatchDecision::root_pipeline_mismatch; + if (!d.root_arguments_bound) return DispatchDecision::unbound_root_argument; if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) return DispatchDecision::group_count_over_limit; return DispatchDecision::forward; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp index ab83b5cc20..17abf36480 100644 --- a/tests/startup_list_dispatch_check.cpp +++ b/tests/startup_list_dispatch_check.cpp @@ -1,7 +1,7 @@ // Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the // desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. // -// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args] +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args|no-pairing|no-bound] // // The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a // compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. @@ -14,7 +14,7 @@ namespace { using namespace x2w_startup; using D = DispatchDecision; int failures, cases; -bool no_limit, no_state, no_root_args; +bool no_limit, no_state, no_root_args, no_pairing, no_bound; void expect(const char* label, const ListDispatch& in, D expected) { @@ -41,7 +41,9 @@ int main(int argc, char** argv) no_limit = !std::strcmp(argv[2], "no-limit"); no_state = !std::strcmp(argv[2], "no-state"); no_root_args = !std::strcmp(argv[2], "no-root-args"); - if (!no_limit && !no_state && !no_root_args) return 2; + no_pairing = !std::strcmp(argv[2], "no-pairing"); + no_bound = !std::strcmp(argv[2], "no-bound"); + if (!no_limit && !no_state && !no_root_args && !no_pairing && !no_bound) return 2; } expect("one group", ready(1, 1, 1), D::forward); expect("limit on every axis", ready(65535, 65535, 65535), D::forward); @@ -61,6 +63,17 @@ int main(int argc, char** argv) d.x = 0; expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); d = ready(8, 1, 1); + d.root_matches_pipeline = false; // pipeline built against a different root signature + expect("root and pipeline differ", d, no_pairing ? D::forward : D::root_pipeline_mismatch); + d = ready(8, 1, 1); + d.root_arguments_bound = false; // a root SRV was never set, or a replacement was rejected + expect("unbound root SRV", d, no_bound ? D::forward : D::unbound_root_argument); + d.x = 0; + expect("unbound root SRV, zero groups", d, no_bound ? D::forward : D::unbound_root_argument); + d = ready(8, 1, 1); + d.root_matches_pipeline = d.root_arguments_bound = true; + expect("paired root with every SRV bound", d, D::forward); + d = ready(8, 1, 1); d.list_open = false; expect("closed list", d, D::list_closed); d = ready(8, 1, 1); From 24c5f55489aa4f3d6cf8a2e6e4545856184d365e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 11:18:48 +0100 Subject: [PATCH 11/25] fix: pass pipeline root out-param in slot86 mesh cached pipeline build --- src/startup_stubs/mesh86_cache.inl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index c368b29559..84b9801192 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -218,7 +218,8 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d std::memcpy(request.stream.data() + request.root_offset + 8, &request.root, sizeof(request.root)); const D3D12_PIPELINE_STATE_STREAM_DESC desktop{request.stream.size(), request.stream.data()}; bool compute = false; - auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, + ID3D12RootSignature* pipeline_root = nullptr; + auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, pipeline_root, static_cast(request.root->own().real)); static LONG loaded; if (result && first_calls(loaded, 24)) From 9828b5d857bc456c4d08fc7cedfb44e8dd932480 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 18:03:24 +0100 Subject: [PATCH 12/25] fix: track which compute root constant words were set; drop slot 40 claim --- CMakeLists.txt | 2 +- src/startup_stubs/root_constant_store.h | 18 ++++++++++++++++-- tests/startup_root_constant_store.cpp | 13 ++++++++++++- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2209538acb..a1f607cee4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -811,7 +811,7 @@ endforeach() add_executable(startup_command_list_slot_names tests/startup_command_list_slot_names.cpp) target_compile_features(startup_command_list_slot_names PRIVATE cxx_std_17) add_test(NAME startup_command_list_slot_names COMMAND startup_command_list_slot_names) -# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, list slots 37, 39 and 40, #870). +# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, compute list slots 37 and 39, #870; slot 40 keeps its own graphics words). add_executable(startup_root_constant_store tests/startup_root_constant_store.cpp) target_compile_features(startup_root_constant_store PRIVATE cxx_std_17) add_test(NAME startup_root_constant_store COMMAND startup_root_constant_store) diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h index 7059b1a378..45b9914008 100644 --- a/src/startup_stubs/root_constant_store.h +++ b/src/startup_stubs/root_constant_store.h @@ -1,5 +1,5 @@ -// Experimental (docs/startup-runtime.md, #870): the 32-bit root arguments a recorded command list keeps for -// translated draws and dispatches. Plain standard C++ with no Windows types, so it can be tested on its own. +// Experimental (docs/startup-runtime.md, #870): the 32-bit compute root arguments a recorded command list keeps +// (list slots 37 and 39; the graphics slot 40 keeps its own words). Plain standard C++ with no Windows types, so it can be tested on its own. // // A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one // that runs past them is cut off at the end of the parameter, so the caller can log either case. @@ -17,11 +17,24 @@ enum class Result { stored, truncated, dropped }; struct Store { std::uint32_t words[parameter_count][words_per_parameter] = {}; + // One bit per word that a write stored, like the graphics path's `constant_words_bound`, so a later + // dispatch can tell "set to 0" from "never set". + std::uint8_t bound[parameter_count] = {}; void clear() noexcept { for (auto& row : words) for (auto& word : row) word = 0; + for (auto& mask : bound) mask = 0; + } + + // True when every word in [offset, offset + count) of `parameter` was written since the last clear. + bool is_bound(unsigned parameter, unsigned offset, unsigned count) const noexcept + { + if (!count || parameter >= parameter_count || offset >= words_per_parameter || count > words_per_parameter - offset) + return false; + const unsigned mask = ((1u << count) - 1) << offset; + return (bound[parameter] & mask) == mask; } // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. @@ -31,6 +44,7 @@ struct Store { const bool cut = count > words_per_parameter - offset; const unsigned n = cut ? words_per_parameter - offset : count; for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; + bound[parameter] |= static_cast(((1u << n) - 1) << offset); return cut ? Result::truncated : Result::stored; } diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp index 30dad50fc1..a07bb3acf1 100644 --- a/tests/startup_root_constant_store.cpp +++ b/tests/startup_root_constant_store.cpp @@ -1,5 +1,5 @@ // Experimental (docs/startup-runtime.md, #870): the root constants a command list keeps for compute -// (list slots 37 and 39) and graphics (slot 40). Plain standard C++; synthetic values, no title data. +// (list slots 37 and 39). Plain standard C++; synthetic values, no title data. #include "../src/startup_stubs/root_constant_store.h" #include @@ -42,8 +42,19 @@ int main() expect(store.set_one(15, 5, 0) == Result::stored && store.word(15, 0) == 5, "parameter 15 is the last one kept"); expect(store.word(16, 0) == 0 && store.word(-1, 0) == 0 && store.word(0, 8) == 0, "reads outside the range give 0"); + expect(store.is_bound(3, 2, 4) && store.is_bound(3, 3, 1), "written words are marked set"); + expect(!store.is_bound(3, 1, 1) && !store.is_bound(3, 1, 2) && !store.is_bound(3, 6, 1), + "words never written are not set, and a range with one unset word is not set"); + expect(store.is_bound(6, 6, 2) && !store.is_bound(6, 6, 3), "a cut-off write marks only the words that fit"); + expect(!store.is_bound(0, 0, 1), "a dropped write marks nothing"); + expect(!store.is_bound(16, 0, 1) && !store.is_bound(0, 8, 1) && !store.is_bound(0, 0, 0) && !store.is_bound(0, 7, 2), + "ranges outside the kept words are never set"); + expect(store.set_one(1, 0, 0) == Result::stored && store.is_bound(1, 0, 1) && store.word(1, 0) == 0, + "writing 0 is set, unlike never written"); + store.clear(); expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); + expect(!store.is_bound(3, 2, 4) && !store.is_bound(1, 0, 1), "clear forgets which words were set"); if (failures) return 1; std::puts("root constant store ok"); From 1e567a029877b07fd2f45ae4f4db97c29534a37d Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 18:26:31 +0100 Subject: [PATCH 13/25] Dispatch translated compute programs with raw table buffers A device slot 67 placeholder keeps the key of its published request. At list slot 14 the stand-in loads the stage cs manifest and compiled program for that key and records the dispatch: raw buffer inputs and outputs from hardware descriptors in the recorded compute tables, entry values from the recorded compute root constants. Other manifest lines leave the pipeline untranslated; a dispatch that cannot be bound completely is refused with one logged reason and records nothing. startup_compute_dispatch_{warp,hardware} drives a source-built program through the stand-in list and reads the output back, with controls before translation, without a Dispatch and for a refused output. Co-Authored-By: Claude Fable 5.2 --- CMakeLists.txt | 4 + docs/experiments.md | 13 ++ src/startup_stubs/d3d12_compute_dispatch.inl | 211 ++++++++++++++++++ src/startup_stubs/d3d12_draw.inl | 8 +- src/startup_stubs/d3d12_xs_device.cpp | 16 +- .../translated_sampler_bindings.h | 8 +- tests/startup_compute_dispatch_check.py | 102 +++++++++ tests/startup_stream_consumer.cpp | 81 ++++++- 8 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 src/startup_stubs/d3d12_compute_dispatch.inl create mode 100644 tests/startup_compute_dispatch_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index eff5d13d47..c1b8aee8c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3498,6 +3498,10 @@ if(EXISTS "${INTAKE_PYTHON}") PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") + add_test(NAME startup_compute_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" diff --git a/docs/experiments.md b/docs/experiments.md index 133e0a7b1e..a3592168ce 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14727,3 +14727,16 @@ Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs witho cmake --build --preset dev --target startup_list_dispatch_check ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V ``` + +## Translated compute Dispatch + +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. This first slice binds raw buffers only: inputs and outputs named by 16-byte hardware buffer descriptors in the compute descriptor tables of slot 35, and entry values from the compute root constants of slots 37 and 39. An input must resolve to a complete GPU-backed range; an output must be a placed buffer that aliases the caller's memory and allows unordered access. Any other manifest line (textures, samplers, root views, other entry-value sources) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason and records nothing. + +`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. The log line `x2w-render compute dispatches: translated , refused , no translation ` follows the render totals. + +Measured on one fixture program. Programs with textures, samplers or outputs in memory that is not aliased are not dispatched. + +```powershell +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V +``` diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl new file mode 100644 index 0000000000..ed6be66741 --- /dev/null +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -0,0 +1,211 @@ +// Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps +// the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and +// .cs.cso. This first slice binds raw buffers only: `srv buf table ` inputs and +// `uav table ` outputs named by hardware buffer descriptors in the compute tables recorded by +// slot 35, with entry values from the compute root constants of slots 37 and 39. Any other manifest line makes +// the translation unavailable; a dispatch that cannot be bound completely is refused with one reason and records +// nothing on the desktop list. + +struct ComputeTranslation { + struct Slot { int a, b; }; // root parameter and byte offset (views), or parameter and word (entry values) + 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 + std::vector uds, srvs, uavs; + x2w_startup::ComPtr root; + x2w_startup::ComPtr pipeline; +}; +std::unordered_map& compute_translations() { static std::unordered_map m; return m; } +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated; + +// draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. +const char* load_compute_translation(ComputeTranslation& tr) +{ + tr.state = 2; + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + tr.retry_manifest_at = GetTickCount64() + 1000; + return nullptr; + } + tr.retry_manifest_at = 0; + unsigned declared_uds = 0, line_number = 0; + for (std::size_t at = 0; at < manifest.size(); ++line_number) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + at = end + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line_number == 0) { + if (line != "x2w-manifest 2") return "manifest version"; + continue; + } + if (line_number == 1) { + if (line != "stage cs") return "not a compute manifest"; + continue; + } + unsigned i = 0, x = 0, y = 0, z = 0; + int a = 0, b = 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; + if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) + tr.uds.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b}); + 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 return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer" + : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant" + : line.rfind("smp", 0) == 0 ? "a sampler" : "an unknown manifest line"; + } + // shortcut: one constants parameter and one table with both ranges; lift when a program without entry values, + // inputs or outputs is requested. + if (tr.uds.empty() || tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.empty() || tr.srvs.size() > 32 || + tr.uavs.empty() || tr.uavs.size() > 8) + return "entry value, input or output count"; + x2w_startup::ComPtr code; + if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), + static_cast(tr.srvs.size()), {}, &tr.root, static_cast(tr.uavs.size())))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + log("x2w-draw compute pipeline %016llx translated: %zu entry values, %zu inputs, %zu outputs", tr.key, tr.uds.size(), + tr.srvs.size(), tr.uavs.size()); + return nullptr; +} + +// True when the bound pipeline is a slot 67 placeholder with a request key: the call is then settled here +// (dispatched, or refused and logged). False leaves it to the desktop-pipeline decision of list_dispatch. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + Pass& pass = pass_of(self); + const u64 key = list && pass.pipeline ? pass.pipeline->own().compute_request_key : 0; + if (!key) return false; + const char* reason = nullptr; + LONG* counter = &compute_dispatches_refused; + struct View { ID3D12Resource* resource; u64 offset, bytes; bool transition; } views[40]{}; + ComputeTranslation* tr = nullptr; + const auto type = list->GetType(); + AcquireSRWLockExclusive(&draw_lock); + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; + else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) + reason = "a group count is over the limit"; + else if (pass.compute_root_wrapper != pass.pipeline->own().compute_request_root) + reason = "the compute root set is not the one the pipeline was created with"; + else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; + else { + tr = &compute_translations()[key]; + tr->key = key; + if (!tr->state || (tr->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { + if (const char* why = load_compute_translation(*tr)) + log("x2w-draw compute pipeline %016llx not translated: %s", key, why); + } + if (tr->state != 1) { + reason = "no translation"; + counter = &compute_dispatches_untranslated; + } + } + const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + 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]; + const u64 entry = slot.a >= 0 && slot.b >= 0 ? pass.compute_tables.table(slot.a).record(static_cast(slot.b), 16) : 0; + std::uint32_t words[4]; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(words))) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(entry), sizeof(words)); + if (!output) { + const IndirectBufferView view = indirect_table_buffer(self, words); + if (!view.resource || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input is not a complete GPU-backed buffer range"; + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + continue; + } + // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result + // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 bytes = u64{stride ? stride : 1} * words[2]; + const auto placed = words[0] == view_token_magic || !bytes || bytes % 4 || bytes > (16u << 20) + ? PlacedVertexView{} : placed_buffer_range(self->own().list_device, address, bytes); + const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; + const u64 offset = placed.alias ? address - reinterpret_cast(placed.owner->own().title_memory) : 0; + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + !(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output is not an aliased placed buffer range with unordered access"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; + views[i] = {placed.alias, offset, bytes, true}; + } + if (reason) { + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(counter); + static LONG refusals; + if (first_calls(refusals, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + return true; + } + const UINT n = static_cast(count); + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; + if (first + n > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(n)); + } + D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; + for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { + const View& view = views[i]; + if (i < inputs) { + if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); + continue; + } + require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = view.offset / 4; + desc.Buffer.NumElements = static_cast(view.bytes / 4); + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, &desc, dest); + } + std::uint32_t values[32] = {}; + for (std::size_t i = 0; i < tr->uds.size(); ++i) values[i] = pass.compute_constants.word(tr->uds[i].a, tr->uds[i].b); + if (!pass.heap_set) { + x2w_startup::bind_translated_heaps(list, draw_heap, nullptr); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; + } + list->SetPipelineState(tr->pipeline.Get()); + list->SetComputeRootSignature(tr->root.Get()); + list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + list->Dispatch(x, y, z); + for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = views[i].resource; + list->ResourceBarrier(1, &barrier); + } + // The translated root replaced the desktop compute root of the title and its arguments. + if (pass.desktop_compute_root) { + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); + } + ReleaseSRWLockExclusive(&draw_lock); + check_device("translated dispatch", 14); + InterlockedIncrement(&compute_dispatches_translated); + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) translated: entry [%x %x %x %x], %zu inputs, %zu outputs", key, x, y, z, + values[0], values[1], values[2], values[3], inputs, count - inputs); + return true; +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index b8deb2c83c..c450f975bc 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -313,10 +313,11 @@ LONG pointer_like_qwords(const std::vector& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } -void publish_compute_request(const void* desc) +// Returns the request key, or 0 when publishing is disabled or the description is refused. +u64 publish_compute_request(const void* desc) { wchar_t marker[MAX_PATH]; - if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return; // publishing disabled + if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return 0; // publishing disabled static LONG logged; const char* refusal = nullptr; u64 words[12]{}; @@ -355,7 +356,7 @@ void publish_compute_request(const void* desc) if (refusal) { InterlockedIncrement(&compute_requests_failed); if (first_calls(logged, 12)) log("x2w-draw compute request not written: %s", refusal); - return; + return 0; } const auto& [code, data, state_a, state_b] = copies; // Pointer words never reach .desc or the key; 9 and 10 are not followed (shortcut: two descriptions that @@ -391,6 +392,7 @@ void publish_compute_request(const void* desc) log("x2w-draw compute request %016llx %s (code %llu bytes, data %llu bytes, state blocks %llu + %llu bytes, " "pointer-like blob qwords %ld)", key, present ? "already present" : written ? "published" : "not written", words[6], words[8], words[2], words[4], pointers); + return key; } // Slot 57 fixed descriptors consumed by a decoded DispatchMesh signature. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 255eab9e46..91013e3c52 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -163,6 +163,8 @@ struct alignas(16) WrapperOwn { LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared + u64 compute_request_key; // PipelineState: key of the slot 67 request it published, or 0 + const void* compute_request_root; // PipelineState: root signature wrapper named by that slot 67 description bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) @@ -3283,8 +3285,10 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } // List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z); void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) { + if (dispatch_translated(self, x, y, z)) return; // a slot 67 placeholder never reaches the desktop decision auto* list = recording(self); x2w_startup::ListDispatch request; request.list_open = list != nullptr; @@ -3359,6 +3363,7 @@ std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_compute_dispatch.inl" #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" @@ -4442,8 +4447,14 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, hex_text(desc, 96, bytes, sizeof(bytes)); log("x2w-d3d12 Device::slot%d(pipeline?) desc=[%s] riid=%s -> placeholder", N, bytes, text); } - if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); + if constexpr (N == 67) { + // A translated Dispatch finds its program by this key (d3d12_compute_dispatch.inl). + if (const u64 key = publish_compute_request(desc)) { + static_cast(*out)->own().compute_request_key = key; + static_cast(*out)->own().compute_request_root = as_wrapper(*static_cast(desc)); + } + } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; } @@ -4809,6 +4820,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld", compute_dispatches_translated, + compute_dispatches_refused, compute_dispatches_untranslated); if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index e11626430c..424a4f9698 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -108,14 +108,16 @@ inline std::vector decode_statics(const TranslatedSam inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + // A compute program's outputs (u0..) follow its resources in the same table. + const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {1, &srv_range}; + parameters[1].DescriptorTable = {uavs ? 2u : 1u, view_ranges}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; UINT count = sampler_root_parameter(srvs); diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py new file mode 100644 index 0000000000..bee4f0ffa2 --- /dev/null +++ b/tests/startup_compute_dispatch_check.py @@ -0,0 +1,102 @@ +"""A translated compute program dispatched through the stand-in's command list (list slot 14). + +usage: startup_compute_dispatch_check.py + +The consumer creates case A of startup_gfx2hlsl_compute_check.py as a device slot 67 pipeline and records, on a +stand-in list, the descriptor heap, the pipeline, its root signature, two root constants, one table of two +hardware buffer descriptors and Dispatch(3, 2, 2). Input and output are placed buffers that alias the consumer's +memory; the output words are read from that memory after the queue's fence. Four runs share one cache: + +1. before translation: the request is published, the Dispatch is refused with "no translation" and every output + word keeps the sentinel (the check fails when nothing translated is dispatched); +2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation; +3. dispatch-none (no Dispatch recorded): every word keeps the sentinel; +4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access): + refused with one logged reason, every word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def dispatch(directory, consumer, env, mode): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack('<%dI' % C.WORDS, out.read_bytes())), result + + +def lines(result, text): + return [line for line in result.stderr.splitlines() if text in line] + + +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(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch') + 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 + + got, result = dispatch(directory, consumer, env, 'dispatch') + 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')) + + got, result = dispatch(directory, consumer, env, 'dispatch-none') + assert got == untouched and not lines(result, 'Dispatch('), 'the output changed without a Dispatch' + + got, result = dispatch(directory, consumer, env, 'dispatch-swapped') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \ + result.stderr[-3000:] + print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation; untouched ' + 'before translation, without a Dispatch and for a refused output)') + + +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 d3f5d5fac2..a97fb2485b 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -161,7 +161,78 @@ static void* desktop_pipeline(void* device) // data-pointer valid, with the first data qword pointing at state block A // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable +// dispatch, dispatch-swapped, dispatch-none: one creation, then dispatch_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; +static void* slot67_root; + +// Case A of startup_gfx2hlsl_compute_check.py through the stand-in's own list: two root constants (slot 39), a +// table (slot 35) of two 16-byte hardware buffer descriptors written into the title heap's memory, and Dispatch +// (slot 14) of 3x2x2 groups with the slot 67 placeholder bound. Input and output are placed buffers 64 KiB apart +// in one allocation, so both alias this process's memory and the result is read from that memory after the queue's +// fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered +// access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +static int dispatch_slot67(void* device, const std::string& mode) +{ + constexpr UINT words = 320; + auto* memory = static_cast(VirtualAlloc(nullptr, 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + for (UINT i = 0; i < words; ++i) { + buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; + buffers[1][i] = 0xc5c5c5c5u; + } + const auto word = [](const void* value) { return reinterpret_cast(value); }; + void* placed[2]{}; + UINT descriptors[2][4]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, i ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(device, 133, word(buffers[i]), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; + const UINT64 address = reinterpret_cast(buffers[i]); + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | 4u << 16, words, 0}; + std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); + } + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + 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; + std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); + const UINT constants[2] = {0x01234567, 0x9e3779b9}; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + invoke(list, 32, 1, word(&heap)); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(slot67_root)); + invoke(list, 39, 0, 2, word(constants), 0); + invoke(list, 35, 1, gpu); + if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + 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; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != 0x8b02a7f1u + i * 0x413b1u) return 79; // the input must stay as written + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) return 2; + std::ofstream(path, std::ios::binary).write(reinterpret_cast(buffers[1]), words * sizeof(UINT)); + return 0; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -218,8 +289,11 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); auto create = [&](const void* d) { void* pipeline = nullptr; - return SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + const bool created = SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && pipeline; + slot67_pipeline = pipeline; + slot67_root = root; + return created; }; if (m == "order") { if (!create(desc)) return false; @@ -258,12 +332,15 @@ int main(int argc, char** argv) ComPtr adapter; void* device = nullptr; void* pso = nullptr; - const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; + const bool hardware = (draw && std::strcmp(argv[4], "hardware") == 0) || + GetEnvironmentVariableW(L"X2W_TEST_DISPATCH_HARDWARE", nullptr, 0) != 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? dispatch_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; From aca6e89573d413d98bf6844bb5f7cf49e6d4ec50 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 18:36:34 +0100 Subject: [PATCH 14/25] Log untranslated compute dispatches on their own line budget Dispatches that arrive before the offline translation no longer use up the lines kept for refusals at bind time. Co-Authored-By: Claude Fable 5.2 --- src/startup_stubs/d3d12_compute_dispatch.inl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index ed6be66741..778b28a31b 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -149,8 +149,9 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) if (reason) { ReleaseSRWLockExclusive(&draw_lock); InterlockedIncrement(counter); - static LONG refusals; - if (first_calls(refusals, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. + static LONG untranslated, refusals; + if (first_calls(counter == &compute_dispatches_untranslated ? untranslated : refusals, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); return true; } const UINT n = static_cast(count); From 8e14a74b04584359ec097d0423231c967eea09e8 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:01:09 +0100 Subject: [PATCH 15/25] Count compute dispatches per key with their first refusal The per-call refusal lines share one small budget, so a run cannot rank keys by dispatch count. Each key now keeps its Dispatch count, the calls recorded and the reason and table descriptor of its first refusal; the periodic totals are followed by the refused dispatches per reason and the 40 keys with the most dispatches. A manifest that exists but cannot be bound is counted apart from an absent one ("not modelled"). Co-Authored-By: Claude Fable 5.2 --- src/startup_stubs/d3d12_compute_dispatch.inl | 70 +++++++++++++++++--- src/startup_stubs/d3d12_xs_device.cpp | 8 ++- tests/startup_compute_dispatch_check.py | 12 ++++ tests/startup_stream_consumer.cpp | 2 + 4 files changed, 79 insertions(+), 13 deletions(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 778b28a31b..6a5ad3275d 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -14,9 +14,13 @@ struct ComputeTranslation { std::vector uds, srvs, uavs; x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; + const char* unmodelled = nullptr; // why a manifest that exists cannot be used + u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded + const char* first_refusal = nullptr; // reason of the first refused call + std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any }; std::unordered_map& compute_translations() { static std::unordered_map m; return m; } -LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated; +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; // draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. const char* load_compute_translation(ComputeTranslation& tr) @@ -92,9 +96,12 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) const char* reason = nullptr; LONG* counter = &compute_dispatches_refused; struct View { ID3D12Resource* resource; u64 offset, bytes; bool transition; } views[40]{}; - ComputeTranslation* tr = nullptr; const auto type = list->GetType(); AcquireSRWLockExclusive(&draw_lock); + ComputeTranslation* const tr = &compute_translations()[key]; + tr->key = key; + ++tr->dispatches; + std::uint32_t words[4] = {}; if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) reason = "a group count is over the limit"; @@ -102,15 +109,14 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) reason = "the compute root set is not the one the pipeline was created with"; else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; else { - tr = &compute_translations()[key]; - tr->key = key; if (!tr->state || (tr->retry_manifest_at && GetTickCount64() >= tr->retry_manifest_at)) { - if (const char* why = load_compute_translation(*tr)) - log("x2w-draw compute pipeline %016llx not translated: %s", key, why); + tr->unmodelled = load_compute_translation(*tr); + if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); } if (tr->state != 1) { - reason = "no translation"; - counter = &compute_dispatches_untranslated; + // A manifest the runtime cannot bind is the dispatch side's work; an absent one is the translator's. + reason = tr->unmodelled ? tr->unmodelled : "no translation"; + counter = tr->unmodelled ? &compute_dispatches_unmodelled : &compute_dispatches_untranslated; } } const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); @@ -118,7 +124,7 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; const u64 entry = slot.a >= 0 && slot.b >= 0 ? pass.compute_tables.table(slot.a).record(static_cast(slot.b), 16) : 0; - std::uint32_t words[4]; + std::memset(words, 0, sizeof(words)); if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(words))) { reason = "a table descriptor is not bound"; break; @@ -147,11 +153,15 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) views[i] = {placed.alias, offset, bytes, true}; } if (reason) { + if (!tr->first_refusal) { + tr->first_refusal = reason; + std::memcpy(tr->refusal_words, words, sizeof(words)); + } ReleaseSRWLockExclusive(&draw_lock); InterlockedIncrement(counter); // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. static LONG untranslated, refusals; - if (first_calls(counter == &compute_dispatches_untranslated ? untranslated : refusals, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + if (first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); return true; } const UINT n = static_cast(count); @@ -201,6 +211,7 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); } + ++tr->translated; ReleaseSRWLockExclusive(&draw_lock); check_device("translated dispatch", 14); InterlockedIncrement(&compute_dispatches_translated); @@ -210,3 +221,42 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) values[0], values[1], values[2], values[3], inputs, count - inputs); return true; } + +// With the periodic totals: refused dispatches by the first refusal reason of their key, then the keys with the +// most dispatches. The per-call log lines above share one small budget, so they cannot rank keys. +void log_compute_census() +{ + struct Reason { const char* text; u64 keys, dispatches; }; + std::vector reasons; + std::vector keys; + AcquireSRWLockShared(&draw_lock); + for (const auto& item : compute_translations()) { + const ComputeTranslation& tr = item.second; + ComputeTranslation copy; + copy.key = tr.key; + copy.dispatches = tr.dispatches; + copy.translated = tr.translated; + copy.first_refusal = tr.first_refusal; + std::memcpy(copy.refusal_words, tr.refusal_words, sizeof(copy.refusal_words)); + keys.push_back(copy); + if (!tr.first_refusal) continue; + auto found = std::find_if(reasons.begin(), reasons.end(), [&](const Reason& r) { return !std::strcmp(r.text, tr.first_refusal); }); + if (found == reasons.end()) found = reasons.insert(reasons.end(), Reason{tr.first_refusal, 0, 0}); + ++found->keys; + found->dispatches += tr.dispatches - tr.translated; + } + ReleaseSRWLockShared(&draw_lock); + if (keys.empty()) return; + std::sort(reasons.begin(), reasons.end(), [](const Reason& a, const Reason& b) { return a.dispatches > b.dispatches; }); + std::sort(keys.begin(), keys.end(), [](const ComputeTranslation& a, const ComputeTranslation& b) { return a.dispatches > b.dispatches; }); + log("x2w-render compute census: %zu keys dispatched", keys.size()); + for (const Reason& r : reasons) + log("x2w-render compute census reason \"%s\": %llu keys, %llu dispatches", r.text, r.keys, r.dispatches); + for (std::size_t i = 0; i < keys.size() && i < 40; ++i) + log("x2w-render compute census key %016llx: %llu dispatches, %llu translated, first refusal: %s [%08x %08x %08x %08x]", + keys[i].key, keys[i].dispatches, keys[i].translated, keys[i].first_refusal ? keys[i].first_refusal : "none", + keys[i].refusal_words[0], keys[i].refusal_words[1], keys[i].refusal_words[2], keys[i].refusal_words[3]); +} + +// Fixtures: the census without waiting for the frame that logs it. +extern "C" __declspec(dllexport) void x2w_d3d12_compute_census() { log_compute_census(); } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 91013e3c52..07933006ff 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4820,9 +4820,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); - if (render_mode() && frame % 300 == 0) - log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld", compute_dispatches_translated, - compute_dispatches_refused, compute_dispatches_untranslated); + if (render_mode() && frame % 300 == 0) { + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled); + log_compute_census(); + } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index bee4f0ffa2..81ad115f25 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -69,6 +69,11 @@ def main(consumer, dxc, adapter): published = lines(result, 'x2w-draw compute request') assert published and ' published ' in published[0], result.stderr[-3000:] key = int(published[0].split()[3], 16) + census = lines(result, 'x2w-render compute census') + assert census == ['x2w-render compute census: 1 keys dispatched', + 'x2w-render compute census reason "no translation": 1 keys, 1 dispatches', + f'x2w-render compute census key {key:016x}: 1 dispatches, 0 translated, first refusal: ' + 'no translation [00000000 00000000 00000000 00000000]'], census 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 @@ -79,6 +84,9 @@ def main(consumer, dxc, adapter): 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:] + census = lines(result, 'x2w-render compute census') + assert len(census) == 2 and census[1].endswith(': 1 dispatches, 1 translated, first refusal: none ' + '[00000000 00000000 00000000 00000000]'), census 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] @@ -86,10 +94,14 @@ def main(consumer, dxc, adapter): got, result = dispatch(directory, consumer, env, 'dispatch-none') assert got == untouched and not lines(result, 'Dispatch('), 'the output changed without a Dispatch' + assert not lines(result, 'x2w-render compute census'), 'a census without a Dispatch' got, result = dispatch(directory, consumer, env, 'dispatch-swapped') assert got == untouched, 'a refused Dispatch wrote the output' refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(census) == 3 and census[1].endswith( + 'reason "an output is not an aliased placed buffer range with unordered access": 1 keys, 1 dispatches') and '[00000000 00000000 ' not in census[2], census assert len(refused) == 1 and 'an output is not an aliased placed buffer range with unordered access' in refused[0], \ result.stderr[-3000:] print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation; untouched ' diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index a97fb2485b..b05070c7c3 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -18,6 +18,7 @@ using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_compute_census(); // A slot-55 patch is a tagged union with room for the full eight-target blend state. struct Patch { UINT tag; D3D12_BLEND_DESC blend; }; @@ -226,6 +227,7 @@ static int dispatch_slot67(void* device, const std::string& mode) } for (UINT i = 0; i < words; ++i) if (buffers[0][i] != 0x8b02a7f1u + i * 0x413b1u) return 79; // the input must stay as written + x2w_d3d12_compute_census(); char path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); if (!n || n >= MAX_PATH) return 2; From f2f7bfccce6465646b143995293e0203d148e088 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:05:35 +0100 Subject: [PATCH 16/25] Dispatch translated compute programs that store to 2D textures A `uav tex2d float table channels 4` manifest line is bound from the token of the unordered access view the title created in its descriptor memory. Everything else is refused with its own reason: an entry that is no such token, a view the desktop did not create, a view that is not 2D, a format a float4 store cannot target, and a texture bound to two slots of one dispatch. Programs without entry values, inputs or outputs load too: the translated root no longer emits an empty range or drops the table when only outputs exist. The fixture stores through the stand-in's own list into a 32x8 RGBA16_FLOAT texture and reads it back with CopyTextureRegion. Co-Authored-By: Claude Fable 5.2 --- CMakeLists.txt | 6 +- src/startup_stubs/d3d12_compute_dispatch.inl | 104 ++++++++++++---- .../translated_sampler_bindings.h | 5 +- .../startup_compute_dispatch_texture_check.py | 111 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 82 +++++++++++++ 5 files changed, 284 insertions(+), 24 deletions(-) create mode 100644 tests/startup_compute_dispatch_texture_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c1b8aee8c0..c60b20353f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3501,7 +3501,11 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) - set_tests_properties(startup_compute_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_dispatch_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 6a5ad3275d..082a85d908 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1,13 +1,14 @@ // Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps // the key of its published request; gfx2hlsl.py --pending answers the request with .txt (`stage cs`) and -// .cs.cso. This first slice binds raw buffers only: `srv buf table ` inputs and -// `uav table ` outputs named by hardware buffer descriptors in the compute tables recorded by -// slot 35, with entry values from the compute root constants of slots 37 and 39. Any other manifest line makes -// the translation unavailable; a dispatch that cannot be bound completely is refused with one reason and records -// nothing on the desktop list. +// .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 texture outputs +// (`uav tex2d float table channels 4`) named by the token of an unordered access view the title +// created (device slot 19). Entry values come from the compute root constants of slots 37 and 39. Any other +// manifest line makes the translation unavailable; a dispatch that cannot be bound completely is refused with one +// reason and records nothing on the desktop list. struct ComputeTranslation { - struct Slot { int a, b; }; // root parameter and byte offset (views), or parameter and word (entry values) + struct Slot { int a, b; bool texture; }; // root parameter and byte offset (views), or parameter and word (entry values) 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 @@ -17,8 +18,25 @@ struct ComputeTranslation { const char* unmodelled = nullptr; // why a manifest that exists cannot be used u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded const char* first_refusal = nullptr; // reason of the first refused call - std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any + std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's + // last word is replaced by its view format | dimension << 16 }; + +// Formats a `float` typed output may be viewed with: the program stores float4. +bool float_output_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: + return true; + default: + return false; + } +} std::unordered_map& compute_translations() { static std::unordered_map m; return m; } LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; @@ -59,19 +77,20 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.srvs.push_back({a, b}); 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 return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer" - : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer" + : line.rfind("uav", 0) == 0 ? "an output that is not a raw table buffer or a 2D float texture" : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant" : line.rfind("smp", 0) == 0 ? "a sampler" : "an unknown manifest line"; } - // shortcut: one constants parameter and one table with both ranges; lift when a program without entry values, - // inputs or outputs is requested. - if (tr.uds.empty() || tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.empty() || tr.srvs.size() > 32 || - tr.uavs.empty() || tr.uavs.size() > 8) + if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) return "entry value, input or output count"; x2w_startup::ComPtr code; if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; - if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), + // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), static_cast(tr.srvs.size()), {}, &tr.root, static_cast(tr.uavs.size())))) return "root signature creation failed"; D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; @@ -95,13 +114,13 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) if (!key) return false; const char* reason = nullptr; LONG* counter = &compute_dispatches_refused; - struct View { ID3D12Resource* resource; u64 offset, bytes; bool transition; } views[40]{}; + struct View { ID3D12Resource* resource; u64 offset, bytes; bool transition, texture, described; unsigned char desc[40]; } views[40]{}; const auto type = list->GetType(); AcquireSRWLockExclusive(&draw_lock); ComputeTranslation* const tr = &compute_translations()[key]; tr->key = key; ++tr->dispatches; - std::uint32_t words[4] = {}; + std::uint32_t words[8] = {}; if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) reason = "a group count is over the limit"; @@ -123,13 +142,51 @@ 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]; - const u64 entry = slot.a >= 0 && slot.b >= 0 ? pass.compute_tables.table(slot.a).record(static_cast(slot.b), 16) : 0; + const u64 entry = slot.a >= 0 && slot.b >= 0 ? pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16) : 0; std::memset(words, 0, sizeof(words)); - if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(words))) { + const std::size_t entry_bytes = slot.texture ? 32 : 16; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { reason = "a table descriptor is not bound"; break; } - std::memcpy(words, reinterpret_cast(entry), sizeof(words)); + std::memcpy(words, reinterpret_cast(entry), entry_bytes); + if (slot.texture) { + // The title's descriptor memory carries the id of the view it created there. Nothing else is bound: + // a null output would drop the program's stores without a trace. + ViewRecord record{}; + bool known = false, created = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) { + record = view_records()[words[1]]; + created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; + ID3D12Resource* const texture = wrapper && wrapper->own().kind == resource_kind && + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0 ? static_cast(wrapper->own().real) : nullptr; + const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + 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)) + reason = "an output texture view was not created on the desktop"; + 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 (!float_output_format(format)) reason = "an output texture format is not a float or normalized one"; + for (std::size_t other = 0; other < i && !reason; ++other) + if (views[other].resource == texture) reason = "an output texture is bound to another slot of the dispatch"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + continue; + } if (!output) { const IndirectBufferView view = indirect_table_buffer(self, words); if (!view.resource || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input is not a complete GPU-backed buffer range"; @@ -155,7 +212,7 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) if (reason) { if (!tr->first_refusal) { tr->first_refusal = reason; - std::memcpy(tr->refusal_words, words, sizeof(words)); + std::memcpy(tr->refusal_words, words, sizeof(tr->refusal_words)); } ReleaseSRWLockExclusive(&draw_lock); InterlockedIncrement(counter); @@ -179,6 +236,11 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) continue; } require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (view.texture) { + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; @@ -196,8 +258,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) } list->SetPipelineState(tr->pipeline.Get()); list->SetComputeRootSignature(tr->root.Get()); - list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); - list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + if (!tr->uds.empty()) list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); + if (n) list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); list->Dispatch(x, y, z); for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote D3D12_RESOURCE_BARRIER barrier{}; diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 424a4f9698..cf64c999a5 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -117,10 +117,11 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT const D3D12_DESCRIPTOR_RANGE view_ranges[2]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}}; parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {uavs ? 2u : 1u, view_ranges}; + // A range of no descriptors does not serialize: a program without resources starts the table at its outputs. + parameters[1].DescriptorTable = {(srvs ? 1u : 0u) + (uavs ? 1u : 0u), srvs ? view_ranges : view_ranges + 1}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs); + UINT count = sampler_root_parameter(srvs + uavs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py new file mode 100644 index 0000000000..143967ed89 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_check.py @@ -0,0 +1,111 @@ +"""Translated compute programs with 2D texture views, dispatched through the stand-in's command list (slot 14). + +usage: startup_compute_dispatch_texture_check.py + +Texture output: the consumer creates the image store program of startup_compute_image_store_d16_check.py as a +device slot 67 pipeline, fills a 32x8 RGBA16_FLOAT texture with sentinel halves, creates an unordered access view of +it at table byte 64 (device slot 19), records Dispatch(2, 1, 1) and copies the texture to a readback buffer. Four +runs share one cache: + +1. before translation: refused with "no translation", every half keeps its sentinel; +2. after gfx2hlsl.py --pending with DXC: the 1024 halves equal mip 0 of the fixture's CPU reference (64 changed); +3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; +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. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_compute_image_store_d16_check as S +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import 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 + + +def run(directory, consumer, env, mode, layout): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack(layout, out.read_bytes())), result + + +def translate(cache, dxc, key): + 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 + + +def clean(result): + assert not lines(result, 'refused'), result.stderr[-3000:] + 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] + layer = lines(result, 'x2w-d3d12 debug layer: ') + return 'enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable' + + +def store(directory, consumer, dxc, env): + 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') + assert S.fixture.GROUP == (4, 2, 1) and S.fixture.GROUPS == 2, 'the consumer hard-codes Dispatch(2, 1, 1)' + (directory / 'program').write_bytes(S.fixture.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(S.fixture.GROUP, S.RSRC2)) + reference = S.fixture.reference() + halves = 32 * 8 * 4 # mip 0 comes first in both halves of the reference + untouched, expected = reference[:halves], reference[len(reference) // 2:][:halves] + assert sum(a != b for a, b in zip(untouched, expected)) == 64 + layout = '<%dH' % halves + + got, result = run(directory, consumer, env, 'texture-store', layout) + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the texture' + assert len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'texture-store', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'half=%d got=%04x expected=%04x (%d halves differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'texture-store-none', layout) + assert got == untouched and not lines(result, 'Dispatch('), 'the texture changed without a Dispatch' + + got, result = run(directory, consumer, env, 'texture-store-denied', layout) + assert got == untouched, 'a refused Dispatch wrote the texture' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + print(f'texture output: all {halves} halves match after translation (64 changed); untouched before translation, ' + f'without a Dispatch and for a refused view; debug layer: {layer}') + + +def main(consumer, dxc, adapter): + env = dict(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' + with tempfile.TemporaryDirectory() as temporary: + store(Path(temporary) / 'store', consumer, dxc, env) + print(f'startup_compute_dispatch_texture: 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 b05070c7c3..5717b2b4c9 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -163,6 +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: one creation, then dispatch_slot67 below +// texture-store, texture-store-none, texture-store-denied: 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; static void* slot67_root; @@ -235,6 +236,85 @@ static int dispatch_slot67(void* device, const std::string& mode) return 0; } +// The image store program of startup_compute_image_store_d16_check.py through the stand-in's own list: a committed +// 32x8 RGBA16_FLOAT texture (device slot 127) filled with sentinel halves by CopyTextureRegion (list slot 16), an +// unordered access view of it (device slot 19) whose token the stand-in writes into the title heap at table byte 64, +// three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go +// to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture +// without unordered access, so the stand-in records its view as not created. +static int texture_slot67(void* device, const std::string& mode) +{ + constexpr UINT width = 32, height = 8, pitch = width * 8, bytes = pitch * height; + 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) { + using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, const GUID*, void**); + const D3D12_HEAP_PROPERTIES heap{type}; + void* resource = nullptr; + const HRESULT hr = reinterpret_cast((*static_cast(device))[127])( + device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); + return SUCCEEDED(hr) ? resource : nullptr; + }; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, + {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}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make(D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make(D3D12_HEAP_TYPE_UPLOAD, buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + 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); + invoke(upload, 9, 0, 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + 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{DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + 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, {DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 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)); + 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); + 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; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + memory = nullptr; + if (!n || n >= MAX_PATH || FAILED(static_cast(invoke(readback, 8, 0, 0, word(&memory)))) || !memory) return 2; + std::ofstream(path, std::ios::binary).write(static_cast(memory), bytes); + invoke(readback, 9, 0, 0); + return 0; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -343,6 +423,8 @@ int main(int argc, char** argv) // slot67 [case]: WARP device and root only, then slot-67 creations. if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? dispatch_slot67(device, argv[8]) : 10; + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; From 15e8b7ab47e25a03679f7c83bd6e13cc37bedb55 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:09:10 +0100 Subject: [PATCH 17/25] Dispatch translated compute programs that read 2D textures A `srv tex2d table ` manifest line is bound from the token of the shader resource view the title created, through the texture the draw path samples for that resource, uploaded first when the title filled it in memory. `smp` lines become static samplers of the translated root. A dispatch is refused, never bound to a null view, when the entry is no such token, the resource has no desktop texture, the view is not 2D or names a packed format, or the upload fails. Sampler heaps, comparison samplers and other texture kinds keep the translation unavailable. The fixture samples a 1x1 texture into the stored words of the raw buffer case; without a view the dispatch is refused and the output is untouched. Co-Authored-By: Claude Fable 5.2 --- src/startup_stubs/d3d12_compute_dispatch.inl | 69 ++++++++++++++++--- .../startup_compute_dispatch_texture_check.py | 58 ++++++++++++++++ tests/startup_stream_consumer.cpp | 45 +++++++++--- 3 files changed, 153 insertions(+), 19 deletions(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 082a85d908..263dd1f709 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1,10 +1,11 @@ // Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps // 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 texture outputs -// (`uav tex2d float table channels 4`) named by the token of an unordered access view the title -// created (device slot 19). Entry values come from the compute root constants of slots 37 and 39. Any other -// manifest line makes the translation unavailable; a dispatch that cannot be bound completely is refused with one +// inputs, `uav table ` outputs) named by hardware buffer descriptors, and 2D textures +// (`srv tex2d table ` inputs, `uav tex2d 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. Any other manifest line makes the translation +// unavailable; a dispatch that cannot be bound completely is refused with one // reason and records nothing on the desktop list. struct ComputeTranslation { @@ -13,6 +14,7 @@ struct ComputeTranslation { int state = 0; // 0 not loaded, 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later std::vector uds, srvs, uavs; + x2w_startup::TranslatedSamplers samplers; // static ones only x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; const char* unmodelled = nullptr; // why a manifest that exists cannot be used @@ -80,10 +82,15 @@ 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 return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer" + 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}); + else if (std::sscanf(line.c_str(), "smp %u %x %x %x %x%n", &i, &x, &y, &z, &x, &used) == 5 && whole() && + 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("udsrc", 0) == 0 ? "an entry value that is not a root constant" - : line.rfind("smp", 0) == 0 ? "a sampler" : "an unknown manifest line"; + : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; } if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) return "entry value, input or output count"; @@ -91,7 +98,7 @@ const char* load_compute_translation(ComputeTranslation& tr) if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), - static_cast(tr.srvs.size()), {}, &tr.root, static_cast(tr.uavs.size())))) + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())))) return "root signature creation failed"; D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); @@ -114,7 +121,14 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) if (!key) return false; const char* reason = nullptr; LONG* counter = &compute_dispatches_refused; - struct View { ID3D12Resource* resource; u64 offset, bytes; bool transition, texture, described; unsigned char desc[40]; } views[40]{}; + struct View { + ID3D12Resource* resource; + u64 offset, bytes; + bool transition, texture, described; + unsigned char desc[40]; // a texture view's description, as the title gave it with a desktop format + Wrapper* wrapper; + } views[40]{}; + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40); const auto type = list->GetType(); AcquireSRWLockExclusive(&draw_lock); ComputeTranslation* const tr = &compute_translations()[key]; @@ -152,7 +166,7 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) std::memcpy(words, reinterpret_cast(entry), entry_bytes); if (slot.texture) { // The title's descriptor memory carries the id of the view it created there. Nothing else is bound: - // a null output would drop the program's stores without a trace. + // a null view would read zeros or drop the program's stores without a trace. ViewRecord record{}; bool known = false, created = false; if (words[0] == view_token_magic) { @@ -165,9 +179,29 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) ReleaseSRWLockShared(¬e_lock); } Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; - ID3D12Resource* const texture = wrapper && wrapper->own().kind == resource_kind && - InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0 ? static_cast(wrapper->own().real) : nullptr; + const bool alive = wrapper && wrapper->own().kind == resource_kind && InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0; + ID3D12Resource* const texture = !alive ? nullptr : output ? static_cast(wrapper->own().real) + : sampled_address_texture(wrapper); const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + if (!output) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= sizeof(desc); + if (described) std::memcpy(&desc, record.desc, sizeof(desc)); + if (desc.Format) desc.Format = desktop_format(desc.Format); + words[3] = static_cast(desc.Format ? desc.Format : resource.Format) | static_cast(desc.ViewDimension) << 16; + if (!known || record.slot != 18) reason = "an input texture entry is not the token of a shader resource view"; + else if (!texture || (resource.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) + reason = "an input texture has no desktop texture to sample"; + else if (described ? desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an input texture view is not 2D"; + // shortcut: a packed format needs the stand-in rules of the draw path; add them with its first user. + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + views[i] = {texture, 0, 0, true, true, described}; + std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; + continue; + } D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; const bool described = record.desc_bytes >= sizeof(desc); if (described) std::memcpy(&desc, record.desc, sizeof(desc)); @@ -209,6 +243,13 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; views[i] = {placed.alias, offset, bytes, true}; } + // A texture the title filled in memory is brought up to date first. An upload recorded before a later one + // fails only syncs content, as a draw sampling that texture would. + for (std::size_t i = 0; i < inputs && !reason; ++i) + if (views[i].texture && !upload_texture(self, views[i].wrapper, views[i].resource)) { + reason = "an input texture could not be uploaded"; + std::memset(words, 0, sizeof(words)); + } if (reason) { if (!tr->first_refusal) { tr->first_refusal = reason; @@ -230,6 +271,12 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; for (std::size_t i = 0; i < count; ++i, dest.ptr += draw_heap_increment) { const View& view = views[i]; + if (i < inputs && view.texture) { + require_state(self, view.resource, sampled_state(self, view.resource) | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + device_of(the_device)->CreateShaderResourceView(view.resource, + view.described ? reinterpret_cast(view.desc) : nullptr, dest); + continue; + } if (i < inputs) { if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index 143967ed89..a94f217597 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -12,6 +12,12 @@ 3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; 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. + +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 +is 1.0 and a shader resource view of it (device slot 18). After translation all 320 words equal the case's +expectation XOR the bits of 1.0f; dispatch-sampled-unbound (no view created) is refused with one logged reason and +every word keeps the sentinel. Exit 77 when the adapter is not available. """ import os @@ -96,12 +102,64 @@ def store(directory, consumer, dxc, env): f'without a Dispatch and for a refused view; debug layer: {layer}') +# 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' +SAMPLED = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D', XOR) + + +def sample(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + assert words[96:100].hex() == '050d0a3a', 'case A no longer holds v_xor_b32 v5, v5, v6 at byte 96' + C.SPLICE[XOR] = '05190a3a' + code = C.splice(*SAMPLED) + pipeline = C.translate('A', code=code) + assert 'v5 = v5 ^ v12;' in pipeline.hlsl_cs() and pipeline.manifest().endswith( + 'srv 0 buf table 1 0\nsrv 1 tex2d table 1 64\nuav 0 table 1 16\nsmp 0 0x0 0x0 0x0 0x0\n'), pipeline.manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + one = struct.unpack('((*static_cast(device))[127])( + device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); + return SUCCEEDED(hr) ? resource : nullptr; +} + // Case A of startup_gfx2hlsl_compute_check.py through the stand-in's own list: two root constants (slot 39), a // table (slot 35) of two 16-byte hardware buffer descriptors written into the title heap's memory, and Dispatch // (slot 14) of 3x2x2 groups with the slot 67 placeholder bound. Input and output are placed buffers 64 KiB apart // in one allocation, so both alias this process's memory and the result is read from that memory after the queue's // fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered // access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +// dispatch-sampled adds what the sampling variant of the case reads: a committed 1x1 RGBA8 texture filled by +// CopyTextureRegion (list slot 16) and a shader resource view of it (device slot 18) whose token the stand-in +// writes at table byte 64. dispatch-sampled-unbound creates no view, so that entry holds no token. static int dispatch_slot67(void* device, const std::string& mode) { constexpr UINT words = 320; @@ -214,6 +230,25 @@ static int dispatch_slot67(void* device, const std::string& mode) const UINT constants[2] = {0x01234567, 0x9e3779b9}; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; invoke(list, 32, 1, word(&heap)); + if (mode.rfind("dispatch-sampled", 0) == 0) { + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}}; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + const unsigned char rgba[4] = {255, 64, 128, 32}; // the program reads red: 1.0f + std::memcpy(texel, rgba, sizeof(rgba)); + invoke(upload, 9, 0, 0); + 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, {DXGI_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, 256}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MipLevels = 1; + if (mode == "dispatch-sampled") invoke(device, 18, word(texture), word(&view), cpu + 64); + } invoke(list, 25, word(slot67_pipeline)); invoke(list, 33, word(slot67_root)); invoke(list, 39, 0, 2, word(constants), 0); @@ -247,13 +282,7 @@ static int texture_slot67(void* device, const std::string& mode) constexpr UINT width = 32, height = 8, pitch = width * 8, bytes = pitch * height; 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) { - using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, - void*, UINT, const void*, const GUID*, void**); - const D3D12_HEAP_PROPERTIES heap{type}; - void* resource = nullptr; - const HRESULT hr = reinterpret_cast((*static_cast(device))[127])( - device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); - return SUCCEEDED(hr) ? resource : nullptr; + return make_committed(device, type, desc, state); }; const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, From 509dc53b8925ed30765c9b5b3644f4a9f0514958 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:09:43 +0100 Subject: [PATCH 18/25] Check a compute manifest without entry values at Dispatch Co-Authored-By: Claude Fable 5.2 --- tests/startup_compute_dispatch_texture_check.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index a94f217597..a4c29c7c21 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -12,6 +12,7 @@ 3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; 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. 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 @@ -98,8 +99,18 @@ def store(directory, consumer, dxc, env): assert got == untouched, 'a refused Dispatch wrote the texture' refused = lines(result, 'refused: ') assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] - print(f'texture output: all {halves} halves match after translation (64 changed); untouched before translation, ' - f'without a Dispatch and for a refused view; debug layer: {layer}') + + # The same compiled program under a manifest without entry values (the program reads none of its three): the + # runtime binds no constants. The manifest is edited here; the translator writes `ud 0` for a root without them. + manifest = cache / f'{key:016x}.txt' + kept = [line for line in manifest.read_text().splitlines() if not line.startswith('udsrc ')] + assert len(kept) == 5 and kept[3] == 'ud 3', kept + manifest.write_bytes(('\n'.join(kept).replace('ud 3', 'ud 0') + '\n').encode()) + got, result = run(directory, consumer, env, 'texture-store', layout) + assert got == expected and lines(result, 'translated: 0 entry values, 0 inputs, 1 outputs'), result.stderr[-3000:] + clean(result) + print(f'texture output: all {halves} halves match after translation (64 changed) and without entry values; ' + f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') # v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed From d3c396ccac70de8d5dbf73c28b18a7b6aee4f591 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:10:03 +0100 Subject: [PATCH 19/25] Document texture views and the census of translated compute Dispatch Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index a3592168ce..077a3554dd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14730,11 +14730,13 @@ ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V ## Translated compute Dispatch -With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. This first slice binds raw buffers only: inputs and outputs named by 16-byte hardware buffer descriptors in the compute descriptor tables of slot 35, and entry values from the compute root constants of slots 37 and 39. An input must resolve to a complete GPU-backed range; an output must be a placed buffer that aliases the caller's memory and allows unordered access. Any other manifest line (textures, samplers, root views, other entry-value sources) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason and records nothing. +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format on a texture not bound to another slot of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, `stride` and `descword3` entry values) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason and records nothing. No view is ever bound null. -`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. The log line `x2w-render compute dispatches: translated , refused , no translation ` follows the render totals. +`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. `tests/startup_compute_dispatch_texture_check.py` does the same for a program that stores to a 32x8 RGBA16_FLOAT texture (1024 halves read back through CopyTextureRegion; controls: before translation, without a Dispatch, a texture without unordered access) and for the raw buffer program with a level-zero sample of a 1x1 texture XORed into each stored word (control: no view at the table entry). The texture output program is also bound under a manifest edited to declare no entry values. -Measured on one fixture program. Programs with textures, samplers or outputs in memory that is not aliased are not dispatched. +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and the 40 keys with the most calls, each with its count, the calls recorded and the first refused table descriptor. + +Measured on three fixture programs. The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. ```powershell cmake --build --preset dev --target startup_stream_consumer From 70b27f2ada77c940834c05e51b3ad222bd7d4b4d Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:21:56 +0100 Subject: [PATCH 20/25] Check the device on every 64th translated Dispatch and drop a liveness test The device check drains the debug layer; a draw runs it on every 64th call and the queue's execute drains the rest. A view token whose resource the caller released is the caller's misuse, as on the draw path. Co-Authored-By: Claude Fable 5.2 --- src/startup_stubs/d3d12_compute_dispatch.inl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 263dd1f709..24f5463bd7 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -179,9 +179,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) ReleaseSRWLockShared(¬e_lock); } Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; - const bool alive = wrapper && wrapper->own().kind == resource_kind && InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0; - ID3D12Resource* const texture = !alive ? nullptr : output ? static_cast(wrapper->own().real) - : sampled_address_texture(wrapper); + ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + : output ? static_cast(wrapper->own().real) : sampled_address_texture(wrapper); const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; if (!output) { D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; @@ -322,7 +321,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) } ++tr->translated; ReleaseSRWLockExclusive(&draw_lock); - check_device("translated dispatch", 14); + static LONG checks; // as translated draws do: the queue's execute drains the rest + if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", 14); InterlockedIncrement(&compute_dispatches_translated); static LONG logged; if (first_calls(logged, 8)) From d0b9e774a5e81a4f40ebc7bc72fd282764ed28dd Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:27:36 +0100 Subject: [PATCH 21/25] Compute dispatch: allow two outputs of one texture, refuse packed outputs, print every census key A texture is refused only when the same call reads and writes it; two outputs of one texture share the unordered access state. A packed output view format gets its own refusal reason. The census prints every dispatched key instead of the first 40, and the wording on refused calls says what may already be recorded (an input texture upload). Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 4 ++-- src/startup_stubs/d3d12_compute_dispatch.inl | 19 ++++++++++++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 077a3554dd..c15bca43c4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14730,11 +14730,11 @@ ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V ## Translated compute Dispatch -With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format on a texture not bound to another slot of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, `stride` and `descword3` entry values) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason and records nothing. No view is ever bound null. +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format that is not packed, on a texture that is not also an input of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, `stride` and `descword3` entry values) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason: no Dispatch is recorded and nothing is bound (the upload of an input texture the caller filled in memory may already be recorded; it only syncs content). No view is ever bound null. `tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. `tests/startup_compute_dispatch_texture_check.py` does the same for a program that stores to a 32x8 RGBA16_FLOAT texture (1024 halves read back through CopyTextureRegion; controls: before translation, without a Dispatch, a texture without unordered access) and for the raw buffer program with a level-zero sample of a 1x1 texture XORed into each stored word (control: no view at the table entry). The texture output program is also bound under a manifest edited to declare no entry values. -The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and the 40 keys with the most calls, each with its count, the calls recorded and the first refused table descriptor. +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled ` follows the render totals; "not modelled" counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and every dispatched key by call count, each with its count, the calls recorded and the first refused table descriptor. Measured on three fixture programs. The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 24f5463bd7..05cad01d2c 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -5,8 +5,9 @@ // (`srv tex2d table ` inputs, `uav tex2d 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. Any other manifest line makes the translation -// unavailable; a dispatch that cannot be bound completely is refused with one -// reason and records nothing on the desktop list. +// unavailable; a dispatch that cannot be bound completely is refused with one reason and records no Dispatch and +// binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only +// syncs content). struct ComputeTranslation { struct Slot { int a, b; bool texture; }; // root parameter and byte offset (views), or parameter and word (entry values) @@ -213,11 +214,15 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) 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"; - for (std::size_t other = 0; other < i && !reason; ++other) - if (views[other].resource == texture) reason = "an output texture is bound to another slot of the dispatch"; + // 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) + if (views[input].wrapper == wrapper) reason = "an output texture is also an input of the dispatch"; views[i] = {texture, 0, 0, true, true, described}; std::memcpy(views[i].desc, &desc, sizeof(desc)); + views[i].wrapper = wrapper; continue; } if (!output) { @@ -331,8 +336,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) return true; } -// With the periodic totals: refused dispatches by the first refusal reason of their key, then the keys with the -// most dispatches. The per-call log lines above share one small budget, so they cannot rank keys. +// With the periodic totals: refused dispatches by the first refusal reason of their key, then every key by +// dispatch count. The per-call log lines above share one small budget, so they cannot rank keys. void log_compute_census() { struct Reason { const char* text; u64 keys, dispatches; }; @@ -361,7 +366,7 @@ void log_compute_census() log("x2w-render compute census: %zu keys dispatched", keys.size()); for (const Reason& r : reasons) log("x2w-render compute census reason \"%s\": %llu keys, %llu dispatches", r.text, r.keys, r.dispatches); - for (std::size_t i = 0; i < keys.size() && i < 40; ++i) + for (std::size_t i = 0; i < keys.size(); ++i) log("x2w-render compute census key %016llx: %llu dispatches, %llu translated, first refusal: %s [%08x %08x %08x %08x]", keys[i].key, keys[i].dispatches, keys[i].translated, keys[i].first_refusal ? keys[i].first_refusal : "none", keys[i].refusal_words[0], keys[i].refusal_words[1], keys[i].refusal_words[2], keys[i].refusal_words[3]); From c821b4b2730e0e4b8e00fa18e6148a132ed15844 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:28:11 +0800 Subject: [PATCH 22/25] startup: avoid calling the compute driver after process termination begins The slot 67 cache owns desktop COM objects until module teardown. During process termination, the driver can already be shut down when static destructors run. Keep normal reference release on explicit unload and skip driver calls only during process termination. AI-assisted with Codex (GPT-6.2 Astra, xhigh). --- src/d3d12_xs_shim.cpp | 7 +++++++ src/startup_stubs/d3d12_compute_dispatch.inl | 9 +++++++++ src/startup_stubs/d3d12_xs_device.cpp | 2 ++ 3 files changed, 18 insertions(+) diff --git a/src/d3d12_xs_shim.cpp b/src/d3d12_xs_shim.cpp index c026600337..887b5f3897 100644 --- a/src/d3d12_xs_shim.cpp +++ b/src/d3d12_xs_shim.cpp @@ -227,6 +227,13 @@ extern "C" HRESULT WINAPI d3d12_xs_CreateRootSignatureDeserializer( bool x2w_d3d12_permissive(); HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parameters, REFIID iid, void** device); +extern bool x2w_d3d12_process_terminating; + +extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) +{ + if (reason == DLL_PROCESS_DETACH && reserved) x2w_d3d12_process_terminating = true; + return TRUE; +} extern "C" HRESULT WINAPI d3d12_xs_XboxCreateDevice( IUnknown* adapter, const void* parameters, REFIID iid, void** device) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 45d590c9da..acce44937d 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -14,6 +14,15 @@ struct ComputeTranslation { std::vector uds, srvs, uavs; x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; + ~ComputeTranslation() + { + // The per-process cache is destroyed during DLL detach. A driver may already have shut + // down when the process is terminating. Explicit unload still releases both references. + if (x2w_d3d12_process_terminating) { + pipeline.Detach(); + root.Detach(); + } + } }; std::unordered_map& compute_translations() { static std::unordered_map m; return m; } LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0e45d60a6c..7fa0b41adb 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -90,6 +90,8 @@ #include #include +bool x2w_d3d12_process_terminating = false; + // The heap-indexing bits src/d3d12_xs_shim.cpp removed for the blob it returned at exactly this // buffer. A build that compiles this file without the shim (offscreen_check) links the fallback, 0. extern "C" std::uint32_t x2w_stripped_root_flags(const void* blob, std::size_t bytes); From 1f5fb5e41d49154d5c6f431e21679cd8f14962af Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:51:09 +0100 Subject: [PATCH 23/25] Repair a broken line in the dispatch check Co-Authored-By: Claude Fable 5.2 --- tests/startup_compute_dispatch_check.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py index 2627d95017..a61c44910a 100644 --- a/tests/startup_compute_dispatch_check.py +++ b/tests/startup_compute_dispatch_check.py @@ -108,8 +108,7 @@ def main(consumer, dxc, adapter): got, result = dispatch(directory, consumer, env, mode) assert got == untouched, f'{mode}: a refused Dispatch wrote the output' refused = lines(result, 'refused: ') - assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused} -{result.stderr[-3000:]}' + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused}\n{result.stderr[-3000:]}' print(f'startup_compute_dispatch: PASS on {adapter} (all {C.WORDS} words match after translation and with the ' 'same root set again; untouched before translation, without a Dispatch and for 6 refusals)') From 76ce41bcb6fd7f807117dc63369161051e413f1c Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:58:27 +0100 Subject: [PATCH 24/25] Pin four existing texture dispatch refusals: integer view format, manifest version, stage, output also an input Co-Authored-By: Claude Fable 5.2 --- .../startup_compute_dispatch_texture_check.py | 19 +++++++++++++++++++ tests/startup_stream_consumer.cpp | 13 +++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py index c1656637a2..4ec3eb5088 100644 --- a/tests/startup_compute_dispatch_texture_check.py +++ b/tests/startup_compute_dispatch_texture_check.py @@ -100,6 +100,25 @@ def store(directory, consumer, dxc, env): refused = lines(result, 'refused: ') assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + # Refusals the runtime already had, each with its one logged reason and an untouched texture: an integer view + # format, another manifest version, another stage, and (with a manifest line added here for a view the consumer + # creates) the output texture named as an input too. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + for mode, old, new, reason in ( + ('texture-store-uint', '', '', 'an output texture format is not a float or normalized one'), + ('texture-store', 'x2w-manifest 2', 'x2w-manifest 3', 'manifest version'), + ('texture-store', 'stage cs', 'stage ps', 'not a compute manifest'), + ('texture-store-self', 'uav 0 tex2d', 'srv 0 tex2d table 1 0' + chr(10) + 'uav 0 tex2d', + 'an output texture is also an input of the dispatch')): + assert not old or original.count(old) == 1, original + manifest.write_bytes(original.replace(old, new).encode() if old else original.encode()) + got, result = run(directory, consumer, env, mode, layout) + refused = lines(result, 'refused: ') + assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( + mode, reason, refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + # The same compiled program under a manifest without entry values (the program reads none of its three): the # runtime binds no constants. The manifest is edited here; the translator writes `ud 0` for a root without them. manifest = cache / f'{key:016x}.txt' diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 3a31231524..5700694f8f 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -295,7 +295,8 @@ static int dispatch_slot67(void* device, const std::string& mode) // unordered access view of it (device slot 19) whose token the stand-in writes into the title heap at table byte 64, // three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go // to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture -// without unordered access, so the stand-in records its view as not created. +// without unordered access, so the stand-in records its view as not created. texture-store-uint makes the texture +// and its view RGBA16_UINT; 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; @@ -303,7 +304,8 @@ static int texture_slot67(void* device, const std::string& mode) const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { return make_committed(device, type, desc, state); }; - const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, + 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, {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}, @@ -329,11 +331,14 @@ 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{DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + const D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + D3D12_SHADER_RESOURCE_VIEW_DESC read{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + read.Texture2D.MipLevels = 1; + 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, {DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 1, pitch}}; + source.PlacedFootprint = {0, {format, width, height, 1, pitch}}; D3D12_TEXTURE_COPY_LOCATION result = source; result.pResource = static_cast(readback); const UINT constants[3] = {1, 2, 3}; From f5b0303944b8697f763e54978e25ddf986382ebb Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:38:53 +0100 Subject: [PATCH 25/25] Drop the repeated compute root reset left by merging two slot 14 snapshots list_compute_root cleared compute_srv_bound and recomputed compute_root_has_arguments twice; the second copy came from the second #1974 snapshot merge and changed nothing. Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/d3d12_xs_device.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 7fa0b41adb..7aba60e34f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2517,9 +2517,6 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } - pass.compute_srv_bound = 0; - // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. - pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { if (pass.desktop_compute_root.Get() != pass.compute_root) pass.desktop_compute_upload_srvs.fill(0);