shader: lower signed DWORD accesses and SMin/SMax atomics in the SPIR-V address window #1240

Merged
tedin7 merged 3 commits from upstream-pr/1247 into main 2026-11-24 05:44:28 +00:00
tedin7 commented 2026-11-24 05:11:48 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:11:48Z.


Change

Extends the SPIR-V address-window adapter (tools/spirv_address_window.py) to signed 32-bit physical accesses: OpConvertUToPtr %_ptr_PSB_int, indexed %rt_int arrays, plain loads and stores, OpAtomicSMin and OpAtomicSMax. Target: shader tooling only, no CPU targets.

  • Every signed access runs in a branch taken only for an aligned, in-window address whose index addition does not wrap. No substitute index or sentinel is used: a load or atomic yields zero and a store changes nothing otherwise.
  • A signed atomic min or max is lowered to a compare-exchange loop with a signed compare. Forwarding it unchanged is wrong: SPIRV-Cross at 57e4efc emits the unsigned InterlockedMin/InterlockedMax on a byte-address buffer, so a negative word would sort above a positive one.
  • Any other atomic or memory operand on a signed pointer is rejected.

Verification

  • python3 -B tests/spirv_window/address_signed.py spirv-as spirv-val spirv-cross (Linux, SPIRV-Tools and SPIRV-Cross from the distro): lowered module validates for Vulkan 1.2, each access is guarded, the HLSL has two compare-exchange loops and no InterlockedMin/InterlockedMax, four unsupported forms are rejected, seven mutations fail the shape check. Passes.
  • Same command against origin/main's tools/: fails with ValueError: unhandled physical pointer operation.
  • python3 -B tests/spirv_window/check.py still passes (unchanged).
  • Readback: new spirv_address_window_signed_{hardware,warp} (in ctest --preset pr through spirv_.*_warp). 11 cases of 16 DWORDs against a separate CPU model, with negative words so signed and unsigned compares differ; misaligned, window-end, wrapping and out-of-view addresses; seven negative controls (SMin or SMax compared unsigned, direction reversed, atomic wrap guard, load alignment guard, store alignment guard dropped), each expected to first diverge at a named case and word. I could not run the D3D12 readback here (Linux, no dxc or D3D12). I checked that the C++ model matches an independent Python model for all 11 cases and derived the control words from that model. The Windows CI run is the first real GPU run.

Evidence and follow-up

The fixture address_signed.spvasm is hand-written for this repo; no external code or data. This PR is AI-assisted. The diff is larger than a minimal change because the readback model and the documentation had to ship together with the lowering.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6575127311 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:11:48Z. --- ## Change Extends the SPIR-V address-window adapter (`tools/spirv_address_window.py`) to signed 32-bit physical accesses: `OpConvertUToPtr %_ptr_PSB_int`, indexed `%rt_int` arrays, plain loads and stores, `OpAtomicSMin` and `OpAtomicSMax`. Target: shader tooling only, no CPU targets. - Every signed access runs in a branch taken only for an aligned, in-window address whose index addition does not wrap. No substitute index or sentinel is used: a load or atomic yields zero and a store changes nothing otherwise. - A signed atomic min or max is lowered to a compare-exchange loop with a signed compare. Forwarding it unchanged is wrong: SPIRV-Cross at `57e4efc` emits the unsigned `InterlockedMin`/`InterlockedMax` on a byte-address buffer, so a negative word would sort above a positive one. - Any other atomic or memory operand on a signed pointer is rejected. ## Verification - `python3 -B tests/spirv_window/address_signed.py spirv-as spirv-val spirv-cross` (Linux, SPIRV-Tools and SPIRV-Cross from the distro): lowered module validates for Vulkan 1.2, each access is guarded, the HLSL has two compare-exchange loops and no `InterlockedMin`/`InterlockedMax`, four unsupported forms are rejected, seven mutations fail the shape check. Passes. - Same command against `origin/main`'s `tools/`: fails with `ValueError: unhandled physical pointer operation`. - `python3 -B tests/spirv_window/check.py` still passes (unchanged). - Readback: new `spirv_address_window_signed_{hardware,warp}` (in `ctest --preset pr` through `spirv_.*_warp`). 11 cases of 16 DWORDs against a separate CPU model, with negative words so signed and unsigned compares differ; misaligned, window-end, wrapping and out-of-view addresses; seven negative controls (SMin or SMax compared unsigned, direction reversed, atomic wrap guard, load alignment guard, store alignment guard dropped), each expected to first diverge at a named case and word. I could not run the D3D12 readback here (Linux, no dxc or D3D12). I checked that the C++ model matches an independent Python model for all 11 cases and derived the control words from that model. The Windows CI run is the first real GPU run. ## Evidence and follow-up The fixture `address_signed.spvasm` is hand-written for this repo; no external code or data. This PR is AI-assisted. The diff is larger than a minimal change because the readback model and the documentation had to ship together with the lowering. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets.
upstream-sync closed this pull request 2026-11-24 06:47:15 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:22:25Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4daa4a814c

ℹ️ 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:R0Y00/Xbox2Windows:review:6034119713 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034119713). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:22:25Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `4daa4a814c` <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>
tedin7 commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:16Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034133179 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034133179). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:16Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:18Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034133372 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034133372). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:18Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:19Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034133580 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034133580). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:19Z. **Review:** COMMENTED --- _No description provided._
chatgpt-codex-connector[bot commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:31:42Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b429d36565

ℹ️ 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:R0Y00/Xbox2Windows:review:6034188407 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034188407). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:31:42Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `b429d36565` <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>
tedin7 commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:32:41Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034195417 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034195417). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:32:41Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:32:42Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034195647 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#pullrequestreview-6034195647). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:32:42Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:50:26 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:21Z.


Fixed in b429d365: compare-exchange failure semantics drop Release and map AcquireRelease to Acquire; a guarded access in a block with OpLoopMerge is rejected; result-derived and store stems use disjoint prefixes. Each has a case in address_signed.py. @codex review

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122916332 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#issuecomment-7122916332). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:21Z. --- Fixed in b429d365: compare-exchange failure semantics drop Release and map AcquireRelease to Acquire; a guarded access in a block with OpLoopMerge is rejected; result-derived and store stems use disjoint prefixes. Each has a case in address_signed.py. @codex review
tedin7 commented 2026-11-24 06:50:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:32:44Z.


