From 5c1c21d069bf700137b49689c84170db15d028ca Mon Sep 17 00:00:00 2001 From: timbot103 <306940367+timbot103@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:21:25 +1000 Subject: [PATCH] shader: extend lane-local lowering in masked pixel regions Part of #3814 --- docs/experiments.md | 4 + .../native-pixel-masked-region-alu.md | 13 ++ src/gfx1013_direct_compute.inl | 9 +- src/gfx1013_direct_graphics.inl | 97 +++++++- .../native_pixel_masked_region_alu.cmake | 14 ++ tests/desktop_gpu.h | 3 +- tests/native_direct_container_check.py | 9 +- tests/native_pixel_masked_region_alu_check.py | 208 ++++++++++++++++++ tests/offscreen_check.cpp | 10 +- tests/startup_image_3d.cpp | 22 +- 10 files changed, 365 insertions(+), 24 deletions(-) create mode 100644 docs/experiments/native-pixel-masked-region-alu.md create mode 100644 tests/cmake/native_pixel_masked_region_alu.cmake create mode 100644 tests/native_pixel_masked_region_alu_check.py diff --git a/docs/experiments.md b/docs/experiments.md index 7c79dabb28..f0026aebde 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18513,3 +18513,7 @@ ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware) ``` Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. + +## Lane-local operations in masked pixel regions + +[Native DXIL lowering and 8×2 readback fixture](experiments/native-pixel-masked-region-alu.md) diff --git a/docs/experiments/native-pixel-masked-region-alu.md b/docs/experiments/native-pixel-masked-region-alu.md new file mode 100644 index 0000000000..2b4686d53d --- /dev/null +++ b/docs/experiments/native-pixel-masked-region-alu.md @@ -0,0 +1,13 @@ +# Lane-local operations in masked pixel regions + +The native pixel translator can flatten a proven EXEC partition and merge each VGPR write with its incoming bits. The supported additions cover `s_clause`, the three `v_fma_mix*` forms, and texture loads and samples with explicit LOD or gradients through fixed bindings. Fixed table buffer loads redirect inactive addresses to the start of the bound view. The binding records the minimum size for that read. + +An arm can use a VCC comparison as the lane bit for `v_cndmask_b32`, and can use numeric scalar arithmetic or fixed-offset scalar buffer reads. The translator expires the arm's SGPR, VCC and SCC results at the corresponding complement or restore. It rejects saved EXEC clobbers. Implicit derivatives, cross-lane operations and new memory writes are outside the supported set. `image_sample_d_cl`, `image_sample_c_l` and graphics MTBUF forms have no lowering in this path. + +```powershell +cmake --build out/build/dev --target compile_dxil offscreen_check native_pixel_ir_dump -- -j 6 +ctest --preset pr --no-tests=error --output-on-failure -R '^native_pixel_masked_region_alu_controls$' +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -R '^native_pixel_masked_region_alu_(warp|hardware)$' +``` + +Repeat with `out/build/release` for Release. The controls validate the generated DXIL and check refusals for implicit sampling, stores, wave operations, escaped scalar results and saved EXEC clobbers. The GPU fixture checks every pixel of an 8×2 draw. Its wrong reference uses the THEN result in the six inactive pixels and must first differ at pixel `(0,0)`. The fixture also gives inactive lanes a deliberately out-of-view raw buffer address. diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 749b71c809..ae38364e7e 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1056,6 +1056,8 @@ struct DirectCompute { valid = ir.value("and i1 " + valid + ", " + cmp("ule", within, to_string(stride - offset - 4*n))); start = ir.binary("add", start, within); } + if (pixel_stage && !graphics_predicate.empty()) + start = select(graphics_predicate, start, "0"); auto result = load_buffer(h, start, true, n); for (unsigned j=0; j> 24) != 128) refuse(i.pc, "unsupported raw root buffer descriptor or offset"); h = root_buffer_handle(low.value, 4*n); } else { - h = resource(i, s, base, kind, raw ? 4 : n * (half ? 2 : 4)); + h = resource(i, s, base, kind, raw && !masked_read ? 4 : n * (half ? 2 : 4)); } auto addr = (i.a & (raw ? 0x1000 : 0x2000)) ? read(256 + (i.b & 255)) : "0"; if (raw) { @@ -1077,6 +1081,9 @@ struct DirectCompute { addr = ir.binary("and", ir.binary("add", addr, operand32(i, i.b >> 24)), "4294967292"); } if (!store) { + // Inactive lanes may carry offsets outside the view. Use its + // first element, whose minimum size is recorded in the binding. + if (masked_read) addr = select(graphics_predicate, addr, "0"); auto ret = load_buffer(h, addr, raw, n); for (unsigned k = 0; k < n; ++k) vector_write(data + k, ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(k))); diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index 0ee9bd2fc7..a3c28bc2d4 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -999,6 +999,70 @@ struct GraphicsMaskRegions { std::multimap entries; for (const auto &i : program.code) if (i.branch()) entries.emplace(i.target(), i.pc); + auto flattened_op = [&](size_t index, unsigned saved, std::set &writes) { + const auto &i = program.code[index]; + const auto &state = program.before[index]; + if (i.dpp_control || i.dpp8_selectors || carry_destination(i)) return false; + if (local_alu(i) || i.name == "s_waitcnt" || i.name == "s_nop" || i.name == "s_clause") + return true; + if (vertex) return false; + if (i.enc == Encoding::Mix) + return i.name == "v_fma_mix_f32" || i.name == "v_fma_mixlo_f16" || i.name == "v_fma_mixhi_f16"; + if (i.enc == Encoding::Image) { + // Explicit LOD/gradients and texel loads do not observe the other lanes. + // Speculation must also use a fixed resource and sampler binding. + const auto &texture = state[((i.b >> 16) & 31) * 4]; + if (texture.type != Symbol::Type::descriptor || texture.value >= 16) return false; + if (i.op == 0 || i.op == 1) return true; + return (i.op == 0x22 || i.op == 0x24 || i.op == 0x27 || i.op == 0x2f) && + state[((i.b >> 21) & 31) * 4].type == Symbol::Type::constant; + } + if (i.enc == Encoding::Mubuf) { + const auto &buffer = state[((i.b >> 16) & 31) * 4]; + return (i.name == "buffer_load_dword" || i.name == "buffer_load_format") && + buffer.type == Symbol::Type::descriptor && buffer.value < 16; + } + if (i.enc == Encoding::Vopc && i.dst == 106 && i.name.substr(0,6) == "v_cmp_" && + !i.clamp && !i.scale && !i.subword && i.name.find("class") == Name::npos) { + // Only CNDMASK can consume this invocation bit in the arm. + writes.insert(106); + if (!wave32) writes.insert(107); + return true; + } + unsigned width = 1; + if (i.enc == Encoding::Smem) { + const auto &buffer = state[i.src[0]]; + // Fixed-offset scalar buffer reads carry a minimum view size + // in the binding. Their results are numeric, not descriptors. + if (i.op < 8 || i.op > 12 || (i.b >> 25) != 125 || (i.b & 0x100003) || + buffer.type != Symbol::Type::descriptor || buffer.value >= 16) return false; + width = memory_count(i); + } else { + auto numeric = [&](unsigned src) { + if (src >= 106) return constant32(i, src).has_value(); + const auto type = state[src].type; + return type == Symbol::Type::unknown || type == Symbol::Type::constant || type == Symbol::Type::masked; + }; + const bool sets_scc = i.name == "s_add_u32" || i.name == "s_lshl_b32"; + const bool binary = sets_scc || i.name == "s_cselect_b32"; + if (i.name != "s_movk_i32" && !((binary || i.name == "s_mov_b32") && + numeric(i.src[0]) && (!binary || numeric(i.src[1])))) return false; + if (sets_scc) writes.insert(128); + } + if (i.dst + width > 106) return false; + if (i.dst < saved + (wave32 ? 1u : 2u) && saved < i.dst + width) + refuse(i.pc, "masked graphics arm overwrites its saved EXEC"); + for (unsigned r = i.dst; r < i.dst + width; ++r) writes.insert(r); + return true; + }; + auto expire_arms = [&](unsigned middle, unsigned end, const std::set &first, + const std::set &second) { + // A skipped wave may never have made these definitions. For VCC + // only the invocation bit of an active lane was available. + if (middle != end) expired[middle].insert(first.begin(), first.end()); + expired[end].insert(first.begin(), first.end()); + expired[end].insert(second.begin(), second.end()); + }; // Only carry SCC into a full numeric mask if its reaching producer // compares ordinary scalar operands, with no join or intervening // scalar writer. Per-lane predicates cannot establish those 64 bits. @@ -1269,15 +1333,18 @@ struct GraphicsMaskRegions { for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) if (it->second != skip.pc && (!two_arms || it->second != else_skip.pc)) refuse(it->first, "branch enters a masked graphics region"); - for (size_t j = k + 2 + split; j < end; ++j) { + std::set first_writes, second_writes; + for (size_t j = begin; j < end; ++j) { const auto &body = program.code[j]; if (two_arms && (j == middle || j == middle + 1)) continue; + auto &writes = two_arms && j > middle ? second_writes : first_writes; if (body.pc != program.code[j - 1].next || body.next != program.code[j + 1].pc || - !(local_alu(body) || body.name == "s_waitcnt" || body.name == "s_nop" || - (!vertex && body.name == "buffer_atomic_add" && !(body.a & 0x2000)) || - (body.enc == Encoding::Image && body.op == 0x27))) + !(flattened_op(j, save.dst, writes) || + (body.enc == Encoding::Image && body.op == 0x27) || + (!vertex && body.name == "buffer_atomic_add" && !(body.a & 0x2000)))) refuse(body.pc, "masked graphics region requires lane-local vector arithmetic"); } + expire_arms(inverse.pc, restore.pc, first_writes, second_writes); saves.insert(save.pc); restores.insert(restore.pc); if (split) skip_proven(program.code[k + 1]); @@ -1316,13 +1383,16 @@ struct GraphicsMaskRegions { const auto &cmp = code[k]; if (cmp.enc != Encoding::Vopc || cmp.name.substr(0,7) != "v_cmpx_" || cmp.dst != 126 || cmp.scale || cmp.clamp || cmp.subword) continue; - auto local = [&](const Inst &i) { + std::set first_writes, second_writes; + auto local = [&](size_t j, std::set &writes) { + const auto &i = code[j]; + if (!vertex) return flattened_op(j, 126, writes); return local_alu(i) || (i.enc == Encoding::Vopc && i.dst == 106 && i.name.substr(0,6) == "v_cmp_" && !i.clamp && !i.scale && !i.subword && i.name.find("class") == Name::npos); }; size_t mid = k + 1; - while (mid < code.size() && local(code[mid])) ++mid; + while (mid < code.size() && local(mid, first_writes)) ++mid; if (mid == code.size()) continue; const auto &inverse = code[mid]; const bool two_arms=inverse.name=="s_andn2_b64" && inverse.src[1]==126; @@ -1331,7 +1401,7 @@ struct GraphicsMaskRegions { size_t end=mid; if (two_arms) { ++end; - while (end < code.size() && local(code[end])) ++end; + while (end < code.size() && local(end, second_writes)) ++end; } if (end == code.size()) continue; const auto &restore = code[end]; @@ -1357,6 +1427,10 @@ struct GraphicsMaskRegions { } } if ((vertex || one_arm) && !local_save) continue; + if (first_writes.count(inverse.src[0]) || first_writes.count(inverse.src[0]+1) || + second_writes.count(inverse.src[0]) || second_writes.count(inverse.src[0]+1)) + refuse(cmp.pc, "masked graphics arm overwrites its saved EXEC"); + expire_arms(inverse.pc, restore.pc, first_writes, second_writes); cmpx_starts.insert(cmp.pc); enclosing_mask.emplace(cmp.pc,inverse.src[0]); if (two_arms) complements.insert(inverse.pc); @@ -2078,8 +2152,11 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = } } } + string coverage_predicate; alu.helper_result_unobserved = [&](unsigned r) { - return straight && r >= 256 && r < 512 && alu.graphics_pc >= last_helper_touch[r-256]; + // A flattened arm can also leave covered lanes inactive. + return straight && alu.graphics_predicate == coverage_predicate && + r >= 256 && r < 512 && alu.graphics_pc >= last_helper_touch[r-256]; }; bool whole_quad = false; bool exact_after_wqm = false; @@ -2548,7 +2625,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (begin) { // Run read-only sampling with the quad intact for derivatives, // then merge only the writes made under the guest coverage. - alu.graphics_predicate = covered_lane(); + alu.graphics_predicate = coverage_predicate = covered_lane(); } else alu.graphics_predicate.clear(); return; } @@ -2601,7 +2678,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (covered.empty()) { covered = covered_lane(); } - alu.graphics_predicate = covered; + alu.graphics_predicate = coverage_predicate = covered; alu.exact_pixel_entry = true; } else { alu.graphics_predicate.clear(); diff --git a/tests/cmake/native_pixel_masked_region_alu.cmake b/tests/cmake/native_pixel_masked_region_alu.cmake new file mode 100644 index 0000000000..c02d885f6a --- /dev/null +++ b/tests/cmake/native_pixel_masked_region_alu.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND TARGET native_pixel_ir_dump AND EXISTS "${INTAKE_PYTHON}") + set(masked_region_check "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pixel_masked_region_alu_check.py") + add_test(NAME native_pixel_masked_region_alu_controls COMMAND "${INTAKE_PYTHON}" -B "${masked_region_check}" + "$" "$" "${DXC_BIN_DIR}" controls) + set_tests_properties(native_pixel_masked_region_alu_controls PROPERTIES TIMEOUT 90) + if(TARGET offscreen_check) + foreach(backend warp hardware) + add_test(NAME native_pixel_masked_region_alu_${backend} COMMAND "${INTAKE_PYTHON}" -B "${masked_region_check}" + "$" "$" "${DXC_BIN_DIR}" + ${backend} "$") + set_tests_properties(native_pixel_masked_region_alu_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() + endif() +endif() diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 9e328d94d8..10e3c5fb87 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -28,7 +28,8 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const bool one_dimensional = false, bool two_dimensional = false, UINT first_mip = 0, UINT view_levels = 0, UINT mip_base = 4, bool cube = false); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, - bool depth16, std::uint32_t words[64], bool array = false); + bool depth16, std::uint32_t words[64], bool array = false, + const char* sampler = nullptr, bool raw = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, const std::uint32_t expected[4], unsigned coverage = 1); // Queries colour formats and returns "typed_uav_load_refused" when one has no typed UAV load, before any draw. diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index 413865f68c..5ee167a850 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -1050,10 +1050,11 @@ def waterfall_pixel(byte_key=False, modifier=None, *, sample_x=None): foreign_mask[12] = 0xbe962408 check("unproven-inner-coverage", "gfx1013-container-ps", patched_pixel(len(foreign_mask), foreign_mask, input_address=1 << 8, input_signature=position_input), "inner EXEC requires saved entry coverage") - unsafe = masked.copy() - unsafe[3] = 0xb0000002 # scalar state changes for the whole guest wave - check("masked-scalar", "gfx1013-container-ps", patched_pixel(len(unsafe), unsafe, - input_address=1 << 8, input_signature=position_input), "lane-local vector arithmetic") + unsafe = [0xbe800381, *masked[:3], 0xb0000002, masked[4], 0x7e000200] + # The masked s_movk_i32 may be skipped wave-wide. The later v_mov + # cannot use its speculative result even though s0 was defined at entry. + check("masked-scalar-escape", "gfx1013-container-ps", patched_pixel(len(unsafe), unsafe, + input_address=1 << 8, input_signature=position_input), "graphics register undefined on an incoming path: 0") full_mask = lanes + [0xbe80036a] check("full-mask", "gfx1013-container-ps", patched_pixel(len(full_mask), full_mask), "consumes a full wave mask") diff --git a/tests/native_pixel_masked_region_alu_check.py b/tests/native_pixel_masked_region_alu_check.py new file mode 100644 index 0000000000..36be4ee0df --- /dev/null +++ b/tests/native_pixel_masked_region_alu_check.py @@ -0,0 +1,208 @@ +"""Synthetic gfx1013 EXEC partitions with DXIL and exact 8x2 readback controls.""" +import re +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, signature +from native_graphics_wqm_check import VERTEX +from native_pixel_compare_mask_check import cndmask, cmp_gt, scalar +from native_pixel_cmpx_if_else_check import bits, execz +from native_scalar_lds_check import sop1, vmove +from startup_image_load_d16_check import FLOAT_MIP1, FLOAT_TEXELS + +REFUSAL = "masked graphics region requires lane-local vector arithmetic" +OLD = bits(8.0) +CLAUSE = 0xBFA10000 # s_clause 0 +WAIT = 0xBF8CC07F +TABLE = [sop1(3, 1, 128), 0xF40C0200, 0xFA000000, WAIT] # s[8:15] = descriptor at offset 0 +SAMPLER = [word for r, value in enumerate((0x12, 0xFFF000, 0x04500000, 0), 4) + for word in (sop1(3, r, 255), value)] + + +def literal(dst, value): + return [vmove(dst, 255), value] + + +def program(then, otherwise=None, *, before=(), after=(), old=OLD, resource=None, cmpx=False): + # v0 is SV_Position.x. THEN owns x=3..7, its complement owns x=0..2. + code = [*before, *literal(2, old)] + if cmpx: + # WQM, a dominating save, then CMPX with no EXECZ shortcut. + code.insert(0, sop1(10, 126, 126)) + code += [sop1(4, 20, 126), 0x7C2200FF, bits(3.0)] + else: + code += [*cmp_gt(106, 256, 255), bits(3.0), sop1(0x24, 20, 106), execz(len(then))] + code += then + if otherwise is not None: + code += [scalar(21, 126, 20, 126)] + if not cmpx: + code += [execz(len(otherwise))] + code += otherwise + code += [sop1(4, 126, 20), *after] + return patched_pixel(len(code), code, table=resource is not None, input_address=1 << 8, + input_signature=((b"ISG1", signature(b"SV_Position", 1)), + (b"OSG1", signature(b"SV_Target", 64, 1 if resource else 3))), + export=(0xF800180F, 0x02020202)) + + +def mix(op, a=242, b=242, c=242): + return [0xCC200002 | (op << 16), a | (b << 9) | (c << 18)] + + +def image(op): + return [0xF0000108 | (op << 18), 0x00220204] + + +def position_words(*values): + return [word for r, value in enumerate(values, 4) for word in literal(r, value)] + + +def reference(then, otherwise): + return b"".join(struct.pack("= 3 else otherwise) * 4 + for _ in range(2) for x in range(8)) + + +def cases(): + packed = 0x41003C00 + yield "clause", program([CLAUSE, vmove(2, 242)]), lambda x: bits(1.0), OLD, None, None + yield "clause-else", program([CLAUSE, vmove(2, 242)], [CLAUSE, vmove(2, 244)]), \ + lambda x: bits(1.0), bits(2.0), None, None + yield "mix-f32", program(mix(0)), lambda x: bits(2.0), OLD, None, "tertiary.f32" + yield "mix-low", program(mix(1), old=packed), lambda x: 0x41004000, packed, None, "legacyF32ToF16" + yield "cmpx-mix-high", program([CLAUSE, *mix(2, b=244)], [CLAUSE, vmove(2, 258)], cmpx=True, old=packed), \ + lambda x: 0x42003C00, packed, None, "legacyF32ToF16" + inner = [*cmp_gt(106, 256, 255), bits(5.0), *cndmask(2, 242, 244, 106)] + yield "compare-cndmask", program(inner), lambda x: bits(2.0 if x >= 5 else 1.0), OLD, None, None + salu = [0xB0170800, scalar(0x1E, 22, 23, 128 + 19), scalar(0, 22, 22, 128), vmove(2, 22)] + yield "scalar-alu", program(salu), lambda x: bits(2.0), OLD, None, None + + for tag, op, coords, value, method in ( + ("image-load", 0, (0, 0), FLOAT_TEXELS[0][0], "textureLoad.f32"), + ("image-load-mip", 1, (0, 0, 1), FLOAT_MIP1[0][0], "textureLoad.f32"), + ("sample-lz", 0x27, (bits(0.0625), bits(0.25)), FLOAT_TEXELS[0][0], "sampleLevel.f32"), + ("sample-l", 0x24, (bits(0.125), bits(0.5), bits(1.0)), FLOAT_MIP1[0][0], "sampleLevel.f32"), + ("sample-d", 0x22, (0, 0, 0, 0, bits(0.0625), bits(0.25)), FLOAT_TEXELS[0][0], "sampleGrad.f32"), + ): + before = [*TABLE, *SAMPLER, *position_words(*coords)] + yield tag, program([*image(op), WAIT], before=before, resource="texture"), \ + lambda x, word=value: word, OLD, "sample" if op >= 0x20 else "texture", method + + raw = [0xE0301000, 0x80020204] # buffer_load_dword v2, v4, s[8:11], 0 offen + # Negative inactive addresses exercise the speculative address guard. + before = [*TABLE, *cmp_gt(106, 256, 255), bits(3.0), *literal(4, 0xFFFFFFFC), *cndmask(4, 260, 128, 106)] + yield "raw-load", program([*raw, WAIT], before=before, resource="raw"), \ + lambda x: FLOAT_TEXELS[0][0], OLD, "raw", "rawBufferLoad.i32" + smem = [0xF4200604, 0xFA000000, WAIT, vmove(2, 24)] # s_buffer_load_dword s24, s[8:11], 0 + yield "scalar-load", program(smem, before=TABLE, resource="raw"), \ + lambda x: FLOAT_TEXELS[0][0], OLD, "raw", "rawBufferLoad.i32" + + comparison = [word for r, value in enumerate((0x08001012, 0xFFF000, 0x04000000, 0), 4) + for word in (sop1(3, r, 255), value)] + before = [*TABLE, *comparison, *position_words(bits(0.5), bits(0.0625), bits(0.25))] + yield "sample-c-lz", program([*image(0x2F), WAIT], before=before, resource="texture"), \ + None, OLD, None, "sampleCmpLevelZero.f32" + typed = [0xE0000000, 0x80020200, WAIT] # buffer_load_format_x v2, off, s[8:11], 0 + yield "formatted-load", program(typed, before=TABLE, resource="buffer"), \ + None, OLD, None, "bufferLoad.i32" + + +def refusals(): + table = dict(before=[*TABLE, *SAMPLER, *position_words(0, 0)], resource="texture") + for tag, op in (("implicit", 0x20), ("implicit-bias", 0x25), ("image-store", 8), + ("sample-d-cl", 0x23), ("sample-c-l", 0x2C)): + yield tag, program(image(op), **table), REFUSAL + for tag, body in ( + ("buffer-store", [0xE0701000, 0x80020204]), + ("buffer-atomic-sub", [0xE0CC1000, 0x80020204]), + ("ds-swizzle", [0xD8D480B1, 0x02000000]), + ("dpp16", [0x060000FA, 0xFF0CB100]), + ("dpp8", [0x060000E9, sum((n & 4) << (8 + 3 * n) for n in range(8))]), + ("readlane", [0xD7600018, 0x00010100]), + ("mbcnt", [0xD7650002, 0x000100C1]), + ("carry-vcc", [0xD70F6A02, 0x00020080]), + ("scalar-unsafe-load", [0xF4200600, 0xFA000000]), + ("compare-sgpr-pair", [*cmp_gt(24, 256, 255), bits(5.0)]), + ): + yield tag, program(body), REFUSAL + yield "saved-exec-high", program([sop1(3, 21, 128)]), "overwrites its saved EXEC" + yield "cmpx-saved-exec", program([sop1(3, 20, 128)], cmpx=True), "overwrites its saved EXEC" + yield "scalar-load-saved-exec", program([0xF4200504, 0xFA000000], before=TABLE, resource="raw"), \ + "overwrites its saved EXEC" + for tag, body, read, reg in ( + ("sgpr", [sop1(3, 24, 242)], [vmove(2, 24)], 24), + ("vcc", cmp_gt(106, 256, 242), cndmask(2, 242, 244, 106), 106), + ("scc", [scalar(0, 24, 128, 128)], [scalar(10, 25, 128, 129), vmove(2, 25)], 128), + ): + for boundary, kwargs in (("restore", dict(after=read)), ("complement", dict(otherwise=read))): + yield f"{tag}-after-{boundary}", program(body, before=[sop1(3, 24, 244)], **kwargs), \ + f"undefined on an incoming path: {reg}" + + +def run(args): + return subprocess.run(args, capture_output=True, text=True, timeout=60) + + +def main(cli, ir_dump, sdk, backend, renderer=None): + dxc = Path(sdk) / "dxc.exe" + # CTest runs from the build directory under out/. + with TemporaryDirectory(dir=Path.cwd()) as tmp: + work = Path(tmp) + guest, ps, vs, expected = (work / name for name in ("guest", "ps.cso", "vs.cso", "expected.bin")) + if renderer: + source = work / "vs.hlsl" + source.write_text(VERTEX["full"], encoding="ascii") + subprocess.run([dxc, "-T", "vs_6_6", "-Fo", vs, source], check=True) + + def draw(resource, data): + expected.write_bytes(data) + args = [renderer, backend] + if resource: + args += ["--startup-image-load-d16", "raw" if resource == "raw" else "rgba32f", vs, ps, expected] + if resource == "sample": + args += ["smp 0 0x12 0xfff000 0x4500000 0x0"] + else: + args += ["--startup-pixel-words", vs, ps, "8", "2", expected] + result = run(args) + if result.returncode == 77: + print(result.stdout, result.stderr) + sys.exit(77) + return result + + for tag, blob, then, inactive, resource, opcode in cases(): + guest.write_bytes(blob) + ir = run([ir_dump, guest]) + assert ir.returncode == 0 and "select i1" in ir.stdout and "br i1" not in ir.stdout, (tag, ir.stderr, ir.stdout) + if tag == "raw-load": + address = re.search(r"(%\w+) = select i1 (%\w+), i32 [^,\n]+, i32 0\n" + r"[^\n]*@dx.op.rawBufferLoad.i32\([^\n]+, i32 \1,", ir.stdout) + assert address and re.search(rf"select i1 {address[2]}, i32 %\w+, i32 {OLD}\b", ir.stdout), ir.stdout + compiled = run([cli, sdk, work / "cache", "gfx1013-container-ps", guest, ps]) + assert compiled.returncode == 0, (tag, compiled.stderr, compiled.stdout) + dump = run([dxc, "-dumpbin", ps]) + assert dump.returncode == 0 and "select i1" in dump.stdout, (tag, dump.stderr, dump.stdout) + if opcode: + assert "@dx.op." + opcode in dump.stdout, (tag, dump.stdout) + print(f"{tag}: validated predicated DXIL", flush=True) + if renderer and then is not None: + correct = draw(resource, reference(then, inactive)) + assert correct.returncode == 0, (tag, correct.stdout, correct.stderr) + if tag == "clause": + print(correct.stdout, end="") + wrong = draw(resource, reference(then, then(3))) + assert wrong.returncode == 1 and "(0,0)" in wrong.stderr and "mismatch" in wrong.stderr and \ + "6 of 16 pixels differ" in wrong.stderr, (tag, wrong.stdout, wrong.stderr) + print(f"{tag}: 16 pixels matched, inactive-lane mutation differed on 6", flush=True) + + if backend == "controls": + for tag, blob, reason in refusals(): + guest.write_bytes(blob) + result = run([ir_dump, guest]) + assert result.returncode == 1 and reason in result.stderr, (tag, reason, result.stderr) + print(f"{tag}: refused ({result.stderr.strip()})", flush=True) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 0750059265..9272cb80a5 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1427,15 +1427,17 @@ OperationResult run_startup_image_load_d16(const OperationContext& ctx) const bool depth16 = std::strcmp(ctx.argv[3], "r16_unorm") == 0 || std::strcmp(ctx.argv[3], "r16_unorm_array") == 0; const bool rgba32f = std::strcmp(ctx.argv[3], "rgba32f") == 0 || std::strcmp(ctx.argv[3], "rgba32f_array") == 0; const bool array = std::strcmp(ctx.argv[3], "r16_unorm_array") == 0 || std::strcmp(ctx.argv[3], "rgba32f_array") == 0; - if (!depth16 && !rgba32f) - return {OutcomeKind::fail, "image_load d16 source mode must be r16_unorm[_array] or rgba32f[_array]"}; + const bool raw = std::strcmp(ctx.argv[3], "raw") == 0; + if ((!depth16 && !rgba32f && !raw) || (ctx.argc == 8 && (!rgba32f || array))) + return {OutcomeKind::fail, "expected r16_unorm[_array], rgba32f[_array], or raw (sampler only with rgba32f)"}; std::uint32_t expected[64]{}; std::ifstream file(ctx.argv[6], std::ios::binary); file.read(reinterpret_cast(expected), sizeof(expected)); if (!file || file.peek() != std::char_traits::eof()) return {OutcomeKind::fail, "expected file does not hold 64 words"}; std::uint32_t actual[64]{}; - check_startup_image_load_d16(ctx.device, ctx.argv[4], ctx.argv[5], depth16, actual, array); + check_startup_image_load_d16(ctx.device, ctx.argv[4], ctx.argv[5], depth16, actual, array, + ctx.argc == 8 ? ctx.argv[7] : nullptr, raw); unsigned differing = 0; for (unsigned i = 0; i < 16; ++i) { const std::uint32_t* want = &expected[i * 4]; @@ -1779,7 +1781,7 @@ const OperationSpec kOperations[] = { {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-cube", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, + {"--startup-image-load-d16", 7, 8, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, {"--startup-flat-param", 6, 7, nullptr, kNoGate, run_startup_flat_param}, diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index be18b7e5b7..fa637e81cd 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -262,7 +262,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const // depth16 == false: DXGI_FORMAT_R32G32B32A32_FLOAT covering four distinct channels per texel, halfway ties // to even, 1-ULP midpoint neighbours, subnormals, signed zero, overflow and quiet NaNs. void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, - bool depth16, std::uint32_t words[64], bool array) + bool depth16, std::uint32_t words[64], bool array, const char* sampler, bool raw) { constexpr UINT width = 8, height = 2, d16_mips = 2; static constexpr std::uint16_t kDepthTexels[width * height] = { @@ -301,9 +301,11 @@ void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); constexpr UINT d16_entry_constants = 5; // ud0..ud3 from FULLSCREEN_VS plus ud4 ('d16unorm16 0') - const x2w_startup::TranslatedSamplers no_samplers{}; + x2w_startup::TranslatedSamplers samplers; + if (sampler && (!samplers.read_manifest_line(sampler) || samplers.statics.size() != 1)) + throw std::runtime_error("Expected one static sampler in the image readback draw"); ComPtr root; - check(x2w_startup::create_translated_root(device, d16_entry_constants, 1, no_samplers, &root), + check(x2w_startup::create_translated_root(device, d16_entry_constants, 1, samplers, &root), "Create translated image_load d16 root signature"); D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; @@ -383,7 +385,19 @@ void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; ComPtr views, rtvs; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "Create image_load d16 SRV heap"); - device->CreateShaderResourceView(texture.Get(), nullptr, views->GetCPUDescriptorHandleForHeapStart()); + const auto srv = views->GetCPUDescriptorHandleForHeapStart(); + if (raw) { + // Expose just the first texel's red word as a raw buffer view. + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Buffer.NumElements = 1; + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(upload.Get(), &view, srv); + } else { + device->CreateShaderResourceView(texture.Get(), nullptr, srv); + } hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image_load d16 RTV heap"); const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart();