Shaders: read the merged stage's LDS size, bound GS vertices (#311) #367

Open
github-bot wants to merge 4 commits from github-bot/gh-367 into main AGit
Owner

@⁠Revens2 on GitHub · 2026-11-24 23:57 UTC · original
Revens2:fix/issue-311 → main · +943 −13 · 8 files · 4 commits · open

Step 2 of #138, for #311. Stacked on #309: this branch starts from #309's, so until #309 merges the diff here includes its commits (and the review fix on it); the commit of this step is the last one. The base is main because the stacked branch is not in this repository.

What is in it

  • StageIo::Es(MergedIo) and StageIo::Gs(MergedIo): the record of either half of a merged stage now gives its LDS bytes (the common record field, as mesh programs already read it). The other stage data after the record (output signature rows, limits) is in a layout nothing in the tree has a fixture for, so it is not read.
  • merged::limits(program): from the code, the vertices a GS program emits along its longest path (s_sendmsg GS_EMIT / GS_EMIT_CUT), the streams used, whether it cuts; a message inside a loop or a program that emits nothing is refused. merged::GsMessage decodes the geometry messages (message, operation and stream bits of simm16).
  • MergedGs::lds_bytes(): the larger of the two records' LDS size.
  • The ES half resolves the runtime table pointer too (same SGPRs as the GS half) when tracked with the merged layout, and io::raise accepts an ES program (no exports, runtime table input only).
  • victory translate: the geometry section gains a line with how many GS programs have a bounded vertex count in their code and the largest bound.

Tested

  • New unit tests on synthetic GCN programs and containers: message decoding, straight-line and branching emit counts, a cut, a message in a loop, no emit, LDS size read from synthetic records (ES and GS, and a record that allocates none), the merged LDS size, the ES half and the runtime table.
  • cargo build --workspace --locked, cargo test --workspace --locked --no-fail-fast -- --test-threads=4: 517 passed, 0 failed, 7 ignored (Windows). One unrelated victory-gpu in-place WARP test failed in a first run and passed in the rerun of that crate and in the full run.

Not tested

  • victory translate over the title: not run, so the new bounded-count line is unmeasured.
  • That the real records' LDS field holds what the synthetic fixtures put there, and that the limits the code gives are what the title's geometry shaders declare: the output topology and instance count are not read at all (no source for them in the tree).
  • No run in game; the host still has no geometry path beyond the rectangle one.

Still to do: #312 (ES half, LDS handoff), #313 (GS output as DXIL stream emits), #314 (pipeline path); #138 stays open.

AI use
Written with Claude Code (Claude Sonnet 5.5). The tests are synthetic programs; no title shaders or game files were read.

