diff --git a/docs/experiments.md b/docs/experiments.md index 7c79dabb2..3c8051b2a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -18473,6 +18473,13 @@ Linux controls (including exhaustive verification against `fractions.Fraction` a Independent Windows 11 (`26200.9974`, DXC `1.9.2602.17`, `debug_layer=unavailable`) measurements on `bd8f6f42` ([comment 1](https://github.com/R0Y00/Xbox2Windows/pull/2857#issuecomment-7196200555)) and `3100f363` ([comment 2](https://github.com/R0Y00/Xbox2Windows/pull/2857#issuecomment-7200844836)) passed `pixel_aot_f16_cvt_norm_hardware` (`AMD Radeon RX 9070 XT` `1002:7550`, driver `32.0.32029.2010`) and `pixel_aot_f16_cvt_norm_warp` with `max_absolute_error=0`, all 20 mutation draws mismatching, and DXIL disassembly confirming the `-Od` pass retains the `mul`/`lshr`/`shl` integer path. Scope limits: under `#839`'s static finite-proof contract (`half16_arith_source` / `half16_dpp_source`), operands are statically known per-lane uniform values, so device draw readbacks do not distinguish lane-routing changes on `dpp16`/`dpp8` (the permutation-to-intrinsic mapping is pinned statically in `check_f16_cvt_norm_controls`), mutation draws compile optimized rather than `-Od`, and the exhaustive 63,488-value check runs in Python rather than on-device. +## Native pixel VCC shortcuts + +The direct DXIL path can lower a forward varying VCCZ shortcut when every live +write keeps the old value for lanes with a clear VCC bit. The +[source-built fixtures](experiments/native-pixel-vcc-shortcuts.md) check both +CNDMASK and matching SAVEEXEC bodies. + ## Native raw pixel buffer UAV binding The native graphics cache and draw stand-in support a single raw pixel UAV from a tracked descriptor table for a direct non-indexed draw without SRVs. The manifest records the table parameter and byte offset; the runtime requires an aligned raw R32_TYPELESS buffer view with valid bounds, UAV resource flags and compatible state, retains the resource, and orders consecutive UAV uses. A structured UAV window is also eligible when its `StructureByteStride` is at least 4 and a multiple of 4, `Format` is `UNKNOWN`, `Flags` is `NONE`, and `CounterOffsetInBytes` is zero. Its byte offset must be 16-byte aligned and its non-empty window must fit within the resource and the D3D12 raw UAV element limit. The runtime rewrites eligible windows to `R32_TYPELESS | FLAG_RAW`. Structured views with a non-4-byte stride, unaligned byte offset or counter are refused. Typed views, mixed views and other draw paths are outside this slice (#3212, #3215; separate from #3094/#2981). diff --git a/docs/experiments/native-pixel-vcc-shortcuts.md b/docs/experiments/native-pixel-vcc-shortcuts.md new file mode 100644 index 000000000..2ed6eb03d --- /dev/null +++ b/docs/experiments/native-pixel-vcc-shortcuts.md @@ -0,0 +1,29 @@ +# Native pixel VCC shortcuts + +A guest `s_cbranch_vccz` skips the body when every VCC bit is clear. In a mixed +wave the guest enters the body, but a plain `v_cndmask_b32 dst, dst, candidate, vcc` +keeps the incoming `dst` for clear lanes. The same lanes keep their VGPRs in a +body bracketed by `s_and_saveexec` on the same VCC and a restore of the saved +EXEC. In these cases the direct pixel translator can branch on each invocation's +bit. It requires a closed forward body with local register arithmetic and +expires unguarded scratch writes at the join. The saved EXEC pair and SCC also +expire. Values selected by the new branch retain the condition's input +dependencies at the join. + +`s_cbranch_vccnz` skips the body for the entire wave when any bit is set. A +body with an inverted CNDMASK would update clear lanes when executed. In a mixed +wave the guest skips those updates, so the translator still refuses that +projection. It accepts VCCNZ when the condition is wave-uniform. A flat +attribute may differ between primitives in the same wave, and a floating +self-compare can see a NaN. Both keep their input dependencies. + +```powershell +ctest --preset pr --no-tests=error --output-on-failure -R '^native_pixel_varying_vcc_branch_controls$' +ctest --preset dev --no-tests=error -R '^native_pixel_varying_vcc_branch_' -V +ctest --preset release --no-tests=error -R '^native_pixel_varying_vcc_branch_' -V +``` + +The fixture validates source-built gfx1013 pixel containers through DXC. Each +draw checks all 16 pixels and requires the opposite reference to report a pixel +mismatch. The controls also exercise scratch reads, mask clobbers, wrong +polarity, incoming branches, exports, stores, implicit LOD and DPP. diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index 0ee9bd2fc..4b67e48bb 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -1474,7 +1474,86 @@ struct GraphicsEdge { std::map exports; }; -void join_graphics(GraphicsStage &g, std::vector &edges, const GraphicsMaskRegions ®ions) { +struct PixelVccSkip { + std::set scratch; + std::optional save, restore; +}; + +std::optional pixel_vcc_skip(const Program &program, const Inst &skip, + const std::multiset &branch_targets, bool wave32) { + // VCCZ may run the body for VCC-clear lanes whenever another lane sets + // its bit. VCCNZ has no analogous lane projection: a single set bit + // skips the body for *all* lanes, including the clear ones. + if (skip.op != 6 || skip.target() <= skip.next || branch_targets.count(skip.target()) != 1) + return std::nullopt; + const size_t k = program.at.at(skip.pc), end = program.at.at(skip.target()); + if (!k || branch_targets.count(skip.pc)) + return std::nullopt; + const auto &producer = program.code[k - 1]; + const bool compare = producer.enc == Encoding::Vopc && producer.dst == 106 && + producer.name.substr(0, 6) == "v_cmp_" && !producer.dpp_control && !producer.dpp8_selectors; + // The WQM emitter already represents a tracked compare pair intersected + // with EXEC as the current invocation's VCC bit. + const bool intersection = !wave32 && producer.name == "s_and_b64" && producer.dst == 106 && + (producer.src[0] == 126 || producer.src[1] == 126); + if (!compare && !intersection) + return std::nullopt; + + PixelVccSkip result; + size_t begin = k + 1, limit = end; + const auto &save = program.code[begin]; + if (save.name == (wave32 ? "s_and_saveexec_b32" : "s_and_saveexec_b64")) { + const auto &restore = program.code[end - 1]; + if (begin + 1 >= end || save.src[0] != 106 || save.dst > (wave32 ? 105u : 104u) || + (!wave32 && (save.dst & 1)) || + restore.name != (wave32 ? "s_mov_b32" : "s_mov_b64") || + restore.dst != 126 || restore.src[0] != save.dst) + return std::nullopt; + result.save = save.pc; + result.restore = restore.pc; + result.scratch.insert(save.dst); + if (!wave32) result.scratch.insert(save.dst + 1); + result.scratch.insert(128); // SCC holds the nonzero result of SAVEEXEC. + ++begin; + --limit; + } + auto entry = branch_targets.lower_bound(skip.next); + if (entry != branch_targets.end() && *entry < skip.target()) + return std::nullopt; + + bool guarded_write = false; + for (size_t j = begin; j < limit; ++j) { + const auto &op = program.code[j]; + if ((op.name == "s_nop" && op.a >> 16 == 0xbf80) || op.name == "s_waitcnt" || op.name == "s_clause") + continue; + if (!result.save && op.name == "s_mov_b32" && op.dst <= 105 && + (op.src[0] <= 105 || constant32(op, op.src[0]))) { + result.scratch.insert(op.dst); + continue; + } + if (!GraphicsMaskRegions::local_alu(op) || op.dpp8_selectors || op.subword || carry_destination(op)) + return std::nullopt; + if (op.name == "v_cndmask_b32") { + if (op.src[2] != 106 || op.abs || op.neg || op.scale || op.clamp || (op.wide && (op.a & 0x7800))) + return std::nullopt; + if (!result.save && (op.src[0] != op.dst || result.scratch.count(op.dst))) + return std::nullopt; + guarded_write = true; + } else if (alu_rules.count(op.name)) { + // This table, with local_alu's lane-op exclusion, writes one + // VGPR. Outside SAVEEXEC its output must be dead at the join. + if (!result.save) result.scratch.insert(op.dst); + } else { + return std::nullopt; + } + } + if (!result.save && !guarded_write) + return std::nullopt; + return result; +} + +void join_graphics(GraphicsStage &g, std::vector &edges, const GraphicsMaskRegions ®ions, + const PixelVccSkip *vcc_skip) { auto &alu = g.alu; alu.guarded_ij.clear(); if (edges.size() == 1) { @@ -1511,7 +1590,11 @@ void join_graphics(GraphicsStage &g, std::vector &edges, const Gra for (const auto &edge : edges) control_inputs |= alu.ir.dependencies[edge.values.at(merge->second)]; } + if (vcc_skip) + control_inputs |= alu.ir.dependencies[edges.front().values.at(106)]; for (unsigned r : g.overwritten_inputs) { + if (vcc_skip && vcc_skip->scratch.count(r)) + continue; if (g.partial.count(r)) continue; string first, incoming; @@ -1541,6 +1624,8 @@ void join_graphics(GraphicsStage &g, std::vector &edges, const Gra if (defined && !same) alu.ir.dependencies[alu.graphics_registers[r]] |= control_inputs; } + if (vcc_skip) + for (unsigned reg : vcc_skip->scratch) alu.write(reg, {}); } // A loop may consume a VGPR defined on a backedge. Give each requested @@ -1987,6 +2072,10 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = } } } + std::multiset branch_targets; + if (pixel) + for (const auto &i : program.code) + if (i.branch()) branch_targets.insert(i.target()); PixelWaterfalls waterfalls; if (pixel) waterfalls.find(program,stage.wave32); PixelWqm wqm; @@ -1997,6 +2086,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = wqm.numeric_guards(program,stage.wave32); } GraphicsMaskRegions regions(program, stage.wave32, !pixel); + for (const auto &edge : regions.then_fallthroughs) + branch_targets.insert(edge.second); const auto first_branch = std::find_if(program.code.begin(), program.code.end(), [](const auto &i) { return i.branch(); }); const bool straight = first_branch == program.code.end(); @@ -2093,6 +2184,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = bool scalar_entry = true; std::set uniform_vector_values; std::set uniform_vcc_values; + std::map vcc_skip_joins; + std::set vcc_skip_saves, vcc_skip_restores; // Follow the helper count within one quad: h + swap_x(h) compared // against -swap_y(h + swap_x(h)). This is a quad vote, whereas the // original SOPP branch joins that vote across the entire guest wave. @@ -2104,6 +2197,12 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = struct IndexRange { unsigned first, last, zero_bits; }; std::map heap_ranges; auto scalar_operand = [](unsigned s) { return s <= 105 || (s >= 128 && s <= 248) || s == 255; }; + auto uniform_operand = [&](unsigned reg) { + if (scalar_operand(reg)) return true; + const auto source = alu.graphics_registers.find(reg); + return reg >= 256 && source != alu.graphics_registers.end() && + uniform_vector_values.count(source->second) != 0; + }; auto covered_lane = [&] { auto helper = alu.ir.invoke("i1","isHelperLane.i1",221,{},"nounwind readonly"); alu.ir.dependencies[helper].set(128); @@ -2372,6 +2471,16 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (auto it = regions.expired.find(pc); it != regions.expired.end()) for (auto reg : it->second) alu.write(reg, {}); + if (vcc_skip_saves.count(pc)) { + // The incoming DXIL edge already selects the lanes in VCC. + saved_exec.erase(i.dst); + alu.write(i.dst, {}); + if (!stage.wave32) alu.write(i.dst + 1, {}); + alu.write(128, {}); + return; + } + if (vcc_skip_restores.count(pc)) + return; if (regions.vertex_anchors.count(pc) || regions.captures.count(pc)) { // A single invocation observes one bit of this saved wave mask. // Never substitute that bit for a numeric 64-bit SGPR read. @@ -2756,6 +2865,11 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = // Keep the invocation bit for CNDMASK and predicated regions. // A whole-wave VCC branch also requires a uniform condition. auto pred = alu.comparison(i); + const bool integer_eq = i.name == "v_cmp_eq_i32" || i.name == "v_cmp_eq_u32"; + const bool integer_ne = i.name == "v_cmp_ne_i32" || i.name == "v_cmp_ne_u32"; + const bool self_compare = pixel && !alu.ir.loop_dependencies && !i.subword && + i.src[0] == i.src[1] && (integer_eq || integer_ne); + if (self_compare) pred = integer_eq ? "true" : "false"; if (!alu.graphics_predicate.empty()) pred = alu.ir.value("and i1 " + alu.graphics_predicate + ", " + pred); auto bit = alu.ir.value("zext i1 " + pred + " to i32"); @@ -2781,7 +2895,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = mask_release.claimed = true; } } - if (i.dst == 106 && alu.graphics_predicate.empty() && scalar_operand(i.src[0]) && scalar_operand(i.src[1]) && + if (i.dst == 106 && alu.graphics_predicate.empty() && + (self_compare || (uniform_operand(i.src[0]) && uniform_operand(i.src[1]))) && alu.ir.dependencies[bit].none()) uniform_vcc_values.insert(bit); return; } @@ -2980,21 +3095,16 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = alu.image_io(i, state); } else { // SGPR values and inline constants are common to the wave. - // Propagate that fact through pure VS arithmetic before a write + // Propagate that fact through pure vector arithmetic before a write // can replace an overlapping source. An FMAC also reads its dst. - bool uniform_vertex = false; + bool uniform_alu = false; auto rule = alu_rules.find(i.name); if (!alu.ir.loop_dependencies && alu.graphics_predicate.empty() && - !i.subword && GraphicsMaskRegions::local_alu(i) && rule != alu_rules.end()) { - auto uniform = [&](unsigned r) { - if (scalar_operand(r)) return true; - auto source = alu.graphics_registers.find(r); - return r >= 256 && source != alu.graphics_registers.end() && - uniform_vector_values.count(source->second) != 0; - }; + !i.subword && !i.dpp8_selectors && GraphicsMaskRegions::local_alu(i) && rule != alu_rules.end()) { const bool mac = i.name == "v_fmac_f32"; const unsigned count = mac || i.name == "v_fmamk_f32" || i.name == "v_fmaak_f32" ? 2 : rule->second.arity; - uniform_vertex = std::all_of(i.src.begin(),i.src.begin()+count,uniform) && (!mac || uniform(i.dst)); + uniform_alu = std::all_of(i.src.begin(),i.src.begin()+count,uniform_operand) && + (!mac || uniform_operand(i.dst)); } // Two complementary packed FMAs under the same EXEC define // the entire VGPR. Its incoming bits are dead when neither operation @@ -3051,7 +3161,17 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (peer!=vertical_peer.end()) negative_sum_source=peer->second; } } + const bool fold_integer = pixel && !alu.ir.loop_dependencies && alu.graphics_predicate.empty() && + !i.subword && !i.dpp_control && !i.dpp8_selectors && !i.abs && !i.neg && !i.scale && !i.clamp && + !(i.wide && (i.a & 0x7800)); + const bool and_zero = fold_integer && i.name == "v_and_b32" && + (constant32(i, i.src[0]) == 0u || constant32(i, i.src[1]) == 0u); alu.arithmetic(i, state); + if (and_zero) alu.write(i.dst, "0"); + if (fold_integer && i.enc == Encoding::Sopc && i.src[0] == i.src[1]) { + if (i.name == "s_cmp_eq_i32" || i.name == "s_cmp_eq_u32") alu.write(128, "1"); + if (i.name == "s_cmp_lg_i32" || i.name == "s_cmp_lg_u32") alu.write(128, "0"); + } if (!horizontal_sum_source.empty()) horizontal_counts.insert(alu.read(i.dst)); if (!negative_sum_source.empty()) negative_peer.emplace(alu.read(i.dst),negative_sum_source); if (heap_range) heap_ranges[alu.read(i.dst)]=*heap_range; @@ -3060,7 +3180,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = ((straight && i.name=="v_cvt_i32_f32" && i.src[0]<=105) || (i.name=="v_cvt_f32_f16" && scalar_operand(i.src[0])) || (i.name=="v_fma_mix_f32" && std::all_of(i.src.begin(),i.src.end(),scalar_operand))); - if (uniform_vertex || uniform_conversion || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && + if (uniform_alu || and_zero || uniform_conversion || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && std::all_of(i.src.begin(), i.src.end(), scalar_operand))) { auto value = alu.read(i.dst); if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); @@ -3095,7 +3215,9 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = alu.ir.body << "g" << label << ":\n"; graphics.pc = label; if (label) { - join_graphics(graphics, edges.at(label), regions); + const auto vcc_skip = vcc_skip_joins.find(label); + join_graphics(graphics, edges.at(label), regions, + vcc_skip == vcc_skip_joins.end() ? nullptr : &vcc_skip->second); edges.erase(label); } for (size_t k = block.begin; k < block.end; ++k) { @@ -3133,8 +3255,18 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = // take the other edge: safe only while nothing after the branch // reads another lane (raster_vote keeps the tail lane-local). if (branch == regions.lane_branches.end() && alu.ir.dependencies[condition].any() && - last.pc != wqm.vote_skip && !quad_vote) - refuse(last.pc, "graphics scalar condition depends on a varying input"); + last.pc != wqm.vote_skip && !quad_vote) { + const auto &body = blocks.at(last.next); + const bool closed = block.successors[1] == last.next && body.successors.size() == 1 && + body.successors.front() == last.target(); + auto proof = pixel && closed && alu.graphics_predicate.empty() && !exact_after_wqm ? + pixel_vcc_skip(program, last, branch_targets, stage.wave32) : std::nullopt; + if (!proof) + refuse(last.pc, "graphics scalar condition depends on a varying input"); + if (proof->save) vcc_skip_saves.insert(*proof->save); + if (proof->restore) vcc_skip_restores.insert(*proof->restore); + vcc_skip_joins.emplace(last.target(), std::move(*proof)); + } alu.ir.body << " br i1 " << condition << ", label %g" << last.target() << ", label %g" << last.next << "\n"; } else diff --git a/tests/cmake/native_pixel_varying_vcc_branch.cmake b/tests/cmake/native_pixel_varying_vcc_branch.cmake new file mode 100644 index 000000000..5f3b256ec --- /dev/null +++ b/tests/cmake/native_pixel_varying_vcc_branch.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}") + set(vcc_branch_check "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pixel_varying_vcc_branch_check.py") + add_test(NAME native_pixel_varying_vcc_branch_controls COMMAND "${INTAKE_PYTHON}" -B + "${vcc_branch_check}" "$" - "${DXC_BIN_DIR}" controls) + set_tests_properties(native_pixel_varying_vcc_branch_controls PROPERTIES TIMEOUT 60) + if(TARGET offscreen_check) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_pixel_varying_vcc_branch_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${vcc_branch_check}" "$" "$" + "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_pixel_varying_vcc_branch_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() + endif() +endif() diff --git a/tests/native_pixel_varying_vcc_branch_check.py b/tests/native_pixel_varying_vcc_branch_check.py new file mode 100644 index 000000000..47847a621 --- /dev/null +++ b/tests/native_pixel_varying_vcc_branch_check.py @@ -0,0 +1,179 @@ +"""Validate source-built pixel VCC shortcuts and compare every pixel of an 8x2 draw.""" + +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_cmpx_if_else_check import bits, readfirstlane +from native_pixel_compare_mask_check import cmp_gt, cndmask +from native_scalar_lds_check import scalar, sop1, vmove + + +VCCZ, VCCNZ, SCC0, SCC1 = 0xBF860000, 0xBF870000, 0xBF840000, 0xBF850000 +ZERO, HALF, ONE, TWO = 128, 240, 242, 244 +REFUSAL = "graphics scalar condition depends on a varying input" +UNDEFINED = "graphics register undefined on an incoming path:" +DOUBLE = 0x100404F4 # v_mul_f32 v2, 2.0, v2 +SCRATCH = 0x100604F4 # v_mul_f32 v3, 2.0, v2 +KEEP_CLEAR = cndmask(2, 258, 259, 106) +KEEP_SET = cndmask(2, 259, 258, 106) +SAVE = sop1(0x24, 4, 106) +RESTORE = sop1(4, 126, 4) + + +def container(code, **kwargs): + return patched_pixel(len(code), code, input_address=1 << 8, + input_signature=((b"ISG1", signature(b"SV_Position", 1)), + (b"OSG1", signature(b"SV_Target", 64))), + export=(0xF800180F, 0x02020202), **kwargs) + + +def shortcut(body, *, limit=3.0, branch=VCCZ, before=(), after=(), **kwargs): + # v_cmp_lt_f32 vcc, limit, v0 (SV_Position.x) + return container([vmove(2, HALF), *before, 0x7C0200FF, bits(limit), + branch | len(body), *body, *after], **kwargs) + + +def uniform_alu(branch, limit, *, wqm_scc=False, readfirst=False): + # s6 = 0.5; v3 = (s6 + vmove(s6)) * 2.0; vcc = (v3 > limit). + prefix = [sop1(10, 126, 126)] if wqm_scc else [] + prefix += [vmove(2, HALF), sop1(3, 6, HALF), vmove(3, 6), + 0x06060606, 0x100606F4] + if readfirst: + prefix += [readfirstlane(7, 3), vmove(3, 7)] + prefix += [*cmp_gt(106, 259, limit)] + if wqm_scc: + prefix += [scalar(15, 4, 106, 126)] # s_and_b64 s[4:5], vcc, exec + return container([*prefix, branch | 1, vmove(2, ONE)]) + + +def cancellation(compare, prefix=()): + # Unguarded live write requires a genuinely uniform condition. + return container([vmove(2, HALF), *prefix, *compare, VCCZ | 1, vmove(2, ONE)]) + + +def flat_branch(): + # v_interp_mov_f32 v3, p0, attr0.x, then an unguarded VCCZ body. + code = [vmove(2, HALF), 0xC80E0002, *cmp_gt(106, 259, HALF), VCCZ | 1, vmove(2, ONE)] + return patched_pixel(len(code), code, + attributes=((6, 0, 1, 0, 0, 0, 0, 1),), + input_signature=((b"ISG1", signature(b"TEXCOORD", mask=1)), + (b"OSG1", signature(b"SV_Target", 64))), + export=(0xF800180F, 0x02020202)) + + +def main(cli, raster, sdk, mode): + dxc = Path(sdk) / "dxc.exe" + cases = [] + for name, body, kwargs in ( + ("cndmask", [SCRATCH, *KEEP_CLEAR], {}), + ("cndmask-wave32", [SCRATCH, *KEEP_CLEAR], {"wave32": True}), + ("saveexec", [SAVE, SCRATCH, vmove(2, 259), RESTORE], {}), + ): + for mask, limit in (("mixed", 3.0), ("all-clear", 9.0), ("all-set", 0.0)): + expected = [1.0 if x + 0.5 > limit else 0.5 for x in range(8)] + cases.append((f"{name}-{mask}", shortcut(body, limit=limit, **kwargs), expected)) + for name, branch, wqm in (("vccz", VCCZ, False), ("vccnz", VCCNZ, False), + ("wqm-scc0", SCC0, True), ("wqm-scc1", SCC1, True)): + for limit, take in ((HALF, True), (TWO, False)): + run_body = take if branch in (VCCZ, SCC0) else not take + cases.append((f"uniform-{name}-{limit}", uniform_alu(branch, limit, wqm_scc=wqm), + [1.0 if run_body else 0.5] * 8)) + cases += [ + ("uniform-readfirstlane", uniform_alu(VCCZ, HALF, readfirst=True), [1.0] * 8), + ("and-zero", cancellation(cmp_gt(106, HALF, 259), [0x36060080]), [1.0] * 8), + ("integer-self-compare", cancellation([0xD4C2006A, 256 | (256 << 9)]), [1.0] * 8), + ("wqm-intersect-compare-with-exec", + container([sop1(10, 126, 126), vmove(2, HALF), *cmp_gt(4, 256, 244), + scalar(15, 106, 126, 4), VCCZ | 3, SCRATCH, *KEEP_CLEAR]), + [0.5] * 2 + [1.0] * 6), + ] + refusals = [ + ("unguarded live write", shortcut([DOUBLE]), REFUSAL), + ("wrong cndmask polarity", shortcut([SCRATCH, *KEEP_SET]), REFUSAL), + # In a mixed wave VCCNZ skips both lanes, even the one with VCC clear. + ("varying vccnz with inverted cndmask", shortcut([SCRATCH, *KEEP_SET], branch=VCCNZ), REFUSAL), + ("scratch VGPR read", shortcut([SCRATCH, *KEEP_CLEAR], before=[vmove(3, TWO)], + after=[vmove(2, 259)]), f"{UNDEFINED} 259"), + ("scratch SGPR read", shortcut([sop1(3, 6, TWO), SCRATCH, *KEEP_CLEAR], + before=[sop1(3, 6, ONE)], after=[vmove(2, 6)]), f"{UNDEFINED} 6"), + ("scratch SGPR dead", shortcut([sop1(3, 6, TWO), SCRATCH, *KEEP_CLEAR], + before=[sop1(3, 6, ONE)]), None), + ("saved EXEC pair read", shortcut([SAVE, DOUBLE, RESTORE], before=[sop1(3, 4, ONE)], + after=[vmove(2, 4)]), f"{UNDEFINED} 4"), + ("SAVEEXEC SCC read", shortcut([SAVE, DOUBLE, RESTORE], before=[sop1(3, 6, ZERO), 0xBF060680], + after=[SCC0 | 1, vmove(2, HALF)]), f"{UNDEFINED} 128"), + ("wrong restore", shortcut([SAVE, DOUBLE, sop1(4, 126, 6)]), REFUSAL), + ("join retains varying control", shortcut([SAVE, vmove(2, ONE), RESTORE], + after=[*cmp_gt(106, 258, HALF), VCCZ | 1, vmove(2, TWO)]), + REFUSAL), + ("overwritten VCC", shortcut([SCRATCH, *cmp_gt(106, 256, ONE), *KEEP_CLEAR]), REFUSAL), + ("clobbered kept value", shortcut([DOUBLE, SCRATCH, *KEEP_CLEAR]), REFUSAL), + ("export", shortcut([0xF800000F, 0x02020202, SCRATCH, *KEEP_CLEAR]), REFUSAL), + ("store", shortcut([0xE0701000, 0x80000405, SCRATCH, *KEEP_CLEAR]), REFUSAL), + ("implicit LOD", shortcut([0xF0800108, 0x00280200, SCRATCH, *KEEP_CLEAR]), REFUSAL), + ("DPP", shortcut([0x7E0602FA, 0xFF00B100, *KEEP_CLEAR]), REFUSAL), + ("branch leaving body", shortcut([SCC0 | 1, SCRATCH, *KEEP_CLEAR]), REFUSAL), + ("branch entering body", shortcut([SCRATCH, *KEEP_CLEAR], + before=[0xBF068080, SCC0 | 3]), REFUSAL), + ("floating self-compare may see NaN", cancellation([0xD402006A, 256 | (256 << 9)]), REFUSAL), + ("flat attribute can vary across primitives", flat_branch(), REFUSAL), + ("varying readfirstlane", container([readfirstlane(7, 0), vmove(2, 7)]), + "graphics readfirstlane requires a wave-uniform reaching value"), + ] + + with TemporaryDirectory() as tmp: + work = Path(tmp) + source, vs, ps = work / "guest", work / "vs.cso", work / "ps.cso" + + def compile_guest(blob): + source.write_bytes(blob) + ps.unlink(missing_ok=True) + return subprocess.run([cli, sdk, work / "cache", "gfx1013-container-ps", source, ps], + capture_output=True, text=True) + + for label, blob, reason in refusals: + result = compile_guest(blob) + if reason: + assert result.returncode and reason in result.stderr and not ps.exists(), ( + label, result.stdout, result.stderr) + else: + assert result.returncode == 0, (label, result.stdout, result.stderr) + print(f"control {label}: ok") + + if mode != "controls": + vertex_source = work / "vs.hlsl" + vertex_source.write_text(VERTEX["full"]) + subprocess.run([dxc, "-T", "vs_6_6", "-Fo", vs, vertex_source], check=True) + expected_path = work / "expected.bin" + + def draw(row): + expected_path.write_bytes(b"".join(struct.pack("<4f", *([value] * 4)) for value in row * 2)) + return subprocess.run([raster, mode, "--startup-pixel-words", vs, ps, "8", "2", expected_path], + capture_output=True, text=True) + + for index, (label, blob, expected) in enumerate(cases): + result = compile_guest(blob) + assert result.returncode == 0, (label, result.stdout, result.stderr) + dump = subprocess.check_output([dxc, "-dumpbin", ps], text=True) + assert "@dx.op.storeOutput" in dump and "@dx.op.wave" not in dump, (label, dump) + if mode != "controls": + result = draw(expected) + if index == 0 or result.returncode: + print(result.stdout, end="") + if result.returncode == 77: + print(result.stderr, end="") + sys.exit(77) + assert result.returncode == 0, (label, result.stdout, result.stderr) + wrong = draw([1.5 - value for value in expected]) + assert wrong.returncode == 1 and "pixel mismatch (0,0)" in wrong.stderr, ( + label, wrong.stdout, wrong.stderr) + print(f"{label}: ok" + (" (opposite reference mismatched)" if mode != "controls" else "")) + + +if __name__ == "__main__": + main(*sys.argv[1:])