Skip to content

fix(shader): pair an optional body exit with a copied skip-target tail - #18379

Merged
oneandonlydean merged 6 commits into
boykopovar:mainfrom
kaiffeetasse:contrib/stencil-replay-copied-tail
Nov 16, 2026
Merged

oneandonlydean merged 6 commits into
boykopovar:mainfrom
kaiffeetasse:contrib/stencil-replay-copied-tail

Conversation

@kaiffeetasse

@kaiffeetasse kaiffeetasse commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What

The optional-body rule of the stencil replay mask proof (MaskReplaySafety::optionalBody) refused every body block that ends in a return and exports. The structurizer can copy the skip target's export tail into the body, so a provably replay-safe shader was refused with stencil reference export emulation requires a replay-safe pixel shader with late tests: PPSA03671, pixel shader 0x11d01d0900, issue #18335.

A body exit now keeps its exports when its whole copied tail pairs with a skip-reachable block of the same non-degenerate startPc/endPc range:

  • Same opcodes in order, equal export records, and operands, SetAttribute guards and conditional terminator conditions related by sameValue, inactiveEquals, or — for a value recomputed in each copy — by a structural match: same opcode, type, flags and operand count, no side effects, lane-local only (no ballot, wave mask, lane permute/read/write, shared memory or sampler opcode), every operand related under a depth limit of 24.
  • The leading phis of both instruction lists are not compared: the body copy is single-entry. A skip-side phi resolves to its incoming value for the predecessor its block was entered with, and every predecessor of the root skip block inside the skip graph is tried. The entry predecessor of every paired skip block is carried along, so a phi that lives in a block the copy was entered from resolves to the incoming value the copy stands for instead of to nothing.
  • A block that carries only phis and an unconditional branch is stepped over on either side, so an empty forwarding block on the skip side alone does not shift the instruction counts of the pair.
  • Words whose cleared lanes are not literally Not(predicate) are related when the cleared side is zero on every lane the predicate is zero on: the predicate itself, an and with such a side, or an own-bit read of a ballot of those lanes.
  • Immediates of any type compare by their bits, so SetAttribute ..., false matches a separately built false instead of only U32 immediates comparing.
  • Successor polarity has to match, so an "any lane left" branch inside a copy has to decide the same way on both sides.

A discard, a differing or degenerate pc range, a differing opcode, a swapped polarity, a phi that differs on active lanes for the paired predecessor, a cleared side that is not zero on inactive lanes and a chain deeper than the limit still refuse, and the merge-phi rule is untouched.

The patch applies cleanly on main. The shape is only reachable once #18322 admits the first-lane read that stops the proof earlier today, so this depends on #18322.

This head adds the review round of @mrfelek and @oneandonlydean:

  • The pair map is filled after the empty-block step, so a pair whose skip side forwards through a phis-only block is recorded with the block it was forwarded to, not with the block it started from.
  • The entry predecessor of every paired skip block now belongs to the path: the map is copied per branch of a conditional pair, so a skip block reached directly on one path and through a predecessor on the other resolves each phi with the entry of its own path instead of the first one recorded.
  • A wave-wide comparison is exact. At the conditional terminator of a pair the two conditions may only be related through a ballot whose lane argument is the same value on both sides, or is provably zero on every lane the predicate is zero on; the lane-local mask-word rules are not used there. The replay runs the body for the lanes the skip left out, so an scc decision over a ballot has to agree on all lanes, and a relation that holds only on the active ones cannot decide it.
  • Three fixtures pin the shapes: a skip target that forwards through an empty block, a skip block with two entry predecessors, and an any lane left branch over two ballot words (positive when both arguments are zero on inactive lanes, negative when they differ on an inactive lane and are not zero there).

This head (80ef6a8ad9) closes the soundness gap @oneandonlydean found in that exact check:

  • The exact path now also requires the two ballot arguments to agree on the active lanes. equalOnActiveLanes strips a conjunction factor that is literally the predicate from both sides (on the lanes the predicate selects, and(p, x) is x), and then demands a full structural match of what is left; the two arguments must additionally still be provably zero on the inactive lanes, so the ballots agree on every lane. and(p, Not(and(p, Q1))) against and(p, Not(and(p, Q2))) with Q1 != Q2 is refused now; it was accepted before this head.
  • inactiveEquals no longer decides anything on the exact path. It is an inactive-lane relation by construction, and it ran before the exact ballot check, so it could accept a wave-wide decision on slack the decision does not have. The same holds for the exclusionLanes strip of a Bool, which is only an equality on the lanes the predicate does not select; both are skipped when the comparison is exact. Only exact relations remain there: sameValue, the strict ballot rule above, an and with a word that is set on every lane, an own-bit read whose mask words satisfy the strict rule, the skip-side phi resolution, and the structural match.
  • touched is keyed by path. An entry that was recorded while walking one path no longer answers for the same block pair reached on another: the map stores the skip block and the entry predecessor of that pairing, and a second visit needs both to match, so a pair reached twice through different predecessors is not waved through on the first path's phis.
  • Fixture: an any lane left branch whose two ballot arguments are both zero on inactive lanes and differ only on an active lane, i.e. exactly the counterexample. It is refused at this head and accepted at b6f6fbd469.

Tested

Linux 6.8.0-51, Intel UHD 630 (i915, Mesa). The new cases are CPU-only IR fixtures, no device involved.

  • agc_masked_select (ctest --test-dir build-libs -R '^agc_masked_select$'), head a3c026161c: 1/1 passed in 0.04 s, 150 cases; the head below carries 156.
  • build-relinker (-DANYPS5_RELINKER_ONLY=ON) rebuilds and links with the change; check_conventions.py --base origin/main reports All conventions checks passed.
  • Regression proof at this head: with d43ef8dc18s StencilReplay.cpp and this test file, exactly four positive cases fail (exit 1) — a phi in an earlier skip block, an own-bit mask whose cleared side is an own-bit read of the predicate's ballot, a dead export guard that is a separately built false, and a ballot argument that is a deep recomputed copy — and every negative case still refuses. With the change all cases pass (exit 0).
  • Each rule is load-bearing on its own: neutralising only the empty-block step (followSkip returns its argument) makes the earlier-skip-block phi case fail, so that case does not pass through the other four rules.
  • Windows, AMD RX 6700 XT (driver 26.10.1), MinGW-w64 GCC 15.2 UCRT, Release, head ed43b0376b, reported by @JJenkx: agc_masked_select passed 3 of 3 runs with ANYPS5_REQUIRE_VULKAN=1 (merged onto 1ceea3c46d) and 3 of 3 with Vulkan hidden (merged onto abcb5369ff).
  • Windows, NVIDIA RTX 3070 (driver 617.42), MinGW, main 62bd7dd61e + fix(shader-recompiler): admit first-lane reads of wave-uniform values in stencil replay #18322 + this PR, reported by @akkadbakkad89: 1/1 passed; with the previous StencilReplay.cpp and this test file the two positive cases that existing then failed (exit 1).
  • Stencil ctest set on main and on d43ef8dc18 (the previous head of this branch), both with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, ctest --test-dir build-libs -R stencil -V: 15/15 pass in both runs. Neither log contains was not found but was requested by env var VK_INSTANCE_LAYERS. Both logs contain the same 12 validation lines, only VUID-vkCmdDraw-None-07629, so the change adds no new VUID- error. The last commit extends the same rule set and was re-run as agc_masked_select above; a full build-libs cannot be rebuilt in this environment (3rdparty/libpsl/list/public_suffix_list.dat is missing), so the GPU-side set was not re-measured at a3c026161c.
  • Head b6f6fbd469: the file holds 156 cases, ctest --test-dir build-libs -R '^agc_masked_select$' reports 100% tests passed, 0 tests failed out of 1 in 0.26 s, and ctest -R stencil reports 100% tests passed, 0 tests failed out of 15 in 9.15 s.
  • Regression proof at this head: with a3c026161cs StencilReplay.cpp and this test file, exactly three cases fail (exit 1) — the skipped-target forwarding case, the two-predecessor case, and the negative any lane left case, which the previous head accepted. Every other case, including all 150 that existed before, decides the same. With the change all 156 pass (exit 0).
  • Head 80ef6a8ad9 (this head): 157 cases, ctest --test-dir build-libs -R '^agc_masked_select$' reports 100% tests passed, 0 tests failed out of 1 in 0.31 s; ctest --test-dir build-libs -R stencil reports 100% tests passed, 0 tests failed out of 15 in 10.31 s; build-relinker (-DANYPS5_RELINKER_ONLY=ON) builds and links; check_conventions.py --base origin/main reports All conventions checks passed.
  • Regression proof at 80ef6a8ad9: with b6f6fbd469s StencilReplay.cpp and this test file, exactly one case fails (exit 1) — the new active-lane negative, which the previous head accepted — and the other 156 cases decide the same as before. With the change the binary exits 0. So the new rules are load-bearing and cost no previous accept.
  • Gate 1 at this head: pr_overlap: cannot confirm overlap with PR 7689: core/shader/recompiler/StencilReplay.cpp / overlap check failed closed. Same as at the previous heads and manually bounded: fix(shader): defer guarded fragment V# type faults #7689 has exactly one hunk in that file, @@ -848,8 +848,13 @@ in StencilReferenceDefinedForKeptInvocations, a free function outside MaskReplaySafety; this branch touches main lines up to 735 and none of StencilReferenceDefinedForKeptInvocations/DeferredBufferFaultsOnly (git diff origin/main...HEAD -- StencilReplay.cpp | grep -c = 0).
  • git merge-tree --write-tree origin/main HEAD at this head: exit 0, so the branch still applies on today's main without a rebase.
  • On the widening question: every rule this PR adds is an additional accept — a widened sameValue (any type, ImmediateU64), a unified exclusionLanes that also strips a side provably zero on inactive lanes, the ballot and mask-word-in-ballot relations, and the depth limit of 24 on the mask-word chain instead of 8. No rule on main was removed and none of the added predicates can turn a comparison that held on main into a refusal, so a shader that compiled before still does. The narrowings only remove accepts this PR itself introduced: the wave-wide ballot rule at a3c026161c, and at 80ef6a8ad9 the active-lane requirement plus the exact path no longer consulting the inactive-lane relations. Nothing here changes a decision relative to main.
  • Not re-run at this head: the GPU validation-layer comparison (made at d43ef8dc18) and the Windows data points, both quoted above at their own heads.
  • Not tested: the PPSA03671 request itself. There is no NVIDIA GPU here, and fix(shader-recompiler): admit first-lane reads of wave-uniform values in stencil replay #18322 has to merge before the shape is reachable. The issue author offered to run a candidate against the logged request; head 80ef6a8ad9 is that candidate.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: fix(shader-recompiler): admit first-lane reads of wave-uniform values in stencil replay #18322
  • Fixes: none
  • Unblocks: none
  • GPUs tested: Intel UHD 630 (i915), Mesa, Linux 6.8.0-51 for the stencil ctest set; the new masked-select cases are CPU-only. Windows data points from @JJenkx (AMD RX 6700 XT) and @akkadbakkad89 (NVIDIA RTX 3070) are quoted above
  • AI-assisted: yes

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 7689 core/shader/recompiler/StencilReplay.cpp
PR 10867 core/libs/prx/libSceAgcDriver/tests/MaskedSelect.cpp
PR 14217 core/shader/recompiler/StencilReplay.cpp

