diff --git a/docs/experiments/native-sampler-heap.md b/docs/experiments/native-sampler-heap.md new file mode 100644 index 0000000000..59dab0b62b --- /dev/null +++ b/docs/experiments/native-sampler-heap.md @@ -0,0 +1,122 @@ +# Sampler descriptors read from the directly indexed sampler heap at a fixed index (translator, stage 1) + +Issue #3076, part of #2935 (related #1143). The native compute translator now accepts a sampler that the program loads from +the sampler heap with `s_load_dwordx4` / `s_load_dwordx8` at a constant 16-byte aligned offset and uses with +`image_sample_l` or `image_sample_lz`. It lowers the sampler to `SamplerDescriptorHeap[index]` in the DXIL module. This is +stage 1: the translator, the binding record, the cache, the root signature and `bind()`. Binding a real, mirrored sampler heap +at dispatch time in the runtime is stage 2 and is not part of this change. + +## Why + +A local start-up capture (counts only; `compile_dxil` at the base commit, 2,689 slot 67 compute requests): 400 compile, +1,830 contain `image_sample*` or `image_gather*`, and in 993 of those at least one sampler is loaded from memory. The +pattern has root flags `0xc00`; the entry SGPR after the resource heap holds the sampler heap base; the program copies it +into an even SGPR pair, sets the high word to 0 and loads one sampler with `s_load_dwordx4` (or two with `s_load_dwordx8`) at +a 16-byte aligned immediate offset; `image_sample_lz` or `image_sample_l` then uses it (95,839 and 20,556 of 127,822 +sample and gather instructions). Before this change the native translator left that SGPR `unbound`, so the load was refused +("direct descriptor address outside bound table") and `sampler_index` refused non-literal words ("nonconstant sampler"). +There is no compiled-count gain on its own: with the mixed-contract chain of #3023 applied locally (uncommitted probe), 130 +requests stop first at such a load (117 `dwordx4`, 13 `dwordx8`). The change removes the next blocker of that chain. + +## What changed + +- `compute_sampler_heap` (`~0u - 1`) is a second sentinel next to `compute_resource_heap`. Under the existing condition + (root flags `0xc00`, exactly two user SGPRs left after the root parameters) the SGPR after the resource heap is now the table + `{table, compute_sampler_heap}` instead of `unbound`. Entry `n` of the sampler heap is title byte offset `16 * n`. +- Direct path, load from the sampler heap (`gfx1013_direct_compute.inl`), refused in this order: a scalar buffer load ("scalar + buffer load from the sampler heap is not translated"); an SGPR offset ("sampler heap load with an SGPR offset (a + GPU-selected sampler) is not translated"); any width but `dwordx4` / `dwordx8` ("sampler heap load must read one or two + samplers"); an immediate offset that is not a multiple of 16 ("sampler heap offset is not a multiple of 16"); an entry + index above 2046 ("sampler heap index beyond 2046 (2047 is the runtime fallback entry)"). The existing rule that the table + address has a constant zero high word then applies. +- HLSL path: a load through that base is refused ("sampler heap reads need the direct DXIL path"). +- `Emit::binding`: a descriptor from the sampler heap used as an image or buffer is refused ("a sampler heap descriptor is + read as a resource"). +- `sampler_index` returns `SamplerRef {heap, index}`. Four words that are all literals take the static-sampler path as before; + four contiguous words of one sampler-heap entry make a heap sampler; anything else is "nonconstant sampler". For a heap + sampler, in this order: gathers ("gather through the sampler heap is not translated"), comparison samplers ("comparison + sampler from the sampler heap is not translated"), gradient samplers ("sampler from the sampler heap needs image_sample_l or + image_sample_lz"). Static and heap samplers may appear in one program (the mixed fixture). +- DXIL: `DxilModule::sampler_heap_handle` emits `createHandleFromHeap(i32 218, i32 , i1 true, i1 false)` and + `annotateHandle` with resource properties `{14, 0}`; the emitter sets module flag `0x80000000` (sampler heap indexing), as DXC + does for `SamplerDescriptorHeap[i]` (DXC reference: flags `0x80000010` with raw buffers). +- Binding record: `ComputeViewKind::heap_sampler`, one per program, `{heap_sampler, compute_sampler_heap, byte_offset 0, + register 0, required_bytes 16 * (highest index + 1)}`. The frontend cache accepts the kind with exactly that root value; an + older decoder rejects it and recomputes. `format_compute_runtime_manifest` returns no manifest for it (root parameter above + 15), so `compile_dxil --requests` publishes `.cs.cso` without `.txt`; the in-process dispatch route refuses the + kind. `compile_dxil` reports `sampler_heap span=`. +- `create_native_compute_pipeline`: `sampler_heap_indexed` adds root flag `0x800` (`SAMPLER_HEAP_DIRECTLY_INDEXED`) and does not + set `heap_indexed` or `0x400`. `NativeComputePipeline::bind` has a last parameter `ID3D12DescriptorHeap *sampler_heap`: with + `sampler_heap_indexed` a null heap throws ("a sampler heap is needed"); with views too, the heaps are set as views first, then + samplers; without it nothing changes. A root without `0x800` and a shader that reads `SamplerDescriptorHeap` fails + `CreateComputePipelineState` with `E_INVALIDARG` (debug layer: "Shader uses sampler descriptor heap indexing, but root + signature is missing the D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED flag"), measured on the RTX 3080 with a + throw-away probe; a root with static samplers and `0x800` with a shader that reads one static and one heap sampler creates + without a debug-layer message. + +## Assumptions for stage 2 + +The runtime must fill the sampler heap bound for a natively translated compute dispatch so that entry `n` is title byte offset +`16 * n` (index parity), with `dynamic_sampler()` decoding (`src/startup_stubs/translated_sampler_bindings.h`: MIN_LOD and MAX_LOD +applied, which is why only the explicit-LOD forms are translated), and entry 2047 (`translated_sampler_fallback`) holding the +fallback sampler. The translator refuses index 2047, so the fallback is never read. None of this is implemented here; the fixture +builds its heap with `dynamic_sampler()` and the index parity itself. + +## Fixture + +`tests/native_sampler_heap.cpp`, `tests/native_sampler_heap_check.py`, `tests/cmake/native_sampler_heap.cmake`; tests +`native_sampler_heap_hardware` and `native_sampler_heap_warp` (`SKIP_RETURN_CODE 77`: WARP has no 32-lane waves). + +The script writes source-built compute requests (`.c67`, as `tests/native_compute_raw_root_check.py`) with the root +`RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))`, group 32x1x1 and +seven user SGPRs (s4 table, s5 resource heap, s6 sampler heap). The instruction words were assembled once with LLVM 15 +(`clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -filetype asm -show-encoding`) and are embedded with one source +comment per instruction; the test needs no LLVM. One SRV+UAV table is accepted by the direct path (no split into two tables was +needed). The programs copy s6 into an even SGPR pair with a constant-zero high word and sample a 4x4 two-mip texture at (1.375, +-0.375), outside [0, 1]: + +| Program | Shape | Expected | +|---|---|---| +| SAMPLE | `s_load_dwordx4` at 0x430 (entry 67), `image_sample_lz` | wrap texel (1, 2) of mip 0 | +| TWO | `s_load_dwordx8` at 0x430, two samples | entry 67 wrap, entry 68 clamp (a swapped second group fails) | +| LOD | `image_sample_l`, LOD 1 | MaxLOD 1 picks mip 1; decoys with MaxLOD 0 (bilinear and point) pick mip 0 | +| MIXED | one literal static sampler and entry 67 | static clamp texel and heap wrap texel; one static sampler in the program | + +The fixture dispatches on the RTX 3080 with a 128-entry sampler heap made with `dynamic_sampler()`. Every entry but the entries +under test is a decoy (clamp, mirror, border, a bilinear border with a white colour). It compares every lane with a CPU model, +then dispatches once per decoy with the decoy in place of the entry under test and requires the result to change. It also calls +`prepare_direct_compute` twice on the same fresh cache directory (a miss, then a hit) and requires exactly one binding +`{heap_sampler, compute_sampler_heap, 0, 0, 16 * (highest index + 1)}` in the computed and in the cached program, and that +`bind()` without a sampler heap throws. + +The script also compiles the refusal shapes and requires each exact text and no `.cso`: offset 0x438, entry 2047, `dwordx8` +at entries 2046 and 2047, `dwordx2` and `dwordx16`, an SGPR offset, a scalar buffer load, a sampler heap entry used as an image +descriptor, mixed literal and heap words in one sampler, a join that replaces the copied base on one path, `image_gather4_lz`, +`image_gather4_c_lz`, `image_sample_c_lz` and `image_sample_d` with a heap sampler, the HLSL profile, and a root with only +`0x400` (today's refusal, unchanged). Each has a control that compiles (entry 2046, `dwordx8` at 2045 and 2046, the branch +without the overwrite, the four operations with a literal sampler). + +## Result + +Environment: NVIDIA GeForce RTX 3080, Windows SDK 10.0.26100.0 DXC, D3D12 debug layer not enabled in the fixture. + +``` +ctest --preset dev --no-tests=error -R "^native_sampler_heap_(hardware|warp)$" -V +``` + +`native_sampler_heap_hardware` passes with 69 `ok:` assertions in the check script (the fixture's own per-mode checks print +`pass:` lines and are counted inside them); +`native_sampler_heap_warp` skips (77: no 32-lane waves). The regression set +`ctest --preset dev --no-tests=error -R "native_|startup_compute_dispatch|compute_heap" -j 6` passes (163 tests, 0 failed, 5 +skips: the four WARP tests that already skipped and the new one). + +## Limits + +- Stage 1 only: no runtime binding of a mirrored sampler heap for natively translated compute dispatch. +- GPU-selected sampler indices (SGPR offset), comparison, gather and gradient sampling through the heap, and containers are + refused. Roots with only the `0x800` flag (10 requests in the capture) are not covered. +- The fixture samples with point filters and compares exact texels; decoys are checked to change the result (and to run: + not the output sentinel), bilinear decoys only that. +- Not exercised by a test: the highest accepted entry 2046 in a sample (the edge controls only load it), and `bind()`'s + "a view heap is needed" throw (no test program reads the sampler heap without a view table). +- A passing fixture supports the behaviour under test; it does not establish that any title shader runs. diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index e633a50b20..5af615e14c 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -127,11 +127,13 @@ NativeComputeShader decode(std::string_view bytes) { unsigned n = in.count(1000000); shader.bindings.reserve(n); for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_buffer_srv))); + auto kind = static_cast(in.count(static_cast(ComputeViewKind::heap_sampler))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); + const bool sampler_heap = kind == ComputeViewKind::heap_sampler; if (!b.array_count || b.array_position >= b.array_count || - (b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) + (sampler_heap ? b.root_parameter != compute_sampler_heap + : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) throw std::runtime_error("invalid cached binding"); shader.bindings.push_back(b); } diff --git a/src/dxil_module.h b/src/dxil_module.h index c0f79867fc..21f344e793 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -154,6 +154,17 @@ class DxilModule { << "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n"; return h; } + // A sampler taken from the directly indexed sampler heap at a constant index (SM 6.6 SamplerDescriptorHeap[index]). + // The handle is annotated as a sampler (resource kind 14). The caller sets the module flag 0x80000000. + Text sampler_heap_handle(const Text &index) { + heap_used = true; + const Text h = "%heap" + std::to_string(sequence++); + body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index + << ", i1 true, i1 false)\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 14, i32 0 })\n"; + return h; + } Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { std::ostringstream out; out << "target datalayout = " diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 4a2f8949c7..3613e8de38 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -764,6 +764,8 @@ struct Emit { const bool indexed = sym.type == Symbol::Type::indexed_descriptor; if ((!indexed && sym.type != Symbol::Type::descriptor) || base + width > state.size()) refuse(i.pc, "unproven resource descriptor s" + to_string(base)); + if (sym.value == compute_sampler_heap) + refuse(i.pc, "a sampler heap descriptor is read as a resource"); const bool byte_window = kind == ComputeViewKind::byte_window_srv || (kind == ComputeViewKind::raw_buffer_uav && width == 4 && i.name == "buffer_store_raw" && state[base + 1].type == Symbol::Type::zero_stride_word); @@ -844,15 +846,44 @@ struct Emit { it->required_bytes = (std::max)(it->required_bytes, bytes); return (write ? "w" : "r") + to_string(it->shader_register); } - unsigned sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false, - bool implicit_sample = false, bool comparison = false) { + // heap: the sampler is entry `index` of the directly indexed sampler heap. Otherwise `index` is the static sampler register. + struct SamplerRef { + bool heap; + unsigned index; + }; + SamplerRef sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false, + bool implicit_sample = false, bool comparison = false) { const unsigned base = ((i.b >> 21) & 31) * 4; ComputeSampler sampler{{}, lod, comparison}; + unsigned literal = 0, heap = 0; + const auto &first = state.at(base); for (unsigned j = 0; j < 4; ++j) { const auto &s = state.at(base + j); - if (s.type != Symbol::Type::constant) - refuse(i.pc, "nonconstant sampler"); - sampler.words[j] = s.value; + literal += s.type == Symbol::Type::constant; + // The heap content is fixed within a dispatch, so contiguity of the four words of one 16-byte entry is enough. + heap += s.type == Symbol::Type::descriptor && s.value == compute_sampler_heap && !s.definition && + first.offset % 16 == 0 && s.offset == first.offset + 4 * j; + if (s.type == Symbol::Type::constant) + sampler.words[j] = s.value; + } + if (literal != 4 && heap != 4) + refuse(i.pc, "nonconstant sampler"); + if (heap == 4) { + if (gather_base_level) + refuse(i.pc, "gather through the sampler heap is not translated"); + if (comparison) + refuse(i.pc, "comparison sampler from the sampler heap is not translated"); + if (implicit_sample) + refuse(i.pc, "sampler from the sampler heap needs image_sample_l or image_sample_lz"); + const unsigned entry = first.offset / 16, bytes = 16 * (entry + 1); + auto &list = result.bindings; + auto found = std::find_if(list.begin(), list.end(), + [](const auto &b) { return b.kind == ComputeViewKind::heap_sampler; }); + if (found == list.end()) + list.push_back({ComputeViewKind::heap_sampler, compute_sampler_heap, 0, 0, bytes}); + else + found->required_bytes = (std::max)(found->required_bytes, bytes); + return {true, entry}; } if (comparison) { // Field constraints from pixel_aot.comparison_sampler_state. The @@ -891,7 +922,7 @@ struct Emit { all.push_back(sampler); it = std::prev(all.end()); } - return first_sampler+static_cast(it - all.begin()); + return {false, first_sampler + static_cast(it - all.begin())}; } void image(const Inst &i, const State &state) { unsigned mask = (i.a >> 8) & 15, base = ((i.b >> 16) & 31) * 4, addr = i.b & 255; @@ -927,7 +958,10 @@ struct Emit { if (lod || gather) { if (gather && mask != 1) refuse(i.pc, "unsupported gather channel"); - body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler_index(i, state, lod) + const auto sampler = sampler_index(i, state, lod); + if (sampler.heap) + refuse(i.pc, "sampler heap reads need the direct DXIL path"); + body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler.index << ",float2(asfloat(" << x << "),asfloat(" << y << "))" << (lod ? ",0);\n" : ");\n"); } else body << "t=" << tex << ".Load(int3(" << x << "," << y << ",0));\n"; @@ -1319,6 +1353,8 @@ struct Emit { if (i.op < 8) { if (s.at(i.src[0]).type != Symbol::Type::table) refuse(i.pc, "unknown scalar table base"); + if (s.at(i.src[0]).value == compute_sampler_heap) + refuse(i.pc, "sampler heap reads need the direct DXIL path"); if (s.at(i.src[0]).value == compute_resource_heap && i.b >> 25 == 125) refuse(i.pc, "unsupported immediate whole-heap descriptor"); if (i.b >> 25 != 125) { @@ -1525,8 +1561,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi } // In this compute ABI the two directly indexed heaps follow the user root parameters. // Require both flags and exactly two remaining user SGPRs, as in the matched native layouts. - if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) + if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) { initial[next] = {Symbol::Type::table, compute_resource_heap}; + initial[next + 1] = {Symbol::Type::table, compute_sampler_heap}; + } const bool wave64 = stage && !stage->wave32; // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 03dc53cec8..318434ae76 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -35,9 +35,15 @@ enum class ComputeViewKind { indexed_atomic_uav, d16_sample_srv, byte_window_srv, - heap_buffer_srv // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value. + heap_buffer_srv, // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value. + // The directly indexed sampler heap; entry n = title byte offset 16 * n (index parity); the runtime fills entries with + // dynamic_sampler() (LOD clamp applied, valid for the explicit-LOD forms translated here); entry 2047 is the runtime + // fallback and never read. + heap_sampler }; inline constexpr unsigned compute_resource_heap = ~0u; +// the directly indexed sampler heap; entry n is title byte offset 16 * n +inline constexpr unsigned compute_sampler_heap = ~0u - 1; // A binding of the whole descriptor heap: it has no table register and no root parameter. inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv; } inline bool compute_buffer_uav(ComputeViewKind kind) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index a2c8030f9c..68e182b253 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -501,6 +501,19 @@ struct DirectCompute { if (i.b & 0xfffff) refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); } + if (!root && low.type == Symbol::Type::table && low.value == compute_sampler_heap) { + // Reads from the directly indexed sampler heap: one or two samplers at a constant 16-byte aligned offset. + if (i.op >= 8) + refuse(i.pc, "scalar buffer load from the sampler heap is not translated"); + if (so != 125) + refuse(i.pc, "sampler heap load with an SGPR offset (a GPU-selected sampler) is not translated"); + if (i.op != 2 && i.op != 3) + refuse(i.pc, "sampler heap load must read one or two samplers"); + if ((i.b & 0xfffff) % 16) + refuse(i.pc, "sampler heap offset is not a multiple of 16"); + if ((i.b & 0xfffff) / 16 + (i.op == 3 ? 2 : 1) - 1 > 2046) + refuse(i.pc, "sampler heap index beyond 2046 (2047 is the runtime fallback entry)"); + } if (i.op < 8 && !root) { if (s.at(i.src[0]).type != Symbol::Type::table || s.at(i.src[0] + 1).type != Symbol::Type::constant || s.at(i.src[0] + 1).value != 0) @@ -813,11 +826,17 @@ struct DirectCompute { if (!store) { string r; if (sample || gather) { - auto sampler_reg = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, - implicit || gradient, compare); - if (i.op == 64 && (analysis.result.samplers.at(sampler_reg - analysis.first_sampler).words[1] & 0xffffff)) + const auto sampler_ref = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, + implicit || gradient, compare); + if (i.op == 64 && !sampler_ref.heap && + (analysis.result.samplers.at(sampler_ref.index - analysis.first_sampler).words[1] & 0xffffff)) refuse(i.pc, "implicit gather requires a sampler fixed to mip zero"); - auto sampler = ir.handle({3, sampler_reg, 14, 0, 0, 0, 1, compare}); + string sampler; + if (sampler_ref.heap) { + ir.features |= 0x80000000; + sampler = ir.sampler_heap_handle(to_string(sampler_ref.index)); + } else + sampler = ir.handle({3, sampler_ref.index, 14, 0, 0, 0, 1, compare}); using Arg = std::pair; std::vector args{{"%dx.types.Handle", h}, {"%dx.types.Handle", sampler}}; const auto size = (i.a & 0x1000u) ? texture_dimensions(h, "0") : string{}; diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp index 4ca6ff9477..ca74343cfe 100644 --- a/src/native_compute_pipeline.cpp +++ b/src/native_compute_pipeline.cpp @@ -35,6 +35,10 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade UINT counts[2]{}; for (const auto &binding : pipeline.bindings) { + if (binding.kind == ComputeViewKind::heap_sampler) { + pipeline.sampler_heap_indexed = true; // SamplerDescriptorHeap reads: no table register + continue; + } if (compute_heap_binding(binding.kind)) { pipeline.heap_indexed = true; // ResourceDescriptorHeap reads: no table register continue; @@ -89,9 +93,10 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param.Constants = {b.shader_register + 1, 0, 2}; } + const UINT root_flags = (pipeline.heap_indexed ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | (pipeline.sampler_heap_indexed ? 0x800u : 0u); // SAMPLER_HEAP_DIRECTLY_INDEXED D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast(samplers.size()), samplers.data(), - pipeline.heap_indexed ? static_cast(0x400) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED - : D3D12_ROOT_SIGNATURE_FLAG_NONE}; + static_cast(root_flags)}; Microsoft::WRL::ComPtr blob; if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), @@ -108,12 +113,24 @@ NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, Shade void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words, - const std::vector &atomic) const { + const std::vector &atomic, ID3D12DescriptorHeap *sampler_heap) const { if (constant_words && !words) throw std::runtime_error("compute root constants missing"); if (atomic.size() != atomic_views) throw std::runtime_error("indexed atomic view metadata missing"); - if (srv_count || uav_count || heap_indexed) + const bool views = srv_count || uav_count || heap_indexed; + if (sampler_heap_indexed) { + if (!sampler_heap) + throw std::runtime_error("a sampler heap is needed"); + if (views) { + if (!heap) + throw std::runtime_error("a view heap is needed"); + // Views first, then samplers, as bind_translated_heaps does. + ID3D12DescriptorHeap *heaps[2]{heap, sampler_heap}; + list->SetDescriptorHeaps(2, heaps); + } else + list->SetDescriptorHeaps(1, &sampler_heap); + } else if (views) list->SetDescriptorHeaps(1, &heap); list->SetComputeRootSignature(root.Get()); list->SetPipelineState(state.Get()); diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h index 9951cc67dc..c25c9ea0f7 100644 --- a/src/native_compute_pipeline.h +++ b/src/native_compute_pipeline.h @@ -20,13 +20,15 @@ struct NativeComputePipeline { bool cache_hit = false, frontend_cache_hit = false; bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set // on the list (bind() does it) and holds the selectable slots from index 0 + bool sampler_heap_indexed = false; // reads SamplerDescriptorHeap: the root has the directly indexed sampler heap flag (0x800), + // and bind() needs the shader-visible sampler heap (entry n = title byte offset 16 * n) double frontend_ms = 0; double backend_ms = 0; double pipeline_ms = 0; void bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words = nullptr, - const std::vector &atomic = {}) const; + const std::vector &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr) const; }; NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, diff --git a/tests/cmake/native_sampler_heap.cmake b/tests/cmake/native_sampler_heap.cmake new file mode 100644 index 0000000000..7f17283419 --- /dev/null +++ b/tests/cmake/native_sampler_heap.cmake @@ -0,0 +1,15 @@ +# Samplers read from the directly indexed sampler heap at a fixed index, translated natively (issue #3076). +# The fixture builds source-written compute requests, runs them on a sampler heap of decoys and compares with a CPU model; +# the check script also covers the compile refusals. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_sampler_heap tests/native_sampler_heap.cpp tests/desktop_gpu.cpp) + target_include_directories(native_sampler_heap PRIVATE src tests) + target_link_libraries(native_sampler_heap PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_sampler_heap PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_sampler_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sampler_heap_check.py" + "$" "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_sampler_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180) + endforeach() +endif() diff --git a/tests/native_sampler_heap.cpp b/tests/native_sampler_heap.cpp new file mode 100644 index 0000000000..17c480717b --- /dev/null +++ b/tests/native_sampler_heap.cpp @@ -0,0 +1,479 @@ +// Native compute fixture: samplers read from the directly indexed sampler heap at a fixed index (issue #3076). +// +// usage: native_sampler_heap SDK CACHE REQ.c67 ADAPTER MODE +// REQ.c67 a source-built compute request (tests/native_sampler_heap_check.py) whose root has +// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED and one SRV+UAV table. +// CACHE a fresh frontend cache directory: the fixture asserts a miss, then a hit on the same request. +// ADAPTER warp | hardware +// MODE sample one s_load_dwordx4 at 0x430 (entry 67), image_sample_lz at a coordinate outside [0, 1] +// two one s_load_dwordx8 at 0x430, two samples with entries 67 and 68 +// lod image_sample_l at LOD 1 of a two-mip texture; MaxLOD of the entry decides the mip +// mixed one literal static sampler and heap entry 67 in one program +// unbound bind() without a sampler heap throws +// The sampler heap has 128 entries, every one but the entries under test a decoy; each decoy is dispatched in place of +// the entry under test and must change the result. Entries are made with dynamic_sampler(), as the runtime does. +// Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "direct_compute_cache.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/translated_sampler_bindings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using x2w_startup::SamplerWords; + +namespace { +constexpr unsigned lanes = 32, heap_entries = 128; +constexpr float u_coordinate = 1.375f, v_coordinate = -0.375f; +constexpr std::uint32_t sentinel = 0x69696969u; +using Texel = std::array; + +// A 4x4 first mip and a 2x2 second mip with a distinct value in every texel and channel. +Texel texel(unsigned level, int x, int y) { + if (level == 0) return {10.f * x + 1, 10.f * y + 2, 100.f + x + 4 * y, 1000.f}; + return {500.f + x, 600.f + y, 700.f + x + 2 * y, 2000.f}; +} + +enum Address : unsigned { wrap = 0, mirror = 1, clamp = 2, border = 6 }; +// Title SQ_IMG_SAMP words in the encoding decode_sampler reads: clamp modes in word 0, MAX_LOD in word 1 (4.8 fixed +// point), filters and mip filter in word 2 (mip filter 1 = point), border colour type in word 3 (2 = opaque white). +SamplerWords title_sampler(Address address, bool bilinear, unsigned max_lod, bool white_border = false) { + const unsigned a = address, filter = bilinear ? 1u : 0u; + return {a | a << 3 | a << 6, (max_lod * 256u) << 12, filter << 20 | filter << 22 | 1u << 26, + white_border ? 2u << 30 : 0u}; +} + +// CPU model of a point-filtered sample at (u_coordinate, v_coordinate): the texel the address mode picks at the level the +// requested LOD gives after the sampler's MAX_LOD clamp. +Texel model(const SamplerWords &words, unsigned requested_lod) { + const unsigned level = (std::min)(requested_lod, (words[1] >> 12 & 0xfffu) / 256u); + const int n = 4 >> level; + int index[2]{int(std::floor(u_coordinate * n)), int(std::floor(v_coordinate * n))}; + bool outside = false; + for (int &i : index) { + switch (words[0] & 7u) { + case wrap: i = ((i % n) + n) % n; break; + case mirror: { + const int m = ((i % (2 * n)) + 2 * n) % (2 * n); + i = m < n ? m : 2 * n - 1 - m; + break; + } + case clamp: i = (std::max)(0, (std::min)(i, n - 1)); break; + default: outside |= i < 0 || i >= n; break; + } + } + if (outside) { + const float white = (words[3] >> 30) == 2 ? 1.f : 0.f; + return {white, white, white, white}; + } + return texel(level, index[0], index[1]); +} + +// One heap entry under test: the float4 of `result` must equal `expected` and a decoy in its place must change it. +struct Probe { + unsigned entry, result; + SamplerWords words; + unsigned lod; +}; +struct Mode { + std::vector probes; + std::vector decoys; + unsigned results = 1, statics = 0; + std::map fixed; // results that do not come from the heap (the static sampler) + unsigned highest_entry = 0; +}; + +Mode make_mode(const std::wstring &name) { + Mode mode; + const auto wrap_point = title_sampler(wrap, false, 0), clamp_point = title_sampler(clamp, false, 0), + mirror_point = title_sampler(mirror, false, 0), border_clear = title_sampler(border, false, 0), + border_white = title_sampler(border, true, 0, true); + if (name == L"sample") { + mode.probes = {{67, 0, wrap_point, 0}}; + mode.decoys = {clamp_point, mirror_point, border_clear, border_white}; + } else if (name == L"two") { + mode.results = 2; + mode.probes = {{67, 0, wrap_point, 0}, {68, 1, clamp_point, 0}}; + mode.decoys = {mirror_point, border_clear, border_white}; + } else if (name == L"lod") { + mode.probes = {{67, 0, title_sampler(wrap, false, 1), 1}}; + // MaxLOD 0 with a bilinear and a point filter (the LOD clamp must matter), and a wrong address mode at MaxLOD 1. + mode.decoys = {title_sampler(wrap, true, 0), title_sampler(wrap, false, 0), title_sampler(clamp, false, 1)}; + } else if (name == L"mixed") { + mode.results = 2; + mode.statics = 1; + mode.probes = {{67, 1, wrap_point, 0}}; + mode.decoys = {clamp_point, mirror_point, border_clear}; + mode.fixed[0] = model(SamplerWords{0x92u, 0, 0, 0}, 0); // the literal static sampler: clamp, point + } + for (const auto &probe : mode.probes) mode.highest_entry = (std::max)(mode.highest_entry, probe.entry); + return mode; +} + +struct Gpu { + ComPtr device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + ComPtr views; + ComPtr texture, output, readback, clear; + UINT view_increment = 0, sampler_increment = 0; + UINT output_bytes = 0; + + ~Gpu() { + if (event) CloseHandle(event); + } + + // Returns 77 when the adapter cannot run the fixture; 0 when ready. + int open(const std::wstring &adapter) { + ComPtr factory; + ComPtr chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + // An older runtime refuses roots with the heap-indexing flags (E_INVALIDARG): a capability skip, not a failure. + { + D3D12_ROOT_SIGNATURE_DESC probe{0, nullptr, 0, nullptr, static_cast(0xc00)}; + ComPtr blob; + ComPtr root; + if (FAILED(D3D12SerializeRootSignature(&probe, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) { + std::puts("adapter refuses a root with the heap-indexing flags 0xc00"); + return 77; + } + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + view_increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + sampler_increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + return 0; + } + + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + template void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + check(device->GetDeviceRemovedReason(), "device removed"); + } + static D3D12_RESOURCE_BARRIER barrier(ID3D12Resource *resource, D3D12_RESOURCE_STATES before, + D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + return b; + } + + // t0 of the guest table: a 4x4 two-mip texture; u0: one float4 per result and lane, as a raw buffer. + void create_resources(unsigned results) { + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = 4; + td.DepthOrArraySize = 1; + td.MipLevels = 2; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + texture = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[2]{}; + UINT64 total = 0; + device->GetCopyableFootprints(&td, 0, 2, 0, footprints, nullptr, nullptr, &total); + auto upload = make_buffer(device.Get(), total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(upload->Map(0, nullptr, &mapped), "texture upload map"); + for (unsigned level = 0; level < 2; ++level) + for (int y = 0; y < (4 >> level); ++y) + for (int x = 0; x < (4 >> level); ++x) + std::memcpy(static_cast(mapped) + footprints[level].Offset + + y * footprints[level].Footprint.RowPitch + x * sizeof(Texel), + texel(level, x, y).data(), sizeof(Texel)); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { + for (UINT level = 0; level < 2; ++level) { + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = footprints[level]; + dst.SubresourceIndex = level; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + auto to_read = barrier(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + l->ResourceBarrier(1, &to_read); + }); + output_bytes = lanes * results * sizeof(Texel); + output = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + readback = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + clear = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(clear->Map(0, nullptr, &mapped), "sentinel map"); + for (unsigned i = 0; i < output_bytes / 4; ++i) static_cast(mapped)[i] = sentinel; + clear->Unmap(0, nullptr); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "view heap"); + auto cpu = views->GetCPUDescriptorHandleForHeapStart(); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = td.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 2; + device->CreateShaderResourceView(texture.Get(), &srv, cpu); + cpu.ptr += view_increment; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = output_bytes / 4; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(output.Get(), nullptr, &uav, cpu); + } + + // The sampler heap of the run: every entry a decoy (cycling through `decoys`), `entries` replaced. + ComPtr sampler_heap(const std::vector &decoys, + const std::map &entries) { + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, heap_entries, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "sampler heap"); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + for (unsigned i = 0; i < heap_entries; ++i) { + auto found = entries.find(i); + const auto desc = x2w_startup::dynamic_sampler(found != entries.end() ? found->second : decoys[i % decoys.size()]); + device->CreateSampler(&desc, cpu); + cpu.ptr += sampler_increment; + } + return heap; + } + + // Fills u0 with a sentinel, dispatches one group of 32 lanes, reads u0 back as floats. + std::vector dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12DescriptorHeap *samplers) { + run([&](ID3D12GraphicsCommandList *l) { + auto to_copy = barrier(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + l->ResourceBarrier(1, &to_copy); + l->CopyBufferRegion(output.Get(), 0, clear.Get(), 0, output_bytes); + auto to_uav = barrier(output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + l->ResourceBarrier(1, &to_uav); + pipeline.bind(l, views.Get(), views->GetGPUDescriptorHandleForHeapStart(), view_increment, nullptr, {}, + samplers); + l->Dispatch(1, 1, 1); + auto to_source = barrier(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + l->ResourceBarrier(1, &to_source); + l->CopyBufferRegion(readback.Get(), 0, output.Get(), 0, output_bytes); + auto back = barrier(output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + l->ResourceBarrier(1, &back); + }); + std::vector out(output_bytes / 4); + void *mapped = nullptr; + D3D12_RANGE range{0, output_bytes}; + check(readback->Map(0, &range, &mapped), "readback map"); + std::memcpy(out.data(), mapped, output_bytes); + D3D12_RANGE written{}; + readback->Unmap(0, &written); + return out; + } +}; + +bool equal(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } +const char *texel_text(const Texel &t, char (&buffer)[96]) { + std::snprintf(buffer, sizeof buffer, "(%g, %g, %g, %g)", t[0], t[1], t[2], t[3]); + return buffer; +} + +// 0: every lane holds `expected` in float4 `result`. Otherwise the first mismatch is printed. +bool lanes_hold(const std::vector &values, unsigned results, unsigned result, const Texel &expected, + const char *what) { + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &values[(lane * results + result) * 4], sizeof got); + if (!equal(got, expected)) { + char a[96], b[96]; + std::printf("FAIL: %s: lane %u result %u is %s, expected %s\n", what, lane, result, texel_text(got, a), + texel_text(expected, b)); + return false; + } + } + return true; +} +// Every lane must hold a result other than `expected`, and not the untouched output sentinel (the dispatch ran). +bool lanes_differ(const std::vector &values, unsigned results, unsigned result, const Texel &expected) { + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &values[(lane * results + result) * 4], sizeof got); + std::uint32_t bits[4]; + std::memcpy(bits, got.data(), sizeof bits); + if (equal(got, expected) || (bits[0] == sentinel && bits[1] == sentinel && bits[2] == sentinel && + bits[3] == sentinel)) + return false; + } + return true; +} + +int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::filesystem::path &marker, Gpu &gpu, + const std::wstring &name) { + const bool unbound = name == L"unbound"; + const Mode mode = make_mode(unbound ? L"sample" : name); + if (mode.probes.empty()) { + std::puts("unknown mode"); + return 2; + } + // Frontend cache: a miss on the fresh directory, then a hit with the same binding record. + bool first_hit = true, second_hit = false; + const auto first = x2w::prepare_direct_compute(marker, 0, false, cache, first_hit); + const auto second = x2w::prepare_direct_compute(marker, 0, false, cache, second_hit); + if (first_hit || !second_hit) { + std::printf("FAIL: frontend cache first call hit=%d second call hit=%d\n", int(first_hit), int(second_hit)); + return 1; + } + std::puts("pass: prepare_direct_compute misses on a fresh cache and hits on the second call"); + for (const auto *program : {&first, &second}) { + unsigned count = 0; + for (const auto &b : program->bindings) { + if (b.kind != x2w::ComputeViewKind::heap_sampler) continue; + ++count; + if (b.root_parameter != x2w::compute_sampler_heap || b.byte_offset != 0 || b.shader_register != 0 || + b.required_bytes != 16 * (mode.highest_entry + 1) || b.array_count != 1 || b.array_position != 0 || + b.image_dimension != 1 || b.scalar_table != x2w::ComputeViewBinding::ScalarTable::unknown) { + std::printf("FAIL: heap_sampler binding root=%u offset=%u register=%u bytes=%u\n", b.root_parameter, + b.byte_offset, b.shader_register, b.required_bytes); + return 1; + } + } + if (count != 1 || program->samplers.size() != mode.statics) { + std::printf("FAIL: %u heap_sampler bindings, %zu static samplers\n", count, program->samplers.size()); + return 1; + } + } + std::printf("pass: one heap_sampler binding {compute_sampler_heap, 0, 0, %u bytes} in the computed and the cached " + "program, %u static samplers\n", 16 * (mode.highest_entry + 1), mode.statics); + + x2w::ShaderDxilCompiler compiler(sdk); + auto pipeline = x2w::create_native_compute_pipeline(gpu.device.Get(), compiler, marker, 0, cache, true); + if (!pipeline.sampler_heap_indexed || pipeline.heap_indexed || pipeline.srv_count != 1 || pipeline.uav_count != 1 || + !pipeline.frontend_cache_hit) { + std::printf("FAIL: pipeline shape sampler_heap_indexed=%d heap_indexed=%d srv=%u uav=%u frontend_hit=%d\n", + int(pipeline.sampler_heap_indexed), int(pipeline.heap_indexed), pipeline.srv_count, + pipeline.uav_count, int(pipeline.frontend_cache_hit)); + return 1; + } + std::puts("pass: pipeline has sampler_heap_indexed, no resource-heap indexing, one SRV and one UAV"); + gpu.create_resources(mode.results); + + if (unbound) { + // bind() without a sampler heap must throw before anything is recorded for it. + bool threw = false; + try { + gpu.run([&](ID3D12GraphicsCommandList *l) { + pipeline.bind(l, gpu.views.Get(), gpu.views->GetGPUDescriptorHandleForHeapStart(), gpu.view_increment); + }); + } catch (const std::runtime_error &error) { + threw = std::string(error.what()) == "a sampler heap is needed"; + std::printf("bind without a sampler heap: %s\n", error.what()); + } + if (!threw) { + std::puts("FAIL: bind without a sampler heap did not throw"); + return 1; + } + std::puts("pass: bind without a sampler heap throws \"a sampler heap is needed\""); + return 0; + } + + std::map entries; + for (const auto &probe : mode.probes) entries[probe.entry] = probe.words; + const auto values = gpu.dispatch(pipeline, gpu.sampler_heap(mode.decoys, entries).Get()); + for (const auto &[result, expected] : mode.fixed) + if (!lanes_hold(values, mode.results, result, expected, "static sampler")) return 1; + if (!mode.fixed.empty()) std::puts("pass: the literal static sampler result matches the CPU model"); + for (const auto &probe : mode.probes) { + const Texel expected = model(probe.words, probe.lod); + if (!lanes_hold(values, mode.results, probe.result, expected, "heap entry")) return 1; + std::printf("pass: entry %u (result %u) equals the CPU model in all %u lanes\n", probe.entry, probe.result, lanes); + // The same program with a decoy in place of the entry under test must give another result. + for (size_t d = 0; d < mode.decoys.size(); ++d) { + auto swapped = entries; + swapped[probe.entry] = mode.decoys[d]; + const auto other = gpu.dispatch(pipeline, gpu.sampler_heap(mode.decoys, swapped).Get()); + if (!lanes_differ(other, mode.results, probe.result, expected)) { + std::printf("FAIL: decoy %zu in place of entry %u leaves result %u unchanged\n", d, probe.entry, + probe.result); + return 1; + } + std::printf("pass: decoy %zu in place of entry %u changes result %u\n", d, probe.entry, probe.result); + } + } + return 0; +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 6) { + std::fputs("usage: native_sampler_heap SDK CACHE REQ.c67 ADAPTER sample|two|lod|mixed|unbound\n", stderr); + return 2; + } + Gpu gpu; + try { + if (int skip = gpu.open(argv[4])) return skip; + return run_mode(argv[1], argv[2], argv[3], gpu, argv[5]); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} diff --git a/tests/native_sampler_heap_check.py b/tests/native_sampler_heap_check.py new file mode 100644 index 0000000000..2d20e2aa8f --- /dev/null +++ b/tests/native_sampler_heap_check.py @@ -0,0 +1,365 @@ +"""Samplers read from the directly indexed sampler heap at a fixed index, translated natively (issue #3076). + +usage: native_sampler_heap_check.py FIXTURE COMPILE_DXIL SDK ADAPTER + +Compute requests are written from source: user SGPRs s4 (the SRV+UAV descriptor table), s5 (the resource heap) and s6 (the +sampler heap) under RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED). The programs copy s6 +into an even SGPR pair with a constant-zero high word, load one sampler (s_load_dwordx4) or two (s_load_dwordx8) at a +16-byte aligned immediate offset (0x430 is entry 67) and sample a two-mip texture at a coordinate outside [0, 1]: + + SAMPLE image_sample_lz with entry 67 TWO entries 67 and 68 from one s_load_dwordx8 + LOD image_sample_l at LOD 1, MaxLOD decides MIXED one literal static sampler and entry 67 + +The `native_sampler_heap` fixture runs them with a sampler heap of decoys, compares every lane with a CPU model, puts each +decoy in place of the entry under test (the result must change), checks the frontend cache round trip and the binding +record, and shows that bind() without a sampler heap throws. This script also compiles the refusal shapes and checks each +refusal text (and that no .cso is written), each with a control that compiles. Exit 77 when the fixture reports a +capability skip (WARP has no 32-lane waves). + +Instruction words were assembled once with LLVM 15 (clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 +-filetype asm -show-encoding); the comment on each line is the assembler source. The test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +# Same helper as native_compute_raw_root_check.py: writes req_.c67 and its parts. +from native_compute_clear_check import write_request + +ROOT_RW = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +ROOT_VIEWS_ONLY = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" + +REFUSALS = { + "buffer": "scalar buffer load from the sampler heap is not translated", + "sgpr": "sampler heap load with an SGPR offset (a GPU-selected sampler) is not translated", + "shape": "sampler heap load must read one or two samplers", + "align": "sampler heap offset is not a multiple of 16", + "bound": "sampler heap index beyond 2046 (2047 is the runtime fallback entry)", + "hlsl": "sampler heap reads need the direct DXIL path", + "resource": "a sampler heap descriptor is read as a resource", + "gather": "gather through the sampler heap is not translated", + "compare": "comparison sampler from the sampler heap is not translated", + "implicit": "sampler from the sampler heap needs image_sample_l or image_sample_lz", + "mixed": "nonconstant sampler", + "table": "direct descriptor address outside bound table", +} + +# --- instruction blocks ------------------------------------------------------------------------------------------- +BASES = [ + 0xbe880304, # s_mov_b32 s8, s4 (s[8:9]: the table pointer, high word constant 0) + 0xbe890380, # s_mov_b32 s9, 0 + 0xbe8a0306, # s_mov_b32 s10, s6 (s[10:11]: the sampler heap base, high word constant 0) + 0xbe8b0380, # s_mov_b32 s11, 0 +] +TABLE_LOADS = [ + 0xf40c0404, 0xfa000000, # s_load_dwordx8 s[16:23], s[8:9], 0x0 (t0: the texture) + 0xf4080604, 0xfa000020, # s_load_dwordx4 s[24:27], s[8:9], 0x20 (u0: the output buffer) +] +SAMPLER_X4 = [ + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 (entry 67) +] +COORDINATES = [ + 0x7e0202ff, 0x3fb00000, # v_mov_b32_e32 v1, 0x3fb00000 (u = 1.375) + 0x7e0402ff, 0xbec00000, # v_mov_b32_e32 v2, 0xbec00000 (v = -0.375) +] +LOD_ONE = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 (LOD 1) +] +WAIT_SCALAR = [ + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) +] +WAIT_VECTOR = [ + 0xbf8c3f70, # s_waitcnt vmcnt(0) +] +END = [ + 0xbf810000, # s_endpgm +] +LITERAL_STATIC = [ + 0xbea803ff, 0x00000092, # s_mov_b32 s40, 0x92 (static sampler: clamp x, y and z, point) + 0xbea90380, # s_mov_b32 s41, 0 + 0xbeaa0380, # s_mov_b32 s42, 0 + 0xbeab0380, # s_mov_b32 s43, 0 +] +STORE_ONE = [ + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen +] +STORE_TWO = [ + 0x34100085, # v_lshlrev_b32_e32 v8, 5, v0 + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen + 0xe0781010, 0x80060c08, # buffer_store_dwordx4 v[12:15], v8, s[24:27], 0 offen offset:16 +] +SAMPLE_LZ_HEAP = [ + 0xf09c0f08, 0x00640401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D +] +# Operands for the refusal and control shapes: four coordinates after u and v, a sampler built from literals. +FILL_V3_V6 = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 + 0x7e0802f2, # v_mov_b32_e32 v4, 1.0 + 0x7e0a02f2, # v_mov_b32_e32 v5, 1.0 + 0x7e0c02f2, # v_mov_b32_e32 v6, 1.0 +] +SAMPLER_LITERAL = [ + 0xbe8c03ff, 0x08001012, # s_mov_b32 s12, 0x8001012 (comparison_program of native_direct_container_check.py) + 0xbe8d03ff, 0x00fff000, # s_mov_b32 s13, 0xfff000 + 0xbe8e03ff, 0x04000000, # s_mov_b32 s14, 0x4000000 + 0xbe8f0380, # s_mov_b32 s15, 0 +] + + +def operation(op_words): + return [*BASES, *TABLE_LOADS, "SAMPLER", *COORDINATES, *FILL_V3_V6, *WAIT_SCALAR, *op_words, *END] + + +OPERATIONS = { + "gather4_lz": [0xf11c0108, 0x00640801], # image_gather4_lz v[8:11], v[1:2], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "gather4_c_lz": [0xf13c0108, 0x00640801], # image_gather4_c_lz v[8:11], v[1:3], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "sample_c_lz": [0xf0bc0108, 0x00640801], # image_sample_c_lz v8, v[1:3], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "sample_d": [0xf0880f08, 0x00640801], # image_sample_d v[8:11], v[1:6], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D +} + + +def with_sampler(program, sampler): + out = [] + for word in program: + out.extend(sampler if word == "SAMPLER" else [word]) + return out + + +PROGRAMS = { + "sample": [*BASES, *TABLE_LOADS, *SAMPLER_X4, *COORDINATES, *WAIT_SCALAR, *SAMPLE_LZ_HEAP, *WAIT_VECTOR, *STORE_ONE, *END], + "two": [ + *BASES, *TABLE_LOADS, + 0xf40c0805, 0xfa000430, # s_load_dwordx8 s[32:39], s[10:11], 0x430 (entries 67 and 68) + *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01040401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[32:35] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x01240c01, # image_sample_lz v[12:15], v[1:2], s[16:23], s[36:39] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_TWO, *END], + "lod": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, *COORDINATES, *LOD_ONE, *WAIT_SCALAR, + 0xf0900f08, 0x00640401, # image_sample_l v[4:7], v[1:3], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_ONE, *END], + "mixed": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, *LITERAL_STATIC, *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01440401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x00640c01, # image_sample_lz v[12:15], v[1:2], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_TWO, *END], + # Refusal shapes. Each one stops at the instruction under test. + "dx2": [*BASES, + 0xf4040305, 0xfa000430, # s_load_dwordx2 s[12:13], s[10:11], 0x430 + *END], + "dx16": [*BASES, + 0xf4100405, 0xfa000400, # s_load_dwordx16 s[16:31], s[10:11], 0x400 + *END], + "off438": [*BASES, + 0xf4080305, 0xfa000438, # s_load_dwordx4 s[12:15], s[10:11], 0x438 + *END], + "idx2047": [*BASES, + 0xf4080305, 0xfa007ff0, # s_load_dwordx4 s[12:15], s[10:11], 0x7ff0 + *END], + "bound2": [*BASES, + 0xf40c0405, 0xfa007fe0, # s_load_dwordx8 s[16:23], s[10:11], 0x7fe0 (entries 2046 and 2047) + *END], + "sgpr_offset": [*BASES, + 0xbe9403ff, 0x00000430, # s_mov_b32 s20, 0x430 + 0xf4080305, 0x28000000, # s_load_dwordx4 s[12:15], s[10:11], s20 + *END], + "bufload": [ + 0xbe880306, # s_mov_b32 s8, s6 + 0xbe890380, # s_mov_b32 s9, 0 + 0xf4200304, 0xfa000000, # s_buffer_load_dword s12, s[8:11], 0x0 + *END], + "asres": [ + *BASES, + 0xf40c0405, 0xfa000400, # s_load_dwordx8 s[16:23], s[10:11], 0x400 (a sampler heap entry as the image descriptor) + *LITERAL_STATIC, *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01440401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + *END], + "mixed_words": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, + 0xbe8c03ff, 0x00000092, # s_mov_b32 s12, 0x92 (word 0 of the sampler becomes a literal; words 1 to 3 stay heap words) + *COORDINATES, *WAIT_SCALAR, *SAMPLE_LZ_HEAP, *END], + "join": [ + *BASES, + 0xbe940381, # s_mov_b32 s20, 1 + 0xbf068014, # s_cmp_eq_u32 s20, 0 + 0xbf850001, # s_cbranch_scc1 1 (skips the next instruction) + 0xbe8a0380, # s_mov_b32 s10, 0 (one path replaces the copied heap base) + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 + *END], + # Controls: the same shapes with the one change that makes them valid. + "join_control": [ + *BASES, + 0xbe940381, # s_mov_b32 s20, 1 + 0xbf068014, # s_cmp_eq_u32 s20, 0 + 0xbf850001, # s_cbranch_scc1 1 + 0xbe950380, # s_mov_b32 s21, 0 (the skipped instruction leaves the heap base alone) + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 + *END], + "edge2046": [*BASES, + 0xf4080305, 0xfa007fe0, # s_load_dwordx4 s[12:15], s[10:11], 0x7fe0 (entry 2046, the last one) + *END], + "x8_edge": [*BASES, + 0xf40c0405, 0xfa007fd0, # s_load_dwordx8 s[16:23], s[10:11], 0x7fd0 (entries 2045 and 2046) + *END], +} +for op_name, op_words in OPERATIONS.items(): + PROGRAMS["heap_" + op_name] = with_sampler(operation(op_words), SAMPLER_X4) + PROGRAMS["literal_" + op_name] = with_sampler(operation(op_words), SAMPLER_LITERAL) + + +def main(): + fixture, compile_dxil, sdk, adapter = sys.argv[1:5] + ok_lines = 0 + + def require(condition, message): + nonlocal ok_lines + if not condition: + print("FAIL: " + message) + sys.exit(1) + ok_lines += 1 + print("ok: " + message) + + def run(command, expect_skip=False): + result = subprocess.run([str(part) for part in command], capture_output=True, timeout=150) + out = result.stdout.decode("utf-8", "replace") + err = result.stderr.decode("utf-8", "replace") + print("$ " + " ".join(pathlib.Path(str(c)).name if i == 0 else str(c) for i, c in enumerate(command))) + for text in (out, err): + for line in text.strip().splitlines(): + print(" " + line) + print(f" -> exit {result.returncode}") + if result.returncode == 77 and expect_skip: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + with tempfile.TemporaryDirectory(prefix="x2w_sampler_heap_") as scratch: + base = pathlib.Path(scratch) + # Sampler heap content, texture and expectations are in the fixture; the requests are written here. + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, 7 << 1) # group 32x1x1, 7 user SGPRs + roots = {} + + def root(text): + if text not in roots: + source = base / f"root{len(roots)}.hlsl" + source.write_text(f'#define RS "{text}"') + binary = base / f"root{len(roots)}.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + roots[text] = binary.read_bytes() + return roots[text] + + counter = 0 + + def request(name, root_text=ROOT_RW): + nonlocal counter + counter += 1 + folder = base / f"req_{counter}_{name}" + folder.mkdir() + return write_request(folder, PROGRAMS[name], root(root_text), sa) + + def compile_request(marker, profile="gfx1013-direct-cs@0", cache=None): + output = marker.with_suffix(".cso") + code, out, err = run([compile_dxil, sdk, cache or marker.parent / "cache", profile, marker, output]) + return code, out, err, output + + def refused(name, key, root_text=ROOT_RW, profile="gfx1013-direct-cs@0"): + marker = request(name, root_text) + code, out, err, output = compile_request(marker, profile) + require(code != 0 and REFUSALS[key] in err and not output.exists(), + f"{name}: refused with \"{REFUSALS[key]}\" and no .cso") + + def accepted(name, message): + marker = request(name) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists() and "sampler_heap span" not in out, message) + return out + + # 1. Fixture runs. A fresh frontend cache per run: the fixture asserts a miss and then a hit. + expected_lines = { + "sample": ["entry 67 (result 0) equals the CPU model in all 32 lanes", + *[f"decoy {n} in place of entry 67 changes result 0" for n in range(4)], + "{compute_sampler_heap, 0, 0, 1088 bytes}"], + "two": ["entry 67 (result 0) equals the CPU model", "entry 68 (result 1) equals the CPU model", + *[f"decoy {n} in place of entry {e} changes result {e - 67}" for e in (67, 68) for n in range(3)], + "{compute_sampler_heap, 0, 0, 1104 bytes}"], + "lod": ["entry 67 (result 0) equals the CPU model", + *[f"decoy {n} in place of entry 67 changes result 0" for n in range(3)], + "{compute_sampler_heap, 0, 0, 1088 bytes}"], + "mixed": ["the literal static sampler result matches the CPU model", "entry 67 (result 1) equals the CPU model", + *[f"decoy {n} in place of entry 67 changes result 1" for n in range(3)], + "1088 bytes}"], + } + for mode, lines in expected_lines.items(): + marker = request(mode) + cache = base / f"cache_{mode}" + cache.mkdir() + code, out, err = run([fixture, sdk, cache, marker, adapter, mode], expect_skip=True) + require(code == 0, f"fixture mode {mode} exits 0") + for line in lines: + require(line in out, f"{mode}: {line}") + require("pass: prepare_direct_compute misses on a fresh cache and hits on the second call" in out, + f"{mode}: frontend cache round trip (miss, then hit)") + require("pass: pipeline has sampler_heap_indexed" in out, f"{mode}: pipeline asks for the sampler heap flag only") + code, out, err = run([fixture, sdk, base / "cache_unbound", request("sample"), adapter, "unbound"], expect_skip=True) + require(code == 0 and "bind without a sampler heap throws" in out, "bind without a sampler heap throws") + + # 2. compile_dxil: the module reads the sampler from the heap and the binding record is reported. + marker = request("sample") + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), "compile_dxil compiles SAMPLE") + require("sampler_heap span=1088" in out, "compile_dxil reports sampler_heap span=1088 for entry 67") + code2, out2, err2, _ = compile_request(marker) + require(code2 == 0 and "frontend_cache_hit=1" in out2, "the second compile hits the frontend cache") + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, text=True).stdout + require("@dx.op.createHandleFromHeap(i32 218, i32 67, i1 true, i1 false)" in listing, + "the module creates the sampler with createHandleFromHeap(218, index 67, sampler heap, uniform)") + require(listing.count("@dx.op.createHandleFromBinding(") >= 2, + "the texture and the output buffer stay table bindings (createHandleFromBinding)") + marker = request("two") + code, out, err, output = compile_request(marker) + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, text=True).stdout + require(code == 0 and "sampler_heap span=1104" in out and + "createHandleFromHeap(i32 218, i32 67, i1 true, i1 false)" in listing and + "createHandleFromHeap(i32 218, i32 68, i1 true, i1 false)" in listing, + "TWO: one s_load_dwordx8 gives sampler heap handles 67 and 68") + marker = request("sample") + requests = marker.parent + out_dir = base / "requests_out" + code, out, err = run([compile_dxil, sdk, base / "cache_requests", "gfx1013-direct-cs@0", "--requests", requests, out_dir]) + stem = marker.stem[len("req_"):] + require(code == 0 and (out_dir / (stem + ".cs.cso")).exists() and not (out_dir / (stem + ".txt")).exists(), + "--requests publishes .cs.cso and no runtime manifest (.txt) for a sampler heap program") + + # 3. Refusals, each with its text, and controls that compile. + refused("off438", "align") + refused("idx2047", "bound") + refused("bound2", "bound") + refused("dx2", "shape") + refused("dx16", "shape") + refused("sgpr_offset", "sgpr") + refused("bufload", "buffer") + refused("asres", "resource") + refused("mixed_words", "mixed") + refused("join", "table") + refused("heap_gather4_lz", "gather") + refused("heap_gather4_c_lz", "gather") + refused("heap_sample_c_lz", "compare") + refused("heap_sample_d", "implicit") + accepted("edge2046", "control: entry 2046 (offset 0x7fe0) compiles") + accepted("x8_edge", "control: s_load_dwordx8 at entries 2045 and 2046 compiles") + accepted("join_control", "control: the same branch without the overwrite compiles") + for op_name in OPERATIONS: + accepted("literal_" + op_name, f"control: {op_name} with a literal sampler compiles") + # The HLSL path has no sampler heap handle; a root with only the views flag has no sampler heap base. + refused("sample", "hlsl", profile="gfx1013-compute-wave32@0") + refused("sample", "table", root_text=ROOT_VIEWS_ONLY) + + print(f"{ok_lines} assertions held") + + +if __name__ == "__main__": + main() diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index 7fb8f8da63..34f7cafcaa 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -124,6 +124,10 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, <<" request_and_translation_ms="<