Fixed in e6f1a2cd: the compare-exchange loop starts from zero instead of a plain load, and the semantics scan covers only atomics on physical signed pointers (a workgroup signed atomic now passes through, with a case). @codex review

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7123047951 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#issuecomment-7123047951). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:32:44Z. --- Fixed in e6f1a2cd: the compare-exchange loop starts from zero instead of a plain load, and the semantics scan covers only atomics on physical signed pointers (a workgroup signed atomic now passes through, with a case). @codex review
chatgpt-codex-connector[bot commented 2026-11-24 06:50:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:39:38Z.


Codex Review: Didn't find any major issues. 🎉

Reviewed commit: e6f1a2cd6c

ℹ️ 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:R0Y00/Xbox2Windows:comment:7123154695 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#issuecomment-7123154695). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:39:38Z. --- <!-- codex-review-receipt:v1 --> Codex Review: Didn't find any major issues. :tada: **Reviewed commit:** `e6f1a2cd6c` <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-24 06:50:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:14:16Z.


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-24T05:39:39.255923Z e6f1a2c 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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122756415 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#issuecomment-7122756415). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:14:16Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"e6f1a2cd6ce37a3935a9652b28528d9e9b5711ae","has_any_findings":false,"has_unresolved_findings":false,"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-24T05:39:39.255923Z">2026-11-24T05:39:39.255923Z</relative-time> | `e6f1a2c` | 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>
chatgpt-codex-connector[bot commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:22:25Z.

Code review location: tools/spirv_address_window.py; line 165

@@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def signed_access(fields, pointers, valid_of, words, label, stem):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",
+             f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"]
+    if store:
+        lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]),
+                      f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"])
+        return lines, stem + "_merge"
+    if atomic:
+        scope, semantics, value = fields[5:8]
+        lines.extend([
+            f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head",
+            f"{stem}_head = OpLabel",
+            f"{stem}_cur = OpPhi %uint {stem}_first {stem}_issue {stem}_seen {stem}_cont",
+            f"OpLoopMerge {stem}_exit {stem}_cont None", f"OpBranch {stem}_body", f"{stem}_body = OpLabel",
+            f"{stem}_cur_int = OpBitcast %int {stem}_cur",
+            f"{stem}_pick = {SIGNED_ATOMICS[fields[2]]} %bool {stem}_cur_int {value}",
+            f"{stem}_want = OpSelect %uint {stem}_pick {stem}_cur {stem}_value",
+            f"{stem}_seen = OpAtomicCompareExchange %uint {ptr} {scope} {semantics} {semantics} {stem}_want {stem}_cur",

P2 Badge Derive legal failure semantics for the signed CAS loop

For a signed atomic using Release or AcquireRelease semantics, this copies the same semantics into both the success and failure operands of OpAtomicCompareExchange. SPIR-V forbids Release and AcquireRelease in the failure operand, so otherwise valid input—for example, semantics 72 (AcquireRelease | UniformMemory)—produces an invalid module that the CLI cannot publish. Derive the failure ordering separately, using relaxed ordering for release and acquire ordering for acquire-release while preserving the applicable memory-class bits.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675856381 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675856381). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:22:25Z. **Code review location:** `tools/spirv_address_window.py`; line 165 ~~~~diff @@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def signed_access(fields, pointers, valid_of, words, label, stem): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", + f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"] + if store: + lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]), + f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"]) + return lines, stem + "_merge" + if atomic: + scope, semantics, value = fields[5:8] + lines.extend([ + f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head", + f"{stem}_head = OpLabel", + f"{stem}_cur = OpPhi %uint {stem}_first {stem}_issue {stem}_seen {stem}_cont", + f"OpLoopMerge {stem}_exit {stem}_cont None", f"OpBranch {stem}_body", f"{stem}_body = OpLabel", + f"{stem}_cur_int = OpBitcast %int {stem}_cur", + f"{stem}_pick = {SIGNED_ATOMICS[fields[2]]} %bool {stem}_cur_int {value}", + f"{stem}_want = OpSelect %uint {stem}_pick {stem}_cur {stem}_value", + f"{stem}_seen = OpAtomicCompareExchange %uint {ptr} {scope} {semantics} {semantics} {stem}_want {stem}_cur", ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Derive legal failure semantics for the signed CAS loop** For a signed atomic using `Release` or `AcquireRelease` semantics, this copies the same semantics into both the success and failure operands of `OpAtomicCompareExchange`. SPIR-V forbids `Release` and `AcquireRelease` in the failure operand, so otherwise valid input—for example, semantics `72` (`AcquireRelease | UniformMemory`)—produces an invalid module that the CLI cannot publish. Derive the failure ordering separately, using relaxed ordering for release and acquire ordering for acquire-release while preserving the applicable memory-class bits. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:22:25Z.

Code review location: tools/spirv_address_window.py; line 149

@@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def signed_access(fields, pointers, valid_of, words, label, stem):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",

P2 Badge Preserve loop headers when guarding a signed load

When a signed load occurs in a loop header before its existing OpLoopMerge, this inserted selection moves the original OpLoopMerge into the generated _merge block, but the loop's continue branch still targets the original header. The backedge consequently targets a block that no longer declares the loop, violating SPIR-V's structured-loop requirements and preventing translation of an otherwise valid loop condition. Rewriting successor phi parents does not repair this edge; the access split also needs to preserve the original loop-header structure.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675856387 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675856387). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:22:25Z. **Code review location:** `tools/spirv_address_window.py`; line 149 ~~~~diff @@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def signed_access(fields, pointers, valid_of, words, label, stem): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve loop headers when guarding a signed load** When a signed load occurs in a loop header before its existing `OpLoopMerge`, this inserted selection moves the original `OpLoopMerge` into the generated `_merge` block, but the loop's continue branch still targets the original header. The backedge consequently targets a block that no longer declares the loop, violating SPIR-V's structured-loop requirements and preventing translation of an otherwise valid loop condition. Rewriting successor phi parents does not repair this edge; the access split also needs to preserve the original loop-header structure. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:22:25Z.

Code review location: tools/spirv_address_window.py; line 341

@@ -255,6 +333,16 @@ def lower(assembly):
             final_label[origin] = label
             output.extend(new)
             continue
+        if ids & physical_ints:
+            if ids & (physical_words | physical_qwords):
+                raise ValueError("unhandled physical word pointer use")
+            fields = line.split()
+            signed_stores += fields[0] == "OpStore"
+            stem = "%x2w_signed_" + (fields[0][1:] if fields[0] != "OpStore" else f"store_{signed_stores}")

P2 Badge Separate result-derived stems from signed store stems