@mrfelek

mrfelek commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse thanks for picking this up so fast. I ran it against the logged request for 0x11d01d0900: main + #18322 + this PR (head ed43b0376b), offline through PrepareResourceProgram. agc_masked_select passes, but the shader is still refused: MaskReplaySafety::Check fails in the same optionalBody call. With the exits traced, tailPairs refuses three ways:

  1. Phis on the skip side. The skip-reachable blocks at pc 0x1a8..0x1b0 and 0x1b8..0x1c8 are where the skip path and the one rejoining body path meet. They start with phis (3 and 2: the saved live mask's ballot words and the values the export uses), and the copies don't have them. So the size check fails, 11 vs 14 and 9 vs 11 instructions. A body value would have to be related to the phi's incoming value along the path the copy stands for, not to the phi itself.
  2. Copied computations. At 0x1b0..0x1b8, the LogicalNot operand is a LogicalAnd computed separately in each copy (Not(And(ownBit, Not(x))), with x itself one of those phis on the skip side). relatedValue needs a structural case: same opcode and flags, operands related recursively, under a depth limit.
  3. Constant vectors. At 0x1c8..0x1d8, the null export's CompositeConstructU32x4(0, 0, 0, 0) is a separate value in each copy, and sameValue only compares U32 immediates. That export's guard is false, so it keeps nothing either way.

The rest of the shape, from the issue: the copies exit through the s_cbranch_scc0 any-lane-left branches, and the export guard is the own bit of a ballot of the remaining live mask. I can rerun the request against a new head within minutes.

AI-assisted.

@github-actions github-actions Bot added shader core/shader agc libSceAgc* labels Nov 11, 2026
@JJenkx

JJenkx commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Windows check of head ed43b0376b. Setup: Windows 11 Enterprise 22621, AMD RX 6700 XT, AMD driver 26.10.1, MinGW-w64 GCC 15.2 UCRT, Release.

agc_masked_select passed in 3 of 3 runs in both setups:

  • GPU, through the shared Windows GPU FIFO with ANYPS5_REQUIRE_VULKAN=1: merged onto main 1ceea3c46d (merge 0e6a74e83d). The binary matched the hash recorded at preparation, and the receipt shows exit 0 and app_count=0.
  • CPU, Vulkan hidden: merged onto main abcb5369ff (merge 737b1f2cae).

AI-assisted: yes.

@akkadbakkad89

Copy link
Copy Markdown
Contributor

Hardware datapoint on NVIDIA GeForce RTX 3070 (driver 617.42), Windows 11, MinGW build — the same GPU class as the original report.

Built main (62bd7dd61e) + #18322 + this PR stacked, plus the two variants for the regression proof:

  • agc_masked_select on the stack: 1/1 passed (~1 s) — all eight new cases plus every existing case.
  • Regression proof (previous StencilReplay.cpp + this PR's test file): exit 1, with the affected cases printed including both positive cases (...copy of the skip target's export tail with the same pc range, ...nested copy of the skip target's any-lane-left tail). Same behavior the PR describes: the two positive cases fail, the negatives still refuse. With the change all pass (exit 0).
  • agc_masked_select is IR-level, so no Vulkan device is created; for reference the machine's device selection was confirmed on the frame-replay suite (NVIDIA RTX 3070 chosen, VK_LAYER_KHRONOS_validation loaded, zero VUID-).

One caveat on end-to-end: our local PPSA03671 capture (acs_stencil.req, wave64, 2 linked programs) fails identically on both builds one stage earlier — SrtWalker::EvaluateRuntimeSources failed to evaluate runtime sources: descriptor source 0 dword 0 — a partial-capture artifact that never reaches the replay-safety proof. So it neither reproduces the refusal nor regresses with the fix; the unit fixtures are the verdict here.

@kaiffeetasse

kaiffeetasse commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Head is now fd189fb3bc, and all three refusals you traced are addressed rather than argued with:

  • Phis on the skip side. tailPairs no longer requires one instruction per instruction across the leading phis: the leading Phi instructions are skipped on both sides and never compared directly. A skip-side phi enters the proof through its operands instead, resolved to its incoming value for the predecessor the copy stands for, and every predecessor of the root skip block inside the skip graph is tried (merge and the skip-graph interiors). Nothing is compared against the phi itself.
  • Copied computations. relatedValue has the structural case you asked for: same opcode, type, flags and operand count, no side effects, every operand related recursively, depth limit 8. It is restricted to lane-local opcodes — ballot, wave mask, lane read/permute/write, shared memory and sampler opcodes are excluded, because two structurally equal copies of those are not equal when the exec mask differs; they still have to come through inactiveEquals, which is why the exclusion is there.
  • Constant vectors. The same rule covers CompositeConstructU32x4(0,0,0,0): the operands are immediates that sameValue already compares, so the two copies' null exports now pair even though the constructs are distinct values. That block's guard is constant false, so it stays harmless either way.

Order in relatedValue: sameValue, then inactiveEquals in both directions, then the phi resolution, then the structural case — so nothing that refused before can now be admitted by a weaker path.

Measured on this head (ctest --test-dir build-libs -R '^agc_masked_select$', 135 cases in the binary): 1/1 passed, exit 0. Twelve new cases next to the existing ones: the phi tail admitted, the same fixture with a differing incoming value for the paired predecessor refused, the constant-vector null export admitted, and a recomputed chain deeper than the limit refused; the six earlier negatives are unchanged. Differential proof: with the previous StencilReplay.cpp and the new test file, exactly the two positive cases (phi tail, constant-vector tail) fail with exit 1 — so they do exercise the new paths.

What I could not check here is the request itself: no NVIDIA GPU, and optionalBody is only reached once #18322 is stacked. Your offer stands — a rerun of 0x11d01d0900 against fd189fb3bc would be the decisive datapoint. If it still refuses, the next trace I would want is which of the two remaining refusals fires: the SetAttribute guard check on an unpaired body block, or tailPairs on a pc range that has no skip counterpart.

AI-assisted: yes.

@mrfelek

mrfelek commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse reran the request against fd189fb3bc (main + #18322 + this head, offline through PrepareResourceProgram). agc_masked_select passes; 0x11d01d0900 is still refused, now further in. Block numbers below are blockInfo ids.

  1. The root pair at 0x1a8 doesn't resolve its phis. The body copy b13 (0x1a8..0x1b0) pairs with the merge b18, whose phis come from b3 (the skip branch) and b17 (0x1a4..0x1a8). b17 is the body block of the one path that rejoins, so it's in region, not in the skip graph, and none of the predecessors tried resolves the phis (relatedValue returns at the phi with no matching skipPred). The incoming value that corresponds is b17's: the copy's own predecessor b12 has b17's pc range (0x1a4..0x1a8). Picking the predecessor whose pc range matches the copy's predecessor would relate %341 (b12) to %379 (b17). Both are the same lane-local own-bit read of s6's words, so the structural case takes them.
  2. The export guards are own bits of ballots. At 0x1b8..0x1c8 the guard is SelectU32(LaneId < 32, lo, hi) >> (LaneId & 31) & 1 != 0 over the live mask's words. In the body copy (b15) the words are CompositeExtractU32x4(Ballot(And(%18, Not(%323))), 0/1). In b21 they come through a phi. From b18 that's a BitwiseAnd32 of words (s_andn2 s20, s20, exec); from b20 it's another Ballot. lateralValue refuses Ballot, so the pair fails at depth 2. The ballot itself is cross-lane, but this read is the lane's own bit, which is the ballot's operand for that lane (0 for a lane that was off at the ballot). A rule that relates two own-bit reads through their lane predicates, for example through own() / the ReplayMask pairs the proof already builds, would cover both the Ballot and the BitwiseAnd32-of-words side.

The final refusal is the copiedExits check: the two copied exports, b15 and b22, stay unpaired. Happy to rerun the next head.

AI-assisted.

The optional-body rule refused every body block that ends in a return and exports, so one structurizer copy of the skip target's tail made the mask proof reject a pixel shader it can prove.

Pair a body block with a skip-reachable block of the same non-degenerate pc range and compare the pair instruction by instruction: same opcodes, same export records, and operands and conditional terminators related by inactiveEquals. A body exit only keeps its exports when its whole copied tail pairs; a discard, a differing pc range or a swapped branch polarity still refuses.
…ed operands

The pairing required one body instruction per skip instruction, so a tail whose
skip block starts with phis was refused, and an operand recomputed in each copy
never compared equal. Skip the leading phis of both lists, resolve a skip phi
through its incoming value for the predecessor the copy stands for, and relate
recomputed values structurally when the opcode is lane-local, side-effect free
and every operand relates under a depth limit.
… lanes

A copied export tail can read the same lane's own bit from mask words built
differently on each side: the body ballots the lanes less the inactive ones,
while the skip side ands that ballot with the cleared-lane ballot or with the
exec mask, so the words never compare equal and the pair was refused.

Relate two words when they agree on the lanes that are active: a word cleared
on the active lanes relates to another word cleared there, and an and with a
word that is set on those lanes is transparent. The same relation now also
covers two own-bit reads whose words come from different ballots of the same
lanes.
@kaiffeetasse
kaiffeetasse force-pushed the contrib/stencil-replay-copied-tail branch from fd189fb to d43ef8d Compare November 11, 2026 18:23
@kaiffeetasse

Copy link
Copy Markdown
Contributor Author

@mrfelek both shapes are implemented rather than argued with; head is now d43ef8dc18 (rebased onto main f57c971559).

  • Root pair's phis. The skipPred candidate set now also contains a predecessor of the skip block that lies in the body region, when its pc range equals the pc range of one of the copy block's own predecessors. For your 0x1a8 pair that offers b17 (because b12 carries 0x1a4..0x1a8), so the merge phi resolves to b17's incoming and %341/%379 meet as the same lane-local own-bit read. The existing skip-graph/merge candidates are tried first and unchanged; the pc range is still a hard condition.
  • Own bits of ballots. Two mask words now relate when they agree on the lanes that are active: a word that is zero there relates to another word that is zero there, and an and with a word that is one there is transparent. That covers CompositeExtract(Ballot(And(x, Not(p)))) on the body side against either CompositeExtract(Ballot(x)) or the s_andn2 word And(ballot(x), ballot(Not(p))) on the skip side, and against a skip-side phi of either. own() was split into a side-effect-free recogniser plus the old restricting wrapper, so a failed comparison no longer widens the restriction set.

Measured on d43ef8dc18 (Linux, Intel UHD 630, CPU-only IR fixtures):

  • agc_masked_select 1/1 Passed, 0.04 s, 142 cases in the binary (19 added by this PR, 7 in this commit).
  • Regression proof: with the previous StencilReplay.cpp and the new test file exactly four positive cases fail — the three you saw last time plus "mask words are an and of the lanes and the cleared-lane ballot" — and every negative still refuses. With the change all 142 pass, exit 0.
  • Negatives kept for the new rules: a rejoining predecessor with a different pc range, own-bit reads over lanes that differ on active lanes, and an and over other active lanes are all still refused.

What it does not do: the word relation is pattern-based on the active-lane identities above, not a general mask-equivalence proof. If a further refusal remains, the block numbers plus which of the two sides is the and word would let me pin it down. Happy for a rerun on d43ef8dc18.

AI-assisted.

@mrfelek

mrfelek commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse reran against d43ef8dc18 (merged onto #18322, offline through PrepareResourceProgram). agc_masked_select passes; 0x11d01d0900 is still refused. Block numbers are blockInfo ids; % numbers are from my IR dump.

The root pair's phis are fixed: b13↔b18 now takes b17 and gets past 0x1a8. To find what's left, I patched a local copy until the proof went through. These patches are only probes, not proposals. The refusals, in order:

  1. The cleared lanes aren't Not(predicate).
    • The body word is Ballot(And(%18, Not(%323))).
    • %323 = And(own bit of (Ballot(%159) & wqm), Not(%247)), and %159 is the branch predicate. So %323 is false on inactive lanes.
    • exclusionLanes only strips Not(predicate) itself.
    • Probe: also strip Not(Y) when Y is the predicate, an And with such a side, or an own-bit read of a word that ballotOfLanes(word, predicate) accepts.
    • The same relation is needed for a Bool in pair b14↔b19 (0x1b0): And(%327, Not(%350)) vs And(%18, Not(%391)), where arg 0 is %327 vs %18.
  2. Phis of an earlier skip block.
    • In b14↔b19, %382 = Phi [%159, b3], [%379, b17] lives in b18, but skipPred is b18 itself. It needs the skipPred that b18 was entered with (b17).
    • The same happens after a phi is resolved, since the nested call passes nullptr.
    • Probe: record each skip block's skipPred in tailPairs and use it when a phi's block is an earlier skip block.
  3. Ballots whose lanes match only through copies.
    • The any-lane test at 0x1b0 and the words at 0x1b8 compare Ballot(And(%327, Not(%350))) with Ballot(And(%18, Not(%391))).
    • %348/%389 and %341/%382 are recomputed copies, and relatedLanes only uses sameValue/inactiveEquals.
    • Probe: relate the ballot arguments with relatedValue. I haven't checked that this is sound for a wave-wide value; that's your call.
    • With it, the chains also exceed the depth limit of 8 (24 was enough).
  4. An empty forwarding block on the skip side only. b20 (pc 0x1b8..0x1b8, no instructions, Branch to b21) has no copy on the body side. b14 goes straight to b22, so the instruction counts differ. Probe: step through such blocks.
  5. false vs false. sameValue only treats U32 immediates as equal, so the null exports b16↔b23 at 0x1c8 fail on SetAttribute ..., false.

With all five, both copied exits (b15, b22) pair and the outer branch at 0x7c..0x94 is proven. The next refusal is the inner branch at 0x94..0x9c (b4 → b5, merge b6):

  • The merge phi %206 = Phi [%138, b4], [%205, b5] reaches ReadFirstLane %295, %247 through %247, its second operand.
  • So quadObserved refuses it.

I stopped there.

AI-assisted.

…asks and empty skip blocks

The skip-side tail can reach its exit through a phi that lives in a block the copy was
entered from, through an empty forwarding block with no body-side counterpart, or
compare mask words whose cleared lanes are an own-bit read of the predicate's ballot
rather than Not(predicate) itself. Relate skip phis by the predecessor each skip block
was entered with, step over blocks that carry only phis and a branch, strip the new
cleared-lane shapes, compare immediates of any type by their bits, and let ballot
arguments resolve through recomputed copies up to a depth of 24.
@kaiffeetasse

Copy link
Copy Markdown
Contributor Author

@mrfelek head is a3c026161c; all five probes are in as rules, and each one is measured.

  1. Cleared lanes. zeroOnInactiveLanes decides it: a side counts as cleared when it is zero on every lane the predicate is zero on — the predicate itself, an and with such a side, or an own-bit read of a ballot of those lanes. exclusionLanes, the Bool operand comparison and inactiveEquals all share that definition now instead of keeping their own copy of the Not(predicate) test.
  2. Earlier skip phis. The pairing carries a map from each skip block to the predecessor it was entered with, so a phi in a block the copy was entered from resolves to the incoming value for that predecessor instead of getting nullptr, and the resolved call keeps the map.
  3. Ballot arguments and depth. Ballot against ballot relates its arguments through relatedLanes and then through relatedValue, and the depth limit of relatedValue/relatedMaskWord is 24. This is the one place I would like your reading: I accept the widened relation because every mask-word comparison it can reach is lane-restricted (clearedOnActiveLanes, setOnActiveLanes, exclusionLanes) and never an exact wave-wide comparison, so a difference on inactive lanes cannot let a word through that would otherwise be refused. If you see a path where the widened relation feeds a plain sameValue comparison of the resulting word, name it and I will pin that path.
  4. Empty forwarding blocks. A block that carries only phis and an unconditional Branch is stepped over on both sides before the instruction counts are compared.
  5. false against false. Immediates compare by type and raw bits, so Bool, F32 and U32 immediates all compare; the U32 case is unchanged.

Tests: MaskedSelect.cpp is at 150 cases (123 on main, 8 new here), each rule with a positive and a negative case. With d43ef8dc18s StencilReplay.cpp and the new test file exactly four positive cases fail — earlier-skip phi, own-bit-of-the-predicate mask, separately built false guard, deep ballot copy — and every negative case still refuses (exit 1); with the change the suite is green in 0.04 s (exit 0). Neutralising only the empty-block step brings the earlier-skip phi failure back, so that rule carries its case on its own rather than through the other four.

Still refused, as you predicted: the inner branch at 0x94..0x9c — the merge phi %206 = Phi [%138, b4], [%205, b5] reaches ReadFirstLane %295, %247 through its second operand, so quadObserved refuses it. I have not touched that yet.

AI-assisted: yes.

@mrfelek

mrfelek commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse reran a3c026161c (merged onto #18322) against the logged request. agc_masked_select passes, but 0x11d01d0900 doesn't reach the inner branch yet: both copied exits (b15, b22) are still unpaired. Two things stop the root pair b13↔b18. With both changed locally, the root and both exits pair, and the refusal moves to quadObserved on the inner branch, as you expected.

  1. touched is filled before the forwarding step.
    • tailPairs puts (bodyBlock, skipBlock) into touched and then forwards through the empty skip block.
    • For b22 vs b20 (b20 is pc 0x1b8..0x1b8, phis only), it records b22→b20 and then calls itself with b22 vs b21. That call finds b22 already recorded with b20 and returns false (touched b22 had b20 now b21).
    • So every pair whose skip side forwards fails. Moving the touched lookup and insert after the forwarding step fixes it here.
  2. skipEntries is one map for the whole walk, filled with emplace.
    • b21 is reached on two paths: from b18 directly, and from b19 through b20.
    • The first path records b21's entry as b18, and the later emplace(b21, b20) is ignored. On the path b14→b22 vs b19→b20→b21, the phi %404 = Phi [%37, b18], [%397, b20] therefore resolves to %37, the entry's live-lane word.
    • The comparison then fails: CompositeExtractU32x4(Ballot(...)) vs BitwiseAnd32.
    • As a probe I replaced emplace with insert_or_assign, which works here because the walk is depth-first. The proper fix is probably an entry that belongs to the path, passed along with the pair.

On your question 3: yes, there is such a path.

  • The s_cbranch_scc0 "any lane left" test at 0x1b0 is LogicalNot(INotEqual32(BitwiseOr32(w0, w1), 0)) over the two words of a ballot.
  • tailPairs compares that condition with relatedValue. It goes through the generic operand recursion (LogicalNot → INotEqual32 → BitwiseOr32 → CompositeExtractU32x4), not through clearedOnActiveLanes, setOnActiveLanes or exclusionLanes. So it reaches Ballot against Ballot, where the arguments are now related with relatedValue.
  • The result decides a wave-wide branch, so it is exact, not lane-restricted. With both changes above, the root pair passes that comparison only because of the widened relation.
  • Whether that holds depends on every lane the ballot counts being one where the predicate is false. That is true when the skip is taken because no lane passes. I haven't checked whether the replay can run this body with some lanes still active.

AI-assisted.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@kaiffeetasse, I read the diff of a3c026161c. This changes MaskReplaySafety::optionalBody, the proof that decides whether a pixel shader may be replayed for stencil reference export, so a wrong accept gives a wrong stencil value and there is no check after it.

Three things need an answer before this can pass:

  • @mrfelek's latest run on this head still refuses 0x11d01d0900, with both copied exits unpaired. Their two findings (touched is filled before the empty skip block is forwarded, and skipEntries is a single map filled with emplace across the walk) match what I see in the diff and are not addressed.
  • The widening is not limited to the copied-tail path. zeroOnInactiveLanes is shared into the existing exclusionLanes and inactiveEquals, and sameValue now compares immediates of any type by ImmediateU64, so shaders that already compiled can take a different decision. Please show that it only changes shaders that were refused before.
  • The "any lane left" scc branch is compared through relatedValue down to Ballot against Ballot. That is a wave-wide decision, not a lane-restricted one, and the PR does not say why the replay cannot run the body with lanes still active.

The 27 new tests are IR fixtures with no execution comparison, and none has the shape of 0x11d01d0900, which is why they pass while the real shader fails. A fixture for that shape would help.

@kaiffeetasse

Copy link
Copy Markdown
Contributor Author

@mrfelek @oneandonlydean head is b6f6fbd469. Both findings are in as code, and the wave-wide ballot question is answered by narrowing the rule rather than by prose.

  1. touched after the forwarding step. tailPairs now runs followBody/followSkip first and records the pair it actually compares, so a skip side that forwards through a phis-only block no longer poisons the map with the pre-forwarding pair.
  2. skipEntries belongs to the path. The map is a by-value parameter and every recursive call gets its own copy, so a skip block reached directly on one path and through a predecessor on the other resolves each phi with the entry of its own path. Measured: the two-predecessor fixture fails on a3c026161c and passes now; the same for the empty-forwarding-block fixture.
  3. Wave-wide ballots must be exact. You're right that the replay can run the body with lanes active that the skip left out — that is the whole point of the replay — so a ballot that decides an scc branch has to agree on every lane. At the conditional terminator of a pair I now accept a ballot-vs-ballot relation only when the two lane arguments are the same value, or both are provably zero on every lane the predicate is zero on; there the lane-local mask-word rules are not used at all. Elsewhere in the tail (export operands, own-bit reads) the lane-local relation stays, because only the lane's own bit is consumed there.

What that means for 0x11d01d0900: at the any-lane test 0x1b0 the two ballot arguments are And(%327, Not(%350)) and And(%18, Not(%391)). If %327/%18 are own-bit reads of a ballot of the branch predicate, zeroOnInactiveLanes proves them zero on inactive lanes and the root pair still pairs; if they are not, the comparison refuses. I cannot run the request here, so that is a prediction, not a measurement. A refusal at that point is the intended outcome: accepting it without the proof is the wrong-stencil case @oneandonlydean describes.

On the widening: every rule this PR adds is an additional accept. sameValue widened to any type by ImmediateU64, exclusionLanes unified and extended by zeroOnInactiveLanes, the ballot and mask-word-in-ballot relations, and the mask-word depth limit raised from 8 to 24. No rule on main was removed, and none of the added predicates can turn a comparison that held on main into a refusal, so no shader that compiled before changes status; the new rules can only reach shaders that were refused. The one narrowing in this head removes accepts this PR itself added at a3c026161c.

Measured at b6f6fbd469 (build-libs, Linux, Intel UHD 630): 156 cases, 100% tests passed, 0 tests failed out of 1 in 0.26 s; ctest -R stencil 100% tests passed, 0 tests failed out of 15 in 9.15 s. Differential with a3c026161cs StencilReplay.cpp and this test file: exactly three cases fail — the forwarding case, the two-predecessor case, and the negative any-lane-left case, which the previous head accepted. Every other case, including all 150 that existed before, decides the same. The three fixtures are named after their shape in MaskedSelect.cpp.

AI-assisted: yes.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@kaiffeetasse thanks for fixing the touched ordering and the per path skipEntries; both look right on b6f6fbd.

One thing still blocks me in the exact ballot check (StencilReplay.cpp 769-773 and 811-815). With exactBallots set, two different ballot arguments are accepted when relatedLanes holds and both are zero on inactive lanes. relatedLanes can succeed through inactiveEquals, and zeroOnInactiveLanes is also about inactive lanes, so nothing compares the two arguments on active lanes. For example And(p, Not(And(p, Q1))) and And(p, Not(And(p, Q2))) pass with Q1 != Q2, and their ballots differ on active lanes. That is the 0x11d01d0900 shape, so a false accept would replay a shader whose stencil values differ.

Could you make the exact path require the arguments to match on active lanes too (or fall back to sameValue only), and add a negative fixture where the two ballot arguments differ only on an active lane? Two smaller points: inactiveEquals at line 801 still runs before the exact check, so it can accept first; and touched (line 884) is still shared across paths, so a pair reached on a second path is not checked against that path's phis.

@kaiffeetasse

Copy link
Copy Markdown
Contributor Author

@oneandonlydean all three points are in, head is 80ef6a8ad9.

  1. Exact ballots now have to agree on the active lanes. equalOnActiveLanes strips a conjunction factor that is literally the predicate from both sides — on the lanes the predicate selects, and(p, x) is x — and then demands a full structural match of what is left; additionally both arguments must still be provably zero on the inactive lanes, so the ballots agree on every lane, not just outside the predicate. Your counterexample, And(p, Not(And(p, Q1))) against And(p, Not(And(p, Q2))) with Q1 != Q2, is refused now: the residuals Not(And(p, Q1)) and Not(And(p, Q2)) differ structurally. It was accepted at b6f6fbd469.
  2. inactiveEquals no longer decides anything on the exact path. You are right that it ran first and is an inactive-lane relation by construction; the exclusionLanes strip of a Bool is the same kind of relation (it changes the value only where the predicate does not select), so both are skipped when the comparison is exact. What remains there is sameValue, the strict ballot rule above, an and with a word that is set on every lane, an own-bit read whose mask words satisfy the strict rule, the skip-side phi resolution, and the structural match.
  3. touched is keyed by path. The map stores the skip block and the entry predecessor of the pairing; a second visit of the same block pair must match both, so a pair reached again through a different predecessor is not answered with the first path's phis. This one only tightens and has no dedicated fixture — I could not build a tail that reaches one block pair twice through different predecessors without a cycle in it; say if you want that case covered and I will add it.

Fixture for (1) is in the same shape as the existing any lane left pair: both ballot arguments zero on inactive lanes and differing only on an active lane.

Measured at 80ef6a8ad9, Linux, Intel UHD 630: 157 cases, ctest --test-dir build-libs -R '^agc_masked_select$' → 100% tests passed, 0 tests failed out of 1 in 0.31 s; ctest -R stencil → 15/15 in 10.31 s; build-relinker links; check_conventions.py --base origin/main reports All conventions checks passed. Differential: with b6f6fbd469s StencilReplay.cpp and this test file exactly one case fails, the new active-lane negative, and the other 156 decide the same; with the change the binary exits 0. The GPU validation-layer set was last run at d43ef8dc18 and is not re-measured at this head.

AI-assisted: yes.

@mrfelek

mrfelek commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse @oneandonlydean reran 80ef6a8ad9 (merged onto #18322) against the logged request. agc_masked_select passes. 0x11d01d0900 is refused at the any-lane test at 0x1b0, as you predicted: the root pair b13↔b18 fails at b14↔b19, and nothing reaches the inner branch. % numbers are from my IR dump.

Where it fails. That is the only comparison that goes through the exact path. With predicate %159 = And(%18, %158) (the skip branch at the end of b3):

  • body argument %354 = And(%327, Not(%350)), with %327 = And(%18, Not(%323)) and %350 = And(%348, Not(%341));
  • skip argument %395 = And(%18, Not(%391)), with %391 = And(%389, Not(%382)) and %382 = Phi [%159, b3], [%379, b17];
  • zeroOnInactiveLanes is false for both arguments, and equalOnActiveLanes is false too.

Why the zero test can't pass for this shape. The skip argument is not zero where the predicate is false. On that path %382 is %159, so on a lane with %159 false the argument is And(%18, Not(%389)), which is set on every lane where %18 is true and %389 is false. The any-lane test on the skip side counts exactly those lanes. So this shader stays refused under any rule that needs both arguments to be zero on inactive lanes.

What does hold, worked out by hand from the IR and not checked by code.

  • %341, %379 and the first operand of %323 are own-bit reads of Ballot(%159) words masked with the WQM live mask (%171, %178). %348 and %389 are the same own-bit read of %145/%152.
  • On a lane where %159 is false, those own bits are 0. Both arguments then come down to And(%18, Not(<own bit of %145/%152>)), so the arguments agree there.
  • On a lane where %159 is true, they differ: the body gives %247, the skip side gives true.
  • The original program takes the skip only when no lane has %159, so every lane on the skip path is inactive. On those lanes the two ballots agree.

So the property that would accept this shader is "the arguments agree on predicate-false lanes" plus "the skip is only reached with the predicate false on every lane". That is weaker than "zero on inactive lanes and equal on active lanes". Whether it is sound depends on whether the replay can reach this tail by the skip side with predicate lanes active. You wrote that it can run the body with lanes the skip left out; I haven't checked what that means for the skip side here.

AI-assisted.

@kaiffeetasse

Copy link
Copy Markdown
Contributor Author

@mrfelek the open question you ended on is answerable from the driver, and it does not go the way your three bullets need. The replay does not re-run the original wave and then pick a path; it re-runs the draw as single triangles, once per candidate reference: recordStencilReplay takes the replay.size() > 1 branch and records piece.indexCount = 3u per triangle (core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp:2618-2637). So the lane set of every replay wave is a different set from the wave that chose the path in the original execution. The question is therefore not "can the skip copy see a predicate-true lane", it is "does the tail return the same value for every lane set the pieces form".

That is what the zero test buys. The failing comparison is the tail's own inner branch (core/shader/recompiler/StencilReplay.cpp:944, the only exactBallots call), and the emitter lowers such a branch to a subgroup ballot plus any-of-the-wave (SpirvFlowEmitter.cpp:149-174). For an any-of vote the result must not depend on which lanes are present. A ballot argument that is zero on predicate-false lanes contributes nothing when those lanes are missing or present; an argument that is merely equal there still contributes — %395 = And(%18, Not(%391)) is set on every lane with %18 and !%391, so a piece of those lanes votes true where a piece whose predicate-false lanes have %391 set votes false. Same tail, two answers, and the stencil reference written for those pixels follows the vote.

So "arguments agree on predicate-false lanes plus the skip is only reached when no lane has the predicate" is not enough once the wave is re-formed; the skip premise is about the original wave, and the replay never executes that wave. The rule stays as it is.

One thing I cannot tell from your dump: whether the 0x1b0 branch is an Exec/Vcc vote or a scalar (scc) branch. For a scalar tail branch the obligation really is per-lane equality and the zero test is over-strong — that variant I would change, with a fixture per branch kind. If 0x1b0 is a wave-mask branch, this shader has to change shape instead: the two arguments have to be zero outside %159 before the tail, which means the skip side must mask %395 with %159-derived lanes rather than carry And(%18, Not(%391)).

AI-assisted.

@mrfelek

mrfelek commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@kaiffeetasse thanks, that answers it. I checked the per-triangle replay (recordStencilReplay, one indexCount = 3 piece per triangle when there is more than one reference), so a replay wave is not the wave that chose the skip, and my premise doesn't hold there.

On your question, from the logged request:

  • The refused pair compares the terminators of b14 and b19 (pc 0x1b0..0x1b8). Both are SccZero (s_cbranch_scc0).
  • The condition is LogicalNot(INotEqual32(BitwiseOr32(w0, w1), 0)), with w0/w1 the two words of Ballot(%354) on the body side and of Ballot(%395) on the skip side. So scc here is "the 64-bit lane mask is not zero", which is what a 64-bit SALU mask op leaves in scc.
  • It is a scalar branch, but it is an any-lane vote over a lane mask, so the result depends on which lanes the piece has. Your zero test is the right obligation for it.
  • The branch before it, at the end of b13/b18 (pc 0x1a8..0x1b0), is ExecZero.

So I agree the rule stays, and 0x11d01d0900 stays refused through this path: the two arguments aren't zero outside %159 before the tail.

AI-assisted.

@oneandonlydean
oneandonlydean merged commit b5cc7c7 into boykopovar:main Nov 16, 2026
16 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants