shader: lower nested control-flow descriptors and immediate sampler phis #739

Open
powplusplus wants to merge 3 commits from upstream-pr/739 into main
powplusplus commented 2026-11-25 06:06:55 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by powplusplus on 2026-11-25T06:06:55Z.


Summary

Eliminates all 40 remaining emit: a descriptor chosen by control flow failures across shaders.rpf (reaching 100% of mesh shaders emitted):

  1. Dead incoming edge pruning on phi fallback (resource::Tracer::phi):
    • Keeps the happy path zero-overhead when all predecessors classify cleanly.
    • When classifying all predecessors fails, prunes provably dead acyclic incoming edges via Tracer::meet, storing None for dead edges in Source::Phi { block, args: Vec<Option<Source>> } and unwrapping a single live Constant or non-dynamic Built source directly.
  2. Arbitrary nested uniform Phi / Select descriptors (emit/lower.rs):
    • Replaces the depth-limited descriptor_phi helper with uniform_heap_index, handling arbitrarily nested Source::Phi and Source::Select over heap-indexed descriptors.
    • Adds const_sampler_choice and const_sampler_index to dispatch image sampling and calculateLOD across distinct immediate constant samplers chosen by control flow (Phi / Select).

Verification

  • Unit tests: cargo test -p victory-shader --lib (173 passed, 0 failed, including new dead_incoming_phi_edge_is_skipped_for_scalar_descriptor and descriptor_chosen_by_control_flow_and_constant_sampler_phi_lower tests).
  • Windows-target clippy (victory-shader -- -D warnings) and workspace check clean on 8dd30ab.
  • Full shaders.rpf census (26,084 programs):
    • VS+PS: 14,164 -> 14,201 / 14,247 (+37, 0 lost)
    • MS: 8,762 -> 8,765 / 8,765 (+3, 100% of mesh programs emitted)
    • CS: 2,672 -> 2,672 / 2,682 (0 lost)
    • emit: a descriptor chosen by control flow: 40 -> 0