A signed load or atomic result named %store_1 receives exactly the same stem as the first signed store. Renaming %loaded to %store_1 throughout address_signed.spvasm reproduces duplicate definitions of %x2w_signed_store_1_issue, %x2w_signed_store_1_ptr, and %x2w_signed_store_1_merge, making the generated module invalid. Such source identifiers are allowed by the input namespace check, which reserves only %x2w_. Use disjoint prefixes for result-derived accesses and numbered stores.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675856391 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675856391). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:22:25Z. **Code review location:** `tools/spirv_address_window.py`; line 341 ~~~~diff @@ -255,6 +333,16 @@ def lower(assembly): final_label[origin] = label output.extend(new) continue + if ids & physical_ints: + if ids & (physical_words | physical_qwords): + raise ValueError("unhandled physical word pointer use") + fields = line.split() + signed_stores += fields[0] == "OpStore" + stem = "%x2w_signed_" + (fields[0][1:] if fields[0] != "OpStore" else f"store_{signed_stores}") ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Separate result-derived stems from signed store stems** A signed load or atomic result named `%store_1` receives exactly the same stem as the first signed store. Renaming `%loaded` to `%store_1` throughout `address_signed.spvasm` reproduces duplicate definitions of `%x2w_signed_store_1_issue`, `%x2w_signed_store_1_ptr`, and `%x2w_signed_store_1_merge`, making the generated module invalid. Such source identifiers are allowed by the input namespace check, which reserves only `%x2w_`. Use disjoint prefixes for result-derived accesses and numbered stores. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:16Z.

Code review location: tools/spirv_address_window.py; line 165

@@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def signed_access(fields, pointers, valid_of, words, label, stem):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",
+             f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"]
+    if store:
+        lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]),
+                      f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"])
+        return lines, stem + "_merge"
+    if atomic:
+        scope, semantics, value = fields[5:8]
+        lines.extend([
+            f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head",
+            f"{stem}_head = OpLabel",
+            f"{stem}_cur = OpPhi %uint {stem}_first {stem}_issue {stem}_seen {stem}_cont",
+            f"OpLoopMerge {stem}_exit {stem}_cont None", f"OpBranch {stem}_body", f"{stem}_body = OpLabel",
+            f"{stem}_cur_int = OpBitcast %int {stem}_cur",
+            f"{stem}_pick = {SIGNED_ATOMICS[fields[2]]} %bool {stem}_cur_int {value}",
+            f"{stem}_want = OpSelect %uint {stem}_pick {stem}_cur {stem}_value",
+            f"{stem}_seen = OpAtomicCompareExchange %uint {ptr} {scope} {semantics} {semantics} {stem}_want {stem}_cur",

Fixed in b429d365

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675868101 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675868101). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:16Z. **Code review location:** `tools/spirv_address_window.py`; line 165 ~~~~diff @@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def signed_access(fields, pointers, valid_of, words, label, stem): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", + f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"] + if store: + lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]), + f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"]) + return lines, stem + "_merge" + if atomic: + scope, semantics, value = fields[5:8] + lines.extend([ + f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head", + f"{stem}_head = OpLabel", + f"{stem}_cur = OpPhi %uint {stem}_first {stem}_issue {stem}_seen {stem}_cont", + f"OpLoopMerge {stem}_exit {stem}_cont None", f"OpBranch {stem}_body", f"{stem}_body = OpLabel", + f"{stem}_cur_int = OpBitcast %int {stem}_cur", + f"{stem}_pick = {SIGNED_ATOMICS[fields[2]]} %bool {stem}_cur_int {value}", + f"{stem}_want = OpSelect %uint {stem}_pick {stem}_cur {stem}_value", + f"{stem}_seen = OpAtomicCompareExchange %uint {ptr} {scope} {semantics} {semantics} {stem}_want {stem}_cur", ~~~~ --- Fixed in b429d365
tedin7 commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:18Z.

Code review location: tools/spirv_address_window.py; line 149

@@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def signed_access(fields, pointers, valid_of, words, label, stem):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",

Fixed in b429d365

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675868260 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675868260). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:18Z. **Code review location:** `tools/spirv_address_window.py`; line 149 ~~~~diff @@ -119,6 +126,54 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def signed_access(fields, pointers, valid_of, words, label, stem): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", ~~~~ --- Fixed in b429d365
tedin7 commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:24:19Z.