**@⁠Revens2** on GitHub · 2026-11-24 23:57 UTC · [original](https://github.com/fxceless/victory-fork/pull/367) `Revens2:fix/issue-311` → `main` · +943 −13 · 8 files · 4 commits · open Step 2 of #138, for #311. **Stacked on #309**: this branch starts from #309's, so until #309 merges the diff here includes its commits (and the review fix on it); the commit of this step is the last one. The base is `main` because the stacked branch is not in this repository. **What is in it** - `StageIo::Es(MergedIo)` and `StageIo::Gs(MergedIo)`: the record of either half of a merged stage now gives its LDS bytes (the common record field, as mesh programs already read it). The other stage data after the record (output signature rows, limits) is in a layout nothing in the tree has a fixture for, so it is **not** read. - `merged::limits(program)`: from the code, the vertices a GS program emits along its longest path (`s_sendmsg` GS_EMIT / GS_EMIT_CUT), the streams used, whether it cuts; a message inside a loop or a program that emits nothing is refused. `merged::GsMessage` decodes the geometry messages (message, operation and stream bits of `simm16`). - `MergedGs::lds_bytes()`: the larger of the two records' LDS size. - The ES half resolves the runtime table pointer too (same SGPRs as the GS half) when tracked with the merged layout, and `io::raise` accepts an ES program (no exports, runtime table input only). - `victory translate`: the `geometry` section gains a line with how many GS programs have a bounded vertex count in their code and the largest bound. **Tested** - New unit tests on synthetic GCN programs and containers: message decoding, straight-line and branching emit counts, a cut, a message in a loop, no emit, LDS size read from synthetic records (ES and GS, and a record that allocates none), the merged LDS size, the ES half and the runtime table. - `cargo build --workspace --locked`, `cargo test --workspace --locked --no-fail-fast -- --test-threads=4`: 517 passed, 0 failed, 7 ignored (Windows). One unrelated `victory-gpu` in-place WARP test failed in a first run and passed in the rerun of that crate and in the full run. **Not tested** - `victory translate` over the title: not run, so the new bounded-count line is unmeasured. - That the real records' LDS field holds what the synthetic fixtures put there, and that the limits the code gives are what the title's geometry shaders declare: the output topology and instance count are not read at all (no source for them in the tree). - No run in game; the host still has no geometry path beyond the rectangle one. **Still to do**: #312 (ES half, LDS handoff), #313 (GS output as DXIL stream emits), #314 (pipeline path); #138 stays open. **AI use** Written with Claude Code (Claude Sonnet 5.5). The tests are synthetic programs; no title shaders or game files were read.
The 195 "an address in an SGPR that is no root parameter" failures are the
GS half of one merged ES+GS stage (#138). Step 1 of its support, without
emitting anything:

- StageIo::Gs and io::raise for a geometry program. User data 0 and 1 of
  the merged stage (s8, s9) are the console runtime's table pointer when the
  root layout puts nothing there; resource tracking traces a load through it
  to resource::RUNTIME_TABLE instead of failing. Other stages and other
  unbound SGPRs fail as before.
- merged::pair_es_gs pairs the ES program (vertex container) with the GS
  program (geometry container): same wave size, one meaning per user-data
  dword, merged root layout. emit::translate_merged_gs runs the pair as far
  as emission.
- emit refuses a geometry program with GS_EMIT ("GS emit"). `translate`
  counts those on their own "geometry" line, not among the failures.

Not done: DXIL geometry emission, the ES to GS handoff through LDS, the
output records, GS_EMIT/GS_CUT, the host pipeline. The runtime table's
contents and the GS stage data are not read.

Refs #138

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
pair_es_gs keeps both halves' ranges of one descriptor table pointer
instead of calling them a user-data conflict. The runtime table pointer
is only inferred through resource::track_merged, i.e. for the merged
layout of a pair (translate_merged_gs) or, in victory translate, as a
stated assumption for an unpaired geometry program: a geometry program
traced alone no longer takes user data 0 and 1 as free.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
StageIo::Es and StageIo::Gs now carry MergedIo (LDS bytes from the common
record). merged::limits counts the vertices a GS program emits along its
longest path from its s_sendmsg GS_EMIT / GS_CUT / GS_EMIT_CUT messages,
refusing a message in a loop. The runtime table pointer is also resolved
for the ES half, which shares the SGPRs. victory translate counts the GS
programs with a bounded vertex count.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Review fixes: a GS program with an indirect jump has no vertex bound, and
the user-data overlap tests saturate the container-supplied SGPR count.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:41:46 +00:00
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 00:18 UTC · original

Both review findings fixed in d8e53e1 (with tests):

  • Unresolved GS control flow (merged.rs): limits now refuses a GS program with an indirect jump (an unresolved jump in a geometry program) instead of counting only the emits before it.
  • SGPR range overflow (io.rs, merged.rs): the overlap tests saturate the container-supplied SGPR count; a test pairs two halves with a u32::MAX count and gets a refusal rather than a wrap.

cargo test -p victory-shader --locked: 233 passed, 0 failed.

**@⁠Revens2** on GitHub · 2026-11-25 00:18 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#issuecomment-7148374204) Both review findings fixed in d8e53e1 (with tests): - **Unresolved GS control flow (`merged.rs`)**: `limits` now refuses a GS program with an indirect jump (`an unresolved jump in a geometry program`) instead of counting only the emits before it. - **SGPR range overflow (`io.rs`, `merged.rs`)**: the overlap tests saturate the container-supplied SGPR count; a test pairs two halves with a `u32::MAX` count and gets a refusal rather than a wrap. `cargo test -p victory-shader --locked`: 233 passed, 0 failed.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 07:10 UTC · original

Rebased on main (a26859f), stacked on #309; head now 4399972. No new conflicts beyond the ones in #309. cargo build --workspace --locked ok; cargo test -p victory-shader -p victory-gpu --locked: 137 + 238 passed, 0 failed. Ready for another review pass.

**@⁠Revens2** on GitHub · 2026-11-25 07:10 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#issuecomment-7155563267) Rebased on main (a26859f), stacked on #309; head now 4399972. No new conflicts beyond the ones in #309. `cargo build --workspace --locked` ok; `cargo test -p victory-shader -p victory-gpu --locked`: 137 + 238 passed, 0 failed. Ready for another review pass.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 09:35 UTC · original

@⁠codex review (head rebased on origin/main; earlier findings were addressed before the rebase)

**@⁠Revens2** on GitHub · 2026-11-25 09:35 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#issuecomment-7158533463) @⁠codex review (head rebased on origin/main; earlier findings were addressed before the rebase)
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:35 UTC · original

Codex Review: Something went wrong. Try again later by commenting “@⁠codex review”.

Setup repeatedly failed. Update the setup script or commit, then try again later.
ℹ️ 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".

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:35 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#issuecomment-7158540928) Codex Review: Something went wrong. Try again later by commenting “@⁠codex review”. ``` Setup repeatedly failed. Update the setup script or commit, then try again later. ``` <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>
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-24 23:57 UTC · original · edited 2026-11-25 09:35 UTC

Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-25T09:35:40.695662Z
We couldn’t complete this review. Comment @codex review to try again.
4399972 Manual request
ℹ️ 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.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-24 23:57 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#issuecomment-7147986316) · edited 2026-11-25 09:35 UTC <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"43999724d3c2fea8d916408c0e1f584cfac37dbe","has_any_findings":true,"has_unresolved_findings":true,"status":"failed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ❌ Failed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ❌ **Failed** <relative-time datetime="2026-11-25T09:35:40.695662Z">2026-11-25T09:35:40.695662Z</relative-time><br/>We couldn’t complete this review. Comment `@codex review` to try again. | `4399972` | Manual request | <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>
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:07 UTC · original
On crates/victory-shader/src/merged.rs line 223 (outdated):

@@ -0,0 +1,437 @@
+//! The merged ES+GS stage (a geometry shader), step 1 of its support.
+//!
+//! The console links two programs into one hardware stage when it creates a
+//! pipeline with a geometry shader: the ES program, which sits in the vertex
+//! container next to the ordinary VS, and the GS program, which is all the
+//! geometry container holds. Both run on the same wave, so they share one
+//! SGPR file: eight system SGPRs first, then the user data of the root
+//! signature ([`HwStage::user_sgpr`]).
+//!
+//! What this step knows, from the title's programs as the issue on this
+//! (fork issue 138) writes it down (static analysis, not a run):
+//!
+//! * The GS half loads from a pointer in user data 0 and 1 (s8 and s9) that
+//!   is no root parameter: the console runtime's own table. [`RUNTIME_TABLE`]
+//!   names it; resource tracking takes the pair as that table when the merged
+//!   root layout (both halves', [`pair_es_gs`]) puts nothing there
+//!   ([`crate::resource::track_merged`]; a geometry program tracked alone cannot
+//!   know the ES half leaves them free), and [`crate::io::Input::RuntimeTable`]
+//!   names the two dwords.
+//! * A root parameter is the same in both halves: [`pair_es_gs`] merges the
+//!   two layouts and refuses programs that disagree about a user-data dword.
+//!
+//! What it does not do yet: translate the stage. The ES half hands its
+//! records over through LDS, the GS half reads them from there and writes
+//! its output vertices there too, with `s_sendmsg` GS_EMIT, GS_CUT and
+//! GS_DONE; none of that is modeled. Emission refuses a geometry program with
+//! [`crate::emit::GS_EMIT`].
+
+use crate::ShaderError::{self, Malformed};
+use crate::gfx10::Fields;
+use crate::ir::{Exit, Program};
+use crate::native::{HwStage, NativeProgram, RootParam, RootType, StageIo};
+
+/// The first user-data dword of the runtime table pointer: it takes dwords 0
+/// (low half) and 1 (high half) of the merged stage's user data.
+pub const RUNTIME_TABLE: u8 = 0;
+
+/// An ES program and the GS program it is linked with.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct MergedGs {
+    pub es: NativeProgram,
+    pub gs: NativeProgram,
+    /// The root parameters of the merged stage: those of either half, by user
+    /// data (a parameter both halves list is in it once).
+    pub layout: Vec<RootParam>,
+}
+
+impl MergedGs {
+    /// LDS bytes the merged stage allocates: what the two records say (they
+    /// describe one allocation; the larger covers a record that says less).
+    pub fn lds_bytes(&self) -> u32 {
+        let of = |p: &NativeProgram| match &p.io {
+            StageIo::Es(io) | StageIo::Gs(io) => io.lds_bytes,
+            _ => 0,
+        };
+        of(&self.es).max(of(&self.gs))
+    }
+
+    /// The GS program as the merged stage runs it: the code of the GS half
+    /// with the root layout of both halves, which is what its user SGPRs
+    /// hold.
+    pub fn program(&self) -> NativeProgram {
+        NativeProgram {
+            layout: self.layout.clone(),
+            ..self.gs.clone()
+        }
+    }
+}
+
+/// Pairs an ES program with the GS program of the same pipeline.
+///
+/// Fails when the programs are not an ES and a GS, run at different wave
+/// sizes, or disagree about what a user-data dword holds (the two halves
+/// share the SGPRs, so a dword has one meaning).
+pub fn pair_es_gs(es: NativeProgram, gs: NativeProgram) -> Result<MergedGs, ShaderError> {
+    if es.stage != HwStage::Es {
+        return Err(Malformed("the vertex half of a merged stage is not an ES program"));
+    }
+    if gs.stage != HwStage::Gs {
+        return Err(Malformed("the geometry half of a merged stage is not a GS program"));
+    }
+    if es.wave64 != gs.wave64 {
+        return Err(Malformed("ES and GS programs run at different wave sizes"));
+    }
+    let mut layout = es.layout.clone();
+    for g in &gs.layout {
+        let overlaps = |e: &RootParam| {
+            let end = |p: &RootParam| u32::from(p.user_data) + p.sgprs;
+            u32::from(e.user_data) < end(g) && u32::from(g.user_data) < end(e)
+        };
+        // The same table pointer listed by both halves with other ranges (the
+        // offset and the base register of a range differ) is one root
+        // parameter read through two ranges: both are kept.
+        let same_pointer = |e: &RootParam| {
+            g.root == RootType::Table
+                && (e.root, e.user_data, e.sgprs, e.slot) == (g.root, g.user_data, g.sgprs, g.slot)
+        };
+        let over: Vec<RootParam> = layout.iter().filter(|e| overlaps(e)).copied().collect();
+        if over.contains(g) && over.iter().all(|e| e == g || same_pointer(e)) {
+            continue;
+        }
+        if !over.iter().all(same_pointer) {
+            return Err(Malformed("ES and GS programs disagree about a user-data dword"));
+        }
+        layout.push(*g);
+    }
+    layout.sort_by_key(|p| (p.user_data, p.slot));
+    Ok(MergedGs { es, gs, layout })
+}
+
+/// A geometry message of `s_sendmsg` (`simm16`: message in bits 0-3,
+/// operation in 4-6, stream in 8-9), the ones the GS half sends instead of
+/// exporting.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GsMessage {
+    /// `GS_OP_EMIT`: the next output vertex of the stream.
+    Emit { stream: u8 },
+    /// `GS_OP_CUT`: end the stream's current strip.
+    Cut { stream: u8 },
+    /// `GS_OP_EMIT_CUT`: the next output vertex, then end the strip.
+    EmitCut { stream: u8 },
+    /// `MSG_GS_DONE`: the wave is finished with its geometry.
+    Done,
+}
+
+const MSG_GS: u16 = 2;
+const MSG_GS_DONE: u16 = 3;
+
+impl GsMessage {
+    /// The message `s_sendmsg` sends with this `simm16`; `None` for any
+    /// other (`GS_ALLOC_REQ`, `GS_OP_NOP`, ...).
+    pub fn decode(simm16: u16) -> Option<GsMessage> {
+        let (msg, op, stream) = (simm16 & 0xF, simm16 >> 4 & 7, (simm16 >> 8 & 3) as u8);
+        match (msg, op) {
+            (MSG_GS_DONE, 0) => Some(GsMessage::Done),
+            (MSG_GS, 1) => Some(GsMessage::Cut { stream }),
+            (MSG_GS, 2) => Some(GsMessage::Emit { stream }),
+            (MSG_GS, 3) => Some(GsMessage::EmitCut { stream }),
+            _ => None,
+        }
+    }
+
+    /// The vertices this message emits (0 or 1).
+    pub fn vertices(self) -> u32 {
+        u32::from(matches!(self, GsMessage::Emit { .. } | GsMessage::EmitCut { .. }))
+    }
+}
+
+/// The geometry message of an instruction, if it is an `s_sendmsg` of one.
+pub fn message_of(inst: &crate::ir::Inst) -> Option<GsMessage> {
+    match inst.fields {
+        Fields::Sopp { imm } if matches!(inst.name(), "s_sendmsg" | "s_sendmsghalt") => {
+            GsMessage::decode(imm)
+        }
+        _ => None,
+    }
+}
+
+/// What a GS program does with its output, from its code. The record does
+/// not give these in a layout this crate reads, so the code is the source: a
+/// geometry shader declares its maximum before it emits.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Limits {
+    /// Vertices emitted along the longest path through the program.
+    pub max_vertices: u32,
+    /// Streams that emit or cut (bit n: stream n).
+    pub streams: u8,
+    /// A `GS_CUT` or `GS_EMIT_CUT` is sent: strips end before the program does.
+    pub cuts: bool,
+}
+
+/// The output limits of a GS program.
+///
+/// Fails when a message is sent inside a loop (no bound), or when the
+/// program emits nothing at all.
+pub fn limits(p: &Program) -> Result<Limits, ShaderError> {
+    let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
+    let counts: Vec<u32> = p
+        .blocks
+        .iter()
+        .map(|b| b.insts.iter().filter_map(message_of).map(GsMessage::vertices).sum())
+        .collect();
+    // A block that can reach itself and sends a message has no bound.
+    let reaches = |from: usize, to: usize| {
+        let mut seen = vec![false; p.blocks.len()];
+        let mut stack = p.blocks[from].exit.successors();
+        while let Some(b) = stack.pop() {
+            if b == to {
+                return true;
+            }
+            if !std::mem::replace(&mut seen[b], true) {
+                stack.extend(p.blocks[b].exit.successors());
+            }
+        }
+        false
+    };
+    let mut streams = 0u8;
+    let mut cuts = false;
+    for (b, block) in p.blocks.iter().enumerate() {
+        let sends: Vec<_> = block.insts.iter().filter_map(message_of).collect();
+        if sends.iter().any(|m| !matches!(m, GsMessage::Done)) && reaches(b, b) {
+            return Err(unsupported("a geometry message inside a loop"));
+        }
+        for m in sends {
+            match m {
+                GsMessage::Emit { stream } => streams |= 1 << stream,
+                GsMessage::Cut { stream } | GsMessage::EmitCut { stream } => {
+                    streams |= 1 << stream;
+                    cuts = true;
+                }
+                GsMessage::Done => {}
+            }
+        }
+    }
+    // The longest path of emits; a loop sends nothing, so its back edge is
+    // not followed.
+    fn longest(p: &Program, counts: &[u32], b: usize, on: &mut Vec<usize>, memo: &mut [Option<u32>]) -> u32 {
+        if let Some(n) = memo[b] {
+            return n;
+        }
+        on.push(b);
+        let after = match p.blocks[b].exit {
+            Exit::End | Exit::Indirect => 0,

P2 Badge Reject unresolved GS control flow when claiming a vertex bound

If a GS has an unresolved s_setpc_b64 whose target reaches another GS block, the IR marks the exit Indirect, but this branch treats it like End. limits then counts only pre-jump emits, so max_vertices can be lower than the shader's actual maximum; reject such paths or resolve their targets before reporting a bound.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:07 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#discussion_r4688353693) On `crates/victory-shader/src/merged.rs` line 223 (outdated): ```diff @@ -0,0 +1,437 @@ +//! The merged ES+GS stage (a geometry shader), step 1 of its support. +//! +//! The console links two programs into one hardware stage when it creates a +//! pipeline with a geometry shader: the ES program, which sits in the vertex +//! container next to the ordinary VS, and the GS program, which is all the +//! geometry container holds. Both run on the same wave, so they share one +//! SGPR file: eight system SGPRs first, then the user data of the root +//! signature ([`HwStage::user_sgpr`]). +//! +//! What this step knows, from the title's programs as the issue on this +//! (fork issue 138) writes it down (static analysis, not a run): +//! +//! * The GS half loads from a pointer in user data 0 and 1 (s8 and s9) that +//! is no root parameter: the console runtime's own table. [`RUNTIME_TABLE`] +//! names it; resource tracking takes the pair as that table when the merged +//! root layout (both halves', [`pair_es_gs`]) puts nothing there +//! ([`crate::resource::track_merged`]; a geometry program tracked alone cannot +//! know the ES half leaves them free), and [`crate::io::Input::RuntimeTable`] +//! names the two dwords. +//! * A root parameter is the same in both halves: [`pair_es_gs`] merges the +//! two layouts and refuses programs that disagree about a user-data dword. +//! +//! What it does not do yet: translate the stage. The ES half hands its +//! records over through LDS, the GS half reads them from there and writes +//! its output vertices there too, with `s_sendmsg` GS_EMIT, GS_CUT and +//! GS_DONE; none of that is modeled. Emission refuses a geometry program with +//! [`crate::emit::GS_EMIT`]. + +use crate::ShaderError::{self, Malformed}; +use crate::gfx10::Fields; +use crate::ir::{Exit, Program}; +use crate::native::{HwStage, NativeProgram, RootParam, RootType, StageIo}; + +/// The first user-data dword of the runtime table pointer: it takes dwords 0 +/// (low half) and 1 (high half) of the merged stage's user data. +pub const RUNTIME_TABLE: u8 = 0; + +/// An ES program and the GS program it is linked with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MergedGs { + pub es: NativeProgram, + pub gs: NativeProgram, + /// The root parameters of the merged stage: those of either half, by user + /// data (a parameter both halves list is in it once). + pub layout: Vec<RootParam>, +} + +impl MergedGs { + /// LDS bytes the merged stage allocates: what the two records say (they + /// describe one allocation; the larger covers a record that says less). + pub fn lds_bytes(&self) -> u32 { + let of = |p: &NativeProgram| match &p.io { + StageIo::Es(io) | StageIo::Gs(io) => io.lds_bytes, + _ => 0, + }; + of(&self.es).max(of(&self.gs)) + } + + /// The GS program as the merged stage runs it: the code of the GS half + /// with the root layout of both halves, which is what its user SGPRs + /// hold. + pub fn program(&self) -> NativeProgram { + NativeProgram { + layout: self.layout.clone(), + ..self.gs.clone() + } + } +} + +/// Pairs an ES program with the GS program of the same pipeline. +/// +/// Fails when the programs are not an ES and a GS, run at different wave +/// sizes, or disagree about what a user-data dword holds (the two halves +/// share the SGPRs, so a dword has one meaning). +pub fn pair_es_gs(es: NativeProgram, gs: NativeProgram) -> Result<MergedGs, ShaderError> { + if es.stage != HwStage::Es { + return Err(Malformed("the vertex half of a merged stage is not an ES program")); + } + if gs.stage != HwStage::Gs { + return Err(Malformed("the geometry half of a merged stage is not a GS program")); + } + if es.wave64 != gs.wave64 { + return Err(Malformed("ES and GS programs run at different wave sizes")); + } + let mut layout = es.layout.clone(); + for g in &gs.layout { + let overlaps = |e: &RootParam| { + let end = |p: &RootParam| u32::from(p.user_data) + p.sgprs; + u32::from(e.user_data) < end(g) && u32::from(g.user_data) < end(e) + }; + // The same table pointer listed by both halves with other ranges (the + // offset and the base register of a range differ) is one root + // parameter read through two ranges: both are kept. + let same_pointer = |e: &RootParam| { + g.root == RootType::Table + && (e.root, e.user_data, e.sgprs, e.slot) == (g.root, g.user_data, g.sgprs, g.slot) + }; + let over: Vec<RootParam> = layout.iter().filter(|e| overlaps(e)).copied().collect(); + if over.contains(g) && over.iter().all(|e| e == g || same_pointer(e)) { + continue; + } + if !over.iter().all(same_pointer) { + return Err(Malformed("ES and GS programs disagree about a user-data dword")); + } + layout.push(*g); + } + layout.sort_by_key(|p| (p.user_data, p.slot)); + Ok(MergedGs { es, gs, layout }) +} + +/// A geometry message of `s_sendmsg` (`simm16`: message in bits 0-3, +/// operation in 4-6, stream in 8-9), the ones the GS half sends instead of +/// exporting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GsMessage { + /// `GS_OP_EMIT`: the next output vertex of the stream. + Emit { stream: u8 }, + /// `GS_OP_CUT`: end the stream's current strip. + Cut { stream: u8 }, + /// `GS_OP_EMIT_CUT`: the next output vertex, then end the strip. + EmitCut { stream: u8 }, + /// `MSG_GS_DONE`: the wave is finished with its geometry. + Done, +} + +const MSG_GS: u16 = 2; +const MSG_GS_DONE: u16 = 3; + +impl GsMessage { + /// The message `s_sendmsg` sends with this `simm16`; `None` for any + /// other (`GS_ALLOC_REQ`, `GS_OP_NOP`, ...). + pub fn decode(simm16: u16) -> Option<GsMessage> { + let (msg, op, stream) = (simm16 & 0xF, simm16 >> 4 & 7, (simm16 >> 8 & 3) as u8); + match (msg, op) { + (MSG_GS_DONE, 0) => Some(GsMessage::Done), + (MSG_GS, 1) => Some(GsMessage::Cut { stream }), + (MSG_GS, 2) => Some(GsMessage::Emit { stream }), + (MSG_GS, 3) => Some(GsMessage::EmitCut { stream }), + _ => None, + } + } + + /// The vertices this message emits (0 or 1). + pub fn vertices(self) -> u32 { + u32::from(matches!(self, GsMessage::Emit { .. } | GsMessage::EmitCut { .. })) + } +} + +/// The geometry message of an instruction, if it is an `s_sendmsg` of one. +pub fn message_of(inst: &crate::ir::Inst) -> Option<GsMessage> { + match inst.fields { + Fields::Sopp { imm } if matches!(inst.name(), "s_sendmsg" | "s_sendmsghalt") => { + GsMessage::decode(imm) + } + _ => None, + } +} + +/// What a GS program does with its output, from its code. The record does +/// not give these in a layout this crate reads, so the code is the source: a +/// geometry shader declares its maximum before it emits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Vertices emitted along the longest path through the program. + pub max_vertices: u32, + /// Streams that emit or cut (bit n: stream n). + pub streams: u8, + /// A `GS_CUT` or `GS_EMIT_CUT` is sent: strips end before the program does. + pub cuts: bool, +} + +/// The output limits of a GS program. +/// +/// Fails when a message is sent inside a loop (no bound), or when the +/// program emits nothing at all. +pub fn limits(p: &Program) -> Result<Limits, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + let counts: Vec<u32> = p + .blocks + .iter() + .map(|b| b.insts.iter().filter_map(message_of).map(GsMessage::vertices).sum()) + .collect(); + // A block that can reach itself and sends a message has no bound. + let reaches = |from: usize, to: usize| { + let mut seen = vec![false; p.blocks.len()]; + let mut stack = p.blocks[from].exit.successors(); + while let Some(b) = stack.pop() { + if b == to { + return true; + } + if !std::mem::replace(&mut seen[b], true) { + stack.extend(p.blocks[b].exit.successors()); + } + } + false + }; + let mut streams = 0u8; + let mut cuts = false; + for (b, block) in p.blocks.iter().enumerate() { + let sends: Vec<_> = block.insts.iter().filter_map(message_of).collect(); + if sends.iter().any(|m| !matches!(m, GsMessage::Done)) && reaches(b, b) { + return Err(unsupported("a geometry message inside a loop")); + } + for m in sends { + match m { + GsMessage::Emit { stream } => streams |= 1 << stream, + GsMessage::Cut { stream } | GsMessage::EmitCut { stream } => { + streams |= 1 << stream; + cuts = true; + } + GsMessage::Done => {} + } + } + } + // The longest path of emits; a loop sends nothing, so its back edge is + // not followed. + fn longest(p: &Program, counts: &[u32], b: usize, on: &mut Vec<usize>, memo: &mut [Option<u32>]) -> u32 { + if let Some(n) = memo[b] { + return n; + } + on.push(b); + let after = match p.blocks[b].exit { + Exit::End | Exit::Indirect => 0, ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Reject unresolved GS control flow when claiming a vertex bound** If a GS has an unresolved `s_setpc_b64` whose target reaches another GS block, the IR marks the exit `Indirect`, but this branch treats it like `End`. `limits` then counts only pre-jump emits, so `max_vertices` can be lower than the shader's actual maximum; reject such paths or resolve their targets before reporting a bound. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:07 UTC · original
On crates/victory-shader/src/io.rs line 317 (outdated):

@@ -302,6 +306,22 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
             ];
             (loaded, &[][..], &ms.outputs[..])
         }
+        // The halves of a merged ES+GS stage share the SGPRs: no exports (the
+        // ES half hands its records over through LDS, the GS half writes its
+        // output vertices there); the runtime table pointer is the one input
+        // known. The root layout wins where it covers those dwords.
+        (StageIo::Gs(_), HwStage::Gs) | (StageIo::Es(_), HwStage::Es) => {
+            let first = native.stage.user_sgpr(crate::merged::RUNTIME_TABLE);
+            let taken = native.layout.iter().any(|p| {
+                let at = u32::from(native.stage.user_sgpr(p.user_data));
+                at < u32::from(first) + 2 && u32::from(first) < at + p.sgprs

P2 Badge Check the SGPR range before adding its untrusted length

For ES/GS containers, RootParam.sgprs is deserialized from the layout without a range check, so a malformed entry with a large count can overflow at + p.sgprs: checked builds panic, while release builds can wrap and incorrectly treat s8/s9 as free. Use checked or widened interval arithmetic here and in pair_es_gs.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:07 UTC · [original](https://github.com/fxceless/victory-fork/pull/367#discussion_r4688353697) On `crates/victory-shader/src/io.rs` line 317 (outdated): ```diff @@ -302,6 +306,22 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { ]; (loaded, &[][..], &ms.outputs[..]) } + // The halves of a merged ES+GS stage share the SGPRs: no exports (the + // ES half hands its records over through LDS, the GS half writes its + // output vertices there); the runtime table pointer is the one input + // known. The root layout wins where it covers those dwords. + (StageIo::Gs(_), HwStage::Gs) | (StageIo::Es(_), HwStage::Es) => { + let first = native.stage.user_sgpr(crate::merged::RUNTIME_TABLE); + let taken = native.layout.iter().any(|p| { + let at = u32::from(native.stage.user_sgpr(p.user_data)); + at < u32::from(first) + 2 && u32::from(first) < at + p.sgprs ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Check the SGPR range before adding its untrusted length** For ES/GS containers, `RootParam.sgprs` is deserialized from the layout without a range check, so a malformed entry with a large count can overflow `at + p.sgprs`: checked builds panic, while release builds can wrap and incorrectly treat s8/s9 as free. Use checked or widened interval arithmetic here and in `pair_es_gs`. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/367/head:github-bot/gh-367'
git switch 'github-bot/gh-367'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-367'
git switch 'github-bot/gh-367'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-367'
git switch 'github-bot/gh-367'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-367'
git switch 'main'
git merge --squash 'github-bot/gh-367'
git switch 'main'
git merge --ff-only 'github-bot/gh-367'
git switch 'main'
git merge 'github-bot/gh-367'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.