<!-- greyfinch-sync:fxceless/victory-fork:issue:6598358679 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739). Originally posted by [powplusplus](https://github.com/powplusplus) on 2026-11-25T06:06:55Z. --- ## Summary Eliminates all 40 remaining `emit: a descriptor chosen by control flow` failures across `shaders.rpf` (reaching 100% of mesh shaders emitted): 1. **Dead incoming edge pruning on phi fallback (`resource::Tracer::phi`)**: - Keeps the happy path zero-overhead when all predecessors classify cleanly. - When classifying all predecessors fails, prunes provably dead acyclic incoming edges via `Tracer::meet`, storing `None` for dead edges in `Source::Phi { block, args: Vec<Option<Source>> }` and unwrapping a single live `Constant` or non-dynamic `Built` source directly. 2. **Arbitrary nested uniform `Phi` / `Select` descriptors (`emit/lower.rs`)**: - Replaces the depth-limited `descriptor_phi` helper with `uniform_heap_index`, handling arbitrarily nested `Source::Phi` and `Source::Select` over heap-indexed descriptors. - Adds `const_sampler_choice` and `const_sampler_index` to dispatch image sampling and `calculateLOD` across distinct immediate constant samplers chosen by control flow (`Phi` / `Select`). ## Verification - Unit tests: `cargo test -p victory-shader --lib` (173 passed, 0 failed, including new `dead_incoming_phi_edge_is_skipped_for_scalar_descriptor` and `descriptor_chosen_by_control_flow_and_constant_sampler_phi_lower` tests). - Windows-target clippy (`victory-shader -- -D warnings`) and workspace check clean on `8dd30ab`. - Full `shaders.rpf` census (26,084 programs): - VS+PS: `14,164 -> 14,201 / 14,247` (+37, 0 lost) - MS: `8,762 -> 8,765 / 8,765` (+3, **100%** of mesh programs emitted) - CS: `2,672 -> 2,672 / 2,682` (0 lost) - `emit: a descriptor chosen by control flow`: `40 -> 0`
Flyander commented 2026-11-25 07:06:04 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by Flyander on 2026-11-25T06:16:11Z.

Review: COMMENTED


I locally added the sampler-choice GPU regression from #718 to this branch and ran it on the RTX 5070 Ti and WARP. The selected wrap/clamp sampler produced the expected texel in both cases. With that test registered, cargo test -p victory-shader --lib --locked --no-fail-fast -- --test-threads=4 passed (217 passed, 0 failed, 3 ignored), and cargo clippy -p victory-shader --all-targets --locked -- -D warnings was clean.

The current descriptor_chosen_by_control_flow_and_constant_sampler_phi_lower test checks emission, while this render test checks the result reaches the target correctly. I recommend keeping that coverage with this implementation, since #739 is the path replacing #718. In a separate local experiment, merging dx.types.ResRet as an aggregate phi caused WARP to remove the device (0x887A0005); the per-channel f32 merges in this branch passed.

<!-- greyfinch-sync:fxceless/victory-fork:review:6052719208 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#pullrequestreview-6052719208). Originally posted by [Flyander](https://github.com/Flyander) on 2026-11-25T06:16:11Z. **Review:** COMMENTED --- I locally added the sampler-choice GPU regression from #718 to this branch and ran it on the RTX 5070 Ti and WARP. The selected wrap/clamp sampler produced the expected texel in both cases. With that test registered, `cargo test -p victory-shader --lib --locked --no-fail-fast -- --test-threads=4` passed (217 passed, 0 failed, 3 ignored), and `cargo clippy -p victory-shader --all-targets --locked -- -D warnings` was clean. The current `descriptor_chosen_by_control_flow_and_constant_sampler_phi_lower` test checks emission, while this render test checks the result reaches the target correctly. I recommend keeping that coverage with this implementation, since #739 is the path replacing #718. In a separate local experiment, merging `dx.types.ResRet` as an aggregate phi caused WARP to remove the device (`0x887A0005`); the per-channel `f32` merges in this branch passed.
chatgpt-codex-connector[bot commented 2026-11-25 07:06:04 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T06:19:08Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 49bb897967

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:fxceless/victory-fork:review:6052745051 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#pullrequestreview-6052745051). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T06:19:08Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `49bb897967` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
chatgpt-codex-connector[bot commented 2026-11-25 07:06:15 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T06:07:07Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T06:19:11.016473Z 49bb897 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:fxceless/victory-fork:comment:7154459528 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#issuecomment-7154459528). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T06:07:07Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"49bb8979678e1d533e855432eeb2d6a711b63eec","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-25T06:19:11.016473Z">2026-11-25T06:19:11.016473Z</relative-time> | `49bb897` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Flyander commented 2026-11-25 07:06:18 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by Flyander on 2026-11-25T06:55:38Z.


I reproduced both P1 cases on this head and opened a focused follow-up against this feature branch: https://github.com/powplusplus/victory-fork/pull/1

It restores the safe direct Loaded source for a one-live-edge ResourceHeap phi and hoists matching join-local sampler selects so their SCC is only used after the join. The sampler regression test panicked with forward reference outside a phi before the fix and now passes; the generated pipeline also creates on the RTX 5070 Ti.

Validation on the follow-up: shader lib tests 216 passed, 0 failed, 3 ignored; Clippy is clean. WARP still rejects this synthetic pipeline with E_INVALIDARG; that limitation is recorded in the follow-up description.

<!-- greyfinch-sync:fxceless/victory-fork:comment:7155303217 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#issuecomment-7155303217). Originally posted by [Flyander](https://github.com/Flyander) on 2026-11-25T06:55:38Z. --- I reproduced both P1 cases on this head and opened a focused follow-up against this feature branch: https://github.com/powplusplus/victory-fork/pull/1 It restores the safe direct `Loaded` source for a one-live-edge `ResourceHeap` phi and hoists matching join-local sampler selects so their SCC is only used after the join. The sampler regression test panicked with `forward reference outside a phi` before the fix and now passes; the generated pipeline also creates on the RTX 5070 Ti. Validation on the follow-up: shader lib tests 216 passed, 0 failed, 3 ignored; Clippy is clean. WARP still rejects this synthetic pipeline with `E_INVALIDARG`; that limitation is recorded in the follow-up description.
chatgpt-codex-connector[bot commented 2026-11-25 07:06:20 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T06:19:08Z.

Code review location: crates/victory-shader/src/resource.rs; line 1364

@@ -1325,23 +1305,79 @@ impl<'a> Tracer<'a> {
                 })
                 .collect()
         };
-        let args = (0..self.p.blocks[block].preds.len())
-            .map(|j| self.classify(&edge(j), joins, known))
-            .collect::<Result<_, _>>();
-        let source = match args {
+        let all = (0..preds.len())
+            .map(|j| self.classify(&edge(j), joins, known).map(Some))
+            .collect::<Result<Vec<_>, _>>();
+        let source = match all {
             Ok(args) => Ok(Source::Phi { block, args }),
-            // An edge holds no descriptor. With only one edge the lanes
-            // that read the descriptor can have come by, it is what the
-            // registers hold on that one (a wave that took another edge
-            // has no lane left that reads it), if that can be named where
-            // it is read.
-            Err(e) => match self.only_edge(block, known) {
-                Some(j) => match self.classify(&edge(j), joins, known) {
-                    Ok(source) if self.anywhere(&source) => Ok(source),
-                    _ => Err(e),
-                },
-                None => Err(e),
-            },
+            // An edge holds no descriptor. Keep only edges the lanes that
+            // reach the access can have taken; provably dead edges become
+            // `None`.
+            Err(e) => {
+                let acyclic = preds.iter().all(|&q| self.rpo[q] < self.rpo[block]);
+                if let Some(lanes) = self.lanes
+                    && acyclic
+                {
+                    let mut parsed: Vec<Option<Source>> = Vec::with_capacity(preds.len());
+                    let mut live_count = 0usize;
+                    let mut failed = None;
+                    for (j, &q) in preds.iter().enumerate() {
+                        let n = known.len();
+                        known.push((lanes.reach[q], true));
+                        if let LaneExit::Branch {
+                            when,
+                            taken,
+                            not_taken,
+                        } = lanes.exits[q]
+                            && taken != not_taken
+                        {
+                            known.push((when, taken == block));
+                        }
+                        let edge_ok = self.meet(lanes, known);
+                        let res = if edge_ok {
+                            self.classify(&edge(j), joins, known).map(Some)
+                        } else {
+                            Ok(None)
+                        };
+                        known.truncate(n);
+                        match res {
+                            Ok(Some(s)) => {
+                                live_count += 1;
+                                parsed.push(Some(s));
+                            }
+                            Ok(None) => parsed.push(None),
+                            Err(err) => {
+                                failed = Some(err);
+                                break;
+                            }
+                        }
+                    }
+                    if failed.is_none() && live_count > 0 {
+                        if live_count == 1
+                            && let Some(only) = parsed.iter().flatten().next()
+                            && matches!(
+                                only,
+                                Source::Constant(_)
+                                    | Source::Built {
+                                        address: Address { dynamic: None, .. },
+                                        ..
+                                    }

P1 Badge Preserve direct loaded sources when only one phi edge is live

For a statically addressed ResourceHeap descriptor with one live edge and a non-descriptor on a dead EXECZ skip edge, the old anywhere() fallback returned Source::Loaded directly. This whitelist instead leaves the load inside a one-live-arm Source::Phi, but slot_stride() returns None for phis. Consequently, smem() loses its stride-based SRV/CBV dispatch and unconditionally annotates the heap entry as a CBV and calls cbufferLoadLegacy, even when the entry is a buffer SRV. This breaks previously supported buffer reads. Preserve the safe direct-loaded case, or make the stride/type lookup follow the new phi.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4691133500 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#discussion_r4691133500). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T06:19:08Z. **Code review location:** `crates/victory-shader/src/resource.rs`; line 1364 ~~~~diff @@ -1325,23 +1305,79 @@ impl<'a> Tracer<'a> { }) .collect() }; - let args = (0..self.p.blocks[block].preds.len()) - .map(|j| self.classify(&edge(j), joins, known)) - .collect::<Result<_, _>>(); - let source = match args { + let all = (0..preds.len()) + .map(|j| self.classify(&edge(j), joins, known).map(Some)) + .collect::<Result<Vec<_>, _>>(); + let source = match all { Ok(args) => Ok(Source::Phi { block, args }), - // An edge holds no descriptor. With only one edge the lanes - // that read the descriptor can have come by, it is what the - // registers hold on that one (a wave that took another edge - // has no lane left that reads it), if that can be named where - // it is read. - Err(e) => match self.only_edge(block, known) { - Some(j) => match self.classify(&edge(j), joins, known) { - Ok(source) if self.anywhere(&source) => Ok(source), - _ => Err(e), - }, - None => Err(e), - }, + // An edge holds no descriptor. Keep only edges the lanes that + // reach the access can have taken; provably dead edges become + // `None`. + Err(e) => { + let acyclic = preds.iter().all(|&q| self.rpo[q] < self.rpo[block]); + if let Some(lanes) = self.lanes + && acyclic + { + let mut parsed: Vec<Option<Source>> = Vec::with_capacity(preds.len()); + let mut live_count = 0usize; + let mut failed = None; + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let edge_ok = self.meet(lanes, known); + let res = if edge_ok { + self.classify(&edge(j), joins, known).map(Some) + } else { + Ok(None) + }; + known.truncate(n); + match res { + Ok(Some(s)) => { + live_count += 1; + parsed.push(Some(s)); + } + Ok(None) => parsed.push(None), + Err(err) => { + failed = Some(err); + break; + } + } + } + if failed.is_none() && live_count > 0 { + if live_count == 1 + && let Some(only) = parsed.iter().flatten().next() + && matches!( + only, + Source::Constant(_) + | Source::Built { + address: Address { dynamic: None, .. }, + .. + } ~~~~ --- **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Preserve direct loaded sources when only one phi edge is live** For a statically addressed `ResourceHeap` descriptor with one live edge and a non-descriptor on a dead EXECZ skip edge, the old `anywhere()` fallback returned `Source::Loaded` directly. This whitelist instead leaves the load inside a one-live-arm `Source::Phi`, but `slot_stride()` returns `None` for phis. Consequently, `smem()` loses its stride-based SRV/CBV dispatch and unconditionally annotates the heap entry as a CBV and calls `cbufferLoadLegacy`, even when the entry is a buffer SRV. This breaks previously supported buffer reads. Preserve the safe direct-loaded case, or make the stride/type lookup follow the new phi. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-25 07:06:20 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T06:19:08Z.

Code review location: crates/victory-shader/src/emit/lower.rs; line 6231

@@ -6096,9 +6094,159 @@ impl<'a> Lower<'a> {
     }
 
     /// A handle for the descriptor `src` read at `site`.
+    /// Registers an immediate sampler's words and returns its static sampler slot.
+    fn sampler_slot(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
+        let words: [u32; 4] = words
+            .get(..4)
+            .and_then(|w| w.try_into().ok())
+            .ok_or("a sampler constant")?;
+        let n = match self.samplers.iter().position(|w| *w == words) {
+            Some(n) => n,
+            None => {
+                self.samplers.push(words);
+                self.samplers.len() - 1
+            }
+        };
+        if cmp {
+            // shortcut: one sampler used with and without comparison
+            // would need two static samplers; it becomes a comparison one.
+            self.s.cmp_samplers |= 1 << n;
+        }
+        Ok(n as u32)
+    }
+
+    /// Uniform heap index for a descriptor loaded from a heap or chosen by
+    /// uniform control flow (`Phi` / `Select`, arbitrarily nested).
+    fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
+        match src {
+            Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
+            Source::Select { scc, args } => {
+                let [a, b] = &args[..] else {
+                    return Err("a descriptor chosen by a condition");
+                };
+                let cond = match self.get(*scc)? {
+                    Val::Bit(x) => x,
+                    _ => return Err("SCC without a value"),
+                };
+                let set = self.uniform_heap_index(a, sampler)?;
+                let clear = self.uniform_heap_index(b, sampler)?;
+                Ok(self.s.m.select(self.cur, cond, set, clear))
+            }
+            Source::Phi { block, args } => {
+                let join = self.block[*block].ok_or("a descriptor chosen by control flow")?;
+                let mut incoming = Vec::new();
+                for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
+                    if self.block[q].is_none() {
+                        continue;
+                    }
+                    let Some(tail) = self.tail[q] else {
+                        return Err("a descriptor chosen by control flow");
+                    };
+                    let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
+                    let index = match arg {
+                        Some(arg) => {
+                            let here = std::mem::replace(&mut self.cur, at);
+                            let index = self.uniform_heap_index(arg, sampler);
+                            self.cur = here;
+                            index?
+                        }
+                        None => self.s.m.i32(0),
+                    };
+                    incoming.push((index, at));
+                }
+                let phi = self.s.m.phi(join, self.s.t.i32);
+                self.s.m.set_phi(phi, incoming);
+                Ok(phi)
+            }
+            _ => Err("a descriptor chosen by control flow"),
+        }
+    }
+
+    /// When a sampler is a uniform `Phi`/`Select` whose leaves are all
+    /// immediate `Source::Constant` samplers, returns `(selector_i32, slots)`
+    /// where `selector_i32` picks into `slots`.
+    fn const_sampler_choice(
+        &mut self,
+        src: &Source,
+        cmp: bool,
+    ) -> Option<Result<(V, Vec<u32>), Why>> {
+        if !matches!(src, Source::Phi { .. } | Source::Select { .. }) {
+            return None;
+        }
+        let leaves = src.leaves();
+        if leaves.is_empty() || !leaves.iter().all(|l| matches!(l, Source::Constant(_))) {
+            return None;
+        }
+        let mut slots = Vec::new();
+        Some(
+            self.const_sampler_index(src, cmp, &mut slots)
+                .map(|sel| (sel, slots)),
+        )
+    }
+
+    fn const_sampler_index(
+        &mut self,
+        src: &Source,
+        cmp: bool,
+        slots: &mut Vec<u32>,
+    ) -> Result<V, Why> {
+        match src {
+            Source::Constant(words) => {
+                let slot = self.sampler_slot(words, cmp)?;
+                let pos = match slots.iter().position(|&s| s == slot) {
+                    Some(p) => p,
+                    None => {
+                        slots.push(slot);
+                        slots.len() - 1
+                    }
+                };
+                Ok(self.s.m.i32(pos as u32))
+            }
+            Source::Select { scc, args } => {
+                let [a, b] = &args[..] else {
+                    return Err("a descriptor chosen by a condition");
+                };
+                let cond = match self.get(*scc)? {
+                    Val::Bit(x) => x,
+                    _ => return Err("SCC without a value"),
+                };
+                let set = self.const_sampler_index(a, cmp, slots)?;
+                let clear = self.const_sampler_index(b, cmp, slots)?;
+                Ok(self.s.m.select(self.cur, cond, set, clear))
+            }
+            Source::Phi { block, args } => {
+                let join = self.block[*block].ok_or("a descriptor chosen by control flow")?;
+                let mut incoming = Vec::new();
+                for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
+                    if self.block[q].is_none() {
+                        continue;
+                    }
+                    let Some(tail) = self.tail[q] else {
+                        return Err("a descriptor chosen by control flow");
+                    };
+                    let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
+                    let idx = match arg {
+                        Some(arg) => {
+                            let here = std::mem::replace(&mut self.cur, at);
+                            let idx = self.const_sampler_index(arg, cmp, slots);

P1 Badge Keep nested sampler selects below their SCC definition

When one immediate-sampler word comes from a control-flow phi and another is chosen by s_cselect after that join, Tracer::phi() produces phi arguments containing selects whose SCC is defined in the join block. Switching self.cur to the predecessor here emits those selects before their SCC definition, violating dominance. A two-arm sampler phi followed by a join-local compare/select and image_sample_lz reproduces a panic in Module::write() with forward reference outside a phi; the parent returned an unsupported-translation error instead. Factor post-join selects outside the phi, or otherwise ensure their conditions dominate the insertion block.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4691133511 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#discussion_r4691133511). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T06:19:08Z. **Code review location:** `crates/victory-shader/src/emit/lower.rs`; line 6231 ~~~~diff @@ -6096,9 +6094,159 @@ impl<'a> Lower<'a> { } /// A handle for the descriptor `src` read at `site`. + /// Registers an immediate sampler's words and returns its static sampler slot. + fn sampler_slot(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + if cmp { + // shortcut: one sampler used with and without comparison + // would need two static samplers; it becomes a comparison one. + self.s.cmp_samplers |= 1 << n; + } + Ok(n as u32) + } + + /// Uniform heap index for a descriptor loaded from a heap or chosen by + /// uniform control flow (`Phi` / `Select`, arbitrarily nested). + fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Select { scc, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.uniform_heap_index(a, sampler)?; + let clear = self.uniform_heap_index(b, sampler)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + Source::Phi { block, args } => { + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let Some(tail) = self.tail[q] else { + return Err("a descriptor chosen by control flow"); + }; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let index = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.uniform_heap_index(arg, sampler); + self.cur = here; + index? + } + None => self.s.m.i32(0), + }; + incoming.push((index, at)); + } + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + _ => Err("a descriptor chosen by control flow"), + } + } + + /// When a sampler is a uniform `Phi`/`Select` whose leaves are all + /// immediate `Source::Constant` samplers, returns `(selector_i32, slots)` + /// where `selector_i32` picks into `slots`. + fn const_sampler_choice( + &mut self, + src: &Source, + cmp: bool, + ) -> Option<Result<(V, Vec<u32>), Why>> { + if !matches!(src, Source::Phi { .. } | Source::Select { .. }) { + return None; + } + let leaves = src.leaves(); + if leaves.is_empty() || !leaves.iter().all(|l| matches!(l, Source::Constant(_))) { + return None; + } + let mut slots = Vec::new(); + Some( + self.const_sampler_index(src, cmp, &mut slots) + .map(|sel| (sel, slots)), + ) + } + + fn const_sampler_index( + &mut self, + src: &Source, + cmp: bool, + slots: &mut Vec<u32>, + ) -> Result<V, Why> { + match src { + Source::Constant(words) => { + let slot = self.sampler_slot(words, cmp)?; + let pos = match slots.iter().position(|&s| s == slot) { + Some(p) => p, + None => { + slots.push(slot); + slots.len() - 1 + } + }; + Ok(self.s.m.i32(pos as u32)) + } + Source::Select { scc, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.const_sampler_index(a, cmp, slots)?; + let clear = self.const_sampler_index(b, cmp, slots)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + Source::Phi { block, args } => { + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let Some(tail) = self.tail[q] else { + return Err("a descriptor chosen by control flow"); + }; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let idx = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let idx = self.const_sampler_index(arg, cmp, slots); ~~~~ --- **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Keep nested sampler selects below their SCC definition** When one immediate-sampler word comes from a control-flow phi and another is chosen by `s_cselect` after that join, `Tracer::phi()` produces phi arguments containing selects whose SCC is defined in the join block. Switching `self.cur` to the predecessor here emits those selects before their SCC definition, violating dominance. A two-arm sampler phi followed by a join-local compare/select and `image_sample_lz` reproduces a panic in `Module::write()` with `forward reference outside a phi`; the parent returned an unsupported-translation error instead. Factor post-join selects outside the phi, or otherwise ensure their conditions dominate the insertion block. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
MKmajster commented 2026-11-25 12:07:04 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by MKmajster on 2026-11-25T11:53:11Z.


Tested on a combined tree, offline: it clears the whole "descriptor chosen by control flow" class there. Two spots need care if this lands together with #353 or #386.

Tree. skornuta/victory-fork main (this repo's 310c6eb plus ZSlayerHQ next), with the LooperSalty/victory lot that carries #353 and #386, plus #188, #258 and #806 of this repo, then this PR (49bb897).

Offline, victory translate --list over the title's shader pack (26,084 programs, all reach IR; counts are refusals at emission). "Before" is the tree without #806, this PR and #215; "after" has all three, so the split per PR is my reading of the reasons, not measured one by one:

Reason Before After
a descriptor chosen by control flow 40 0
a hardware SGPR input (#215) 10 0
everything else 203 203

cargo test -p victory-shader --lib: 238 passed, 0 failed, 3 ignored (235 on the tree before the three PRs).

Two conflicts, and how I resolved them:

  1. sampler_slot. This PR's version keeps one static sampler per set of words and makes it a comparison sampler if any use compares. #386 (in the LooperSalty lot) gives a sampler used both ways two slots, because the DXIL validator wants the kinds to match, and changes samplers to (words, comparison) pairs. I kept your call sites and moved #386's two-slot logic into sampler_slot, including the cmp_samplers bit being cleared for the non-comparison slot.
  2. sampleLevel LOD from texels. This PR computes Log(texels) * LOG2_E, as main does today. #353 changes that line to Log(texels) alone, because DXIL Log (opcode 23) is already base 2. On the merged tree I kept #353's version inside this PR's new tail_args structure. Whichever of the two lands second will hit this line.

Not verified: a game run with this tree. The numbers above are the offline pack and the unit tests only.

AI-assisted (Claude Code). No game data attached.

<!-- greyfinch-sync:fxceless/victory-fork:comment:7161634876 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/739#issuecomment-7161634876). Originally posted by [MKmajster](https://github.com/MKmajster) on 2026-11-25T11:53:11Z. --- Tested on a combined tree, offline: it clears the whole "descriptor chosen by control flow" class there. Two spots need care if this lands together with #353 or #386. **Tree.** `skornuta/victory-fork` `main` (this repo's `310c6eb` plus ZSlayerHQ `next`), with the LooperSalty/victory lot that carries #353 and #386, plus #188, #258 and #806 of this repo, then this PR (`49bb897`). **Offline, `victory translate --list` over the title's shader pack** (26,084 programs, all reach IR; counts are refusals at emission). "Before" is the tree without #806, this PR and #215; "after" has all three, so the split per PR is my reading of the reasons, not measured one by one: | Reason | Before | After | |---|---|---| | a descriptor chosen by control flow | 40 | 0 | | a hardware SGPR input (#215) | 10 | 0 | | everything else | 203 | 203 | `cargo test -p victory-shader --lib`: 238 passed, 0 failed, 3 ignored (235 on the tree before the three PRs). **Two conflicts, and how I resolved them:** 1. **`sampler_slot`.** This PR's version keeps one static sampler per set of words and makes it a comparison sampler if any use compares. #386 (in the LooperSalty lot) gives a sampler used both ways two slots, because the DXIL validator wants the kinds to match, and changes `samplers` to `(words, comparison)` pairs. I kept your call sites and moved #386's two-slot logic into `sampler_slot`, including the `cmp_samplers` bit being cleared for the non-comparison slot. 2. **`sampleLevel` LOD from `texels`.** This PR computes `Log(texels) * LOG2_E`, as `main` does today. #353 changes that line to `Log(texels)` alone, because DXIL `Log` (opcode 23) is already base 2. On the merged tree I kept #353's version inside this PR's new `tail_args` structure. Whichever of the two lands second will hit this line. Not verified: a game run with this tree. The numbers above are the offline pack and the unit tests only. AI-assisted (Claude Code). No game data attached.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/739:upstream-pr/739'
git switch 'upstream-pr/739'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/739'
git switch 'upstream-pr/739'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/739'
git switch 'upstream-pr/739'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/739'
git switch 'main'
git merge --squash 'upstream-pr/739'
git switch 'main'
git merge --ff-only 'upstream-pr/739'
git switch 'main'
git merge 'upstream-pr/739'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
fxceless/victory-fork!739
No description provided.