From 0192a5ed9904a952106e3e1b1f90a78eb9e4ae5f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 19:53:44 +0100 Subject: [PATCH 01/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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/35] 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 f5c3c857314c7155266fd02c1a5e30d3a4a48100 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:51:45 +0100 Subject: [PATCH 22/35] startup: compute input named by a resource heap record a root constant indexes gfx2hlsl.py lowers one form of a register-offset load through the directly indexed resource heap pointer of a compute root signature: s_lshl_b32 R, , 5 s_load_dwordx4 D, s[H:H+1], R ; s[H+1] a constant zero, no offset: with no write of R and no branch target in between. D is a buffer descriptor and the manifest names it `srv buf heap rootconst `. Every other form keeps a refusal that names it, including an index read from a buffer. The stand-in records the title memory of the list's view heap on every slot 32 call (it kept only the sampler heap and, for oversized heaps, the wrapper) and a Dispatch reads the 16-byte descriptor at byte `word << 5` of that memory, then binds it through the path a table record takes. A record outside the heap refuses the dispatch and binds nothing. Checks: tests/startup_gfx2hlsl_heap_record_check.py (manifest and HLSL exact, 19 refused controls, one translator mutation, LLVM 15 reassembly) and tests/startup_compute_dispatch_heap_check.py on WARP and a physical adapter. Refs #2274 Co-Authored-By: Claude Fable 5.2 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 7 +- docs/experiments.md | 16 ++ src/startup_stubs/d3d12_compute_dispatch.inl | 15 +- src/startup_stubs/d3d12_draw.inl | 9 +- src/startup_stubs/d3d12_xs_device.cpp | 1 + tests/startup_compute_dispatch_heap_check.py | 87 +++++++ tests/startup_gfx2hlsl_heap_record_check.py | 238 +++++++++++++++++++ tests/startup_stream_consumer.cpp | 16 +- tools/startup/gfx2hlsl.py | 46 ++++ 11 files changed, 429 insertions(+), 9 deletions(-) create mode 100644 tests/startup_compute_dispatch_heap_check.py create mode 100644 tests/startup_gfx2hlsl_heap_record_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a0229f0b06..ce0f222b39 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -92,6 +92,7 @@ jobs: (["tests/startup_compute_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), @@ -246,6 +247,7 @@ jobs: tests/startup_gfx2hlsl_join_symbols_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ + tests/startup_gfx2hlsl_heap_record_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2851ded0c5..e802904362 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c4165cc7ff..3608b2a395 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2944,6 +2944,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_gather_lz_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -3544,8 +3546,11 @@ if(EXISTS "${INTAKE_PYTHON}") 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}) + add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} - PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + startup_compute_dispatch_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index cb55406acd..75ce45cf69 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14814,6 +14814,22 @@ cmake --build --preset dev --target startup_stream_consumer ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V ``` +### An input named by a resource heap record + +A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. + +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. + +`tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). + +Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. + +```powershell +python -B tests/startup_gfx2hlsl_heap_record_check.py --llvm-mc llvm-mc-15 +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_" -V +``` + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 05cad01d2c..54dce4f3fc 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -10,7 +10,9 @@ // syncs content). struct ComputeTranslation { - struct Slot { int a, b; bool texture; }; // root parameter and byte offset (views), or parameter and word (entry values) + // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root + // constant (parameter and word) that indexes its 32-byte record in the list's view heap. + struct Slot { int a, b; bool texture, heap; }; 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 @@ -78,6 +80,9 @@ const char* load_compute_translation(ComputeTranslation& tr) 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(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({a, b, false, true}); else if (std::sscanf(line.c_str(), "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() && @@ -157,11 +162,15 @@ 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), slot.texture ? 32 : 16) : 0; + // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by + // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.a < 0 || slot.b < 0 ? 0 + : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) + : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); std::memset(words, 0, 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"; + reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; break; } std::memcpy(words, reinterpret_cast(entry), entry_bytes); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index b33c4bfddc..a5b2e10cc0 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2336,10 +2336,12 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign } // List slot 32, SetDescriptorHeaps. Track the title's shader-visible sampler -// source while translated draws use their own physical descriptor heaps. +// source while translated draws use their own physical descriptor heaps, and the +// title memory of the view heap for a program that indexes the heap itself. void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; + x2w_startup::ViewTable heap_records; u64 view_heap = 0; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); @@ -2349,6 +2351,10 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && heap.logical_count > heap.count) view_heap = heap.wrapper; + if (heap.wrapper == reinterpret_cast(heaps[i]) && + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, + heap.increment, heap.desktop_gpu); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2364,6 +2370,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* } pass.source_view_heap = view_heap; pass.title_samplers = source; + pass.title_view_heap = heap_records; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a658754e6f..f8932b12a4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2298,6 +2298,7 @@ struct Pass { x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; + x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) u64 root_address[16] = {}; // title address of each root descriptor x2w_root_constants::Store constants; // graphics root constants (slot 40) unsigned char constant_words_bound[16] = {}; diff --git a/tests/startup_compute_dispatch_heap_check.py b/tests/startup_compute_dispatch_heap_check.py new file mode 100644 index 0000000000..c5addfad71 --- /dev/null +++ b/tests/startup_compute_dispatch_heap_check.py @@ -0,0 +1,87 @@ +"""A translated compute program whose input is the resource heap record a root constant indexes (list slot 14). + +usage: startup_compute_dispatch_heap_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_record_check.py as a device slot 67 pipeline, with a +root signature that indexes the resource heap directly, and records the descriptor heap, the pipeline, the root +signature, three root constants, one table and Dispatch(3, 2, 2). The output descriptor is at table byte 16 as in +startup_compute_dispatch_check.py. The input descriptor is only in heap record 2 (heap byte 64), which the third +root constant indexes; heap bytes 0 and 32 hold the output's descriptor, so a dispatch that ignores the index or +scales it by 16 is refused instead of passing. Three runs share one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the heap record and all 320 words equal the + expectation of case A of startup_gfx2hlsl_compute_check.py (the program computes the same words); +3. dispatch-heap-outside (the constant is 0x07ffffff, a record past the heap): 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 subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +OUTSIDE = "a heap record is outside the list's view heap" + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and H.INDEX_WORD == 2, 'the consumer hard-codes the dispatch and the index word' + (directory / 'program').write_bytes(H.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == H.MANIFEST + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + 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-heap-outside') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and OUTSIDE in refused[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{OUTSIDE}": 1 keys, 1 dispatches'), census + print(f'startup_compute_dispatch_heap: PASS on {adapter} (all {C.WORDS} words match through heap record 2; ' + 'untouched before translation and for a record outside the heap)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py new file mode 100644 index 0000000000..bdbb0f97ac --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -0,0 +1,238 @@ +"""A compute program that reads a buffer descriptor from the resource heap record a root constant indexes. + +usage: startup_gfx2hlsl_heap_record_check.py [--llvm-mc ] + +The root signature has three root constants (s4-s6), one descriptor table (s7) and the directly indexed +resource heap (root flag 0x400, pointer in s8). The program is case A of startup_gfx2hlsl_compute_check.py +with its input descriptor loaded as + + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +after s9 is set to zero. gfx2hlsl.py names that input `srv 0 buf heap rootconst 0 2` in the manifest: the +dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are +compared whole. Every other form keeps a refusal: another shift, another index, an index register written +again, a branch target between the shift and the load, a high word that is not a constant zero, an offset +modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the +record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +""" +import argparse +import struct + +from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, TGID_Z, assemble, refused, tidig + +GROUP, GROUPS = (2, 3, 4), (3, 2, 2) +RSRC2 = (9 << 1) | TGID_X | TGID_Y | TGID_Z | tidig(3) # s0-s3, three constants, the table, the heap pointer +INDEX_WORD = 2 # the root constant word the program shifts + +SHIFT, CLEAR, LOAD = 's_lshl_b32 s6, s6, 5', 's_mov_b32 s9, 0', 's_load_dwordx4 s[16:19], s[8:9], s6' +READ = 'buffer_load_dword v5, v4, s[16:19], 0 offen' +WRITE = 'buffer_store_dword v5, v4, s[20:23], 0 offen' +PROGRAM = ( + 's_mov_b32 s12, s7', 's_mov_b32 s13, 0', 's_load_dwordx4 s[20:23], s[12:13], 0x10', + 's_mov_b32 s14, s9', CLEAR, SHIFT, LOAD, 's_waitcnt lgkmcnt(0)', + 'v_mad_u32_u24 v3, v1, 2, v0', 'v_mad_u32_u24 v3, v2, 6, v3', 's_mul_i32 s24, s10, 3', 's_add_u32 s24, s24, s14', + 's_mul_i32 s25, s11, 6', 's_add_u32 s24, s24, s25', 's_mul_i32 s24, s24, 24', 'v_add_nc_u32 v3, s24, v3', + 'v_lshlrev_b32 v4, 2, v3', READ, 'v_mul_lo_u32 v6, v3, s5', 'v_add_nc_u32 v6, s4, v6', 's_waitcnt vmcnt(0)', + 'v_mul_lo_u32 v5, v5, 33', 'v_xor_b32 v5, v5, v6', WRITE, 's_endpgm') +# Every instruction of the program and of the controls, recorded from llvm-mc 15. +ENCODED = { + 's_mov_b32 s12, s7': '07038cbe', 's_mov_b32 s13, 0': '80038dbe', + 's_load_dwordx4 s[20:23], s[12:13], 0x10': '060508f4100000fa', 's_mov_b32 s14, s9': '09038ebe', + CLEAR: '800389be', SHIFT: '0685068f', LOAD: '040408f40000000c', 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 'v_mad_u32_u24 v3, v1, 2, v0': '030043d501050104', 'v_mad_u32_u24 v3, v2, 6, v3': '030043d5020d0d04', + 's_mul_i32 s24, s10, 3': '0a831893', 's_add_u32 s24, s24, s14': '180e1880', 's_mul_i32 s25, s11, 6': '0b861993', + 's_add_u32 s24, s24, s25': '18191880', 's_mul_i32 s24, s24, 24': '18981893', 'v_add_nc_u32 v3, s24, v3': '1806064a', + 'v_lshlrev_b32 v4, 2, v3': '82060834', READ: '001030e004050480', 'v_mul_lo_u32 v6, v3, s5': '060069d5030b0000', + 'v_add_nc_u32 v6, s4, v6': '040c0c4a', 's_waitcnt vmcnt(0)': '703f8cbf', 'v_mul_lo_u32 v5, v5, 33': '050069d505430100', + 'v_xor_b32 v5, v5, v6': '050d0a3a', WRITE: '001070e004050580', 's_endpgm': '000081bf', + 's_lshl_b32 s6, s6, 4': '0684068f', 's_lshl_b32 s6, s6, 6': '0686068f', 's_lshl_b32 s6, s6, s5': '0605068f', + 's_lshl_b32 s6, s14, 5': '0e85068f', 's_mov_b32 s9, 1': '810389be', 's_mov_b32 s9, s5': '050389be', + 's_load_dwordx4 s[16:19], s[8:9], s6 offset:0x20': '040408f42000000c', + 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', + 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', + 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', + 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', +} +TABLE_LOAD = 's_load_dwordx4 s[28:31], s[12:13], 0x20' +JUMP = ('s_cmp_eq_u32 s4, 0', 's_cbranch_scc0 1', 's_nop 0') # the instruction after the s_nop is a branch target + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf heap rootconst 0 2 +uav 0 table 1 16 +""" +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +RWByteAddressBuffer u0 : register(u0); +""" +MAIN = """\ +[numthreads(2, 3, 4)] +void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) { + uint s6 = 0, s9 = 0, s10 = 0, s11 = 0, s13 = 0, s14 = 0, s24 = 0, s25 = 0; + uint v0 = 0, v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0; + uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0; + s9 = gid.x; + s10 = gid.y; + s11 = gid.z; + v0 = tid.x; + v1 = tid.y; + v2 = tid.z; + s13 = 0x00000000u; + s14 = s9; + s9 = 0x00000000u; + s6 = ud2 << (0x00000005u & 31); + scc = s6 != 0; + v3 = (v1 & 0xffffffu) * (0x00000002u & 0xffffffu) + v0; + v3 = (v2 & 0xffffffu) * (0x00000006u & 0xffffffu) + v3; + s24 = s10 * 0x00000003u; + s24 = s24 + s14; + s25 = s11 * 0x00000006u; + s24 = s24 + s25; + s24 = s24 * 0x00000018u; + v3 = s24 + v3; + v4 = v3 << (0x00000002u & 31); + a = v4 + 0; + v5 = r0.Load(a + 0); + v6 = v3 * ud1; + v6 = ud0 + v6; + v5 = v5 * 0x00000021u; + v5 = v5 ^ v6; + a = (v4 + 0) & 0xfffffffcu; + u0.Store(a, v5); +} +""" + + +def root_blob(table_range=False, flags=0x400): + """RTS0: param 0 = three root constants (b0), param 1 = a descriptor table, the resource heap directly indexed. + table_range gives the table one SRV range, as startup_gfx2hlsl_compute_check.root_blob does for a device.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + ranges = struct.pack('<6I', 0, 1, 0, 0, 0, 0xffffffff) if table_range else b'' + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8 + len(ranges), flags) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 3) + struct.pack('<2I', len(ranges) // 24, table_at + 8) + ranges) + part = b'RTS0' + struct.pack('(cpu), descriptors, sizeof(descriptors)); - const UINT constants[2] = {0x01234567, 0x9e3779b9}; + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; + if (heap_record) + for (const UINT at : {0u, 32u, 64u}) + std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; invoke(list, 32, 1, word(&heap)); if (mode.rfind("dispatch-sampled", 0) == 0) { @@ -251,7 +259,7 @@ static int dispatch_slot67(void* device, const std::string& mode) } invoke(list, 25, word(slot67_pipeline)); invoke(list, 33, word(slot67_root)); - invoke(list, 39, 0, 2, word(constants), 0); + invoke(list, 39, 0, heap_record ? 3 : 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; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a33bc741fc..b8b538f25b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1693,6 +1693,8 @@ def translate(self): } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) + self.heap_index_was = {} # the marks the current instruction's destinations held before it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -1721,6 +1723,7 @@ def translate(self): # branch-free program is past it too (dead code). self.past_entry = bool(self.blocks) or 0 in targets if off in targets: + self.heap_index.clear() # another path into the join may hold a different word pre_uniform = { r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) if r not in self.varying_s and r not in self.masks @@ -1950,6 +1953,11 @@ def one(self, name, asm): if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] self.last_v = None + if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state + # Any write ends a register's mark; the lowering below sets the new one, if any. + wrote = scalar_destinations(name, asm) + wrote = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote} term = self.lower(base, asm, ops, mods) uniform_written = self._uniform_written if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: @@ -2543,6 +2551,15 @@ def known(tok): high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) self.set_s(d, expr, scc=scc) + if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) + and int(srcs[1], 0) == 5): + # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a + # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). + r = reg_range(srcs[0]) + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): + self.heap_index[d] = ('buffer',) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -2794,8 +2811,31 @@ def op_s_load_dwordx4(self, ops, mods, count=4): self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return + if p[1] == ('resheap',) and self.kind == 'cs': + return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def heap_record(self, dst, base, token, imm, count): + """s_load_dwordx4 D, , R in a compute program, where R is a root constant word + shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in + the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch + reads the record. Only this exact form is modelled.""" + what = 's_load of a resource heap record' + r = reg_range(token) + index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + if index == ('buffer',): + raise Unsupported('%s whose index is read from a buffer' % what) + if not index or index[0] != 'rootconst': + raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) + if count != 4: + raise Unsupported('%s of %d dwords' % (what, count)) + if imm is not None: + raise Unsupported('%s with offset:%#x' % (what, imm)) + if self.sym.get(base[2]) != ('const', 0): + raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + for i in range(count): + self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" if len(ops) != 3: @@ -2956,6 +2996,8 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) + if hasattr(self, 'heap_index'): + self.heap_index[dst[1] + i] = ('bufword',) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -5473,10 +5515,14 @@ def manifest(self): where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] + elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': + where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) for (source, off), r in self.uavs.items(): + if source[0] != 'table': + raise Unsupported('store through %s' % (source,)) where = 'table %d %d' % (source[1], off) if r['kind'] == 'raw': lines.append('uav %d %s' % (r['index'], where)) From b6bc3c3065385d7688e72efb5b60269ddb054f53 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:59:57 +0100 Subject: [PATCH 23/35] startup: drop a heap record control whose branch target was inside an instruction The second positive case of startup_gfx2hlsl_heap_record_check.py branched to the second dword of the two-dword heap load. The case with a branch target before the shift already covers the form outside the entry block. The experiments entry now says that WARP's descriptor increment is not 32 bytes. Refs #2274 Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 2 +- tests/startup_gfx2hlsl_heap_record_check.py | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 75ce45cf69..8fd58e3d6e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14822,7 +14822,7 @@ Every other form keeps a refusal that names it: another shift or index, an index `tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). -Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. +Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes (WARP is such an adapter, so its run covers the literal offset only) is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. ```powershell python -B tests/startup_gfx2hlsl_heap_record_check.py --llvm-mc llvm-mc-15 diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py index bdbb0f97ac..0ea8575862 100644 --- a/tests/startup_gfx2hlsl_heap_record_check.py +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -146,10 +146,8 @@ def check_lowering(): hlsl = pipe.hlsl_cs() assert pipe.manifest() == MANIFEST, pipe.manifest() assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] - # A branch that is not a target between the shift and the load, and a branch target before the shift, change - # nothing. + # A branch target before the shift changes nothing: the form is not tied to the entry block. assert pipeline({SHIFT: JUMP + (SHIFT,)}).manifest() == MANIFEST - assert pipeline({SHIFT: (SHIFT,) + JUMP[:2], LOAD: (LOAD, 's_nop 0')}).manifest() == MANIFEST def check_refusals(): From fdba77975d0f5c0c21caf03047288ae3e00dc38b Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:21:22 +0100 Subject: [PATCH 24/35] startup: read the stage kind as the other handlers do in the heap load A check added on main calls op_s_load_dwordx8 on a stage built without a kind; the heap record branch read self.kind directly. Co-Authored-By: Claude Fable 5.2 --- tools/startup/gfx2hlsl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5ef34f693a..7e4778c499 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3310,7 +3310,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return - if p[1] == ('resheap',) and self.kind == 'cs': + if p[1] == ('resheap',) and getattr(self, 'kind', None) == 'cs': return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) 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 25/35] 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 26/35] 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 27/35] 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 ba79c8b0880e6b8e560d55dcc002c3bb680d3177 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:27:45 +0100 Subject: [PATCH 28/35] startup: bind a compute heap record whose index is a table buffer word at a dispatch-constant offset A compute program that reads its heap record index with s_buffer_load from an unmodified table buffer, at a literal byte offset or at a root constant word times a literal plus a literal (dword-aligned), then shifts it left by 5 for the heap s_load, is translated: the manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the runtime reads that word from the recording's upload memory, where no GPU command writes, and binds the record it indexes. A word outside the buffer or outside upload memory refuses the dispatch with one reason. Every other index source keeps the buffer refusal. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 8 +- src/startup_stubs/d3d12_compute_dispatch.inl | 51 +++++- ...tartup_compute_dispatch_heap_word_check.py | 94 ++++++++++ tests/startup_gfx2hlsl_heap_record_check.py | 16 +- tests/startup_gfx2hlsl_heap_word_check.py | 160 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 23 ++- tools/startup/gfx2hlsl.py | 86 ++++++++-- 9 files changed, 406 insertions(+), 35 deletions(-) create mode 100644 tests/startup_compute_dispatch_heap_word_check.py create mode 100644 tests/startup_gfx2hlsl_heap_word_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 9d3d76bc35..74eed51e0d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -94,6 +94,7 @@ jobs: (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_word_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), @@ -257,6 +258,7 @@ jobs: tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ tests/startup_gfx2hlsl_heap_record_check.py \ + tests/startup_gfx2hlsl_heap_word_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/AGENTS.md b/AGENTS.md index ab4d690cc2..a7b600870c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,6 +168,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_word_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 22fed478a8..8ef9897a42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3006,6 +3006,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") + add_test(NAME startup_gfx2hlsl_heap_word COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_word_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -3658,8 +3660,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} - startup_compute_dispatch_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 2a0b2433e3..f590f25be0 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -11,8 +11,15 @@ struct ComputeTranslation { // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root - // constant (parameter and word) that indexes its 32-byte record in the list's view heap. - struct Slot { int a, b; bool texture, heap; }; + // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param + // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: + // at alone) is the index. + struct Slot { + int a, b; + bool texture, heap; + int word_param = -1, word_byte = 0; + std::uint32_t at = 0, times = 0; + }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // only an absent manifest can become ready later @@ -81,7 +88,7 @@ const char* load_compute_translation(ComputeTranslation& tr) continue; } unsigned i = 0, x = 0, y = 0, z = 0, w = 0; - int a = 0, b = 0, used = 0; + int a = 0, b = 0, c = 0, d = 0, used = 0; const auto whole = [&] { return used == static_cast(line.size()); }; if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; @@ -92,6 +99,12 @@ const char* load_compute_translation(ComputeTranslation& tr) else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u%n", &i, &a, &b, &x, &used) == 4 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({-1, 0, false, true, a, b, x}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u rootconst %d %d times %u%n", &i, &a, &b, &x, + &c, &d, &y, &used) == 7 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({c, d, false, true, a, b, x, y}); else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) tr.uavs.push_back({a, b}); else if (std::sscanf(line.c_str(), "uav %u tex2d float table %d %d channels 4%n", &i, &a, &b, &used) == 3 && whole() && @@ -174,12 +187,34 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; - // A heap record sits at the 32-bit byte offset the program computes, the root constant word shifted left by - // 5, in the title memory of the list's view heap: a literal byte offset, as a table's is. - const u64 entry = slot.a < 0 || slot.b < 0 ? 0 - : slot.heap ? pass.title_view_heap.record(std::uint32_t{pass.compute_constants.word(slot.a, slot.b)} << 5, 16) - : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); + std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); + if (slot.word_param >= 0) { + // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command + // writes there), at the dword-aligned 32-bit byte offset the program reads it at. + const u64 table_entry = pass.compute_tables.table(slot.word_param).record(static_cast(slot.word_byte), 16); + if (!table_entry || !x2w_local::readable(reinterpret_cast(table_entry), 16)) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast(table_entry), 16); + const std::uint32_t at = slot.at + index * slot.times; + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + if (words[0] == view_token_magic || !list_upload_range(self, address + at, 4).resource) { + reason = "a heap index word is not in the list's upload memory"; + break; + } + if (u64{at} + 4 > u64{stride ? stride : 1} * words[2]) { + reason = "a heap index word is outside its table buffer"; + break; + } + std::memcpy(&index, reinterpret_cast(address + at), 4); + } + // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the + // title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.heap ? (slot.word_param >= 0 || slot.a >= 0 ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast(slot.b), slot.texture ? 32 : 16); const std::size_t entry_bytes = slot.texture ? 32 : 16; if (!entry || !x2w_local::readable(reinterpret_cast(entry), entry_bytes)) { reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; diff --git a/tests/startup_compute_dispatch_heap_word_check.py b/tests/startup_compute_dispatch_heap_word_check.py new file mode 100644 index 0000000000..4ddb8ad31f --- /dev/null +++ b/tests/startup_compute_dispatch_heap_word_check.py @@ -0,0 +1,94 @@ +"""A translated compute program whose input is the resource heap record a word of a table buffer indexes (slot 14). + +usage: startup_compute_dispatch_heap_word_check.py + +The consumer creates the program of startup_gfx2hlsl_heap_word_check.py as a device slot 67 pipeline and records it +as startup_compute_dispatch_heap_check.py does, with root constant word 2 set to 1 and a buffer in the recording's +upload memory (list slot 148) at table byte 96. Word 288 + 336 * 1 of that buffer is 2, the heap record of the +input. Heap records 0 and 1 hold the output's descriptor and every other word of the buffer names one of them, so +a dispatch that ignores the word, the root constant, its scale or the byte offset is refused instead of passing. +Runs sharing one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the word and all 320 words equal the expectation of + case A of startup_gfx2hlsl_compute_check.py; +3. dispatch-heap-word-outside (the word is 0x07ffffff, a record past the heap), dispatch-heap-word-past (the + buffer ends at the word) and dispatch-heap-word-placed (the buffer is the placed input, not upload memory): + each refused with one logged reason, every output word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +import startup_gfx2hlsl_heap_word_check as W +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +CONTROLS = ( + ('dispatch-heap-word-outside', "a heap record is outside the list's view heap"), + ('dispatch-heap-word-past', 'a heap index word is outside its table buffer'), + ('dispatch-heap-word-placed', "a heap index word is not in the list's upload memory"), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and W.FORM == '288 rootconst 0 2 times 336', 'the consumer hard-codes these' + (directory / 'program').write_bytes(W.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == W.MANIFEST % W.FORM + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + for mode, reason in CONTROLS: + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, '%s: a refused Dispatch wrote the output' % mode + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and reason in refused[0], '%s:\n%s' % (mode, result.stderr[-3000:]) + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (mode, census) + print(f'startup_compute_dispatch_heap_word: PASS on {adapter} (all {C.WORDS} words match through the index word; ' + f'untouched before translation and for {len(CONTROLS)} refused controls)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py index 0ea8575862..ff517ffc80 100644 --- a/tests/startup_gfx2hlsl_heap_record_check.py +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -13,8 +13,9 @@ dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are compared whole. Every other form keeps a refusal: another shift, another index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an offset -modifier, eight dwords, an index read from a buffer (named as such), a formatted load or a store through the -record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +modifier, eight dwords, an index read from a buffer at an offset that differs between groups (named as such; +startup_gfx2hlsl_heap_word_check.py covers the buffer forms that are accepted), a formatted load or a store through +the record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. """ import argparse import struct @@ -52,7 +53,8 @@ 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', - 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s26, s[28:31], 0x0': '8e0620f4000000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_buffer_load_dword s26, s[28:31], s14': '8e0620f40000001c', 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', @@ -166,10 +168,10 @@ def check_refusals(): ('index register loaded from a buffer after the shift', {SHIFT: (SHIFT, TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0')}, not_shifted), ('branch target between the shift and the load', {SHIFT: (SHIFT,) + JUMP}, not_shifted), - ('index read from a buffer', {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], 0x0', 's_lshl_b32 s6, s26, 5')}, - from_buffer), - ('index read from a buffer into the shifted register', - {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0', SHIFT)}, from_buffer), + ('index read from a buffer at a group-ID offset', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], s14', 's_lshl_b32 s6, s26, 5')}, from_buffer), + ('index read from a buffer at a group-ID offset into the shifted register', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], s14', SHIFT)}, from_buffer), ('high word 1', {CLEAR: ('s_mov_b32 s9, 1',)}, high), ('high word a root constant', {CLEAR: ('s_mov_b32 s9, s5',)}, high), ('high word left as the group ID', {CLEAR: ()}, high), diff --git a/tests/startup_gfx2hlsl_heap_word_check.py b/tests/startup_gfx2hlsl_heap_word_check.py new file mode 100644 index 0000000000..68578488d4 --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_word_check.py @@ -0,0 +1,160 @@ +"""A compute program whose resource heap record index is a word it reads from a table buffer. + +usage: startup_gfx2hlsl_heap_word_check.py [--llvm-mc ] + +The program of startup_gfx2hlsl_heap_record_check.py with its index no longer the root constant itself: root constant +word 2 picks the byte offset of a word in the buffer of table byte 96, and that word is the index: + + s_load_dwordx4 s[28:31], s[12:13], 0x60 + s_mulk_i32 s6, 0x150 + s_add_u32 s6, s6, 0x120 + s_buffer_load_dword s6, s[28:31], s6 + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +gfx2hlsl.py names that input `srv 1 buf heap word table 1 96 at 288 rootconst 0 2 times 336`: the dispatch reads the +word at byte 288 + 336 * (root constant word 2) of that buffer, then the 32-byte heap record it indexes. The byte +offset is the same for every thread of the dispatch. A literal byte offset, an offset modifier, s_mul_i32 and +s_addk_i32 and a later word of a wider load give the same line with their own numbers; the HLSL and the manifest of +the first form are compared whole. Every other form keeps a refusal: an offset from the group ID, an offset read +from a buffer, a scale or a byte offset that is not a multiple of 4, a register added after the arithmetic, a +modified descriptor, and a branch target between the arithmetic and the load. --llvm-mc reassembles every +instruction used here and compares the words. +""" +import argparse + +import startup_gfx2hlsl_heap_record_check as H +from startup_gfx2hlsl_compute_check import G, assemble, refused + +TABLE = 's_load_dwordx4 s[28:31], s[12:13], 0x60' +SCALE, ADD = 's_mulk_i32 s6, 0x150', 's_add_u32 s6, s6, 0x120' +READ_INDEX = 's_buffer_load_dword s6, s[28:31], s6' +WAIT = 's_waitcnt lgkmcnt(0)' +INDEX = (TABLE, SCALE, ADD, WAIT, READ_INDEX, WAIT, H.SHIFT) +# Every instruction added here, recorded from llvm-mc 15. +ENCODED = { + TABLE: '060708f4600000fa', SCALE: '500106b8', ADD: '06ff068020010000', READ_INDEX: '8e0120f40000000c', + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6': '8e0624f40000000c', 's_lshl_b32 s6, s27, 5': '1b85068f', + 's_buffer_load_dword s6, s[28:31], 0x40': '8e0120f4400000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_mulk_i32 s6, 0x152': '520106b8', 's_add_u32 s6, s6, 0x122': '06ff068022010000', + 's_and_b32 s29, s29, 0xffff': '1dff1d87ffff0000', 's_add_u32 s6, s6, s14': '060e0680', + 's_mul_i32 s6, s6, s5': '06050693', 's_mul_i32 s6, s6, 0x150': '06ff069350010000', 's_addk_i32 s6, 0x120': '200186b7', + 's_buffer_load_dword s6, s[28:31], s6 offset:0x10': '8e0120f41000000c', +} +ALL = {**H.ENCODED, **ENCODED} + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf table 1 96 +srv 1 buf heap word table 1 96 at %s +uav 0 table 1 16 +""" +FORM = '288 rootconst 0 2 times 336' +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +ByteAddressBuffer r1 : register(t1); +RWByteAddressBuffer u0 : register(u0); +""" +# The heap record program's body with the index read through r0 (the table buffer) and the input through r1. +MAIN = H.MAIN.replace(' s6 = ud2 << (0x00000005u & 31);\n', """\ + s6 = ud2 * 0x00000150u; + s6 = s6 + 0x00000120u; + s6 = r0.Load(s6 + 0); + s6 = s6 << (0x00000005u & 31); +""").replace('v5 = r0.Load(a + 0);', 'v5 = r1.Load(a + 0);') +assert MAIN.count('r0.Load') == 1 and MAIN.count('r1.Load') == 1 + + +def words(index=INDEX): + """The heap record program with the index lines in place of its shift.""" + return b''.join(bytes.fromhex(ALL[line]) for original in H.PROGRAM + for line in (index if original == H.SHIFT else (original,))) + + +WORDS = words() + + +def pipeline(index=INDEX): + return G.ComputePipeline(words(index), H.root_blob(), H.RSRC2, H.GROUP) + + +def replace(old, *new): + assert old in INDEX + return tuple(line for original in INDEX for line in (new if original == old else (original,))) + + +def check_lowering(): + pipe = pipeline() + hlsl = pipe.hlsl_cs() + assert pipe.manifest() == MANIFEST % FORM, pipe.manifest() + assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] + forms = ( + ('literal byte offset', (TABLE, WAIT, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, H.SHIFT), '64'), + ('offset modifier', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s6 offset:0x10'), + '304 rootconst 0 2 times 336'), + ('s_mul_i32 and s_addk_i32', replace(ADD, 's_addk_i32 s6, 0x120'), FORM), + ('s_mul_i32 by a literal', replace(SCALE, 's_mul_i32 s6, s6, 0x150'), FORM), + ('second word of a wider load', replace(H.SHIFT, 's_lshl_b32 s6, s27, 5')[:4] + ( + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6', WAIT, 's_lshl_b32 s6, s27, 5'), '292 rootconst 0 2 times 336'), + # A branch target before the arithmetic changes nothing. + ('branch target before the arithmetic', (TABLE,) + H.JUMP + INDEX[1:], FORM), + ) + for name, index, form in forms: + got = pipeline(index).manifest() + assert got == MANIFEST % form, '%s:\n%s' % (name, got) + return len(forms) + + +def check_refusals(): + other = ('s_load of a resource heap record whose index is read from a buffer other than a table buffer at a ' + 'dispatch-constant offset') + controls = ( + ('offset from the group ID', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s14')), + ('offset read from a buffer', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, READ_INDEX)), + ('scale not a multiple of 4', replace(SCALE, 's_mulk_i32 s6, 0x152')), + ('byte offset not a multiple of 4', replace(ADD, 's_add_u32 s6, s6, 0x122')), + ('a register added after the arithmetic', replace(ADD, ADD, 's_add_u32 s6, s6, s14')), + ('scaled by a register', replace(SCALE, 's_mul_i32 s6, s6, s5')), + ('modified descriptor', replace(TABLE, TABLE, WAIT, 's_and_b32 s29, s29, 0xffff')), + ('branch target between the arithmetic and the load', replace(ADD, ADD, *H.JUMP)), + ) + for name, index in controls: + try: + refused(other, lambda: pipeline(index).manifest()) + except AssertionError as error: + raise AssertionError('%s: %s' % (name, error)) from None + # A branch target between the load and the shift ends the word's mark, as for a root constant. + refused('whose offset is not a root constant shifted left by 5', + lambda: pipeline(replace(READ_INDEX, READ_INDEX, *H.JUMP)).manifest()) + # Only a buffer read is named in the manifest; another kind through such a record is refused there. + pipe = pipeline() + key = next(k for k in pipe.resources if k[0][:2] == ('resheap', 'word')) + pipe.resources[key]['kind'] = 'tex2d' + refused("resource through ('resheap', 'word'", pipe.manifest) + return len(controls) + 2 + + +def check_binary(llvm_mc): + for line, encoded in ENCODED.items(): + assert assemble(llvm_mc, line + '\n') == bytes.fromhex(encoded), line + text = [line for original in H.PROGRAM for line in (INDEX if original == H.SHIFT else (original,))] + assert assemble(llvm_mc, '\n'.join(text) + '\n') == WORDS + print('heap word fixture: %d instructions reassembled to the recorded words' % len(ENCODED)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + args = parser.parse_args() + if args.llvm_mc: + check_binary(args.llvm_mc) + forms = check_lowering() + count = check_refusals() + print('startup_gfx2hlsl_heap_word: PASS (manifest and HLSL exact; %d more forms; %d refused controls)' % (forms, count)) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 235f24e4ba..865fba10c9 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -163,7 +163,7 @@ static void* desktop_pipeline(void* device) // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable // dispatch, dispatch-swapped, dispatch-none, dispatch-sampled, dispatch-sampled-unbound, dispatch-heap, -// dispatch-heap-outside: one creation, then dispatch_slot67 below +// dispatch-heap-outside, dispatch-heap-word*: one creation, then dispatch_slot67 below // texture-store, texture-store-none, texture-store-denied: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. static void* slot67_pipeline; @@ -196,6 +196,10 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's // descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. // dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// dispatch-heap-word runs the program of startup_gfx2hlsl_heap_word_check.py: the constant is 1 and picks the word +// of the upload buffer at table byte 96 that holds the index, 2. dispatch-heap-word-outside makes that word +// 0x07ffffff, dispatch-heap-word-past ends the buffer at that word, and dispatch-heap-word-placed names the placed +// input buffer instead of upload memory. // Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets // another compute root and the first one again after the constants, dispatch-same-root sets the same root again; // dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other @@ -243,7 +247,8 @@ static int dispatch_slot67(void* device, const std::string& mode) if (heap_record) for (const UINT at : {0u, 32u, 64u}) std::memcpy(reinterpret_cast(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); - const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : 2u}; + const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; + const UINT constants[3] = {0x01234567, 0x9e3779b9, mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; const auto bind = [&] { invoke(list, 32, 1, word(&heap)); @@ -281,6 +286,20 @@ static int dispatch_slot67(void* device, const std::string& mode) bind(); } if (heap_record) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_word) { + // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 + // holds the index, 2; every other word names record 0 or 1, the output's descriptor. + constexpr UINT bytes = 0x400, at = 0x270; + auto* const index = static_cast(reinterpret_cast(invoke(list, 148, bytes, 256))); + if (!index) return 81; + std::memset(index, 0, bytes); + index[0x120 / 4] = index[0x150 / 4] = 1; + index[at / 4] = mode == "dispatch-heap-word-outside" ? 0x07ffffffu : 2u; + const UINT64 address = reinterpret_cast(mode == "dispatch-heap-word-placed" ? buffers[0] : index); + const UINT view[4] = {static_cast(address), static_cast(address >> 32), + mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; + std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); + } invoke(list, 35, 1, gpu); if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); if (FAILED(static_cast(invoke(list, 9)))) return 75; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 7e4778c499..407a7acded 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3028,15 +3028,8 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False - if (base == 's_lshl_b32' and hasattr(self, 'heap_index') and re.fullmatch(r'0x[0-9a-f]+|[0-9]+', srcs[1]) - and int(srcs[1], 0) == 5): - # index << 5 is the byte offset of a 32-byte resource-heap record. The index is named only when it is a - # root constant word (the dispatch knows it) or a word an s_buffer_load wrote (refused by name). - r = reg_range(srcs[0]) - if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': - self.heap_index[d] = self.pipe.uds[syms[0][1]] - elif r and r[0] == 's' and {**self.heap_index, **self.heap_index_was}.get(r[1]) == ('bufword',): - self.heap_index[d] = ('buffer',) + if hasattr(self, 'heap_index'): + self.mark_heap_index(base, d, srcs, syms) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -3045,6 +3038,38 @@ def known(tok): self.set_s(d + 1, self.S(high) if high is not None else '0u', uniform=high_uniform) return None + def heap_word_offset(self, tok, sym): + """(param, word, scale, add) when tok, whose symbol before this instruction is sym, holds root constant word + (param, word) times scale plus add, modulo 2^32 (see mark_heap_index); else None.""" + if sym and sym[0] == 'ud' and self.pipe.uds[sym[1]][0] == 'rootconst': + return self.pipe.uds[sym[1]][1:] + (1, 0) + r = reg_range(tok) + mark = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + return mark[1:] if mark and mark[0] == 'rc' else None + + def mark_heap_index(self, base, d, srcs, syms): + """Marks of SGPR d for heap_record. index << 5 is the byte offset of a 32-byte resource-heap record; the index + is named when it is a root constant word (the dispatch knows it) or a word an s_buffer_load wrote (see + op_s_buffer_load_dword). A root constant word times a literal plus a literal ('rc') is the byte offset such a + load may read the index word at: the same for every thread of the dispatch.""" + lit = [int(t, 0) & 0xffffffff if re.fullmatch(r'0x[0-9a-f]+|[0-9]+', t) else None for t in srcs] + r = reg_range(srcs[0]) + if base == 's_lshl_b32' and lit[1:] == [5]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif word and word[0] == 'bufword': + self.heap_index[d] = ('buffer',) + word[1:] + elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: + for i in (0, 1): + k = lit[1 - i] + offset = self.heap_word_offset(srcs[i], syms[i]) if k is not None else None + if offset: + p, w, scale, add = offset + self.heap_index[d] = (('rc', p, w, scale * k & 0xffffffff, add * k & 0xffffffff) if base == 's_mul_i32' + else ('rc', p, w, scale, add + k & 0xffffffff)) + break + def set_exec_scc(self, expr): self.exec_known = False self.scc_effect = 'emitted' @@ -3138,6 +3163,11 @@ def scalar_accumulate(self, base, ops, mods): self.set_s(d, '0x%08xu' % value, ('const', value)) else: self.set_s(d, result) + offset = self.heap_word_offset(ops[0], sym) if hasattr(self, 'heap_index') else None + if offset: + p, w, scale, plus = offset + self.heap_index[d] = ('rc', p, w, scale, plus + imm & 0xffffffff) if add else ( + 'rc', p, w, scale * imm & 0xffffffff, plus * imm & 0xffffffff) self.masks.discard(d) return None @@ -3315,16 +3345,19 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load with a register offset through %s' % (p[1],)) def heap_record(self, dst, base, token, imm, count): - """s_load_dwordx4 D, , R in a compute program, where R is a root constant word - shifted left by 5 with no later write of R and no branch target in between: D is the buffer descriptor in - the 32-byte heap record that the root constant indexes. The manifest names the root constant; the dispatch - reads the record. Only this exact form is modelled.""" + """s_load_dwordx4 D, , R in a compute program, where R is an index shifted left by 5 + with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap + record that the index names. The index is a root constant word, or a word an s_buffer_load read from an + unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal + (the marks, see mark_heap_index, end at a branch target). The manifest names the root constant or where the + word is; the dispatch reads the word and the record. Only these exact forms are modelled.""" what = 's_load of a resource heap record' r = reg_range(token) index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None if index == ('buffer',): - raise Unsupported('%s whose index is read from a buffer' % what) - if not index or index[0] != 'rootconst': + raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' + 'offset' % what) + if not index or index[0] not in ('rootconst', 'buffer'): raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) if count != 4: raise Unsupported('%s of %d dwords' % (what, count)) @@ -3332,8 +3365,9 @@ def heap_record(self, dst, base, token, imm, count): raise Unsupported('%s with offset:%#x' % (what, imm)) if self.sym.get(base[2]) != ('const', 0): raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] for i in range(count): - self.sym[dst[1] + i] = ('desc', ('resheap',) + index[1:], 0, i) + self.sym[dst[1] + i] = ('desc', source, 0, i) def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" @@ -3489,6 +3523,19 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: self.emit('a = %s;' % offset) offset = 'a' + # A word read from an unmodified table buffer at a literal offset or at a root constant word times a literal + # plus a literal is the same for the whole dispatch: heap_record names it by (table parameter, table byte, + # root constant parameter and word or None, scale, byte offset). Any other buffer word is only marked. + where = () + if hasattr(self, 'heap_index'): + key, r, sreg = self.descriptor(ops[1]), reg_range(ops[1]), reg_range(token) + first = self.sym.get(r[1]) + at = (None, None, 0, val) if is_lit else self.heap_word_offset( + token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) + if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant + and first[0] == 'desc' and key[0][0] == 'table' and key not in self.pipe.modified + and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) for n in range(4))): + where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. uniform = self.tracks_uniformity() and self.uniform_source(token) for i in range(count): @@ -3496,7 +3543,7 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) if hasattr(self, 'heap_index'): - self.heap_index[dst[1] + i] = ('bufword',) + self.heap_index[dst[1] + i] = ('bufword',) + (where[:5] + ((where[5] + 4 * i) & 0xffffffff,) if where else ()) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -6131,6 +6178,11 @@ def manifest(self): where = 'root %d' % source[1] elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes + elif source[0] == 'resheap' and source[1] == 'word' and r['kind'] == 'buf': + # The record the word at byte `at` (+ root constant word * `times`) of table buffer indexes. + table, byte, param, word, scale, at = source[2:] + where = 'heap word table %d %d at %d' % (table, byte, at) + ( + '' if param is None else ' rootconst %d %d times %d' % (param, word, scale)) else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) From 5c248dc126a0796851c338ff6206a889d7cb8dd5 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:35:39 +0100 Subject: [PATCH 29/35] docs: a compute heap record whose index is read from a table buffer Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index e9a39bc09f..25cb723c7c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15180,7 +15180,7 @@ ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. -Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer (`s_load of a resource heap record whose index is read from a buffer`). A formatted load or a store through such a record, and the graphics stages, are refused as before. +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer in any form other than the one below (`s_load of a resource heap record whose index is read from a buffer other than a table buffer at a dispatch-constant offset`). A formatted load or a store through such a record, and the graphics stages, are refused as before. `tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). @@ -15192,6 +15192,19 @@ cmake --build --preset dev --target startup_stream_consumer ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_" -V ``` +#### A heap record index read from a table buffer + +The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_load_dword(xN)` from a table buffer descriptor that no instruction modified, at a literal byte offset or at ` * k + c` built with `s_mul_i32`, `s_mulk_i32`, `s_add_u32`, `s_add_i32` or `s_addk_i32` and literals (plus any `offset:` modifier), dword-aligned, with no branch target between the arithmetic and the load or between the load and the shift. The manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the stand-in reads the table record, computes the byte offset in 32-bit arithmetic, reads the index word from the buffer's memory and binds the heap record it names as above. The read is made at record time, so it is sound only when the GPU does not write the word: the stand-in reads it only when the buffer lies in the recording's upload memory (list slot 148), which no GPU command writes. A buffer elsewhere refuses the dispatch (`a heap index word is not in the list's upload memory`), and so does a word past the buffer's `stride * num_records` bytes (`a heap index word is outside its table buffer`). An index from a per-thread value, a group ID, another buffer word, a register sum or a modified descriptor keeps the refusal. + +`tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. + +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index; all 153 now stop later and none translates fully yet. Their next first refusals are a per-lane `vcc` live at an `s_cbranch_execz` join (82), `v_fma_mix_f32` (24), `src_scc` in `s_mul_i32` (14), a buffer read in another form (6), a formatted load without a hardware table descriptor (6) and 21 others. About 97 of the programs also load an 8-dword heap record, which stays refused. + +```powershell +python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_word_" -V +``` + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as From 62b5ccc032fb7f1bccaf4aba6804ef3b24a0e215 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:38:17 +0100 Subject: [PATCH 30/35] docs: state the measured first refusals and the heap-record ceiling exactly Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 25cb723c7c..0fffe0b0c9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15198,7 +15198,7 @@ The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_ `tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. -Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index; all 153 now stop later and none translates fully yet. Their next first refusals are a per-lane `vcc` live at an `s_cbranch_execz` join (82), `v_fma_mix_f32` (24), `src_scc` in `s_mul_i32` (14), a buffer read in another form (6), a formatted load without a hardware table descriptor (6) and 21 others. About 97 of the programs also load an 8-dword heap record, which stays refused. +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index. All 153 change their first refusal and none translates fully yet: 145 now stop at a later instruction (82 at a per-lane `vcc` live at an `s_cbranch_execz` join, 24 at `v_fma_mix_f32`, 14 at `src_scc` in `s_mul_i32`, 25 at others), 6 at a buffer read in another form and 2 at an 8-dword record. 145 programs hold a heap load that now lowers, but 120 of the 158 still hold a refused heap-record load somewhere: 101 a buffer read in another form, 32 an offset that is not a root constant shifted by 5, 2 an 8-dword record (this counts every refusal site, including sites after an earlier refusal). Most of the buffer-form sites compute the offset or read the word before a branch target, which ends the marks because another path into the join may hold a different word; in about 97 programs an 8-dword (image) heap record would stay refused even past that. ```powershell python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 From f5b0303944b8697f763e54978e25ddf986382ebb Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:38:53 +0100 Subject: [PATCH 31/35] 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); From 5955e40e3c1c0df713e7436a2d74bce3df2d4e5d Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:39:30 +0100 Subject: [PATCH 32/35] startup: keep the descriptor load tag when checking the index word's table buffer Co-Authored-By: Claude Fable 5.2 --- tools/startup/gfx2hlsl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9685848766..a4a8a4685d 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3839,7 +3839,7 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant and first[0] == 'desc' and key[0][0] == 'table' and key not in self.pipe.modified - and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) for n in range(4))): + and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) + first[4:] for n in range(4))): where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. uniform = self.tracks_uniformity() and self.uniform_source(token) From 6c1960c3d9b63f27f033d15bfc894fe05235349b Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:52:41 +0100 Subject: [PATCH 33/35] startup: read the pipe's modified set tolerantly in the heap index word check Three existing checks build a stage on a bare pipe object without it. Co-Authored-By: Claude Fable 5.2 --- tools/startup/gfx2hlsl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a4a8a4685d..179b372442 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3838,7 +3838,7 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): at = (None, None, 0, val) if is_lit else self.heap_word_offset( token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant - and first[0] == 'desc' and key[0][0] == 'table' and key not in self.pipe.modified + and first[0] == 'desc' and key[0][0] == 'table' and key not in getattr(self.pipe, 'modified', ()) # probes build a bare pipe and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) + first[4:] for n in range(4))): where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. From 51b88e01c48c53b392db1d68d38bc68119550947 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 23:10:17 +0100 Subject: [PATCH 34/35] startup: compute entry values from the words of a bound buffer descriptor A translated compute program's manifest may take entry values from the descriptor a buffer input or output is bound from: the input's stride and word 3 (formatted loads) and the output's word 3, the upper half of word 1 and the record count (formatted stores). Dispatch now takes each from the descriptor words the same call binds the view from; word 3 of an input goes through the draw path's formatted-buffer check, now shared. A FORMAT the program does not decode refuses with one reason; any other source keeps a named refusal. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 +- docs/experiments.md | 14 +- src/startup_stubs/d3d12_compute_dispatch.inl | 59 +++++++- src/startup_stubs/d3d12_draw.inl | 44 +++--- tests/startup_compute_dispatch_entry_check.py | 129 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 17 ++- 6 files changed, 239 insertions(+), 29 deletions(-) create mode 100644 tests/startup_compute_dispatch_entry_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c1ed8f84c5..1f06cf97d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3847,9 +3847,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_entry_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_entry_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} - PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + startup_compute_dispatch_entry_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 81a20267ee..94245424a0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15542,7 +15542,7 @@ the field layouts rather than assembled. ## 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 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. The entry values live in the compute root-constant store of #1975: a word no slot 37 or 39 call wrote since the compute root was set (slot 33 with another root, or a list reset) has no value and is refused with `an entry value was not set since the compute root`; setting the same root again keeps the words, and the graphics words of slot 40 are separate. +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, entry values that are neither a root constant nor a buffer descriptor word) 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. The entry values live in the compute root-constant store of #1975: a word no slot 37 or 39 call wrote since the compute root was set (slot 33 with another root, or a list reset) has no value and is refused with `an entry value was not set since the compute root`; setting the same root again keeps the words, and the graphics words of slot 40 are separate. `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 two entry values arrive through slot 37 and slot 39, with other values written through slot 40 in between; `dispatch-same-root` must still give the expected words, and five refused modes must log their reason and keep the sentinels: a missing word, another compute root set and the first set again, a list reset, a compute root that is not the pipeline's, and one buffer named as input and output. `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. @@ -15555,6 +15555,18 @@ cmake --build --preset dev --target startup_stream_consumer ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V ``` +### Entry values from a buffer descriptor + +A formatted buffer load passes the input's stride and word 3 as entry values (`udsrc stride `, `udsrc descword3 `), and a formatted buffer store (`buffer_store_format_d16_x`, and `buffer_store_format_xyzw` of #2530) passes the output's word 3, the upper half of word 1 and the record count (`uav_descword3`, `uav_stride`, `uav_numrecords`). At Dispatch the stand-in takes each from the descriptor words the same call binds the view from: the stride as the draw path takes it (from the hardware descriptor, or from the title's buffer view for a token), word 3 through the draw path's formatted-buffer check (a token's word is built from its view; a FORMAT the program does not decode refuses the dispatch with `a formatted input has no word 3 the program decodes`), and the output words unmasked, since the store helper checks the swizzle bits itself. A descriptor that is not bound refuses the dispatch as before; an entry value naming a texture slot leaves the pipeline untranslated, and so does any other source. + +`tests/startup_compute_dispatch_entry_check.py` dispatches two source-built programs on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back: the formatted load of `startup_gfx2hlsl_compute_check.py` with two word-3 values on one translation, and the `buffer_store_format_d16_x` program of `startup_compute_store_d16_x_check.py` with three output descriptors (two formats, and another stride and record count). A FORMAT the program does not decode is refused with every output word at its sentinel. Returning a constant output stride and record count in the runtime makes the third store run fail. + +Measured on two synthetic programs. In a local set of 29 compute programs whose first refusal was this manifest line (about 1.4 million calls in one run), 27 now pass the manifest (about 1.39 million calls; 17 of them, about 0.6 million calls, use the store of #2530) and 2 stop at a 1D or 3D texture input. Which bind-time reason the 27 meet next has not been measured. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_entry_" -V +``` + ### An input named by a resource heap record A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index f590f25be0..eb8962dd86 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -4,7 +4,9 @@ // 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 +// values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is +// bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record +// count of an output (`uav_descword3`, `uav_stride`, `uav_numrecords`). Any other manifest line makes the translation // 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). @@ -13,12 +15,14 @@ struct ComputeTranslation { // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: - // at alone) is the index. + // at alone) is the index. An entry value that is not a root constant names input or output a by its source. + enum Source { root_constant, input_stride, input_word3, output_word3, output_stride, output_records }; struct Slot { int a, b; bool texture, heap; int word_param = -1, word_byte = 0; std::uint32_t at = 0, times = 0; + Source source = root_constant; }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable @@ -89,11 +93,22 @@ const char* load_compute_translation(ComputeTranslation& tr) } unsigned i = 0, x = 0, y = 0, z = 0, w = 0; int a = 0, b = 0, c = 0, d = 0, used = 0; + char name[16] = ""; const auto whole = [&] { return used == static_cast(line.size()); }; + // The manifest names of the Source values after root_constant, in their order. + const auto source = [&] { + static const char* const names[] = {"stride", "descword3", "uav_descword3", "uav_stride", "uav_numrecords"}; + for (int s = 0; s < 5; ++s) + if (!std::strcmp(name, names[s])) return static_cast(s + 1); + return ComputeTranslation::root_constant; + }; 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(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && + source() != ComputeTranslation::root_constant) + tr.uds.push_back({a, 0, false, false, -1, 0, 0, 0, source()}); 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(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && @@ -117,11 +132,17 @@ const char* load_compute_translation(ComputeTranslation& tr) 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("udsrc", 0) == 0 ? "an entry value that is not a root constant or a buffer descriptor word" : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; } 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"; + for (const ComputeTranslation::Slot& ud : tr.uds) { + const auto& slots = ud.source >= ComputeTranslation::output_word3 ? tr.uavs : tr.srvs; + if (ud.source != ComputeTranslation::root_constant && + (ud.a < 0 || static_cast(ud.a) >= slots.size() || slots[ud.a].texture)) + return "an entry value names a descriptor that is not a buffer input or output"; + } x2w_startup::ComPtr code; 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. @@ -155,6 +176,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) bool transition, texture, described; unsigned char desc[40]; // a texture view's description, as the title gave it with a desktop format Wrapper* wrapper; + std::uint32_t words[4]; // a buffer's descriptor words as it was bound from, and its stride + UINT stride; } views[40]{}; static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40); const auto type = list->GetType(); @@ -182,7 +205,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) } // A word no slot 37 or 39 call wrote since the compute root was set has no value to pass (it is not 0). for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) - if (!pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) reason = "an entry value was not set since the compute root"; + if (tr->uds[i].source == ComputeTranslation::root_constant && !pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) + reason = "an entry value was not set since the compute root"; 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; @@ -285,6 +309,8 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) 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}; + views[i].stride = view.stride; + std::memcpy(views[i].words, words, sizeof(views[i].words)); continue; } // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result @@ -302,6 +328,29 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) 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}; + std::memcpy(views[i].words, words, sizeof(views[i].words)); + } + // An entry value from a descriptor comes from the words its view was bound from in the loop above. + std::uint32_t values[32] = {}; + for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) { + const ComputeTranslation::Slot& ud = tr->uds[i]; + const View& view = views[ud.source >= ComputeTranslation::output_word3 ? inputs + ud.a : ud.a]; + std::uint32_t format = 0, word[4]; + switch (ud.source) { + case ComputeTranslation::root_constant: values[i] = pass.compute_constants.word(ud.a, ud.b); break; + case ComputeTranslation::input_stride: values[i] = view.stride; break; + case ComputeTranslation::input_word3: + std::memcpy(word, view.words, sizeof(word)); + if (formatted_buffer_word3(word, format)) { + reason = "a formatted input has no word 3 the program decodes"; + std::memcpy(words, view.words, sizeof(view.words)); + } + values[i] = word[3]; + break; + case ComputeTranslation::output_word3: values[i] = view.words[3]; break; + case ComputeTranslation::output_stride: values[i] = view.words[1] >> 16; break; // unmasked: the program checks the swizzle bits + case ComputeTranslation::output_records: values[i] = view.words[2]; break; + } } // 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. @@ -358,8 +407,6 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) 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; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2c353ee156..a8fd562e49 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1819,6 +1819,29 @@ struct FormattedBufferDescriptor { std::uint32_t words[8] = {}; }; +// Word 3 of a buffer descriptor as a formatted load decodes it (words[3]): the title's hardware word, or for a typed +// buffer view the title created (words[0] its token) the word the driver builds from its format and component +// mapping. Returns the refusal, with an unsupported FORMAT in format. Draws and compute Dispatch share it. +const char* formatted_buffer_word3(std::uint32_t* words, std::uint32_t& format) +{ + if (words[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || record.slot != 18 || record.desc_bytes < 40) return "missing hardware descriptor"; + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, record.desc, 40); + return x2w_startup::view_word3(view, words[3]); + } + if (const auto code = x2w_startup::formatted_buffer_code(words[3]); !x2w_startup::formatted_buffer_supported(code)) { + format = code; + return "unsupported FORMAT"; + } + return x2w_startup::descriptor_word3_refusal(words[3]); +} + bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) { const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { @@ -1841,25 +1864,8 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(descriptor.words))) return refuse(ud.a, "missing hardware descriptor"); std::memcpy(descriptor.words, reinterpret_cast(entry), sizeof(descriptor.words)); - if (descriptor.words[0] == view_token_magic) { - // A typed buffer view the title created: the driver builds word 3 from its format and component mapping. - ViewRecord record{}; - AcquireSRWLockShared(¬e_lock); - const bool known = descriptor.words[1] < view_records().size(); - if (known) record = view_records()[descriptor.words[1]]; - ReleaseSRWLockShared(¬e_lock); - if (!known || record.slot != 18 || record.desc_bytes < 40) - return refuse(ud.a, "missing hardware descriptor"); - D3D12_SHADER_RESOURCE_VIEW_DESC view; - std::memcpy(&view, record.desc, 40); - if (const char* reason = x2w_startup::view_word3(view, descriptor.words[3])) return refuse(ud.a, reason); - descriptor.entry = entry; - continue; - } - const auto format = x2w_startup::formatted_buffer_code(descriptor.words[3]); - if (!x2w_startup::formatted_buffer_supported(format)) - return refuse(ud.a, "unsupported FORMAT", format); - if (const char* reason = x2w_startup::descriptor_word3_refusal(descriptor.words[3])) return refuse(ud.a, reason); + std::uint32_t format = 0; + if (const char* reason = formatted_buffer_word3(descriptor.words, format)) return refuse(ud.a, reason, format); descriptor.entry = entry; } return true; diff --git a/tests/startup_compute_dispatch_entry_check.py b/tests/startup_compute_dispatch_entry_check.py new file mode 100644 index 0000000000..8c6986decd --- /dev/null +++ b/tests/startup_compute_dispatch_entry_check.py @@ -0,0 +1,129 @@ +"""Translated compute programs whose entry values are words of a bound buffer descriptor (list slot 14). + +usage: startup_compute_dispatch_entry_check.py + +The consumer records each program as startup_compute_dispatch_check.py does, with the input words and the stride, +record count and word 3 of both table descriptors set by this script (X2W_TEST_DISPATCH_IN and _FIELDS). Each +program writes the same lanes in every group, so the consumer's Dispatch(3, 2, 2) gives the result of one group. + +1. Case L-uint of startup_gfx2hlsl_compute_check.py reads its input with buffer_load_format_xyzw; the manifest + takes `stride 0` and `descword3 0` from the input's descriptor. Stride 6 and the word 3 of L-uint, then of + L-unorm on the same translation, must each give that case's 320 words. A FORMAT the program does not decode is + refused with one reason and keeps every output word at its sentinel. +2. Case F of startup_compute_store_d16_x_check.py stores with buffer_store_format_d16_x; the manifest takes + `uav_descword3 0`, `uav_stride 0` and `uav_numrecords 0` from the output's descriptor. Three descriptors give + three different expectations: 32_FLOAT with stride 8 and 12 records, 16_FLOAT with the same, and 32_FLOAT with + stride 12 and 7 records. +Before translation each program is refused with "no translation". 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_store_d16_x_check as D +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +RAW = (4, C.WORDS, 0) # the consumer's default stride, record count and word 3 +UNDECODED = 'a formatted input has no word 3 the program decodes' + + +def store_f32(halves, stride, records): + out = bytearray(struct.pack('<%dI' % C.WORDS, *[C.SENTINEL] * C.WORDS)) + for lane in range(records): + struct.pack_into('> 12) & 127 in (1, 5, 14, 22, 23, 24, 27, 29, 56, 60, 64, 71, 74, 77) + # 20 records of 6 bytes cover the last lane's 4-byte read at byte 6 * 15 + 3. + run_program(root, 'formatted', consumer, dxc, adapter, (words_l, rsrc2_l, group_l), + 'udsrc 2 stride 0\nudsrc 3 descword3 0\nsrv 0 buf table 1 0\nuav 0 table 1 16\n', [ + ('dispatch-formatted-uint', formatted, ((6, 20, C.L_WORD3['L-uint']), RAW), C.expected('L-uint')), + ('dispatch-formatted-unorm', formatted, ((6, 20, C.L_WORD3['L-unorm']), RAW), C.expected('L-unorm')), + ('dispatch-formatted-undecoded', formatted, ((6, 20, undecoded), RAW), UNDECODED), + ]) + + _, words_f, rsrc2_f, group_f, _ = D.PROGRAMS['F'] + runs = [] + for variant in ('F-f32', 'F-f16'): + _, source, constants, expected, _ = D.case_inputs(variant) + runs.append(('dispatch-store-' + variant[2:], source, (RAW, tuple(constants[3:5]) + (constants[2],)), expected)) + word3_f32, halves = D.F_VARIANTS['F-f32'][0], D.FP16_VALUES + runs.append(('dispatch-store-f32-stride12', D.poisoned_source(halves), (RAW, (12, 7, word3_f32)), store_f32(halves, 12, 7))) + assert runs[0][3] != runs[2][3] != runs[1][3] + run_program(root, 'store', consumer, dxc, adapter, (words_f, rsrc2_f, group_f), + 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n', runs) + print(f'startup_compute_dispatch_entry: PASS on {adapter} (5 descriptor-word dispatches match, ' + '1 refused; untouched before translation)') + + +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 865fba10c9..30527d0caa 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -204,6 +204,9 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // another compute root and the first one again after the constants, dispatch-same-root sets the same root again; // dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other // root; dispatch-same-buffer names the output buffer as the input too. +// For any mode, X2W_TEST_DISPATCH_IN names 1280 bytes that replace the input words, and X2W_TEST_DISPATCH_FIELDS +// names six words that replace, for the input and then the output descriptor, the stride (word 1 bits 16-31), the +// record count (word 2) and word 3, which are otherwise 4, 320 and 0. static int dispatch_slot67(void* device, const std::string& mode) { constexpr UINT words = 320; @@ -214,6 +217,16 @@ static int dispatch_slot67(void* device, const std::string& mode) buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; buffers[1][i] = 0xc5c5c5c5u; } + UINT fields[2][3] = {{4, words, 0}, {4, words, 0}}; + const auto from_file = [](const char* variable, void* data, std::streamsize bytes) { + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA(variable, path, MAX_PATH); + return !n || (n < MAX_PATH && std::ifstream(path, std::ios::binary).read(static_cast(data), bytes).gcount() == bytes); + }; + if (!from_file("X2W_TEST_DISPATCH_IN", buffers[0], words * sizeof(UINT)) || + !from_file("X2W_TEST_DISPATCH_FIELDS", fields, sizeof(fields))) return 2; + UINT input[words]; + std::memcpy(input, buffers[0], sizeof(input)); const auto word = [](const void* value) { return reinterpret_cast(value); }; void* placed[2]{}; UINT descriptors[2][4]{}; @@ -223,7 +236,7 @@ static int dispatch_slot67(void* device, const std::string& mode) 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[mode == "dispatch-same-buffer" ? 1 : i]); - const UINT view[4] = {static_cast(address), static_cast(address >> 32) | 4u << 16, words, 0}; + const UINT view[4] = {static_cast(address), static_cast(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } const struct { @@ -310,7 +323,7 @@ static int dispatch_slot67(void* device, const std::string& mode) Sleep(1); } for (UINT i = 0; i < words; ++i) - if (buffers[0][i] != 0x8b02a7f1u + i * 0x413b1u) return 79; // the input must stay as written + if (buffers[0][i] != input[i]) 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); From 2efebc4ccd0084b921628153f45ca4893961b5f8 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 23:15:25 +0100 Subject: [PATCH 35/35] startup: check that compute output strides keep the swizzle bits A store run with SWIZZLE_ENABLE set in the output descriptor must translate and store nothing; masking the stride entry value to 14 bits makes it fail. The docs state the soffset bound the fixture does not cover. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 4 ++-- tests/startup_compute_dispatch_entry_check.py | 15 ++++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 94245424a0..84aa30b4a9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15559,9 +15559,9 @@ ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V A formatted buffer load passes the input's stride and word 3 as entry values (`udsrc stride `, `udsrc descword3 `), and a formatted buffer store (`buffer_store_format_d16_x`, and `buffer_store_format_xyzw` of #2530) passes the output's word 3, the upper half of word 1 and the record count (`uav_descword3`, `uav_stride`, `uav_numrecords`). At Dispatch the stand-in takes each from the descriptor words the same call binds the view from: the stride as the draw path takes it (from the hardware descriptor, or from the title's buffer view for a token), word 3 through the draw path's formatted-buffer check (a token's word is built from its view; a FORMAT the program does not decode refuses the dispatch with `a formatted input has no word 3 the program decodes`), and the output words unmasked, since the store helper checks the swizzle bits itself. A descriptor that is not bound refuses the dispatch as before; an entry value naming a texture slot leaves the pipeline untranslated, and so does any other source. -`tests/startup_compute_dispatch_entry_check.py` dispatches two source-built programs on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back: the formatted load of `startup_gfx2hlsl_compute_check.py` with two word-3 values on one translation, and the `buffer_store_format_d16_x` program of `startup_compute_store_d16_x_check.py` with three output descriptors (two formats, and another stride and record count). A FORMAT the program does not decode is refused with every output word at its sentinel. Returning a constant output stride and record count in the runtime makes the third store run fail. +`tests/startup_compute_dispatch_entry_check.py` dispatches two source-built programs on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back: the formatted load of `startup_gfx2hlsl_compute_check.py` with two word-3 values on one translation, and the `buffer_store_format_d16_x` program of `startup_compute_store_d16_x_check.py` with four output descriptors (two formats, another stride and record count, and SWIZZLE_ENABLE set in word 1, for which the translated program stores nothing). A FORMAT the program does not decode is refused with every output word at its sentinel. Returning a constant output stride and record count in the runtime, or masking the stride to 14 bits as the draw path does, makes a store run fail. The record count cannot be checked apart from the bound range, which is sized from the same word. -Measured on two synthetic programs. In a local set of 29 compute programs whose first refusal was this manifest line (about 1.4 million calls in one run), 27 now pass the manifest (about 1.39 million calls; 17 of them, about 0.6 million calls, use the store of #2530) and 2 stop at a 1D or 3D texture input. Which bind-time reason the 27 meet next has not been measured. +Measured on two synthetic programs. In a local set of 29 compute programs whose first refusal was this manifest line (about 1.4 million calls in one run), 27 now pass the manifest (about 1.39 million calls; 17 of them, about 0.6 million calls, use the store of #2530) and 2 stop at a 1D or 3D texture input. Every formatted store in the 27 passes a zero `soffset`: a nonzero one in structured mode can store past `stride * records` bytes, outside the bound range, and is not checked here. Which bind-time reason the 27 meet next has not been measured. ```powershell ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_entry_" -V diff --git a/tests/startup_compute_dispatch_entry_check.py b/tests/startup_compute_dispatch_entry_check.py index 8c6986decd..1098908b27 100644 --- a/tests/startup_compute_dispatch_entry_check.py +++ b/tests/startup_compute_dispatch_entry_check.py @@ -13,7 +13,8 @@ 2. Case F of startup_compute_store_d16_x_check.py stores with buffer_store_format_d16_x; the manifest takes `uav_descword3 0`, `uav_stride 0` and `uav_numrecords 0` from the output's descriptor. Three descriptors give three different expectations: 32_FLOAT with stride 8 and 12 records, 16_FLOAT with the same, and 32_FLOAT with - stride 12 and 7 records. + stride 12 and 7 records. A fourth sets SWIZZLE_ENABLE (word 1 bit 31): the dispatch is translated and the + program stores nothing, which holds only while the entry value keeps the upper bits of word 1. Before translation each program is refused with "no translation". Exit 77 when the adapter is not available. """ import os @@ -82,8 +83,8 @@ def run(source, fields): assert len(census) == 3 and census[1].endswith(f'reason "{expected}": 1 keys, 1 dispatches'), (label, census) print(f'{label}: refused ({expected}), output untouched') continue - assert expected != untouched - wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert (expected == untouched) == label.endswith('-swizzle') + wrong =[i for i in range(C.WORDS) if got[i] != expected[i]] assert not wrong, '%s: word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( label, 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 refused, result.stderr[-3000:] @@ -111,15 +112,15 @@ def main(consumer, dxc, adapter): _, words_f, rsrc2_f, group_f, _ = D.PROGRAMS['F'] runs = [] - for variant in ('F-f32', 'F-f16'): + for variant, label in (('F-f32', 'f32'), ('F-f16', 'f16'), ('F-swizzle-en', 'f32-swizzle')): _, source, constants, expected, _ = D.case_inputs(variant) - runs.append(('dispatch-store-' + variant[2:], source, (RAW, tuple(constants[3:5]) + (constants[2],)), expected)) + runs.append(('dispatch-store-' + label, source, (RAW, tuple(constants[3:5]) + (constants[2],)), expected)) word3_f32, halves = D.F_VARIANTS['F-f32'][0], D.FP16_VALUES runs.append(('dispatch-store-f32-stride12', D.poisoned_source(halves), (RAW, (12, 7, word3_f32)), store_f32(halves, 12, 7))) - assert runs[0][3] != runs[2][3] != runs[1][3] + assert runs[0][3] != runs[3][3] != runs[1][3] run_program(root, 'store', consumer, dxc, adapter, (words_f, rsrc2_f, group_f), 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n', runs) - print(f'startup_compute_dispatch_entry: PASS on {adapter} (5 descriptor-word dispatches match, ' + print(f'startup_compute_dispatch_entry: PASS on {adapter} (6 descriptor-word dispatches match, ' '1 refused; untouched before translation)')