Code review location: tools/spirv_address_window.py; line 341

@@ -255,6 +333,16 @@ def lower(assembly):
             final_label[origin] = label
             output.extend(new)
             continue
+        if ids & physical_ints:
+            if ids & (physical_words | physical_qwords):
+                raise ValueError("unhandled physical word pointer use")
+            fields = line.split()
+            signed_stores += fields[0] == "OpStore"
+            stem = "%x2w_signed_" + (fields[0][1:] if fields[0] != "OpStore" else f"store_{signed_stores}")

Fixed in b429d365

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675868424 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675868424). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:24:19Z. **Code review location:** `tools/spirv_address_window.py`; line 341 ~~~~diff @@ -255,6 +333,16 @@ def lower(assembly): final_label[origin] = label output.extend(new) continue + if ids & physical_ints: + if ids & (physical_words | physical_qwords): + raise ValueError("unhandled physical word pointer use") + fields = line.split() + signed_stores += fields[0] == "OpStore" + stem = "%x2w_signed_" + (fields[0][1:] if fields[0] != "OpStore" else f"store_{signed_stores}") ~~~~ --- Fixed in b429d365
chatgpt-codex-connector[bot commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:31:42Z.

Code review location: tools/spirv_address_window.py; line 170

@@ -119,6 +127,65 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def failure_semantics(name, value):
+    """Return the ID and any new declaration of the compare-exchange failure semantics for an atomic's semantics.
+
+    The failure path may not release, so Release is dropped and AcquireRelease becomes Acquire. The memory-class
+    bits stay."""
+    failure = value & ~0xc | (0x2 if value & 0x8 else 0)
+    if failure == value:
+        return name, []
+    return f"%x2w_failure_{failure}", [f"%x2w_failure_{failure} = OpConstant %uint {failure}"]
+
+
+def signed_access(fields, pointers, valid_of, words, label, stem, failures):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",
+             f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"]
+    if store:
+        lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]),
+                      f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"])
+        return lines, stem + "_merge"
+    if atomic:
+        scope, semantics, value = fields[5:8]
+        lines.extend([
+            f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head",

P2 Badge Make the compare-exchange seed read atomic

When multiple invocations perform signed atomics on the same DWORD, this seed OpLoad can overlap with another invocation's compare-exchange write. That introduces a non-atomic/atomic data race into otherwise race-free source operations, so the lowered SPIR-V no longer preserves defined behavior under contention. The later CAS does not make the earlier load atomic, and the single-invocation fixture cannot expose this. Use an atomic read with load-legal semantics, or initialize the expected value to a constant and let the first CAS obtain the actual word.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675914657 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675914657). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:31:42Z. **Code review location:** `tools/spirv_address_window.py`; line 170 ~~~~diff @@ -119,6 +127,65 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def failure_semantics(name, value): + """Return the ID and any new declaration of the compare-exchange failure semantics for an atomic's semantics. + + The failure path may not release, so Release is dropped and AcquireRelease becomes Acquire. The memory-class + bits stay.""" + failure = value & ~0xc | (0x2 if value & 0x8 else 0) + if failure == value: + return name, [] + return f"%x2w_failure_{failure}", [f"%x2w_failure_{failure} = OpConstant %uint {failure}"] + + +def signed_access(fields, pointers, valid_of, words, label, stem, failures): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", + f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"] + if store: + lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]), + f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"]) + return lines, stem + "_merge" + if atomic: + scope, semantics, value = fields[5:8] + lines.extend([ + f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head", ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Make the compare-exchange seed read atomic** When multiple invocations perform signed atomics on the same DWORD, this seed `OpLoad` can overlap with another invocation's compare-exchange write. That introduces a non-atomic/atomic data race into otherwise race-free source operations, so the lowered SPIR-V no longer preserves defined behavior under contention. The later CAS does not make the earlier load atomic, and the single-invocation fixture cannot expose this. Use an atomic read with load-legal semantics, or initialize the expected value to a constant and let the first CAS obtain the actual word. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:31:42Z.

Code review location: tools/spirv_address_window.py; line 287

@@ -190,15 +260,37 @@ def lower(assembly):
     if physical_qwords and WIDE_POINTER_TYPE not in lines or uses_arrays64 and (
             WIDE_ARRAY_POINTER_TYPE not in lines or not set(WIDE_ARRAY_DECLARATIONS) <= set(lines)):
         raise ValueError("unsupported physical pointer or scalar layout")
+    signed_arrays = {}
+    signed_words = {}
+    signed_stores = 0
+    if physical_ints or any(cast and cast[2] == "arri" for cast in map(CAST.fullmatch, lines)):
+        if not set(SIGNED_POINTER_TYPES + SIGNED_ARRAY_DECLARATIONS) <= set(lines):
+            raise ValueError("unsupported physical pointer or scalar layout")
     if physical_qwords:
         declarations += ["%x2w_one = OpConstant %uint 1", "%x2w_shift_wide = OpConstant %uint 3",
                          "%x2w_shift_half = OpConstant %uint 32", "%x2w_mask_wide = OpConstant %ulong 7",
                          # The last valid QWORD ends at the same DWORD as the last valid DWORD access.
                          "%x2w_end_wide = OpConstant %ulong 4294967288"]
+    # A guarded access splits its block, which would strand an OpLoopMerge in the generated merge block.
+    loop_headers, start = set(), 0
+    for number, line in enumerate(lines):
+        if line.endswith(" = OpLabel"):
+            start = number
+        elif line.startswith("OpLoopMerge "):
+            loop_headers.update(range(start, number))
+    constants = {m[1]: int(m[2]) for m in map(CONSTANT.fullmatch, lines) if m}
+    failures = {}
     for line in lines:
+        fields = line.split()
+        if len(fields) == 8 and fields[2] in SIGNED_ATOMICS:
+            if fields[6] not in constants:
+                raise ValueError("signed atomic semantics must be a constant")

P2 Badge Limit failure-semantics scanning to transformed physical atomics

If the input also contains a workgroup OpAtomicSMin or OpAtomicSMax with a legal semantics constant such as %relaxed = OpConstant %int 0, this unconditional scan raises signed atomic semantics must be a constant, although that atomic is not being lowered. Adding such a workgroup atomic to subtract.spvasm reproduces the regression: the parent accepts and preserves it, while this revision rejects it. Restrict this pre-pass to pointers in physical_ints rather than imposing the physical-lowering constant format on unrelated atomics.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675914661 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675914661). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:31:42Z. **Code review location:** `tools/spirv_address_window.py`; line 287 ~~~~diff @@ -190,15 +260,37 @@ def lower(assembly): if physical_qwords and WIDE_POINTER_TYPE not in lines or uses_arrays64 and ( WIDE_ARRAY_POINTER_TYPE not in lines or not set(WIDE_ARRAY_DECLARATIONS) <= set(lines)): raise ValueError("unsupported physical pointer or scalar layout") + signed_arrays = {} + signed_words = {} + signed_stores = 0 + if physical_ints or any(cast and cast[2] == "arri" for cast in map(CAST.fullmatch, lines)): + if not set(SIGNED_POINTER_TYPES + SIGNED_ARRAY_DECLARATIONS) <= set(lines): + raise ValueError("unsupported physical pointer or scalar layout") if physical_qwords: declarations += ["%x2w_one = OpConstant %uint 1", "%x2w_shift_wide = OpConstant %uint 3", "%x2w_shift_half = OpConstant %uint 32", "%x2w_mask_wide = OpConstant %ulong 7", # The last valid QWORD ends at the same DWORD as the last valid DWORD access. "%x2w_end_wide = OpConstant %ulong 4294967288"] + # A guarded access splits its block, which would strand an OpLoopMerge in the generated merge block. + loop_headers, start = set(), 0 + for number, line in enumerate(lines): + if line.endswith(" = OpLabel"): + start = number + elif line.startswith("OpLoopMerge "): + loop_headers.update(range(start, number)) + constants = {m[1]: int(m[2]) for m in map(CONSTANT.fullmatch, lines) if m} + failures = {} for line in lines: + fields = line.split() + if len(fields) == 8 and fields[2] in SIGNED_ATOMICS: + if fields[6] not in constants: + raise ValueError("signed atomic semantics must be a constant") ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Limit failure-semantics scanning to transformed physical atomics** If the input also contains a workgroup `OpAtomicSMin` or `OpAtomicSMax` with a legal semantics constant such as `%relaxed = OpConstant %int 0`, this unconditional scan raises `signed atomic semantics must be a constant`, although that atomic is not being lowered. Adding such a workgroup atomic to `subtract.spvasm` reproduces the regression: the parent accepts and preserves it, while this revision rejects it. Restrict this pre-pass to pointers in `physical_ints` rather than imposing the physical-lowering constant format on unrelated atomics. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:43 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:32:41Z.

Code review location: tools/spirv_address_window.py; line 170

@@ -119,6 +127,65 @@ def wide_access(kind, stem, valid, label, word, fields):
     return lines, stem + "_merge"
 
 
+def failure_semantics(name, value):
+    """Return the ID and any new declaration of the compare-exchange failure semantics for an atomic's semantics.
+
+    The failure path may not release, so Release is dropped and AcquireRelease becomes Acquire. The memory-class
+    bits stay."""
+    failure = value & ~0xc | (0x2 if value & 0x8 else 0)
+    if failure == value:
+        return name, []
+    return f"%x2w_failure_{failure}", [f"%x2w_failure_{failure} = OpConstant %uint {failure}"]
+
+
+def signed_access(fields, pointers, valid_of, words, label, stem, failures):
+    """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address.
+
+    The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange
+    loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a
+    byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise.
+    Returns the lines and the label that follows."""
+    store = fields[0] == "OpStore"
+    pointer = fields[1] if store else fields[4]
+    atomic = not store and fields[2] in SIGNED_ATOMICS
+    operands = fields[3:] if store else fields[5:]
+    if store:
+        shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS
+    elif atomic:
+        shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int"
+    else:
+        shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS
+    if not shape or pointer not in pointers or len(pointers) != 1:
+        raise ValueError("unhandled physical word pointer use")
+    ptr = stem + "_ptr"
+    lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge",
+             f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"]
+    if store:
+        lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]),
+                      f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"])
+        return lines, stem + "_merge"
+    if atomic:
+        scope, semantics, value = fields[5:8]
+        lines.extend([
+            f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head",

Fixed in e6f1a2cd

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675920599 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675920599). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:32:41Z. **Code review location:** `tools/spirv_address_window.py`; line 170 ~~~~diff @@ -119,6 +127,65 @@ def wide_access(kind, stem, valid, label, word, fields): return lines, stem + "_merge" +def failure_semantics(name, value): + """Return the ID and any new declaration of the compare-exchange failure semantics for an atomic's semantics. + + The failure path may not release, so Release is dropped and AcquireRelease becomes Acquire. The memory-class + bits stay.""" + failure = value & ~0xc | (0x2 if value & 0x8 else 0) + if failure == value: + return name, [] + return f"%x2w_failure_{failure}", [f"%x2w_failure_{failure} = OpConstant %uint {failure}"] + + +def signed_access(fields, pointers, valid_of, words, label, stem, failures): + """Lower a signed DWORD load, store, SMin or SMax into a branch taken only for a valid address. + + The heap holds unsigned words, so the value is bit-cast. A signed atomic min or max is a compare-exchange + loop with a signed compare: SPIRV-Cross emits the unsigned InterlockedMin or InterlockedMax for it on a + byte-address buffer. A load yields zero, a store changes nothing and an atomic returns zero otherwise. + Returns the lines and the label that follows.""" + store = fields[0] == "OpStore" + pointer = fields[1] if store else fields[4] + atomic = not store and fields[2] in SIGNED_ATOMICS + operands = fields[3:] if store else fields[5:] + if store: + shape = len(fields) >= 3 and operands in SIGNED_MEMORY_OPERANDS + elif atomic: + shape = len(fields) == 8 and fields[1] == "=" and fields[3] == "%int" + else: + shape = fields[1:4] == ["=", "OpLoad", "%int"] and fields[4:5] and operands in SIGNED_MEMORY_OPERANDS + if not shape or pointer not in pointers or len(pointers) != 1: + raise ValueError("unhandled physical word pointer use") + ptr = stem + "_ptr" + lines = [f"OpSelectionMerge {stem}_merge None", f"OpBranchConditional {valid_of[pointer]} {stem}_issue {stem}_merge", + f"{stem}_issue = OpLabel", f"{ptr} = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 {words[pointer]}"] + if store: + lines.extend([f"{stem}_value = OpBitcast %uint {fields[2]}", " ".join(["OpStore", ptr, f"{stem}_value", *operands]), + f"OpBranch {stem}_merge", f"{stem}_merge = OpLabel"]) + return lines, stem + "_merge" + if atomic: + scope, semantics, value = fields[5:8] + lines.extend([ + f"{stem}_value = OpBitcast %uint {value}", f"{stem}_first = OpLoad %uint {ptr}", f"OpBranch {stem}_head", ~~~~ --- Fixed in e6f1a2cd
tedin7 commented 2026-11-24 06:50:43 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:32:42Z.

Code review location: tools/spirv_address_window.py; line 287

@@ -190,15 +260,37 @@ def lower(assembly):
     if physical_qwords and WIDE_POINTER_TYPE not in lines or uses_arrays64 and (
             WIDE_ARRAY_POINTER_TYPE not in lines or not set(WIDE_ARRAY_DECLARATIONS) <= set(lines)):
         raise ValueError("unsupported physical pointer or scalar layout")
+    signed_arrays = {}
+    signed_words = {}
+    signed_stores = 0
+    if physical_ints or any(cast and cast[2] == "arri" for cast in map(CAST.fullmatch, lines)):
+        if not set(SIGNED_POINTER_TYPES + SIGNED_ARRAY_DECLARATIONS) <= set(lines):
+            raise ValueError("unsupported physical pointer or scalar layout")
     if physical_qwords:
         declarations += ["%x2w_one = OpConstant %uint 1", "%x2w_shift_wide = OpConstant %uint 3",
                          "%x2w_shift_half = OpConstant %uint 32", "%x2w_mask_wide = OpConstant %ulong 7",
                          # The last valid QWORD ends at the same DWORD as the last valid DWORD access.
                          "%x2w_end_wide = OpConstant %ulong 4294967288"]
+    # A guarded access splits its block, which would strand an OpLoopMerge in the generated merge block.
+    loop_headers, start = set(), 0
+    for number, line in enumerate(lines):
+        if line.endswith(" = OpLabel"):
+            start = number
+        elif line.startswith("OpLoopMerge "):
+            loop_headers.update(range(start, number))
+    constants = {m[1]: int(m[2]) for m in map(CONSTANT.fullmatch, lines) if m}
+    failures = {}
     for line in lines:
+        fields = line.split()
+        if len(fields) == 8 and fields[2] in SIGNED_ATOMICS:
+            if fields[6] not in constants:
+                raise ValueError("signed atomic semantics must be a constant")

Fixed in e6f1a2cd

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675920766 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1247#discussion_r4675920766). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:32:42Z. **Code review location:** `tools/spirv_address_window.py`; line 287 ~~~~diff @@ -190,15 +260,37 @@ def lower(assembly): if physical_qwords and WIDE_POINTER_TYPE not in lines or uses_arrays64 and ( WIDE_ARRAY_POINTER_TYPE not in lines or not set(WIDE_ARRAY_DECLARATIONS) <= set(lines)): raise ValueError("unsupported physical pointer or scalar layout") + signed_arrays = {} + signed_words = {} + signed_stores = 0 + if physical_ints or any(cast and cast[2] == "arri" for cast in map(CAST.fullmatch, lines)): + if not set(SIGNED_POINTER_TYPES + SIGNED_ARRAY_DECLARATIONS) <= set(lines): + raise ValueError("unsupported physical pointer or scalar layout") if physical_qwords: declarations += ["%x2w_one = OpConstant %uint 1", "%x2w_shift_wide = OpConstant %uint 3", "%x2w_shift_half = OpConstant %uint 32", "%x2w_mask_wide = OpConstant %ulong 7", # The last valid QWORD ends at the same DWORD as the last valid DWORD access. "%x2w_end_wide = OpConstant %ulong 4294967288"] + # A guarded access splits its block, which would strand an OpLoopMerge in the generated merge block. + loop_headers, start = set(), 0 + for number, line in enumerate(lines): + if line.endswith(" = OpLabel"): + start = number + elif line.startswith("OpLoopMerge "): + loop_headers.update(range(start, number)) + constants = {m[1]: int(m[2]) for m in map(CONSTANT.fullmatch, lines) if m} + failures = {} for line in lines: + fields = line.split() + if len(fields) == 8 and fields[2] in SIGNED_ATOMICS: + if fields[6] not in constants: + raise ValueError("signed atomic semantics must be a constant") ~~~~ --- Fixed in e6f1a2cd
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
R0Y00/Xbox2Windows!1240
No description provided.