mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 22:20:28 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2713c9e049 | ||
|
|
bd13b17f30 | ||
|
|
5b99b6bd63 | ||
|
|
b23e6fd6e5 | ||
|
|
d2ca4c3995 | ||
|
|
59b6c4db5e | ||
|
|
ca2fe15d3e | ||
|
|
8fbef1e31f | ||
|
|
6fd254825d |
No files matched your search
@@ -10,6 +10,10 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Review follow-up on the proposed `victory-shader` import (#394): `translate_native` now reports immediate samplers as static samplers (a sampled texel read 0 on the GPU before), BetterXen's GPU tests use a host that `VICTORY_WARP` cannot redirect, the double-precision probes take run-time operands and were rerun (same result), and a per-file provenance review records that the crate was developed against one commercial title's shaders. **The import is not approved; a maintainer decision is required** (`docs/research/victory-shader-provenance.md`). Earlier statements that the crate had nothing game-specific are withdrawn.
|
||||
- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
|
||||
- Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's ten tests or the whole upstream suite. It takes both the runner and the test executable from the messages of the cargo invocations that built them, and stops if a build fails (review fix: an earlier version piped cargo into the parser, so a failed build exited 0 and ran a stale executable, and it assumed the runner was under `target/`). `scripts/hybrid/test-run-shader-gpu-tests.sh` is a stubbed regression test for both. It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; there is no fallback to a guessed path. Not independently reviewed.
|
||||
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
|
||||
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
|
||||
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
|
||||
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
|
||||
|
||||
Generated
+209
-8
@@ -2,6 +2,19 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -126,6 +139,24 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -137,12 +168,60 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -150,16 +229,132 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
name = "victory-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
"thiserror",
|
||||
"windows",
|
||||
"windows-sys",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -243,3 +438,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "xenora-texture"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
@@ -15,3 +15,7 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
|
||||
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
|
||||
|
||||
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
|
||||
|
||||
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
|
||||
|
||||
Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed.
|
||||
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "victory-shader"
|
||||
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders. Vendored from skakwy/victory-mac; see UPSTREAM.md."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
thiserror = "2.0.21"
|
||||
zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] }
|
||||
|
||||
[features]
|
||||
# Host D3D12 pipeline checks (`emit::host`); Windows targets only.
|
||||
host = ["dep:windows"]
|
||||
# Debugging switches (emitted-module dumps and the like).
|
||||
diagnostics = []
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_System_LibraryLoader"] }
|
||||
windows = { version = "0.62.2", optional = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
] }
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
] }
|
||||
|
||||
[lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
unused_must_use = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
all = { level = "warn", priority = -1 }
|
||||
# Same allowances as the upstream workspace (victory-mac Cargo.toml [workspace.lints.clippy]).
|
||||
type_complexity = "allow"
|
||||
needless_range_loop = "allow"
|
||||
chunks_exact_to_as_chunks = "allow"
|
||||
sliced_string_as_bytes = "allow"
|
||||
collapsible_match = "allow"
|
||||
manual_clamp = "allow"
|
||||
implicit_saturating_sub = "allow"
|
||||
min_max = "allow"
|
||||
undocumented_unsafe_blocks = "allow"
|
||||
@@ -0,0 +1,36 @@
|
||||
# Upstream provenance: victory-shader
|
||||
|
||||
**Not approved for merge.** This crate was developed against one commercial title's shaders; the per-file review and the open maintainer decision are in `docs/research/victory-shader-provenance.md`.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Source | <https://github.com/skakwy/victory-mac>, directory `crates/victory-shader/` (Cargo.toml and `src/`) |
|
||||
| Repository head when copied | `22b3f8e45a59` (2026-11-25); the directory's last change is commit `559357432b41` |
|
||||
| Licence | GPL-3.0 (repository `LICENSE`); workspace manifest declares `GPL-3.0-or-later`, the same as BetterXen. No file in the crate carries a different licence |
|
||||
| Third-party notice kept in place | `src/gfx10/opcodes.rs`: opcode names generated from Mesa's `aco_opcodes.py` (tag mesa-22.3.0), MIT, Copyright (c) 2018 Valve Corporation; the notice is in the file header |
|
||||
| Authorization | skakwy and the VIctory-macOS maintainer authorize reuse of their contributions (relayed by the BetterXen maintainer). Other authors' lines are used under the repository's GPL-3.0 |
|
||||
| Authors (commits touching this directory, from `git shortlog`) | Marvis (33), skakwy (12), fxceless (11), r4. (6), Duff (4), 9hvn9yt2vk-netizen (3), tedin7 (3), DexNom (2), Luiz Neves (2), Saitken91 (2), others; some commits are credited to an AI assistant |
|
||||
| What it is | Xbox Series shader containers (DXBC with Xbox additions) and precompiled GFX10 (RDNA 2) machine code translated to PC DXIL (SM 6.6): GFX10 decoder and SP3 printer, control-flow structurizer, IR, register spilling, wave emulation, fp64 by integer operations, an own LLVM 3.7 bitcode writer and container signing |
|
||||
| Upstream commit-level history | Not carried; see the upstream repository. This directory is a snapshot, so later upstream fixes must be merged by comparing with the pinned commit |
|
||||
|
||||
## Modifications made by BetterXen
|
||||
|
||||
Changes to upstream files (19 lines, nothing functional) and files BetterXen added (marked `BetterXen addition`, GPL-3.0-or-later): `src/emit/betterxen.rs` (a public `translate_native` for raw compute programs, same stages as `translate`) and `src/emit/betterxen_tests.rs` (BetterXen gfx1030 fixtures through the recompiler, and on the GPU under CrossOver). Two lines in `src/emit/mod.rs` declare them. Validation record: `docs/research/victory-shader-integration.md`.
|
||||
|
||||
### Edits to upstream files
|
||||
|
||||
- `Cargo.toml` rewritten: workspace-inherited dependency versions replaced by explicit ones (`thiserror` 2.0.21, `zlib-rs` 0.6.8, `windows` 0.62.2, `windows-sys` 0.61.2), same features and lint allowances as upstream's workspace.
|
||||
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
|
||||
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
|
||||
|
||||
### Functional edits to upstream files (research/shader-wave-semantics, PR #392)
|
||||
|
||||
- `src/emit/lower.rs` (`active_f64_sum`, about 90 lines): the whole-wave f64 sum no longer emits a native `double` wave operation (`makeDouble`, `waveActiveOp.f64`, `splitDouble`); it builds the console's balanced tree over the lanes with the crate's own integer `add_f64`, reading partner runs through `waveReadLaneAt` and a ballot for lanes that are not present, and no longer sets the doubles feature flag. Why: D3DMetal reports no double-precision shader operations and a shader that uses a `double` ran without writing anything (docs/research/shader-wave-semantics.md).
|
||||
- `src/emit/bitcode.rs`: two `#[allow(dead_code)]` for the double type, now never constructed.
|
||||
- `src/emit/host.rs`: `Host::wave_lane_count_max()` and `Host::hardware()` (test host only; `hardware()` ignores `VICTORY_WARP`).
|
||||
- `src/emit/mod.rs`: the static-sampler construction is factored into `static_samplers()` so `translate_native` reports immediate samplers.
|
||||
- `src/emit/wave64_tests.rs`: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` checks the device's wave width and, on a device narrower than 64 lanes, asserts the recompiler's refusal instead of running a 64-lane lowering.
|
||||
|
||||
## Not carried
|
||||
|
||||
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. No shader binaries or dumps of the title the upstream project targets are included, but comments and behaviour in this crate refer to that title's shaders; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
|
||||
@@ -0,0 +1,696 @@
|
||||
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
|
||||
//! instruction returns for one ray and one node. The emitter lowers the
|
||||
//! instruction to the same arithmetic in the same order
|
||||
//! (`emit/intersect.rs`), so its code can be compared against this dword
|
||||
//! for dword.
|
||||
//!
|
||||
//! The instruction tests one ray against one 64-byte node of a bounding
|
||||
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
|
||||
//! transforms, culling, the hit distance `numerator / denominator`) is the
|
||||
//! program's own code.
|
||||
//!
|
||||
//! # Node pointers
|
||||
//!
|
||||
//! A node pointer's low three bits are the node's kind, the rest its byte
|
||||
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
|
||||
//! base address of the descriptor (40 bits in dword 0 and the low byte of
|
||||
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
|
||||
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
|
||||
//! with base 0 for every structure and adds `address >> 3` itself.
|
||||
//!
|
||||
//! | kind | node |
|
||||
//! |---|---|
|
||||
//! | 0-3 | triangle 0-3 of a triangle node |
|
||||
//! | 4 | box node, 16-bit floats (64 bytes) |
|
||||
//! | 5 | box node, 32-bit floats (128 bytes) |
|
||||
//! | 6 | instance: not read by the instruction |
|
||||
//! | 7 | procedural primitive: not read by the instruction |
|
||||
//!
|
||||
//! # Box nodes
|
||||
//!
|
||||
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
|
||||
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
|
||||
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
|
||||
//! 112-127 are not read). The result is the pointers of the children whose
|
||||
//! box the ray enters before its extent, nearest entry first when the
|
||||
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
|
||||
//!
|
||||
//! # Triangle nodes
|
||||
//!
|
||||
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
|
||||
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
|
||||
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
|
||||
//! input triangle's second vertex at the former, its third at the latter
|
||||
//! and its first at the remaining one, so I and J are the weights of the
|
||||
//! input triangle's second and third vertices). Triangle `k` of the node
|
||||
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
|
||||
//! keeps fewer triangles in a node uses the bytes of the unused vertices
|
||||
//! for its own data.
|
||||
//!
|
||||
//! With the descriptor's triangle return mode set (bit 120) the result is
|
||||
//! the hit distance's numerator, its denominator, and the numerators of I
|
||||
//! and J over the same denominator, as floats. The denominator is positive
|
||||
//! for a triangle whose vertices run clockwise seen from the ray's origin
|
||||
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
|
||||
//! The ray's extent is not tested for triangles.
|
||||
//!
|
||||
//! # Where this comes from
|
||||
//!
|
||||
//! The node formats, the descriptor bits and the tests are those of the
|
||||
//! public software emulation of this instruction in the open-source Vulkan
|
||||
//! driver for this GPU family (box test and sorting network as there; the
|
||||
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
|
||||
//! JCGT 2013), and agree with what the title's own structure
|
||||
//! builder writes and its trace programs read. Not known from either: how
|
||||
//! the console rounds, which of two boxes entered at the same distance it
|
||||
//! returns first, and what it returns for a ray exactly through an edge
|
||||
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
|
||||
//! a triangle miss; the title's programs do not read it).
|
||||
|
||||
/// The result dword for a box the ray misses, or a child that is not there.
|
||||
pub const NONE: u32 = 0xffff_ffff;
|
||||
|
||||
/// The node's vertices that make triangle 0-3, by the triangle's own
|
||||
/// vertex numbers 0-2.
|
||||
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
|
||||
|
||||
/// Descriptor dword 1: boxes are returned nearest first.
|
||||
pub const BOX_SORT: u32 = 1 << 31;
|
||||
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
|
||||
/// a triangle id and a hit status, which nothing here produces).
|
||||
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
|
||||
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
|
||||
/// structure.
|
||||
pub const DESCRIPTOR_TYPE: u32 = 8;
|
||||
|
||||
/// The ray as the instruction takes it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub extent: f32,
|
||||
pub origin: [f32; 3],
|
||||
pub direction: [f32; 3],
|
||||
/// What the program computed as `1 / direction`.
|
||||
pub inverse: [f32; 3],
|
||||
}
|
||||
|
||||
impl Ray {
|
||||
/// A ray with the inverse direction a program computes by division.
|
||||
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
|
||||
Self {
|
||||
extent,
|
||||
origin,
|
||||
direction,
|
||||
inverse: direction.map(|d| 1.0 / d),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of the node a pointer names.
|
||||
pub fn kind(pointer: u64) -> u32 {
|
||||
(pointer & 7) as u32
|
||||
}
|
||||
|
||||
/// The byte address of the node `pointer` names, for a descriptor whose
|
||||
/// first two dwords are `word0` and `word1`.
|
||||
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
|
||||
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
|
||||
base.wrapping_add((pointer >> 3) << 6)
|
||||
}
|
||||
|
||||
/// What the instruction returns for the node at `words` (its first 28
|
||||
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
|
||||
/// of this `kind`, with box sorting as `sort` says and the triangle return
|
||||
/// mode set.
|
||||
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
match kind & 7 {
|
||||
4 => boxes(&children(words), &boxes16(words), ray, sort),
|
||||
5 => boxes(&children(words), &boxes32(words), ray, sort),
|
||||
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
|
||||
_ => MISS.map(f32::to_bits),
|
||||
}
|
||||
}
|
||||
|
||||
/// A box node's four child pointers.
|
||||
pub fn children(words: &[u32; 28]) -> [u32; 4] {
|
||||
[words[0], words[1], words[2], words[3]]
|
||||
}
|
||||
|
||||
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
|
||||
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| {
|
||||
std::array::from_fn(|k| {
|
||||
let half = 6 * b + k;
|
||||
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The four boxes of a 32-bit box node.
|
||||
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
|
||||
}
|
||||
|
||||
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
|
||||
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
|
||||
/// 0x042).
|
||||
pub fn vertex_map(k: u32) -> u32 {
|
||||
let v = TRIANGLE_VERTICES[(k & 3) as usize];
|
||||
v[0] | v[1] << 4 | v[2] << 8
|
||||
}
|
||||
|
||||
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
|
||||
/// the one neither barycentric weighs, then I's, then J's.
|
||||
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
|
||||
let id = words[15] >> (8 * k);
|
||||
let (i, j) = (id & 3, id >> 2 & 3);
|
||||
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
|
||||
// what this arithmetic lands on (a vertex of the node), as the emitted
|
||||
// code does.
|
||||
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
|
||||
[first, i, j].map(|n| {
|
||||
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
|
||||
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
|
||||
})
|
||||
}
|
||||
|
||||
/// The box test: child pointers of the boxes the ray enters, `NONE` for
|
||||
/// the others; sorted by entry distance when `sort`, in child order
|
||||
/// otherwise.
|
||||
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
// An infinite inverse (a direction component of 0) would turn an
|
||||
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
|
||||
// the emitted code: a NaN becomes the lower bound, where `clamp` would
|
||||
// keep it.)
|
||||
#[allow(clippy::manual_clamp)]
|
||||
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
|
||||
let mut ids = [NONE; 4];
|
||||
let mut distances = [f32::INFINITY; 4];
|
||||
for (n, b) in boxes.iter().enumerate() {
|
||||
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
|
||||
for a in 0..3 {
|
||||
let low = (b[a] - ray.origin[a]) * inverse[a];
|
||||
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
|
||||
near[a] = low.min(high);
|
||||
far[a] = low.max(high);
|
||||
}
|
||||
let enter = near[0].max(near[1]).max(near[2]);
|
||||
let leave = far[0].min(far[1]).min(far[2]);
|
||||
// A box whose minimum x is NaN is switched off.
|
||||
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
|
||||
ids[n] = children[n];
|
||||
distances[n] = enter;
|
||||
}
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
if distances[b] < distances[a] {
|
||||
distances.swap(a, b);
|
||||
ids.swap(a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// What a triangle the ray misses returns.
|
||||
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
|
||||
|
||||
/// The triangle test: the hit distance's numerator, the denominator, and
|
||||
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
|
||||
/// Watertight: the vertices are sheared so the ray runs along its largest
|
||||
/// axis, and the signs of the three edge functions decide, so a ray
|
||||
/// between two triangles that share an edge cannot miss both. Any NaN
|
||||
/// misses, and so does a triangle seen edge-on.
|
||||
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
|
||||
let d = ray.direction;
|
||||
let size = d.map(f32::abs);
|
||||
// The largest axis, and the other two in an order that keeps the
|
||||
// triangle's winding.
|
||||
let kz = if size[0] >= size[1] {
|
||||
if size[0] >= size[2] { 0 } else { 2 }
|
||||
} else if size[1] >= size[2] {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
|
||||
if d[kz] < 0.0 {
|
||||
std::mem::swap(&mut kx, &mut ky);
|
||||
}
|
||||
let sz = ray.inverse[kz];
|
||||
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
|
||||
let sheared = |v: &[f32; 3]| {
|
||||
let r = [
|
||||
v[0] - ray.origin[0],
|
||||
v[1] - ray.origin[1],
|
||||
v[2] - ray.origin[2],
|
||||
];
|
||||
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
|
||||
};
|
||||
let (ax, ay, az) = sheared(&p[0]);
|
||||
let (bx, by, bz) = sheared(&p[1]);
|
||||
let (cx, cy, cz) = sheared(&p[2]);
|
||||
let u = cx * by - cy * bx;
|
||||
let v = ax * cy - ay * cx;
|
||||
let w = bx * ay - by * ax;
|
||||
let behind = u < 0.0 || v < 0.0 || w < 0.0;
|
||||
let before = u > 0.0 || v > 0.0 || w > 0.0;
|
||||
let det = u + (v + w);
|
||||
let t = (u * az + v * bz) + w * cz;
|
||||
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
|
||||
if !(behind && before) && ahead {
|
||||
[t, det, v, w]
|
||||
} else {
|
||||
MISS
|
||||
}
|
||||
}
|
||||
|
||||
/// A 16-bit float as a 32-bit one (exact).
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
let sign = u32::from(h >> 15) << 31;
|
||||
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
|
||||
let bits = match exponent {
|
||||
0 if mantissa == 0 => sign,
|
||||
0 => {
|
||||
// Subnormal: normalise.
|
||||
let shift = mantissa.leading_zeros() - 21;
|
||||
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
|
||||
}
|
||||
0x1f => sign | 0xff << 23 | mantissa << 13,
|
||||
e => sign | (e + 112) << 23 | mantissa << 13,
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The smallest 16-bit float not below `x` (`up`) or not above it.
|
||||
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
|
||||
let mut best: Option<u16> = None;
|
||||
for h in 0..=0xffffu16 {
|
||||
let f = half_to_f32(h);
|
||||
if f.is_nan() || if up { f < x } else { f > x } {
|
||||
continue;
|
||||
}
|
||||
best = match best {
|
||||
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
|
||||
_ => Some(h),
|
||||
};
|
||||
}
|
||||
best.expect("a half")
|
||||
}
|
||||
|
||||
/// A 32-bit box node.
|
||||
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
w[4 + 6 * b + k] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A 16-bit box node holding `boxes` rounded outward.
|
||||
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
let half = 6 * b + k;
|
||||
let h = if x.is_nan() {
|
||||
0x7e00
|
||||
} else {
|
||||
f32_to_half(*x, k >= 3)
|
||||
};
|
||||
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A triangle node: up to five vertices, and the dword at byte 60.
|
||||
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
for (n, v) in vertices.iter().enumerate() {
|
||||
for (c, x) in v.iter().enumerate() {
|
||||
w[3 * n + c] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w[15] = id;
|
||||
w
|
||||
}
|
||||
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
|
||||
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
|
||||
std::array::from_fn(|k| b[k] + by[k % 3])
|
||||
}
|
||||
|
||||
const OFF: [f32; 6] = [f32::NAN; 6];
|
||||
|
||||
#[test]
|
||||
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
|
||||
// The 64-bit form as the title uses it: base 0, the structure's
|
||||
// address folded into the pointer.
|
||||
let structure = 0x12_3456_7800u64;
|
||||
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
|
||||
assert_eq!(kind(pointer), 5);
|
||||
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
|
||||
// The 32-bit form: the base in the descriptor.
|
||||
let word0 = (structure >> 8) as u32;
|
||||
let word1 = (structure >> 40) as u32 | BOX_SORT;
|
||||
assert_eq!(
|
||||
node_address(word0, word1, 0x1000 >> 3 | 4),
|
||||
structure + 0x1000
|
||||
);
|
||||
// A base past 4 GiB of 256-byte units.
|
||||
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halves_convert_exactly() {
|
||||
assert_eq!(half_to_f32(0x3c00), 1.0);
|
||||
assert_eq!(half_to_f32(0xc000), -2.0);
|
||||
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
|
||||
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x7bff), 65504.0);
|
||||
assert!(half_to_f32(0x7e00).is_nan());
|
||||
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
|
||||
// Outward rounding of the test helper.
|
||||
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
|
||||
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boxes_are_returned_nearest_first_and_misses_last() {
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
|
||||
let node = box32(
|
||||
children,
|
||||
[
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
// Without sorting: child order, the miss in its place.
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &ray, false),
|
||||
[0x105, 0x20c, NONE, 0x400]
|
||||
);
|
||||
// The extent cuts the far ones off (entered at 9, 19, 29).
|
||||
let short = Ray {
|
||||
extent: 19.5,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &short, true),
|
||||
[0x20c, 0x400, NONE, NONE]
|
||||
);
|
||||
// An entry exactly at the extent is no hit.
|
||||
let exact = Ray {
|
||||
extent: 19.0,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
|
||||
// Backwards: nothing.
|
||||
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
|
||||
let node = box32(
|
||||
[8, 16, NONE, NONE],
|
||||
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
|
||||
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
|
||||
// Even with a tiny extent the box around the origin is a hit.
|
||||
let tiny = Ray {
|
||||
extent: 1e-6,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
|
||||
// Direction components of 0: the inverse is infinite.
|
||||
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert!(ray.inverse[1].is_infinite());
|
||||
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
|
||||
// would be a NaN; with the inverse held finite it is 0, and the ray
|
||||
// running along the face is inside.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
// Along the +y face it is outside: the face's plane is left at 0
|
||||
// and the box is entered at 4 (as the public emulation has it).
|
||||
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
|
||||
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
|
||||
// -0 gives -infinity.
|
||||
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
|
||||
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
|
||||
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_switched_off_and_a_missing_child_return_none() {
|
||||
let node = box32(
|
||||
[8, NONE, 24, 32],
|
||||
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
|
||||
);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
// Child 1 is hit but is not there: its pointer is what "none" is.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_distances_keep_child_order() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT; 4]);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_float_boxes_test_like_their_widened_values() {
|
||||
let boxes = [
|
||||
moved(UNIT, [30.0, 0.1, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.3]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.7, 0.0, 0.0]),
|
||||
];
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
let node = box16(children, boxes);
|
||||
let wide = boxes16(&node);
|
||||
for (w, b) in wide.iter().zip(&boxes) {
|
||||
for k in 0..3 {
|
||||
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
|
||||
}
|
||||
}
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
assert_eq!(
|
||||
intersect(&node, 4, &ray, true),
|
||||
intersect(&box32(children, wide), 5, &ray, true)
|
||||
);
|
||||
}
|
||||
|
||||
/// The hit a result describes: distance, I, J, front face.
|
||||
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
|
||||
let [t, det, i, j] = r.map(f32::from_bits);
|
||||
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
|
||||
}
|
||||
|
||||
/// Clockwise seen from the origin looking down +z in a left-handed
|
||||
/// system (x right, y up): the front face.
|
||||
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
|
||||
#[test]
|
||||
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!(t, 5.0);
|
||||
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
|
||||
assert_eq!((i, j), (0.25, 0.25));
|
||||
assert!(front);
|
||||
// Near vertex 1: I near 1.
|
||||
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert!(i > 0.85 && j < 0.1, "{i} {j}");
|
||||
// From behind: the same weights, the back face.
|
||||
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
|
||||
// An unnormalised direction: the distance is in its units.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
|
||||
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triangle_is_missed_beside_behind_and_edge_on() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let miss = MISS.map(f32::to_bits);
|
||||
// Beside it.
|
||||
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// It lies behind the origin.
|
||||
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// In its plane.
|
||||
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// A triangle with no area.
|
||||
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
|
||||
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&flat, 0, &ray, true), miss);
|
||||
// A vertex that is not a number, a direction of zero.
|
||||
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&nan, 0, &ray, true), miss);
|
||||
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &still, true), miss);
|
||||
// The extent is the program's to test: a far triangle is a hit.
|
||||
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
|
||||
assert!(hit(intersect(&node, 0, &short, true)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
|
||||
// Two triangles of a quad sharing the diagonal, wound alike.
|
||||
let quad = [
|
||||
[-1.0, -1.0, 4.0],
|
||||
[-1.0, 1.0, 4.0],
|
||||
[1.0, 1.0, 4.0],
|
||||
[1.0, -1.0, 4.0],
|
||||
];
|
||||
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
|
||||
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
|
||||
// A fan of rays crossing the diagonal, some exactly on it.
|
||||
for n in -40..=40 {
|
||||
let x = n as f32 / 64.0;
|
||||
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
|
||||
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
|
||||
// Aim at (ox, oy, 4).
|
||||
let s = 4.0 / d[2];
|
||||
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
|
||||
let a = hit(intersect(&first, 0, &ray, true));
|
||||
let b = hit(intersect(&second, 0, &ray, true));
|
||||
assert!(
|
||||
a.is_some() || b.is_some(),
|
||||
"a hole at {ox} {oy} along {d:?}"
|
||||
);
|
||||
for h in [a, b].into_iter().flatten() {
|
||||
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
|
||||
// What the title's builder does with an input triangle (a, b, c)
|
||||
// and an id byte: a at the vertex neither field names, b at I's,
|
||||
// c at J's.
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
|
||||
let mut stored = [[0f32; 3]; 3];
|
||||
stored[(3 - i - j) as usize] = a;
|
||||
stored[i as usize] = b;
|
||||
stored[j as usize] = c;
|
||||
let node = triangles(&stored, i | j << 2);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
|
||||
}
|
||||
// The higher bits of the byte (opaque and the like) change nothing.
|
||||
let node = triangles(&[a, b, c], 9 | 0x80);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let far = [50.0, 50.0, 50.0];
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for k in 1..4u32 {
|
||||
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
|
||||
let mut vertices = [far; 5];
|
||||
let at = TRIANGLE_VERTICES[k as usize];
|
||||
vertices[at[0] as usize] = a;
|
||||
vertices[at[1] as usize] = b;
|
||||
vertices[at[2] as usize] = c;
|
||||
// Triangle 0's byte would be malformed here; only byte k counts.
|
||||
let node = triangles(&vertices, 9 << (8 * k));
|
||||
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
|
||||
}
|
||||
// A pair as the title's builder stores it: the second triangle's
|
||||
// own vertex at node vertex 3, named by I.
|
||||
let d = [2.0, 2.0, 5.0];
|
||||
// Input triangles (a, b, c) and (a, d, b): they share a and b.
|
||||
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
|
||||
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
|
||||
let got = triangle_vertices(&node, 1);
|
||||
assert_eq!(got, [b, d, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_and_procedural_nodes_return_a_triangle_miss() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
for k in [6, 7] {
|
||||
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
|
||||
// The same triangle and ray turned so the ray's largest axis is each
|
||||
// of the three, forwards and backwards. Both turns are rotations,
|
||||
// so the facing stays.
|
||||
let turn = |v: [f32; 3], axis: usize, flip: bool| {
|
||||
let mut r = v;
|
||||
for _ in 0..axis {
|
||||
r = [r[2], r[0], r[1]];
|
||||
}
|
||||
if flip {
|
||||
// Half a turn about the axis after the largest one's next.
|
||||
let largest = (2 + axis) % 3;
|
||||
r[largest] = -r[largest];
|
||||
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
|
||||
}
|
||||
r
|
||||
};
|
||||
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
|
||||
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
|
||||
for axis in 0..3 {
|
||||
for flip in [false, true] {
|
||||
let p = TRIANGLE.map(|v| turn(v, axis, flip));
|
||||
let r = Ray::new(
|
||||
turn(ray.origin, axis, flip),
|
||||
turn(ray.direction, axis, flip),
|
||||
100.0,
|
||||
);
|
||||
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
|
||||
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
|
||||
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
|
||||
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! The DXBC container: a header, then a table of FourCC-tagged parts.
|
||||
//!
|
||||
//! ```text
|
||||
//! 0x00 "DXBC"
|
||||
//! 0x04 digest[16]
|
||||
//! 0x14 version major u16, minor u16
|
||||
//! 0x18 total size u32
|
||||
//! 0x1C part count u32
|
||||
//! 0x20 part offsets u32[count]
|
||||
//! part: fourcc[4], size u32, data[size]
|
||||
//! ```
|
||||
|
||||
use crate::ShaderError;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct FourCC(pub [u8; 4]);
|
||||
|
||||
impl FourCC {
|
||||
pub const DXIL: FourCC = FourCC(*b"DXIL");
|
||||
pub const STAT: FourCC = FourCC(*b"STAT");
|
||||
pub const RTS0: FourCC = FourCC(*b"RTS0");
|
||||
pub const PSV0: FourCC = FourCC(*b"PSV0");
|
||||
pub const ISG1: FourCC = FourCC(*b"ISG1");
|
||||
pub const OSG1: FourCC = FourCC(*b"OSG1");
|
||||
/// Per-primitive outputs of a mesh shader.
|
||||
pub const PSG1: FourCC = FourCC(*b"PSG1");
|
||||
pub const SFI0: FourCC = FourCC(*b"SFI0");
|
||||
pub const HASH: FourCC = FourCC(*b"HASH");
|
||||
pub const ILDB: FourCC = FourCC(*b"ILDB");
|
||||
pub const ILDN: FourCC = FourCC(*b"ILDN");
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FourCC {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FourCC {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for &b in &self.0 {
|
||||
let c = if b.is_ascii_graphic() { b as char } else { '.' };
|
||||
write!(f, "{c}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Part<'a> {
|
||||
pub fourcc: FourCC,
|
||||
/// Offset of the part header within the container.
|
||||
pub offset: usize,
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Container<'a> {
|
||||
pub digest: [u8; 16],
|
||||
pub version: (u16, u16),
|
||||
pub parts: Vec<Part<'a>>,
|
||||
}
|
||||
|
||||
const HEADER_SIZE: usize = 0x20;
|
||||
const MAX_PARTS: usize = 256;
|
||||
|
||||
impl<'a> Container<'a> {
|
||||
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
|
||||
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
|
||||
return Err(ShaderError::NotDxbc);
|
||||
}
|
||||
let digest = data[4..20].try_into().expect("16 bytes");
|
||||
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
|
||||
let total = u32_at(data, 0x18)? as usize;
|
||||
if total > data.len() || total < HEADER_SIZE {
|
||||
return Err(ShaderError::Malformed("container size disagrees with data"));
|
||||
}
|
||||
let data = &data[..total];
|
||||
let count = u32_at(data, 0x1C)? as usize;
|
||||
if count > MAX_PARTS {
|
||||
return Err(ShaderError::Malformed("implausible part count"));
|
||||
}
|
||||
let mut parts = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
|
||||
let fourcc = FourCC(
|
||||
data.get(offset..offset + 4)
|
||||
.ok_or(ShaderError::Malformed("part header out of bounds"))?
|
||||
.try_into()
|
||||
.expect("4 bytes"),
|
||||
);
|
||||
let size = u32_at(data, offset + 4)? as usize;
|
||||
let body = data
|
||||
.get(offset + 8..offset + 8 + size)
|
||||
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
|
||||
parts.push(Part {
|
||||
fourcc,
|
||||
offset,
|
||||
data: body,
|
||||
});
|
||||
}
|
||||
Ok(Container {
|
||||
digest,
|
||||
version,
|
||||
parts,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
|
||||
self.parts.iter().find(|p| p.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
|
||||
data.get(at..at + 2)
|
||||
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
|
||||
data.get(at..at + 4)
|
||||
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
|
||||
data.get(at..at + 8)
|
||||
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
/// Builds a container from parts (test helper).
|
||||
#[cfg(test)]
|
||||
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
|
||||
let table = HEADER_SIZE + 4 * parts.len();
|
||||
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend_from_slice(b"DXBC");
|
||||
out.extend_from_slice(&[0; 16]);
|
||||
out.extend_from_slice(&1u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&(total as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
|
||||
let mut offset = table;
|
||||
for (_, d) in parts {
|
||||
out.extend_from_slice(&(offset as u32).to_le_bytes());
|
||||
offset += 8 + d.len();
|
||||
}
|
||||
for (fourcc, d) in parts {
|
||||
out.extend_from_slice(&fourcc.0);
|
||||
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(d);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_parts() {
|
||||
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
assert_eq!(c.parts.len(), 2);
|
||||
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
|
||||
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
|
||||
assert!(c.part(FourCC::DXIL).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
|
||||
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
|
||||
let last = bytes.len() - 1;
|
||||
bytes[0x20] = 0xFF; // corrupt the first part offset
|
||||
assert!(Container::parse(&bytes).is_err());
|
||||
bytes.truncate(last);
|
||||
assert!(Container::parse(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
|
||||
//!
|
||||
//! ```text
|
||||
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
|
||||
//! 0x04 size in dwords u32
|
||||
//! 0x08 "DXIL" <- bitcode offset is relative to here
|
||||
//! 0x0C dxil version u32
|
||||
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
|
||||
//! 0x14 bitcode size u32
|
||||
//! ```
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::u32_at;
|
||||
|
||||
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
|
||||
#[cfg(test)]
|
||||
const STANDARD_BITCODE_OFFSET: u32 = 16;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ShaderKind {
|
||||
Pixel,
|
||||
Vertex,
|
||||
Geometry,
|
||||
Hull,
|
||||
Domain,
|
||||
Compute,
|
||||
Library,
|
||||
RayGeneration,
|
||||
Intersection,
|
||||
AnyHit,
|
||||
ClosestHit,
|
||||
Miss,
|
||||
Callable,
|
||||
Mesh,
|
||||
Amplification,
|
||||
Node,
|
||||
Unknown(u16),
|
||||
}
|
||||
|
||||
impl ShaderKind {
|
||||
fn from_raw(v: u16) -> Self {
|
||||
use ShaderKind::*;
|
||||
match v {
|
||||
0 => Pixel,
|
||||
1 => Vertex,
|
||||
2 => Geometry,
|
||||
3 => Hull,
|
||||
4 => Domain,
|
||||
5 => Compute,
|
||||
6 => Library,
|
||||
7 => RayGeneration,
|
||||
8 => Intersection,
|
||||
9 => AnyHit,
|
||||
10 => ClosestHit,
|
||||
11 => Miss,
|
||||
12 => Callable,
|
||||
13 => Mesh,
|
||||
14 => Amplification,
|
||||
15 => Node,
|
||||
other => Unknown(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DxilProgram<'a> {
|
||||
pub kind: ShaderKind,
|
||||
pub shader_model: (u8, u8),
|
||||
pub dxil_version: u32,
|
||||
/// LLVM bitcode (starts with `BC C0 DE`).
|
||||
pub bitcode: &'a [u8],
|
||||
/// Bytes between the bitcode header and the bitcode. Empty on PC.
|
||||
pub prefix: &'a [u8],
|
||||
/// Bytes after the bitcode, up to the program size. Empty on PC.
|
||||
pub trailer: &'a [u8],
|
||||
}
|
||||
|
||||
/// Xbox additions recognised around the bitcode.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct XboxExtras {
|
||||
/// The prefix starts with an `XDAT` table.
|
||||
pub xdat: bool,
|
||||
/// The trailer contains an `xbop` blob (compiler options).
|
||||
pub xbop: bool,
|
||||
}
|
||||
|
||||
impl<'a> DxilProgram<'a> {
|
||||
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
|
||||
let version = u32_at(part, 0)?;
|
||||
let size = (u32_at(part, 4)? as usize)
|
||||
.checked_mul(4)
|
||||
.filter(|&s| s <= part.len() && s >= 24)
|
||||
.ok_or(ShaderError::Malformed(
|
||||
"program size disagrees with part size",
|
||||
))?;
|
||||
let part = &part[..size];
|
||||
if part.get(8..12) != Some(b"DXIL") {
|
||||
return Err(ShaderError::Malformed("missing DXIL magic"));
|
||||
}
|
||||
let dxil_version = u32_at(part, 12)?;
|
||||
let offset = u32_at(part, 16)?;
|
||||
let len = u32_at(part, 20)? as usize;
|
||||
let start = 8 + offset as usize;
|
||||
let bitcode = part
|
||||
.get(start..start + len)
|
||||
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
|
||||
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
|
||||
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
|
||||
}
|
||||
let prefix = part
|
||||
.get(24..start)
|
||||
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
|
||||
Ok(DxilProgram {
|
||||
kind: ShaderKind::from_raw((version >> 16) as u16),
|
||||
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
|
||||
dxil_version,
|
||||
bitcode,
|
||||
prefix,
|
||||
trailer: &part[start + len..],
|
||||
})
|
||||
}
|
||||
|
||||
/// True for a program laid out exactly like PC DXIL.
|
||||
pub fn is_standard_layout(&self) -> bool {
|
||||
self.prefix.is_empty() && self.trailer.is_empty()
|
||||
}
|
||||
|
||||
pub fn xbox_extras(&self) -> XboxExtras {
|
||||
XboxExtras {
|
||||
xdat: self.prefix.starts_with(b"XDAT"),
|
||||
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a standard PC-layout program around `bitcode` (test helper).
|
||||
#[cfg(test)]
|
||||
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
|
||||
let padded = bitcode.len().next_multiple_of(4);
|
||||
let size_dwords = (24 + padded) / 4;
|
||||
out.extend_from_slice(&version.to_le_bytes());
|
||||
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
|
||||
out.extend_from_slice(b"DXIL");
|
||||
out.extend_from_slice(&dxil_version.to_le_bytes());
|
||||
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
|
||||
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(bitcode);
|
||||
out.resize(24 + padded, 0);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fake_bitcode() -> Vec<u8> {
|
||||
let mut b = LLVM_BITCODE_MAGIC.to_vec();
|
||||
b.extend_from_slice(&[0xAA; 12]);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_standard_layout() {
|
||||
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
|
||||
let p = DxilProgram::parse(&bytes).unwrap();
|
||||
assert_eq!(p.kind, ShaderKind::Pixel);
|
||||
assert_eq!(p.shader_model, (6, 0));
|
||||
assert!(p.is_standard_layout());
|
||||
assert_eq!(p.xbox_extras(), XboxExtras::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_xbox_layout() {
|
||||
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
|
||||
let bitcode = fake_bitcode();
|
||||
let xdat = b"XDAT\x01\x00\x00\x00";
|
||||
let trailer = b"xbop\x02\x00\x00\x00";
|
||||
let mut bytes = Vec::new();
|
||||
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
|
||||
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
|
||||
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(b"DXIL");
|
||||
bytes.extend_from_slice(&0x105u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(xdat);
|
||||
bytes.extend_from_slice(&bitcode);
|
||||
bytes.extend_from_slice(trailer);
|
||||
|
||||
let p = DxilProgram::parse(&bytes).unwrap();
|
||||
assert_eq!(p.kind, ShaderKind::Compute);
|
||||
assert_eq!(p.shader_model, (6, 5));
|
||||
assert!(!p.is_standard_layout());
|
||||
assert_eq!(
|
||||
p.xbox_extras(),
|
||||
XboxExtras {
|
||||
xdat: true,
|
||||
xbop: true
|
||||
}
|
||||
);
|
||||
assert_eq!(p.bitcode, &bitcode[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_bitcode_magic() {
|
||||
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
|
||||
assert!(DxilProgram::parse(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen addition to the vendored victory-shader crate (see ../../UPSTREAM.md): a public
|
||||
// entry point for a raw compute program, with the same stages `translate` runs for a container.
|
||||
|
||||
use super::{HostShader, lower};
|
||||
use crate::native::{HwStage, NativeProgram};
|
||||
use crate::{ShaderError, io, resource, spill, structure};
|
||||
|
||||
/// Translates a compute program that is already a [`NativeProgram`] (machine code plus its
|
||||
/// root layout) instead of one stored in a console shader container. Only the compute stage is
|
||||
/// accepted: graphics stages need signatures that only a container carries.
|
||||
pub fn translate_native(native: &NativeProgram) -> Result<HostShader, ShaderError> {
|
||||
if native.stage != HwStage::Cs {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "translate_native takes compute programs only",
|
||||
});
|
||||
}
|
||||
// (what an earlier program's lowering on this thread left behind)
|
||||
lower::take_needs();
|
||||
let p = spill::build(native)?;
|
||||
let st = structure::structure(&p);
|
||||
let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
|
||||
let io = io::raise(&p, native)?;
|
||||
let st = st?;
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
Ok(HostShader {
|
||||
stage: native.stage,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
static_samplers: super::static_samplers(&lowered.samplers, lowered.cmp_samplers),
|
||||
samplers: lowered.samplers,
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen tests for the vendored victory-shader crate (see ../../UPSTREAM.md).
|
||||
//
|
||||
// BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled
|
||||
// with LLVM's llvm-mc) are translated to DXIL by the vendored recompiler. Their expected output
|
||||
// words come from `fixtures/manifest.toml`, derived by hand there and checked by BetterXen's own
|
||||
// independent reference; nothing in this file derives an expectation from the recompiler.
|
||||
//
|
||||
// Fixture ABI (docs/interfaces.md): v0 = grid index, V# of the input buffer in s[0:3], of the
|
||||
// output buffer in s[4:7]. The vendored recompiler instead gets descriptors from a table, so
|
||||
// the program is wrapped in a prologue that loads both from a descriptor table into s[0:3] and
|
||||
// s[4:7] and then continues into the fixture's code unchanged.
|
||||
|
||||
use super::translate_native;
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
|
||||
const MANIFEST: &str = include_str!("../../../../fixtures/manifest.toml");
|
||||
|
||||
/// Fixtures that bind an input and an output buffer and have expected words in the manifest.
|
||||
/// Keyed by the file name in the manifest's `path`.
|
||||
const BINARIES: &[(&str, &[u8])] = &[
|
||||
("add.bin", include_bytes!("../../../../fixtures/rdna2/add.bin")),
|
||||
("float-exact.bin", include_bytes!("../../../../fixtures/rdna2/float-exact.bin")),
|
||||
("bitwise-branch.bin", include_bytes!("../../../../fixtures/rdna2/bitwise-branch.bin")),
|
||||
("or.bin", include_bytes!("../../../../fixtures/rdna2/or.bin")),
|
||||
("shifts.bin", include_bytes!("../../../../fixtures/rdna2/shifts.bin")),
|
||||
("ashr.bin", include_bytes!("../../../../fixtures/rdna2/ashr.bin")),
|
||||
];
|
||||
|
||||
struct Fixture {
|
||||
id: String,
|
||||
code: &'static [u8],
|
||||
input: Vec<u32>,
|
||||
expected: Vec<u32>,
|
||||
}
|
||||
|
||||
fn words(line: &str) -> Vec<u32> {
|
||||
line.trim()
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.split(',')
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.map(|t| t.trim().parse().expect("a decimal word"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fixtures with input and expected words in the manifest. A fixture the manifest lists with
|
||||
/// expected words but that is not embedded above fails the test instead of being skipped.
|
||||
fn fixtures() -> Vec<Fixture> {
|
||||
let mut out = Vec::new();
|
||||
for block in MANIFEST.split("[[fixture]]").skip(1) {
|
||||
let get = |key: &str| {
|
||||
block
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix(&format!("{key} = ")))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let (Some(input), Some(expected)) = (get("input"), get("expected")) else { continue };
|
||||
let (input, expected) = (words(&input), words(&expected));
|
||||
if input.is_empty() || expected.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let id = get("id").unwrap().trim_matches('"').to_owned();
|
||||
let path = get("path").unwrap().trim_matches('"').to_owned();
|
||||
let name = path.rsplit('/').next().unwrap();
|
||||
let code = BINARIES
|
||||
.iter()
|
||||
.find(|(n, _)| *n == name)
|
||||
.unwrap_or_else(|| panic!("fixture {id} ({name}) is in the manifest but not embedded"))
|
||||
.1;
|
||||
out.push(Fixture { id, code, input, expected });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `s_mov_b32 sdst, 0` (inline constant 0 is source 0x80).
|
||||
const fn s_mov_b32_zero(sdst: u32) -> u32 {
|
||||
0xBE80_0000 | sdst << 16 | 0x03 << 8 | 0x80
|
||||
}
|
||||
|
||||
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
|
||||
const fn s_load_dwordx4(dst: u32, base: u32, byte_offset: u32) -> [u32; 2] {
|
||||
[0x3D << 26 | 0x02 << 18 | dst << 6 | base >> 1, 125 << 25 | byte_offset]
|
||||
}
|
||||
|
||||
/// `s_waitcnt lgkmcnt(0)` with the other counters left alone.
|
||||
const S_WAITCNT_LGKM0: u32 = 0xBF8C_C07F;
|
||||
|
||||
/// Wraps a fixture so its descriptors arrive through a descriptor table. The table's two
|
||||
/// 32-byte slots hold the input SRV (heap index 0) and the output UAV (heap index 1).
|
||||
fn program(code: &[u8], threads: u32) -> NativeProgram {
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(s_mov_b32_zero(9)); // upper half of the table address; the lower half is user data s8
|
||||
w.extend(s_load_dwordx4(0, 8, 0x00)); // input V# -> s[0:3]
|
||||
w.extend(s_load_dwordx4(4, 8, 0x20)); // output V# -> s[4:7]
|
||||
w.push(S_WAITCNT_LGKM0);
|
||||
let mut bytes: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
bytes.extend_from_slice(code);
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![
|
||||
UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
|
||||
dwords: 4,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
},
|
||||
UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 8,
|
||||
lower_bound: 0,
|
||||
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
|
||||
dwords: 4,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
},
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 9 << 1, threads: [threads, 1, 1] }),
|
||||
code: bytes,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_embedded_fixture_is_listed_in_the_manifest() {
|
||||
let listed = fixtures();
|
||||
assert_eq!(listed.len(), BINARIES.len(), "embedded list and manifest disagree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_translate_to_a_dxil_container() {
|
||||
for f in fixtures() {
|
||||
assert!(!f.expected.is_empty(), "{}: no expected words", f.id);
|
||||
let native = program(f.code, f.input.len() as u32);
|
||||
let shader = translate_native(&native)
|
||||
.unwrap_or_else(|e| panic!("{}: translate_native failed: {e}", f.id));
|
||||
assert_eq!(&shader.dxil[..4], b"DXBC", "{}: not a DXBC/DXIL container", f.id);
|
||||
assert!(shader.dxil.len() > 100, "{}: container too small", f.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod on_the_gpu {
|
||||
use super::*;
|
||||
use crate::emit::host::{Dispatch, Host, Root, Stride, View};
|
||||
|
||||
fn run_on_gpu(host: &Host, f: &Fixture) -> Vec<u32> {
|
||||
let shader = translate_native(&program(f.code, f.input.len() as u32)).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
// The table parameter's value is the heap offset: both views start at heap index 0.
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[
|
||||
View::Buffer { data: &f.input, stride: Stride::Raw },
|
||||
View::RawUav(f.input.len() as u32),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{}: dispatch failed: {e}", f.id));
|
||||
out[0][..f.expected.len()].to_vec()
|
||||
}
|
||||
|
||||
/// Runs each fixture on the default D3D12 device and compares every output word with the
|
||||
/// manifest. If no suitable device exists the test fails loudly rather than passing: a
|
||||
/// skipped run is not GPU verification.
|
||||
#[test]
|
||||
fn fixtures_on_the_default_d3d12_device_match_the_manifest() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let mut ran = 0;
|
||||
for f in fixtures() {
|
||||
let got = run_on_gpu(&host, &f);
|
||||
assert_eq!(got, f.expected, "{}: output words differ from the manifest", f.id);
|
||||
eprintln!("betterxen fixture {} ran on the GPU and matched the manifest", f.id);
|
||||
ran += 1;
|
||||
}
|
||||
assert_eq!(ran, fixtures().len());
|
||||
}
|
||||
|
||||
/// Negative control: the comparison above must be able to fail. A copy of each expected
|
||||
/// output with one bit flipped must not equal what the GPU produced, and the output must
|
||||
/// not be the untouched zeroed buffer or an echo of the input (unless the manifest says so).
|
||||
#[test]
|
||||
fn a_wrong_expectation_is_detected() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
for f in fixtures() {
|
||||
let got = run_on_gpu(&host, &f);
|
||||
let mut wrong = f.expected.clone();
|
||||
wrong[0] ^= 1;
|
||||
assert_ne!(got, wrong, "{}: a flipped expectation was accepted", f.id);
|
||||
assert!(got.iter().any(|&w| w != 0) || f.expected.iter().all(|&w| w == 0), "{}: output is the zeroed buffer", f.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- f64 whole-wave sum (research/shader-wave-semantics) --------------------------------------
|
||||
//
|
||||
// The console's whole-wave f64 sum, as `valu_tests::whole_wave_f64_sum_and_cvt_f32_f64` builds it,
|
||||
// but storing both words of the f64 result instead of converting to f32, so all 64 bits are
|
||||
// compared. Upstream lowered it to a native `double` wave operation, which D3DMetal does not run
|
||||
// (docs/research/shader-wave-semantics.md); it is now done with the integer fp64 add.
|
||||
// Expected results come from a CPU model of the balanced tree over the lanes in their order
|
||||
// (lanes 2k and 2k+1, then pairs, ...) with the CPU's own f64 additions, `+0.0` for lanes that
|
||||
// are not launched; nothing is taken from the recompiler.
|
||||
|
||||
const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
|
||||
0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
[
|
||||
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
|
||||
]
|
||||
}
|
||||
|
||||
const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] {
|
||||
[
|
||||
0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF),
|
||||
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8,
|
||||
]
|
||||
}
|
||||
|
||||
/// A one-group compute program over `threads` threads: each lane's f64 is root constants
|
||||
/// `(s0, s1)`; the program sums the wave and stores the sum's low then high word to the UAV.
|
||||
fn f64_wave_sum_program(threads: u32) -> NativeProgram {
|
||||
let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)];
|
||||
let v_mov_row_mirror = |vdst: u8, vsrc: u8| {
|
||||
[
|
||||
vop1(0x001, vdst, 0xFA),
|
||||
vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28),
|
||||
]
|
||||
};
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(0xBE80_0000 | 5 << 16 | 0x03 << 8 | 0x80); // s_mov_b32 s5, 0 (table address high)
|
||||
w.extend_from_slice(&[0x3D << 26 | 0x02 << 18 | 8 << 6 | (4 >> 1), 125 << 25]); // s_load_dwordx4 s[8:11], s[4:5], 0
|
||||
w.push(vop1(0x001, 6, 0)); // v_mov_b32 v6, s0
|
||||
w.push(vop1(0x001, 7, 1)); // v_mov_b32 v7, s1
|
||||
w.push(0xBE80_0000 | 12 << 16 | 0x3D << 8 | 0xC1); // s_or_saveexec_b32 s12, -1
|
||||
w.extend_from_slice(&vop3(0x101, 2, 0x80, 256 + 6, 12));
|
||||
w.extend_from_slice(&vop3(0x101, 3, 0x80, 256 + 7, 12));
|
||||
for sel in [14570689u32, 9658386, 2340] {
|
||||
w.extend_from_slice(&v_mov_dpp8(4, 2, sel));
|
||||
w.extend_from_slice(&v_mov_dpp8(5, 3, sel));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); // v_add_f64
|
||||
}
|
||||
w.extend_from_slice(&v_mov_row_mirror(4, 2));
|
||||
w.extend_from_slice(&v_mov_row_mirror(5, 3));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
|
||||
w.extend_from_slice(&vop3(0x378, 4, 256 + 2, 0x80, 0x80)); // v_permlanex16_b32
|
||||
w.extend_from_slice(&vop3(0x378, 5, 256 + 3, 0x80, 0x80));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
|
||||
w.extend_from_slice(&vop3(0x360, 14, 256 + 2, 0x80, 0)); // v_readlane_b32 s14, v2, 0
|
||||
w.extend_from_slice(&vop3(0x360, 15, 256 + 3, 0x80, 0)); // v_readlane_b32 s15, v3, 0
|
||||
w.push(0xBE80_0000 | 16 << 16 | 0x03 << 8 | 14); // s_mov_b32 s16, s14
|
||||
w.push(0xBE80_0000 | 17 << 16 | 0x03 << 8 | 15); // s_mov_b32 s17, s15
|
||||
w.push(0xBE80_0000 | 126 << 16 | 0x03 << 8 | 12); // s_mov_b32 exec_lo, s12
|
||||
w.push(vop1(0x001, 0, 16)); // v_mov_b32 v0, s16 (low word)
|
||||
w.extend_from_slice(&buffer_store_dword(0, 8, 0));
|
||||
w.push(vop1(0x001, 0, 17)); // v_mov_b32 v0, s17 (high word)
|
||||
w.extend_from_slice(&buffer_store_dword(0, 8, 4));
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
let param = |root, sgprs, user_data, slot| RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 12,
|
||||
layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [threads, 1, 1] }),
|
||||
code,
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU model: the balanced tree over 32 lanes, the first `launched` holding `x`, the rest `+0.0`.
|
||||
fn tree_sum(x: f64, launched: usize) -> f64 {
|
||||
let mut v: Vec<f64> = (0..32).map(|l| if l < launched { x } else { 0.0 }).collect();
|
||||
while v.len() > 1 {
|
||||
v = v.chunks(2).map(|p| p[0] + p[1]).collect();
|
||||
}
|
||||
v[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_f64_wave_sum_is_lowered_without_native_doubles() {
|
||||
let shader = translate_native(&f64_wave_sum_program(4)).expect("translate");
|
||||
let c = crate::dxbc::Container::parse(&shader.dxil).expect("container");
|
||||
let sfi0 = c.part(crate::dxbc::FourCC::SFI0).expect("SFI0 part").data;
|
||||
let features = u64::from_le_bytes(sfi0[..8].try_into().unwrap());
|
||||
assert_ne!(features & 0x4000, 0, "the sum uses wave operations (sanity check of this parse)");
|
||||
assert_eq!(features & 0x1, 0, "no native double may be declared: D3DMetal does not run them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cpu_model_is_the_balanced_tree() {
|
||||
// 4 lanes of 1.25: (1.25 + 1.25) twice, then 2.5 + 2.5, then the rest +0
|
||||
assert_eq!(tree_sum(1.25, 4), 5.0);
|
||||
assert_eq!(tree_sum(1.25, 32), 40.0);
|
||||
// the order matters for values that round: this is not the sequential sum
|
||||
let x = 0.1;
|
||||
let sequential: f64 = (0..32).fold(0.0, |a, _| a + x);
|
||||
assert_ne!(tree_sum(x, 32).to_bits(), sequential.to_bits());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod f64_on_the_gpu {
|
||||
use super::*;
|
||||
use crate::emit::host::{Dispatch, Host, Root, View};
|
||||
|
||||
/// Whole-wave f64 sums on the default D3D12 device, all 64 bits compared with the CPU model,
|
||||
/// for full and partial waves and for values that round. Fails when there is no device.
|
||||
#[test]
|
||||
fn f64_wave_sums_match_the_cpu_tree_bit_for_bit() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let mut ran = 0;
|
||||
for threads in [1u32, 4, 20, 32] {
|
||||
let shader = translate_native(&f64_wave_sum_program(threads)).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
for x in [1.25f64, 0.1, -3.75e10, 1.0e-300, 123456.789, f64::from_bits(0x3FF0_0000_0000_0001)] {
|
||||
let b = x.to_bits();
|
||||
let inputs = [b as u32, (b >> 32) as u32, 0, 0];
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
ud[u.index as usize] = match (u.root, u.slot) {
|
||||
(RootType::Constants, 0) => inputs[u.dword as usize],
|
||||
(RootType::Table, 1) => 0,
|
||||
other => panic!("unexpected user data {other:?}"),
|
||||
};
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(2)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
let got = u64::from(out[0][0]) | u64::from(out[0][1]) << 32;
|
||||
let want = tree_sum(x, threads as usize).to_bits();
|
||||
assert_eq!(got, want, "{threads} threads of {x:e}: got {got:#018x}, want {want:#018x}");
|
||||
ran += 1;
|
||||
}
|
||||
}
|
||||
eprintln!("betterxen: {ran} f64 wave sums ran on the GPU and matched the CPU tree bit for bit");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- immediate samplers through translate_native ---------------------------------------------
|
||||
//
|
||||
// A compute program that builds its sampler from constants in the code (an immediate sampler)
|
||||
// needs a static sampler in the host's root signature. `translate_native` must report it, as the
|
||||
// container path does; the buffer-only fixtures above cannot notice.
|
||||
|
||||
/// Samples texel (0.5, 0.5) of the 2D texture in table slot 0 with an immediate sampler and stores
|
||||
/// the red channel to the raw UAV in table slot 1.
|
||||
fn immediate_sampler_program() -> NativeProgram {
|
||||
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
|
||||
let smem = |op: u32, dst: u32, base: u32, off: u32| [0x3D << 26 | op << 18 | dst << 6 | base >> 1, 125 << 25 | off];
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(0xBE80_0300 | 2 << 16); // s_mov_b32 s2, s0 (table address)
|
||||
w.push(0xBE80_0380 | 3 << 16); // s_mov_b32 s3, 0
|
||||
w.extend(smem(0x03, 8, 2, 0)); // s_load_dwordx8 s[8:15]: the texture SRV
|
||||
w.extend(smem(0x02, 20, 2, 32)); // s_load_dwordx4 s[20:23]: the UAV
|
||||
w.push(0x7E00_02F0 | 2 << 17); // v_mov_b32 v2, 0.5
|
||||
w.push(0x7E00_02F0 | 3 << 17); // v_mov_b32 v3, 0.5
|
||||
for (i, word) in [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0].into_iter().enumerate() {
|
||||
w.extend(s_mov_lit(16 + i as u8, word)); // s[16:19]: the sampler, as constants
|
||||
}
|
||||
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:2D
|
||||
w.extend([0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, (16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2]);
|
||||
w.extend([0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8]); // buffer_store_dword v4
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let used = |kind, table_offset_dwords, dwords| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![used(ResourceType::Srv, 0, 8), used(ResourceType::Uav, 8, 4)],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 1 << 1, threads: [1, 1, 1] }),
|
||||
code: w.iter().flat_map(|x| x.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translate_native_reports_immediate_samplers_as_static_samplers() {
|
||||
let shader = translate_native(&immediate_sampler_program()).expect("translate");
|
||||
assert_eq!(shader.samplers.len(), 1, "the program has one immediate sampler");
|
||||
assert_eq!(shader.static_samplers.len(), 1, "the host builds s0 from this list");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn immediate_sampler_samples_the_texture_on_the_gpu() {
|
||||
use crate::emit::host::{Dispatch, Host, Root, View};
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let shader = translate_native(&immediate_sampler_program()).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let texels = [[0.25f32, 0.5, 0.75, 1.0]];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::Texture(1, 1, &texels), View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.expect("dispatch");
|
||||
assert_eq!(out[0][0], 0.25f32.to_bits(), "red of the only texel");
|
||||
eprintln!("betterxen: the immediate-sampler program sampled the texture on the GPU");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_samplers_keep_the_comparison_filter_flag() {
|
||||
let words = [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0];
|
||||
let list = super::static_samplers(&[words, words], 0b10);
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list[0].filter & 0x80, 0, "sampler 0 is not a comparison sampler");
|
||||
assert_ne!(list[1].filter & 0x80, 0, "sampler 1 is");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,174 @@
|
||||
//! Counts of a module's instructions by kind (a diagnostic): what a
|
||||
//! translated program costs before the driver's compiler sees it.
|
||||
//!
|
||||
//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of
|
||||
//! the module a thread wrote last are read with [`take`]. The `translate`
|
||||
//! command writes them as a table (see `apps/victory/src/translate.rs`).
|
||||
|
||||
use super::{Cast, Module, Op, Tag, Term, V};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// The kinds, in the order of [`Census::counts`].
|
||||
pub const KINDS: [&str; 26] = [
|
||||
"total",
|
||||
"arith",
|
||||
"math_call",
|
||||
"bitcast",
|
||||
"cast",
|
||||
"select",
|
||||
"guard_select",
|
||||
"phi",
|
||||
"extract",
|
||||
"buffer_load",
|
||||
"cbuffer_load",
|
||||
"texture_read",
|
||||
"lds_load",
|
||||
"buffer_store",
|
||||
"lds_store",
|
||||
"atomic",
|
||||
"handle",
|
||||
"annotate",
|
||||
"dimensions",
|
||||
"barrier",
|
||||
"wave_op",
|
||||
"io_other",
|
||||
"gep",
|
||||
"clamp",
|
||||
"loop_counter",
|
||||
"blocks",
|
||||
];
|
||||
|
||||
/// Instruction counts of one written module, by [`KINDS`].
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Census {
|
||||
pub counts: [u32; KINDS.len()],
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The modules this thread wrote since the last [`take`]: the length and
|
||||
/// a hash of each one's bitcode, with its counts (a program may be
|
||||
/// emitted in several forms before one is kept).
|
||||
static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set).
|
||||
pub fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some())
|
||||
}
|
||||
|
||||
/// The counts of the module whose bitcode the container `dxil` holds, if
|
||||
/// this thread wrote it since the last call (which forgets the others).
|
||||
pub fn take(dxil: &[u8]) -> Option<Census> {
|
||||
let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut()));
|
||||
let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
|
||||
written
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash))
|
||||
.map(|w| w.2)
|
||||
}
|
||||
|
||||
/// Counts `m`, whose written form is `bitcode`, and keeps the result for
|
||||
/// [`take`].
|
||||
pub(crate) fn note(m: &Module, bitcode: &[u8]) {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let c = m.census();
|
||||
WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c)));
|
||||
}
|
||||
|
||||
fn kind(name: &str) -> usize {
|
||||
let n = name.strip_prefix("dx.op.").unwrap_or(name);
|
||||
let n = n.split('.').next().unwrap_or(n);
|
||||
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
|
||||
match n {
|
||||
"unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16"
|
||||
| "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"),
|
||||
"bufferLoad" | "rawBufferLoad" => k("buffer_load"),
|
||||
"cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"),
|
||||
"bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"),
|
||||
"atomicBinOp" | "atomicCompareExchange" => k("atomic"),
|
||||
"createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"),
|
||||
"annotateHandle" => k("annotate"),
|
||||
"getDimensions" => k("dimensions"),
|
||||
"barrier" => k("barrier"),
|
||||
_ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"),
|
||||
_ if n.starts_with("textureLoad")
|
||||
|| n.starts_with("sample")
|
||||
|| n.starts_with("textureGather")
|
||||
|| n.starts_with("calculateLOD") =>
|
||||
{
|
||||
k("texture_read")
|
||||
}
|
||||
_ => k("io_other"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
/// The instructions [`Module::write`] writes, by kind.
|
||||
pub(crate) fn census(&self) -> Census {
|
||||
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
|
||||
let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect();
|
||||
let live = self.live();
|
||||
// The blocks `write` lays out: those reached from the entry.
|
||||
let mut seen = vec![false; self.blocks.len()];
|
||||
let mut stack = vec![0usize];
|
||||
if !self.blocks.is_empty() {
|
||||
seen[0] = true;
|
||||
}
|
||||
while let Some(b) = stack.pop() {
|
||||
for &s in super::successors(self.blocks[b].term).iter() {
|
||||
if !seen[s] {
|
||||
seen[s] = true;
|
||||
stack.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut c = Census::default();
|
||||
for (b, blk) in self.blocks.iter().enumerate() {
|
||||
if !seen[b] {
|
||||
continue;
|
||||
}
|
||||
c.counts[k("blocks")] += 1;
|
||||
let _: Option<Term> = blk.term;
|
||||
for &i in blk
|
||||
.phis
|
||||
.iter()
|
||||
.filter(|&&i| live[i as usize])
|
||||
.chain(&blk.body)
|
||||
{
|
||||
c.counts[0] += 1;
|
||||
let at = match &self.insts[i as usize].op {
|
||||
Op::Bin(..) | Op::Cmp(..) => k("arith"),
|
||||
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
|
||||
Op::Cast(..) => k("cast"),
|
||||
Op::Select(..) => k("select"),
|
||||
Op::Extract(..) => k("extract"),
|
||||
Op::Phi(_) => k("phi"),
|
||||
Op::Gep(..) => k("gep"),
|
||||
Op::Load(_) => k("lds_load"),
|
||||
Op::Store(..) => k("lds_store"),
|
||||
Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"),
|
||||
Op::Call(f, _) => call_kind[*f as usize],
|
||||
};
|
||||
c.counts[at] += 1;
|
||||
match self.tags.get(&i) {
|
||||
Some(Tag::Guard) => c.counts[k("guard_select")] += 1,
|
||||
Some(Tag::Clamp) => c.counts[k("clamp")] += 1,
|
||||
Some(Tag::Counter) => c.counts[k("loop_counter")] += 1,
|
||||
None => {}
|
||||
}
|
||||
let _ = V::Inst(i);
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,419 @@
|
||||
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
|
||||
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
|
||||
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
|
||||
//! the container hash that D3D12 checks.
|
||||
|
||||
/// One signature element: one row (D3D12 links stages by semantic).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct SigElement {
|
||||
pub name: String,
|
||||
pub index: u32,
|
||||
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
|
||||
pub kind: u8,
|
||||
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
|
||||
pub comp: u8,
|
||||
/// DXIL interpolation mode (0 for none).
|
||||
pub interp: u8,
|
||||
/// Start row, if the element has a register.
|
||||
pub row: Option<u32>,
|
||||
pub col: u8,
|
||||
pub cols: u8,
|
||||
/// Components read (inputs) or written (outputs), relative to `col`.
|
||||
pub usage: u8,
|
||||
/// 16-bit on the console (declared 32-bit here).
|
||||
pub half: bool,
|
||||
}
|
||||
|
||||
impl SigElement {
|
||||
fn system_value(&self) -> u32 {
|
||||
match self.kind {
|
||||
1 => 6, // vertex id
|
||||
2 => 8, // instance id
|
||||
3 => 1, // position
|
||||
4 => 4, // render target array index
|
||||
5 => 5, // viewport array index
|
||||
6 => 2, // clip distance
|
||||
7 => 3, // cull distance
|
||||
10 => 7, // primitive id
|
||||
12 => 10,
|
||||
13 => 9, // front face
|
||||
14 => 66,
|
||||
15 => 70,
|
||||
16 => 64, // target
|
||||
17 => 65, // depth
|
||||
18 => 68,
|
||||
19 => 67,
|
||||
20 => 69,
|
||||
28 => 23, // barycentrics
|
||||
30 => 25, // cull primitive
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn sig_comp(&self) -> u32 {
|
||||
match self.comp {
|
||||
1 | 5 => 1, // bool and u32
|
||||
4 => 2,
|
||||
9 => 3,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mask(&self) -> u8 {
|
||||
((1u8 << self.cols) - 1) << self.col
|
||||
}
|
||||
}
|
||||
|
||||
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
|
||||
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend((elements.len() as u32).to_le_bytes());
|
||||
out.extend(8u32.to_le_bytes());
|
||||
// Validator 1.6 writes one name per element in element order, repeats
|
||||
// included, except that system values share theirs (it keys names by
|
||||
// the semantic's string, which is one static string per system value);
|
||||
// the rows sorted by register (unallocated last).
|
||||
let mut offsets: Vec<u32> = Vec::new();
|
||||
let mut next = 8 + 32 * elements.len() as u32;
|
||||
let mut names = Vec::new();
|
||||
for (i, e) in elements.iter().enumerate() {
|
||||
let shared = (e.kind != 0)
|
||||
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
|
||||
.flatten();
|
||||
match shared {
|
||||
Some(j) => offsets.push(offsets[j]),
|
||||
None => {
|
||||
offsets.push(next);
|
||||
next += e.name.len() as u32 + 1;
|
||||
names.push(&e.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut order: Vec<usize> = (0..elements.len()).collect();
|
||||
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
|
||||
for i in order {
|
||||
let (e, offset) = (&elements[i], offsets[i]);
|
||||
let used = e.usage << e.col;
|
||||
let rw = if input { used } else { !used & 0xf };
|
||||
for v in [
|
||||
0,
|
||||
offset,
|
||||
e.index,
|
||||
e.system_value(),
|
||||
e.sig_comp(),
|
||||
e.row.unwrap_or(u32::MAX),
|
||||
] {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
out.extend([e.mask(), rw, 0, 0]);
|
||||
out.extend(0u32.to_le_bytes());
|
||||
}
|
||||
for name in names {
|
||||
out.extend(name.as_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The most a mesh shader's outputs may take, in bytes (D3D12).
|
||||
pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024;
|
||||
|
||||
/// A mesh shader's output size as the DXIL validator measures it against
|
||||
/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element
|
||||
/// and primitive element, times the maxima rounded up to multiples of 32.
|
||||
pub(crate) fn mesh_output_bytes(
|
||||
vertex: &[SigElement],
|
||||
primitive: &[SigElement],
|
||||
max_vertices: u32,
|
||||
max_primitives: u32,
|
||||
) -> u64 {
|
||||
let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>();
|
||||
let align = |n: u32| u64::from(n).next_multiple_of(32);
|
||||
4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives))
|
||||
}
|
||||
|
||||
/// A resource bound by register, as `PSV0` lists it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Binding {
|
||||
/// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV.
|
||||
pub kind: u32,
|
||||
pub space: u32,
|
||||
pub register: u32,
|
||||
/// DXIL resource kind (13 cbuffer, 14 sampler).
|
||||
pub dxil_kind: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct Psv<'a> {
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute.
|
||||
pub stage: u8,
|
||||
/// Vertex: writes `SV_Position`. Pixel: writes depth.
|
||||
pub flag: bool,
|
||||
pub inputs: &'a [SigElement],
|
||||
pub outputs: &'a [SigElement],
|
||||
/// Mesh: per-primitive outputs.
|
||||
pub prims: &'a [SigElement],
|
||||
/// Mesh: its state and the group-shared bytes it declares.
|
||||
pub mesh: Option<(super::shader::Mesh, u32)>,
|
||||
/// Geometry (triangles in, triangle strips out on stream 0): its
|
||||
/// maximum vertex count. `flag`: writes `SV_Position`.
|
||||
pub geometry: Option<u32>,
|
||||
pub bindings: &'a [Binding],
|
||||
/// Compute: thread-group size and required wave size.
|
||||
pub threads: [u32; 3],
|
||||
pub wave_size: Option<u32>,
|
||||
}
|
||||
|
||||
/// `PSV0` with runtime info version 2 (validator 1.6).
|
||||
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
|
||||
let vectors = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row)
|
||||
.map(|r| r + 1)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
|
||||
let mut out = Vec::new();
|
||||
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
|
||||
for v in vs {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
};
|
||||
u32s(&mut out, &[48]);
|
||||
let mut info = [0u8; 48];
|
||||
info[0] = u8::from(p.flag);
|
||||
if p.stage == 0 {
|
||||
// PSInfo.SampleFrequency: an input interpolated per sample, or the
|
||||
// sample index.
|
||||
info[1] = u8::from(
|
||||
p.inputs
|
||||
.iter()
|
||||
.any(|e| matches!(e.interp, 6 | 7) || e.kind == 12),
|
||||
);
|
||||
}
|
||||
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
|
||||
info[16..20].copy_from_slice(&min.to_le_bytes());
|
||||
info[20..24].copy_from_slice(&max.to_le_bytes());
|
||||
info[24] = p.stage;
|
||||
for (k, n) in p.threads.into_iter().enumerate() {
|
||||
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
|
||||
}
|
||||
info[28] = p.inputs.len() as u8;
|
||||
info[29] = p.outputs.len() as u8;
|
||||
info[31] = in_vectors as u8;
|
||||
info[32] = out_vectors as u8;
|
||||
if let Some((mesh, shared)) = p.mesh {
|
||||
info[0..4].copy_from_slice(&shared.to_le_bytes());
|
||||
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
|
||||
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
|
||||
info[26] = vectors(p.prims) as u8;
|
||||
info[27] = mesh.topology;
|
||||
info[30] = p.prims.len() as u8;
|
||||
}
|
||||
if let Some(max_vertices) = p.geometry {
|
||||
// Input primitive (3: triangles), output topology (5: triangle
|
||||
// strips), stream mask, position written; the vertex maximum.
|
||||
info[0..4].copy_from_slice(&3u32.to_le_bytes());
|
||||
info[4..8].copy_from_slice(&5u32.to_le_bytes());
|
||||
info[8..12].copy_from_slice(&1u32.to_le_bytes());
|
||||
info[12] = u8::from(p.flag);
|
||||
info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes());
|
||||
}
|
||||
out.extend(info);
|
||||
u32s(&mut out, &[p.bindings.len() as u32]);
|
||||
if !p.bindings.is_empty() {
|
||||
u32s(&mut out, &[24]);
|
||||
for b in p.bindings {
|
||||
u32s(
|
||||
&mut out,
|
||||
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
// Names of arbitrary semantics (system values use ""), then indices.
|
||||
let mut strings = vec![0u8];
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
let mut elements = Vec::new();
|
||||
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
|
||||
let name = if e.kind == 0 {
|
||||
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
|
||||
match find(&strings, &needle) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
strings.extend(&needle);
|
||||
strings.len() - needle.len()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let index = match indices.iter().position(|&i| i == e.index) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
indices.push(e.index);
|
||||
indices.len() - 1
|
||||
}
|
||||
};
|
||||
let (start, alloc) = match e.row {
|
||||
Some(r) => (r as u8, 0x40 | (e.col << 4)),
|
||||
None => (0, 0),
|
||||
};
|
||||
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
|
||||
}
|
||||
strings.resize(strings.len().next_multiple_of(4), 0);
|
||||
u32s(&mut out, &[strings.len() as u32]);
|
||||
out.extend(&strings);
|
||||
u32s(&mut out, &[indices.len() as u32]);
|
||||
u32s(&mut out, &indices);
|
||||
if !elements.is_empty() {
|
||||
u32s(&mut out, &[16]);
|
||||
for (name, index, start, cols, e) in elements {
|
||||
u32s(&mut out, &[name, index]);
|
||||
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
|
||||
}
|
||||
}
|
||||
// Input-to-output dependencies, as the view-id state declares them:
|
||||
// every output scalar on every input scalar.
|
||||
if in_vectors > 0 && out_vectors > 0 {
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
|
||||
let per = (out_vectors * 4).div_ceil(32);
|
||||
for i in 0..in_vectors * 4 {
|
||||
for k in 0..per {
|
||||
let bits = if i < ni {
|
||||
no.saturating_sub(32 * k).min(32)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mask = if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1u32 << bits) - 1
|
||||
};
|
||||
u32s(&mut out, &[mask]);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
/// The container: parts in order, hashed.
|
||||
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
|
||||
let table = 0x20 + 4 * parts.len();
|
||||
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend(b"DXBC");
|
||||
out.extend([0; 16]);
|
||||
out.extend(1u16.to_le_bytes());
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend((total as u32).to_le_bytes());
|
||||
out.extend((parts.len() as u32).to_le_bytes());
|
||||
let mut offset = table;
|
||||
for (_, d) in parts {
|
||||
out.extend((offset as u32).to_le_bytes());
|
||||
offset += 8 + d.len();
|
||||
}
|
||||
for (fourcc, d) in parts {
|
||||
out.extend(*fourcc);
|
||||
out.extend((d.len() as u32).to_le_bytes());
|
||||
out.extend(*d);
|
||||
}
|
||||
let digest = hash(&out[20..]);
|
||||
out[4..20].copy_from_slice(&digest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The container hash D3D12 checks: MD5 whose last block carries the bit
|
||||
/// count first and `2 × bytes + 1` last instead of standard padding.
|
||||
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
|
||||
let len = data.len();
|
||||
let left = len % 64;
|
||||
let mut tail = Vec::with_capacity(128);
|
||||
if left < 56 {
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(60, 0);
|
||||
} else {
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(64, 0);
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.resize(124, 0);
|
||||
}
|
||||
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
for block in data[..len - left]
|
||||
.as_chunks::<64>()
|
||||
.0
|
||||
.iter()
|
||||
.chain(tail.as_chunks::<64>().0)
|
||||
{
|
||||
md5_block(&mut state, block);
|
||||
}
|
||||
let mut out = [0; 16];
|
||||
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
|
||||
o.copy_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
|
||||
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
||||
let x: Vec<u32> = block
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| u32::from_le_bytes(*c))
|
||||
.collect();
|
||||
let [mut a, mut b, mut c, mut d] = *state;
|
||||
for i in 0..64 {
|
||||
let (f, g) = match i / 16 {
|
||||
0 => ((b & c) | (!b & d), i),
|
||||
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
|
||||
2 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * i) % 16),
|
||||
};
|
||||
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
|
||||
let rotated = a
|
||||
.wrapping_add(f)
|
||||
.wrapping_add(k)
|
||||
.wrapping_add(x[g])
|
||||
.rotate_left(S[(i / 16) * 4 + i % 4]);
|
||||
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
|
||||
}
|
||||
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
|
||||
*s = s.wrapping_add(v);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn md5_core_matches_the_standard() {
|
||||
// Standard MD5 of "abc" with standard padding, through md5_block.
|
||||
let mut block = b"abc".to_vec();
|
||||
block.push(0x80);
|
||||
block.resize(56, 0);
|
||||
block.extend(24u64.to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
md5_block(&mut state, block.as_slice().try_into().unwrap());
|
||||
let hex: String = state
|
||||
.iter()
|
||||
.flat_map(|s| s.to_le_bytes())
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,411 @@
|
||||
//! 64-bit floating point by integer operations: the host (D3DMetal, Metal) has no fp64, and the
|
||||
//! console's shaders use a little of it (`v_cvt_f32_f64` of a constant stored as a double,
|
||||
//! `v_add_f64` sums). The algorithms are written once over [`Ops`], on values that are 64-bit
|
||||
//! integers, and run on the IR builder in the lowering and on `u64` in the tests, where they are
|
||||
//! checked against the CPU's own `f64`.
|
||||
//!
|
||||
//! Round-to-nearest-even throughout, denormals included (the f32 result of a conversion may be
|
||||
//! one too).
|
||||
|
||||
/// What the algorithms need: 64-bit integer values and conditions. Shifts are by amounts below 64.
|
||||
pub(crate) trait Ops {
|
||||
type V: Copy;
|
||||
type C: Copy;
|
||||
fn k(&mut self, v: u64) -> Self::V;
|
||||
fn and(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn or(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
#[allow(dead_code)]
|
||||
fn xor(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn add(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn sub(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn shl(&mut self, a: Self::V, by: Self::V) -> Self::V;
|
||||
fn lshr(&mut self, a: Self::V, by: Self::V) -> Self::V;
|
||||
fn eq(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
fn ne(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
/// Unsigned a < b.
|
||||
fn ult(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
/// Signed a >= b.
|
||||
fn sge(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
fn sel(&mut self, c: Self::C, a: Self::V, b: Self::V) -> Self::V;
|
||||
}
|
||||
|
||||
fn kshl<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
|
||||
let n = o.k(n);
|
||||
o.shl(a, n)
|
||||
}
|
||||
|
||||
fn klshr<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
|
||||
let n = o.k(n);
|
||||
o.lshr(a, n)
|
||||
}
|
||||
|
||||
fn kn_plus_one<O: Ops>(o: &mut O, n: u64) -> O::V {
|
||||
o.k(n + 1)
|
||||
}
|
||||
|
||||
fn kand<O: Ops>(o: &mut O, a: O::V, m: u64) -> O::V {
|
||||
let m = o.k(m);
|
||||
o.and(a, m)
|
||||
}
|
||||
|
||||
/// `v_cvt_f32_f64`: the f32 bits (in the low 32 bits of the result) of the double `b`.
|
||||
pub(crate) fn cvt_f32_f64<O: Ops>(o: &mut O, b: O::V) -> O::V {
|
||||
let sign = klshr(o, b, 63);
|
||||
let e = klshr(o, b, 52);
|
||||
let e = kand(o, e, 0x7ff);
|
||||
let m = kand(o, b, (1 << 52) - 1);
|
||||
let (zero, one) = (o.k(0), o.k(1));
|
||||
// infinity and NaN (a quiet NaN with the payload's top bits)
|
||||
let payload = klshr(o, m, 29);
|
||||
let qnan = o.k(0x40_0000);
|
||||
let payload = o.or(payload, qnan);
|
||||
let m_zero = o.eq(m, zero);
|
||||
let payload = o.sel(m_zero, zero, payload);
|
||||
let inf = o.k(0x7f80_0000);
|
||||
let special = o.or(inf, payload);
|
||||
// normal results
|
||||
let bias = o.k(896); // 1023 - 127
|
||||
let ee = o.sub(e, bias);
|
||||
let rem = kand(o, m, 0x1fff_ffff);
|
||||
let q = klshr(o, m, 29);
|
||||
let half = o.k(1 << 28);
|
||||
let above = o.ult(half, rem);
|
||||
let tie = o.eq(rem, half);
|
||||
let odd = o.and(q, one);
|
||||
let up_tie = o.sel(tie, odd, zero);
|
||||
let up = o.sel(above, one, up_tie);
|
||||
let ee23 = kshl(o, ee, 23);
|
||||
let normal = o.add(ee23, q);
|
||||
let normal = o.add(normal, up);
|
||||
// results below the smallest normal
|
||||
let implicit = o.k(1 << 52);
|
||||
let mant = o.or(m, implicit);
|
||||
let thirty = o.k(30);
|
||||
let raw = o.sub(thirty, ee);
|
||||
let sixty3 = o.k(63);
|
||||
let too_far = o.ult(sixty3, raw); // raw > 63, or negative (huge)
|
||||
let raw = o.sel(too_far, sixty3, raw);
|
||||
let ee_pos = o.sge(ee, one);
|
||||
let s = o.sel(ee_pos, thirty, raw);
|
||||
let q2 = o.lshr(mant, s);
|
||||
let mask = o.shl(one, s);
|
||||
let mask = o.sub(mask, one);
|
||||
let rem2 = o.and(mant, mask);
|
||||
let sm1 = o.sub(s, one);
|
||||
let half2 = o.shl(one, sm1);
|
||||
let above2 = o.ult(half2, rem2);
|
||||
let tie2 = o.eq(rem2, half2);
|
||||
let odd2 = o.and(q2, one);
|
||||
let up_tie2 = o.sel(tie2, odd2, zero);
|
||||
let up2 = o.sel(above2, one, up_tie2);
|
||||
let denormal = o.add(q2, up2);
|
||||
// choose
|
||||
let k255 = o.k(255);
|
||||
let big = o.sge(ee, k255);
|
||||
let mag = o.sel(ee_pos, normal, denormal);
|
||||
let mag = o.sel(big, inf, mag);
|
||||
let e_zero = o.eq(e, zero);
|
||||
let mag = o.sel(e_zero, zero, mag);
|
||||
let k7ff = o.k(0x7ff);
|
||||
let e_all = o.eq(e, k7ff);
|
||||
let mag = o.sel(e_all, special, mag);
|
||||
let sign = kshl(o, sign, 31);
|
||||
o.or(sign, mag)
|
||||
}
|
||||
|
||||
/// `v_add_f64`: the bits of `a + b` for the doubles `a` and `b`.
|
||||
pub(crate) fn add_f64<O: Ops>(o: &mut O, a: O::V, b: O::V) -> O::V {
|
||||
let (zero, one) = (o.k(0), o.k(1));
|
||||
let magnitude = |o: &mut O, x: O::V| kand(o, x, (1 << 63) - 1);
|
||||
let (ma, mb) = (magnitude(o, a), magnitude(o, b));
|
||||
// `big` has the larger magnitude
|
||||
let swap = o.ult(ma, mb);
|
||||
let big = o.sel(swap, b, a);
|
||||
let small = o.sel(swap, a, b);
|
||||
let parts = |o: &mut O, x: O::V| {
|
||||
let s = klshr(o, x, 63);
|
||||
let e = klshr(o, x, 52);
|
||||
let e = kand(o, e, 0x7ff);
|
||||
let m = kand(o, x, (1 << 52) - 1);
|
||||
(s, e, m)
|
||||
};
|
||||
let (sb, eb0, mb_) = parts(o, big);
|
||||
let (ss, es0, ms_) = parts(o, small);
|
||||
let k7ff = o.k(0x7ff);
|
||||
// 53-bit significands (a denormal has no implicit bit and the exponent 1)
|
||||
let implicit = o.k(1 << 52);
|
||||
let sig = |o: &mut O, e: O::V, m: O::V| {
|
||||
let full = o.or(m, implicit);
|
||||
let z = o.k(0);
|
||||
let is0 = o.eq(e, z);
|
||||
o.sel(is0, m, full)
|
||||
};
|
||||
let (mant_b, mant_s) = (sig(o, eb0, mb_), sig(o, es0, ms_));
|
||||
let eff = |o: &mut O, e: O::V| {
|
||||
let z = o.k(0);
|
||||
let one = o.k(1);
|
||||
let is0 = o.eq(e, z);
|
||||
o.sel(is0, one, e)
|
||||
};
|
||||
let (eb, es) = (eff(o, eb0), eff(o, es0));
|
||||
// three extra low bits (guard, round, sticky)
|
||||
let mant_b = kshl(o, mant_b, 3);
|
||||
let mant_s = kshl(o, mant_s, 3);
|
||||
// align the smaller one
|
||||
let d = o.sub(eb, es);
|
||||
let sixty3 = o.k(63);
|
||||
let far = o.ult(sixty3, d);
|
||||
let sh = o.sel(far, sixty3, d);
|
||||
let shifted = o.lshr(mant_s, sh);
|
||||
let mask = o.shl(one, sh);
|
||||
let mask = o.sub(mask, one);
|
||||
let lost = o.and(mant_s, mask);
|
||||
let lost = o.ne(lost, zero);
|
||||
let sticky = o.sel(lost, one, zero);
|
||||
let shifted = o.or(shifted, sticky);
|
||||
// add or subtract
|
||||
let same = o.eq(sb, ss);
|
||||
let sum = o.add(mant_b, shifted);
|
||||
let diff = o.sub(mant_b, shifted);
|
||||
let mut v = o.sel(same, sum, diff);
|
||||
let mut e = eb;
|
||||
// carry out: bit 56
|
||||
let top = o.k(1 << 56);
|
||||
let carry = o.and(v, top);
|
||||
let carried = o.ne(carry, zero);
|
||||
let lowbit = o.and(v, one);
|
||||
let halved = klshr(o, v, 1);
|
||||
let halved = o.or(halved, lowbit);
|
||||
v = o.sel(carried, halved, v);
|
||||
let e_plus = o.add(e, one);
|
||||
e = o.sel(carried, e_plus, e);
|
||||
// cancellation: shift left until bit 55 is set
|
||||
for n in [32u64, 16, 8, 4, 2, 1] {
|
||||
// the top n bits below bit 56: bits 55 down to 56 - n
|
||||
let ones = (1u64 << n) - 1;
|
||||
let field = ones << (56 - n);
|
||||
let top_bits = kand(o, v, field);
|
||||
let empty = o.eq(top_bits, zero);
|
||||
let nonzero = o.ne(v, zero);
|
||||
let kn = o.k(n);
|
||||
let shift = o.sel(empty, kn, zero);
|
||||
let shift = o.sel(nonzero, shift, zero);
|
||||
// not below the exponent 1: the result is then a denormal
|
||||
let np1 = kn_plus_one(o, n);
|
||||
let allowed = o.sge(e, np1);
|
||||
let shift = o.sel(allowed, shift, zero);
|
||||
v = o.shl(v, shift);
|
||||
e = o.sub(e, shift);
|
||||
}
|
||||
// round to nearest even
|
||||
let low = kand(o, v, 7);
|
||||
let m = klshr(o, v, 3);
|
||||
let k4 = o.k(4);
|
||||
let above = o.ult(k4, low);
|
||||
let tie = o.eq(low, k4);
|
||||
let odd = o.and(m, one);
|
||||
let up_tie = o.sel(tie, odd, zero);
|
||||
let up = o.sel(above, one, up_tie);
|
||||
let m = o.add(m, up);
|
||||
// (exponent - 1) << 52 plus the significand with its hidden bit: a carry out of the
|
||||
// significand, and a denormal that rounds up to the smallest normal, add to the exponent
|
||||
let e_minus = o.sub(e, one);
|
||||
let e_field = kshl(o, e_minus, 52);
|
||||
let bits = o.add(e_field, m);
|
||||
let sign = kshl(o, sb, 63);
|
||||
let inf_mag = o.k(0x7ff0_0000_0000_0000);
|
||||
let overflow = o.ult(bits, inf_mag);
|
||||
let mag = o.sel(overflow, bits, inf_mag);
|
||||
let finite = o.or(sign, mag);
|
||||
// exact cancellation: +0, or -0 for two negative zeros
|
||||
let result_zero = o.eq(v, zero);
|
||||
let neg_zero = o.sel(same, sign, zero);
|
||||
let r = o.sel(result_zero, neg_zero, finite);
|
||||
// infinities and NaNs
|
||||
let a_all = {
|
||||
let ea = {
|
||||
let t = klshr(o, a, 52);
|
||||
kand(o, t, 0x7ff)
|
||||
};
|
||||
o.eq(ea, k7ff)
|
||||
};
|
||||
let b_all = {
|
||||
let eb2 = {
|
||||
let t = klshr(o, b, 52);
|
||||
kand(o, t, 0x7ff)
|
||||
};
|
||||
o.eq(eb2, k7ff)
|
||||
};
|
||||
let a_m = kand(o, a, (1 << 52) - 1);
|
||||
let b_m = kand(o, b, (1 << 52) - 1);
|
||||
let a_nan = {
|
||||
let nz = o.ne(a_m, zero);
|
||||
let x = o.sel(nz, one, zero);
|
||||
o.sel(a_all, x, zero)
|
||||
};
|
||||
let b_nan = {
|
||||
let nz = o.ne(b_m, zero);
|
||||
let x = o.sel(nz, one, zero);
|
||||
o.sel(b_all, x, zero)
|
||||
};
|
||||
let nan_bits = o.k(0x7ff8_0000_0000_0000);
|
||||
let any_nan = o.or(a_nan, b_nan);
|
||||
let any_nan = o.ne(any_nan, zero);
|
||||
// a (or b) is an infinity: the result is that infinity, a NaN if the other is the opposite one
|
||||
let a_inf = a_all;
|
||||
let b_inf = b_all;
|
||||
let (sa, sb2) = (klshr(o, a, 63), klshr(o, b, 63));
|
||||
let signs_differ = o.ne(sa, sb2);
|
||||
let both_inf = {
|
||||
let x = o.sel(a_inf, one, zero);
|
||||
let y = o.sel(b_inf, one, zero);
|
||||
let z = o.and(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
let inf_nan = {
|
||||
let x = o.sel(both_inf, one, zero);
|
||||
let y = o.sel(signs_differ, one, zero);
|
||||
let z = o.and(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
let r = o.sel(b_inf, b, r);
|
||||
let r = o.sel(a_inf, a, r);
|
||||
let nan_case = {
|
||||
let x = o.sel(any_nan, one, zero);
|
||||
let y = o.sel(inf_nan, one, zero);
|
||||
let z = o.or(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
o.sel(nan_case, nan_bits, r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The algorithms on `u64`.
|
||||
struct Native;
|
||||
|
||||
impl Ops for Native {
|
||||
type V = u64;
|
||||
type C = bool;
|
||||
fn k(&mut self, v: u64) -> u64 { v }
|
||||
fn and(&mut self, a: u64, b: u64) -> u64 { a & b }
|
||||
fn or(&mut self, a: u64, b: u64) -> u64 { a | b }
|
||||
fn xor(&mut self, a: u64, b: u64) -> u64 { a ^ b }
|
||||
fn add(&mut self, a: u64, b: u64) -> u64 { a.wrapping_add(b) }
|
||||
fn sub(&mut self, a: u64, b: u64) -> u64 { a.wrapping_sub(b) }
|
||||
fn shl(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a << by }
|
||||
fn lshr(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a >> by }
|
||||
fn eq(&mut self, a: u64, b: u64) -> bool { a == b }
|
||||
fn ne(&mut self, a: u64, b: u64) -> bool { a != b }
|
||||
fn ult(&mut self, a: u64, b: u64) -> bool { a < b }
|
||||
fn sge(&mut self, a: u64, b: u64) -> bool { a as i64 >= b as i64 }
|
||||
fn sel(&mut self, c: bool, a: u64, b: u64) -> u64 { if c { a } else { b } }
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn cvt(x: f64) -> u32 {
|
||||
cvt_f32_f64(&mut Native, x.to_bits()) as u32
|
||||
}
|
||||
|
||||
fn same_f32(got: u32, want: f32) -> bool {
|
||||
if want.is_nan() {
|
||||
f32::from_bits(got).is_nan()
|
||||
} else {
|
||||
got == want.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::approx_constant)] // 3.14159265358979 is a test value, not the constant
|
||||
fn f32_from_f64_edges() {
|
||||
let cases = [
|
||||
0.0, -0.0, 1.0, -1.0, 0.5, 3.14159265358979, 1e-10, 1e10, 1e38, 3.4028234663852886e38, 3.4028235677973366e38,
|
||||
3.4028236e38, 1e39, -1e39, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 1e-38, 1.1754943508222875e-38, 1e-40,
|
||||
1.4e-45, 7e-46, 7.006492321624085e-46, 7.006492321624086e-46, 1e-50, 5e-324, 2.2250738585072014e-308,
|
||||
// ties: 1 + 2^-24 (halfway between two f32), and just above and below
|
||||
1.0 + 2f64.powi(-24), 1.0 + 2f64.powi(-24) + 2f64.powi(-40), 1.0 + 3.0 * 2f64.powi(-24),
|
||||
16777217.0, 16777219.0, 8388609.5,
|
||||
];
|
||||
for x in cases {
|
||||
let got = cvt(x);
|
||||
assert!(same_f32(got, x as f32), "{x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_from_f64_random() {
|
||||
let mut r = Rng(0x1234_5678_9abc_def1);
|
||||
for i in 0..400_000u32 {
|
||||
let bits = r.next();
|
||||
// spread over exponents near the f32 range as well as everywhere
|
||||
let bits = if i % 2 == 0 { bits } else { (bits & !(0x7ff << 52)) | ((896 - 30 + (r.next() % 330)) << 52) };
|
||||
let x = f64::from_bits(bits);
|
||||
let got = cvt(x);
|
||||
assert!(same_f32(got, x as f32), "{bits:#018x} {x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
fn add(a: f64, b: f64) -> u64 {
|
||||
add_f64(&mut Native, a.to_bits(), b.to_bits())
|
||||
}
|
||||
|
||||
fn same_f64(got: u64, want: f64) -> bool {
|
||||
let g = f64::from_bits(got);
|
||||
if want.is_nan() {
|
||||
g.is_nan()
|
||||
} else {
|
||||
got == want.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f64_sums_edges() {
|
||||
let vals = [
|
||||
0.0, -0.0, 1.0, -1.0, 0.5, 3.0, -3.0, 1e300, -1e300, 1.7976931348623157e308, 2.0f64.powi(-1022), 1.5,
|
||||
5e-324, -5e-324, 2.2250738585072014e-308, 1.0 + f64::EPSILON, 1.0 - f64::EPSILON / 2.0, 1e-300, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 123456.789, 2f64.powi(53),
|
||||
2f64.powi(53) + 2.0, 4.0 / 3.0,
|
||||
];
|
||||
for a in vals {
|
||||
for b in vals {
|
||||
let got = add(a, b);
|
||||
assert!(same_f64(got, a + b), "{a:e} + {b:e}: got {:e} ({got:#x}), want {:e} ({:#x})", f64::from_bits(got), a + b, (a + b).to_bits());
|
||||
}
|
||||
}
|
||||
// signed zeros
|
||||
assert_eq!(add(-0.0, -0.0), (-0.0f64).to_bits());
|
||||
assert_eq!(add(0.0, -0.0), 0.0f64.to_bits());
|
||||
assert_eq!(add(1.0, -1.0), 0.0f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f64_sums_random() {
|
||||
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
for i in 0..400_000u32 {
|
||||
let (mut x, mut y) = (r.next(), r.next());
|
||||
// exponents within a few bits of each other make cancellation and carries common
|
||||
if i % 3 != 0 {
|
||||
let e = 1000 + (r.next() % 50);
|
||||
x = (x & !(0x7ff << 52)) | (e << 52);
|
||||
y = (y & !(0x7ff << 52)) | ((e + (r.next() % 4) - 1) << 52);
|
||||
}
|
||||
if i % 7 == 0 {
|
||||
// a nearly cancelling pair
|
||||
y = x ^ (1 << 63) ^ (r.next() & 0xfff);
|
||||
}
|
||||
let (a, b) = (f64::from_bits(x), f64::from_bits(y));
|
||||
let got = add(a, b);
|
||||
assert!(same_f64(got, a + b), "{x:#018x} + {y:#018x}: got {got:#018x}, want {:#018x}", (a + b).to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,557 @@
|
||||
//! The console's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
|
||||
//! that tests one ray against one node of the title's own structures.
|
||||
//!
|
||||
//! [`crate::bvh`] says what the instruction computes and is the reference:
|
||||
//! the code made here does the same float operations in the same order
|
||||
//! (DXIL float operations carry no fast-math flags, so the host may not
|
||||
//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
|
||||
//! the card against the reference.
|
||||
//!
|
||||
//! The title's nodes are in title memory, named by address: they are read
|
||||
//! through the host's copies of title memory ([`Lower::memory`]), one look
|
||||
//! in its directory per node (two for a 128-byte box node).
|
||||
//!
|
||||
//! Shape of the code, under the instruction's lane guard:
|
||||
//!
|
||||
//! ```text
|
||||
//! kind = pointer & 7
|
||||
//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
|
||||
//! four slab tests; the sorting network
|
||||
//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
|
||||
//! other (6, 7): a triangle miss
|
||||
//! ```
|
||||
//!
|
||||
//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
|
||||
//! box node, 16 for a 16-bit one, 10 for a triangle.
|
||||
|
||||
use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
|
||||
use crate::bvh;
|
||||
use crate::resource::BvhNodes;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
|
||||
/// heap slot holding a raw buffer, and the title address of its first
|
||||
/// byte. (The card tests have no host to keep copies of title memory
|
||||
/// and their directory.)
|
||||
pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
|
||||
const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Where the instruction's node is.
|
||||
#[derive(Clone, Copy)]
|
||||
enum NodeAt {
|
||||
/// At this byte of a raw buffer of the host.
|
||||
Buffer { handle: V, byte: V },
|
||||
/// In title memory: the raw view of the host copy holding the node's
|
||||
/// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
|
||||
/// and the node's address, for the second half of a 128-byte node.
|
||||
Memory { handle: V, byte: V, low: V, high: V },
|
||||
}
|
||||
|
||||
/// The ray operands, as floats.
|
||||
struct Ray {
|
||||
extent: V,
|
||||
origin: [V; 3],
|
||||
direction: [V; 3],
|
||||
inverse: [V; 3],
|
||||
}
|
||||
|
||||
impl<'a> Lower<'a> {
|
||||
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
|
||||
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
|
||||
let Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
dmask,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
..
|
||||
} = &inst.fields
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
|
||||
return Err("a ray-tracing node test with 16-bit operands or a partial result");
|
||||
}
|
||||
let wide = inst.name() == "image_bvh64_intersect_ray";
|
||||
// Operand VGPRs in order: the node pointer (two dwords in the
|
||||
// 64-bit form), the ray's extent, origin, direction and inverse
|
||||
// direction.
|
||||
let mut regs = Vec::new();
|
||||
for a in addr {
|
||||
if let Operand::Vector { reg, dwords } = *a {
|
||||
regs.extend((0..dwords).map(|k| reg + k));
|
||||
}
|
||||
}
|
||||
if regs.len() != if wide { 12 } else { 11 } {
|
||||
return Err("a ray-tracing node test's operands");
|
||||
}
|
||||
let Operand::Vector { reg: dst, .. } = *data else {
|
||||
return Err("a ray-tracing node test's result");
|
||||
};
|
||||
let site = (b, i);
|
||||
let nodes = self
|
||||
.x
|
||||
.res
|
||||
.bvh
|
||||
.iter()
|
||||
.find(|n| n.0 == site)
|
||||
.map(|n| n.1)
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let (sort, barycentrics) = match nodes {
|
||||
BvhNodes::Resource => (true, true),
|
||||
BvhNodes::Memory { word1, word3 } => (
|
||||
word1 & bvh::BOX_SORT != 0,
|
||||
word3 & bvh::RETURN_BARYCENTRICS != 0,
|
||||
),
|
||||
};
|
||||
if !barycentrics {
|
||||
// Mode 0 returns a triangle id and a hit status in the last two
|
||||
// dwords; no program of the title asks for it.
|
||||
return Err("a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
let guard = self.guard(b, i)?;
|
||||
let mut x = Vec::with_capacity(regs.len());
|
||||
for &r in ®s {
|
||||
let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
|
||||
x.push(self.i32_of(v)?);
|
||||
}
|
||||
let pointer = x[0];
|
||||
let pointer_high = wide.then(|| x[1]);
|
||||
let f: Vec<V> = x[1 + usize::from(wide)..]
|
||||
.iter()
|
||||
.map(|&v| self.as_float(v))
|
||||
.collect();
|
||||
let ray = Ray {
|
||||
extent: f[0],
|
||||
origin: [f[1], f[2], f[3]],
|
||||
direction: [f[4], f[5], f[6]],
|
||||
inverse: [f[7], f[8], f[9]],
|
||||
};
|
||||
let c = self.cur;
|
||||
let at = match nodes {
|
||||
BvhNodes::Resource => {
|
||||
let src = self
|
||||
.descriptors
|
||||
.get(&(site, false))
|
||||
.copied()
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let handle = self.handle(site, src, false, (11, 0))?;
|
||||
// (pointer >> 3) << 6 from the buffer's start.
|
||||
let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
|
||||
let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
|
||||
let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
|
||||
NodeAt::Buffer { handle, byte }
|
||||
}
|
||||
BvhNodes::Memory { .. } => {
|
||||
let Operand::Scalar { code, .. } = *rsrc else {
|
||||
return Err("a ray-tracing structure descriptor not in SGPRs");
|
||||
};
|
||||
let mut words = [pointer; 2];
|
||||
for (k, w) in words.iter_mut().enumerate() {
|
||||
let v = inst
|
||||
.read(Reg::S(code + k as u8))
|
||||
.ok_or("an unread operand")?;
|
||||
*w = self.i32_of(v)?;
|
||||
}
|
||||
let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
|
||||
// One look for the node's copy, before the branches: a
|
||||
// node is 64 bytes on 64, so its first half lies in one
|
||||
// 64 KiB page whatever its kind.
|
||||
let (handle, byte) = self.bvh_memory(low, high, guard);
|
||||
NodeAt::Memory {
|
||||
handle,
|
||||
byte,
|
||||
low,
|
||||
high,
|
||||
}
|
||||
}
|
||||
};
|
||||
let zero = self.s.m.i32(0);
|
||||
let gate = self.begin_guarded(guard);
|
||||
let head = self.cur;
|
||||
let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
|
||||
let kind = self.s.m.bin(head, Bin::And, pointer, k7);
|
||||
let pair = self.s.m.bin(head, Bin::And, pointer, k6);
|
||||
let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
|
||||
let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
|
||||
let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(is_box, box_block, leaf_block));
|
||||
self.s
|
||||
.m
|
||||
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
|
||||
self.cur = box_block;
|
||||
let boxes = self.bvh_boxes(at, kind, &ray, sort);
|
||||
let box_end = self.cur;
|
||||
self.s.m.terminate(box_end, Term::Br(join));
|
||||
self.cur = triangle_block;
|
||||
let triangle = self.bvh_triangle(at, kind, &ray);
|
||||
let triangle_end = self.cur;
|
||||
self.s.m.terminate(triangle_end, Term::Br(join));
|
||||
self.cur = join;
|
||||
// Kinds 6 and 7 (an instance, a procedural primitive): not known
|
||||
// what the console returns; the title's programs do not read it.
|
||||
let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
|
||||
let i32t = self.s.t.i32;
|
||||
let mut results = Vec::with_capacity(4);
|
||||
for k in 0..4 {
|
||||
let phi = self.s.m.phi(join, i32t);
|
||||
self.s.m.set_phi(
|
||||
phi,
|
||||
vec![
|
||||
(boxes[k], box_end),
|
||||
(triangle[k], triangle_end),
|
||||
(other[k], leaf_block),
|
||||
],
|
||||
);
|
||||
results.push((phi, zero));
|
||||
}
|
||||
let results = self.end_guarded(gate, &results);
|
||||
for (k, &r) in results.iter().enumerate() {
|
||||
self.write(inst, Reg::V(dst + k as u8), r, guard);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Title memory at `low`/`high` for a node's bytes: the raw view of the
|
||||
/// host copy holding the address and the byte in that view
|
||||
/// ([`Lower::memory`]: a page the host has no copy of reads zeros and
|
||||
/// is left for the host to fetch, for lanes that run).
|
||||
fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
|
||||
#[cfg(test)]
|
||||
if let Some((slot, base)) = TEST_MEMORY.get() {
|
||||
// The buffer at heap slot `slot` holds the bytes from title
|
||||
// address `base` on; any other address reads past its end,
|
||||
// which is zeros.
|
||||
let c = self.cur;
|
||||
let slot = self.s.m.i32(slot);
|
||||
let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
|
||||
let (base_low, base_high) =
|
||||
(self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
|
||||
let at = self.s.m.bin(c, Bin::Sub, low, base_low);
|
||||
let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
|
||||
let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
|
||||
let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
|
||||
let outside = self.s.m.i32(0xffff_ff00);
|
||||
let at = self.s.m.select(c, inside, at, outside);
|
||||
return (handle, at);
|
||||
}
|
||||
self.memory(low, high, guard)
|
||||
}
|
||||
|
||||
/// `count` dwords of the node from its byte `base` + `offset` (`base`
|
||||
/// computed, `offset` fixed; none of the node's bytes past 127), read
|
||||
/// four at a time.
|
||||
fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
|
||||
let c = self.cur;
|
||||
let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
|
||||
// The second half of a 128-byte node may lie in the next 64 KiB
|
||||
// page, which may be in another copy: its own look, made once.
|
||||
let mut second = None;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for start in (0..count).step_by(4) {
|
||||
let n = (count - start).min(4);
|
||||
let node_byte = offset + 4 * start;
|
||||
let (handle, mut byte) = match at {
|
||||
NodeAt::Buffer { handle, byte } => (handle, byte),
|
||||
NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
|
||||
NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
|
||||
let (low, high) = self.address_plus(low, high, 64);
|
||||
// Every lane in this block runs the instruction.
|
||||
let (handle, byte) = self.bvh_memory(low, high, None);
|
||||
let k64 = self.s.m.i32(64);
|
||||
(handle, self.s.m.bin(c, Bin::Sub, byte, k64))
|
||||
}),
|
||||
};
|
||||
if let Some(b) = base {
|
||||
byte = self.s.m.bin(c, Bin::Add, byte, b);
|
||||
}
|
||||
let k = self.s.m.i32(node_byte);
|
||||
let byte = self.s.m.bin(c, Bin::Add, byte, k);
|
||||
let mask = self.s.m.i8((1u8 << n) - 1);
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"rawBufferLoad.f32",
|
||||
Attr::ReadOnly,
|
||||
self.s.t.res_ret,
|
||||
139,
|
||||
&[handle, byte, undef, mask, align],
|
||||
);
|
||||
for k in 0..n {
|
||||
let f = self.s.m.extract(c, r, k);
|
||||
out.push(self.as_int(f));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node's title address, [`bvh::node_address`]: the descriptor's
|
||||
/// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
|
||||
/// `(pointer >> 3) << 6`.
|
||||
fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
|
||||
let c = self.cur;
|
||||
let i64t = self.s.m.int(64);
|
||||
let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
|
||||
let base_high = self.s.m.bin(c, Bin::And, word1, byte);
|
||||
let base = self.join64(word0, base_high);
|
||||
let k8 = self.s.m.int_const(i64t, 8);
|
||||
let base = self.s.m.bin(c, Bin::Shl, base, k8);
|
||||
let p = self.join64(pointer, pointer_high.unwrap_or(zero));
|
||||
let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
|
||||
let p = self.s.m.bin(c, Bin::LShr, p, k3);
|
||||
let p = self.s.m.bin(c, Bin::Shl, p, k6);
|
||||
let a = self.s.m.bin(c, Bin::Add, base, p);
|
||||
self.s.flags |= flags::INT64;
|
||||
self.split64(a)
|
||||
}
|
||||
|
||||
/// The box test ([`bvh::boxes`]): four result dwords. Starts in the
|
||||
/// current block and leaves `self.cur` at the block it ends in.
|
||||
fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
|
||||
let head = self.cur;
|
||||
let children = self.bvh_node_words(at, None, 0, 4);
|
||||
let k5 = self.s.m.i32(5);
|
||||
let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
|
||||
let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let join = self.s.m.new_block();
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(wide, wide_block, half_block));
|
||||
// 32-bit floats: 24 dwords from byte 16.
|
||||
self.cur = wide_block;
|
||||
let k16 = self.s.m.i32(16);
|
||||
let words = self.bvh_node_words(at, None, 16, 24);
|
||||
let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
|
||||
self.s.m.terminate(wide_block, Term::Br(join));
|
||||
// 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
|
||||
// of a dword first.
|
||||
self.cur = half_block;
|
||||
let words = self.bvh_node_words(at, None, 16, 12);
|
||||
let f32t = self.s.t.f32;
|
||||
let mut halves = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let mut h = words[n / 2];
|
||||
if n % 2 == 1 {
|
||||
h = self.s.m.bin(half_block, Bin::LShr, h, k16);
|
||||
}
|
||||
// The conversion reads the low 16 bits.
|
||||
halves.push(self.s.op(
|
||||
half_block,
|
||||
"legacyF16ToF32",
|
||||
Attr::ReadNone,
|
||||
f32t,
|
||||
131,
|
||||
&[h],
|
||||
));
|
||||
}
|
||||
self.s.m.terminate(half_block, Term::Br(join));
|
||||
self.cur = join;
|
||||
let mut coords = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let phi = self.s.m.phi(join, f32t);
|
||||
self.s
|
||||
.m
|
||||
.set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
|
||||
coords.push(phi);
|
||||
}
|
||||
// The inverse direction held finite ([`bvh::boxes`]).
|
||||
let (most, least) = (
|
||||
self.s.m.f32(f32::MAX.to_bits()),
|
||||
self.s.m.f32((-f32::MAX).to_bits()),
|
||||
);
|
||||
let inverse = ray.inverse.map(|x| {
|
||||
let x = self.binary(35, x, least);
|
||||
self.binary(36, x, most)
|
||||
});
|
||||
let c = join;
|
||||
let (none, infinity, fzero) = (
|
||||
self.s.m.i32(bvh::NONE),
|
||||
self.s.m.f32(f32::INFINITY.to_bits()),
|
||||
self.s.m.f32(0),
|
||||
);
|
||||
let mut ids = [none; 4];
|
||||
let mut distances = [infinity; 4];
|
||||
for n in 0..4 {
|
||||
let bx = &coords[6 * n..6 * n + 6];
|
||||
let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
|
||||
for a in 0..3 {
|
||||
let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
|
||||
let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
|
||||
let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
|
||||
let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
|
||||
near[a] = self.binary(36, low, high);
|
||||
far[a] = self.binary(35, low, high);
|
||||
}
|
||||
let enter = self.binary(35, near[0], near[1]);
|
||||
let enter = self.binary(35, enter, near[2]);
|
||||
let leave = self.binary(36, far[0], far[1]);
|
||||
let leave = self.binary(36, leave, far[2]);
|
||||
let from = self.binary(35, enter, fzero);
|
||||
// Ordered compares: a NaN anywhere is a miss.
|
||||
let through = self.s.m.cmp(c, pred::OGE, leave, from);
|
||||
let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
|
||||
let off = self.is_nan_f32(bx[0]);
|
||||
let on = self.s.m.bool(true);
|
||||
let on = self.s.m.bin(c, Bin::Xor, off, on);
|
||||
let hit = self.s.m.bin(c, Bin::And, through, before);
|
||||
let hit = self.s.m.bin(c, Bin::And, hit, on);
|
||||
ids[n] = self.s.m.select(c, hit, children[n], none);
|
||||
distances[n] = self.s.m.select(c, hit, enter, infinity);
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
|
||||
let (da, db) = (distances[a], distances[b]);
|
||||
distances[a] = self.s.m.select(c, swap, db, da);
|
||||
distances[b] = self.s.m.select(c, swap, da, db);
|
||||
let (ia, ib) = (ids[a], ids[b]);
|
||||
ids[a] = self.s.m.select(c, swap, ib, ia);
|
||||
ids[b] = self.s.m.select(c, swap, ia, ib);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
|
||||
/// four result dwords, made in the current block.
|
||||
fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
|
||||
let c = self.cur;
|
||||
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
|
||||
// The triangle's byte of the dword at byte 60: which of its
|
||||
// vertices barycentric I and J weigh.
|
||||
let id = self.bvh_node_words(at, None, 60, 1)[0];
|
||||
let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
|
||||
let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
|
||||
let id = self.s.m.bin(c, Bin::LShr, id, shift);
|
||||
let i = self.s.m.bin(c, Bin::And, id, k3);
|
||||
let j = self.s.m.bin(c, Bin::LShr, id, k2);
|
||||
let j = self.s.m.bin(c, Bin::And, j, k3);
|
||||
let first = self.s.m.bin(c, Bin::Sub, k3, i);
|
||||
let first = self.s.m.bin(c, Bin::Sub, first, j);
|
||||
let first = self.s.m.bin(c, Bin::And, first, k3);
|
||||
// The node's vertices the triangle is made of, four bits each.
|
||||
let (k0, k1) = (k(self, 0), k(self, 1));
|
||||
let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
|
||||
let (is0, is1, is2) = (
|
||||
self.s.m.cmp(c, pred::EQ, kind, k0),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k1),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k2),
|
||||
);
|
||||
let map = self.s.m.select(c, is2, maps[2], maps[3]);
|
||||
let map = self.s.m.select(c, is1, maps[1], map);
|
||||
let map = self.s.m.select(c, is0, maps[0], map);
|
||||
let mut p = Vec::with_capacity(3);
|
||||
for n in [first, i, j] {
|
||||
let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
|
||||
let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
|
||||
let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
|
||||
let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
|
||||
let words = self.bvh_node_words(at, Some(byte), 0, 3);
|
||||
// Relative to the ray's origin.
|
||||
let r: Vec<V> = (0..3)
|
||||
.map(|a| {
|
||||
let f = self.as_float(words[a]);
|
||||
self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
|
||||
})
|
||||
.collect();
|
||||
p.push([r[0], r[1], r[2]]);
|
||||
}
|
||||
// The ray's largest axis z, and x and y after it in an order that
|
||||
// keeps the winding.
|
||||
let fzero = self.s.m.f32(0);
|
||||
let size = ray.direction.map(|d| self.unary(6, d));
|
||||
let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
|
||||
let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
|
||||
let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
|
||||
let z0 = self.s.m.bin(c, Bin::And, xy, xz);
|
||||
let on = self.s.m.bool(true);
|
||||
let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
|
||||
let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
|
||||
// Component (kz + n) % 3 of `q`.
|
||||
let pick = |l: &mut Self, q: [V; 3], n: usize| {
|
||||
let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
|
||||
l.s.m.select(c, z0, q[n % 3], rest)
|
||||
};
|
||||
let dz = pick(self, ray.direction, 0);
|
||||
let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
|
||||
// (x, y, z) of `q`: the two after the largest axis, swapped for a
|
||||
// ray that runs backwards along it.
|
||||
let axes = |l: &mut Self, q: [V; 3]| {
|
||||
let (x, y) = (pick(l, q, 1), pick(l, q, 2));
|
||||
[
|
||||
l.s.m.select(c, backwards, y, x),
|
||||
l.s.m.select(c, backwards, x, y),
|
||||
pick(l, q, 0),
|
||||
]
|
||||
};
|
||||
let d = axes(self, ray.direction);
|
||||
let sz = pick(self, ray.inverse, 0);
|
||||
let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
|
||||
let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
|
||||
let mut sheared = Vec::with_capacity(3);
|
||||
for r in p {
|
||||
let r = axes(self, r);
|
||||
let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
|
||||
let x = self.s.m.bin(c, Bin::Sub, r[0], x);
|
||||
let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
|
||||
let y = self.s.m.bin(c, Bin::Sub, r[1], y);
|
||||
let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
|
||||
sheared.push((x, y, z));
|
||||
}
|
||||
let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
|
||||
unreachable!()
|
||||
};
|
||||
// p * q - r * s.
|
||||
let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
|
||||
let a = l.s.m.bin(c, Bin::Mul, p, q);
|
||||
let b = l.s.m.bin(c, Bin::Mul, r, s);
|
||||
l.s.m.bin(c, Bin::Sub, a, b)
|
||||
};
|
||||
let u = cross(self, cx, by, cy, bx);
|
||||
let v = cross(self, ax, cy, ay, cx);
|
||||
let w = cross(self, bx, ay, by, ax);
|
||||
let any = |l: &mut Self, p: u8| {
|
||||
let a = l.s.m.cmp(c, p, u, fzero);
|
||||
let b = l.s.m.cmp(c, p, v, fzero);
|
||||
let d = l.s.m.cmp(c, p, w, fzero);
|
||||
let a = l.s.m.bin(c, Bin::Or, a, b);
|
||||
l.s.m.bin(c, Bin::Or, a, d)
|
||||
};
|
||||
let behind = any(self, pred::OLT);
|
||||
let before = any(self, pred::OGT);
|
||||
let outside = self.s.m.bin(c, Bin::And, behind, before);
|
||||
let inside = self.s.m.bin(c, Bin::Xor, outside, on);
|
||||
let det = self.s.m.bin(c, Bin::Add, v, w);
|
||||
let det = self.s.m.bin(c, Bin::Add, u, det);
|
||||
let t = self.s.m.bin(c, Bin::Mul, u, az);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
// The distance is not negative: the numerator has the
|
||||
// denominator's sign (or is 0). Ordered compares: a denominator
|
||||
// of 0 or a NaN is a miss.
|
||||
let front = self.s.m.cmp(c, pred::OGT, det, fzero);
|
||||
let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
|
||||
let front = self.s.m.bin(c, Bin::And, front, front_ahead);
|
||||
let back = self.s.m.cmp(c, pred::OLT, det, fzero);
|
||||
let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
|
||||
let back = self.s.m.bin(c, Bin::And, back, back_ahead);
|
||||
let ahead = self.s.m.bin(c, Bin::Or, front, back);
|
||||
let hit = self.s.m.bin(c, Bin::And, inside, ahead);
|
||||
let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
|
||||
let out = [t, det, v, w];
|
||||
std::array::from_fn(|n| {
|
||||
let f = self.s.m.select(c, hit, out[n], miss[n]);
|
||||
self.as_int(f)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! The ray-tracing node test end to end: a synthetic compute program that
|
||||
//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
|
||||
//! lowered to DXIL, validated by `dxil.dll` when present, run on the host
|
||||
//! GPU and WARP, and compared dword for dword with the CPU reference
|
||||
//! ([`crate::bvh`]).
|
||||
//!
|
||||
//! The nodes are in a raw buffer. Two ways to name it are run: the
|
||||
//! buffer's descriptor from the program's table (a resource of the host,
|
||||
//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
|
||||
//! descriptor of numbers over title memory with the structure's address in
|
||||
//! the node pointer or in the descriptor. These tests have no host that
|
||||
//! keeps copies of title memory and their directory, so for the second
|
||||
//! they put a stand-in under the node reader
|
||||
//! (`lower::intersect::TEST_MEMORY`); without it the same program reads
|
||||
//! through the directory, which is only checked to lower and validate.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::lower::intersect::TEST_MEMORY;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::bvh::{self, Ray, tests as nodes};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::resource::BvhNodes;
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Threads of one group, each with its own record.
|
||||
const THREADS: u32 = 32;
|
||||
/// Bytes of a thread's record: the node pointer (two dwords), the ray's
|
||||
/// extent, origin, direction and inverse direction, and whether the
|
||||
/// thread runs the instruction.
|
||||
const RECORD: u32 = 64;
|
||||
/// Where the nodes start in the buffer.
|
||||
const NODES: u32 = THREADS * RECORD;
|
||||
/// What the result registers hold before the instruction.
|
||||
const BEFORE: [u32; 4] = [1, 2, 3, 4];
|
||||
|
||||
/// How the program names the nodes' memory.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Descriptor {
|
||||
/// The buffer's descriptor from the table.
|
||||
Table,
|
||||
/// Numbers, as the title builds it: dwords 0 and 1 (the base address
|
||||
/// in 256-byte units and the box sorting bit); the size and the rest of
|
||||
/// the flags as the title sets them.
|
||||
Numbers(u32, u32),
|
||||
}
|
||||
|
||||
/// The descriptor the title builds for the 64-bit form: the whole address
|
||||
/// space, sorted boxes, barycentrics returned.
|
||||
const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
|
||||
|
||||
/// The program: per thread, the record's twelve operand dwords in v1-v12,
|
||||
/// the instruction's result in v13-v16 (under a lane mask of the threads
|
||||
/// whose record says so), stored to the UAV at 16 bytes a thread.
|
||||
fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
|
||||
let mut w = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x3428_0086, // v_lshlrev_b32 v20, 6, v0
|
||||
0xE038_1000,
|
||||
0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
|
||||
0xE038_1010,
|
||||
0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
|
||||
0xE038_1020,
|
||||
0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
|
||||
0xE030_1030,
|
||||
0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
|
||||
];
|
||||
for k in 0..4u32 {
|
||||
// v_mov_b32 v13+k, 1+k
|
||||
w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
|
||||
}
|
||||
let rsrc = match descriptor {
|
||||
Descriptor::Table => 8,
|
||||
Descriptor::Numbers(word0, word1) => {
|
||||
// s_mov_b32 s24, word0
|
||||
w.extend([0xBE98_03FF, word0]);
|
||||
if word1 == bvh::BOX_SORT {
|
||||
// As the title makes it.
|
||||
w.push(0xBE99_0B81); // s_brev_b32 s25, 1
|
||||
} else {
|
||||
w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
|
||||
}
|
||||
w.extend([
|
||||
0xBE9A_03C1, // s_mov_b32 s26, -1
|
||||
0xBE9B_03FF,
|
||||
0x8900_03FF, // s_mov_b32 s27, 0x890003ff
|
||||
]);
|
||||
24
|
||||
}
|
||||
};
|
||||
w.extend([
|
||||
0xBE94_037E, // s_mov_b32 s20, exec_lo
|
||||
0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
|
||||
]);
|
||||
let first = 0x0000_0D01 | (rsrc >> 2) << 16;
|
||||
if wide {
|
||||
// image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
|
||||
} else {
|
||||
// image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
|
||||
}
|
||||
w.extend([
|
||||
0xBEFE_0314, // s_mov_b32 exec_lo, s20
|
||||
0x342A_0084, // v_lshlrev_b32 v21, 4, v0
|
||||
0xE078_1000,
|
||||
0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
]);
|
||||
w
|
||||
}
|
||||
|
||||
fn native(words: &[u32]) -> NativeProgram {
|
||||
let table = |kind, at| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: at,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 22,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [THREADS, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowers the program; the DXIL is validated when the validator is there.
|
||||
fn build(
|
||||
wide: bool,
|
||||
descriptor: Descriptor,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
let native = native(&program(wide, descriptor));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
Ok((shader, res))
|
||||
}
|
||||
|
||||
/// One thread's test: a node (by its index in the node list), the kind its
|
||||
/// pointer carries, and the ray; `None` leaves the thread masked out.
|
||||
type Case = Option<(usize, u32, Ray)>;
|
||||
|
||||
/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
|
||||
/// where each node starts, in dwords from the first node.
|
||||
struct Scene {
|
||||
words: Vec<u32>,
|
||||
starts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
words: Vec::new(),
|
||||
starts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a node of `dwords` (16 or 32) and returns its index.
|
||||
fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
|
||||
self.starts.push(self.words.len());
|
||||
let mut padded = [0u32; 32];
|
||||
padded[..28].copy_from_slice(&node);
|
||||
// Bytes the instruction must not read as part of the node: what
|
||||
// follows a 64-byte node, and a box node's last 16 bytes.
|
||||
for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
|
||||
*w = 0x7fc0_dead;
|
||||
}
|
||||
self.words.extend(&padded[..dwords]);
|
||||
self.starts.len() - 1
|
||||
}
|
||||
|
||||
/// The pointer of node `n` with `kind`, counted from the first node.
|
||||
fn pointer(&self, n: usize, kind: u32) -> u32 {
|
||||
(4 * self.starts[n] as u32) >> 3 | kind
|
||||
}
|
||||
|
||||
/// What the instruction reads of node `n`.
|
||||
fn node(&self, n: usize) -> [u32; 28] {
|
||||
std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A small generator of repeatable numbers.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self
|
||||
.0
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) as u32
|
||||
}
|
||||
|
||||
/// A float in -1..1 in steps of 1/4096 (exactly representable).
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() % 8193) as f32 / 4096.0 - 1.0
|
||||
}
|
||||
|
||||
fn vector(&mut self, scale: f32) -> [f32; 3] {
|
||||
[
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The scene and batches of cases over it.
|
||||
fn scene() -> (Scene, Vec<Vec<Case>>) {
|
||||
let mut s = Scene::new();
|
||||
let mut g = Numbers(0x5eed);
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
let moved =
|
||||
|b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
|
||||
let off = [f32::NAN; 6];
|
||||
let mut box_nodes = Vec::new();
|
||||
// The boxes of the reference's own tests, in both widths.
|
||||
let lined = [
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
];
|
||||
let ids = [0x105, 0x20c, 0x304, 0x400];
|
||||
box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
|
||||
// Boxes around the origin, one switched off, one child missing.
|
||||
let around = [
|
||||
UNIT,
|
||||
moved(UNIT, [0.5, 0.5, 0.5]),
|
||||
off,
|
||||
[-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
|
||||
];
|
||||
let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
|
||||
box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
|
||||
// Random boxes.
|
||||
for n in 0..6 {
|
||||
let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
|
||||
let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
|
||||
std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
|
||||
});
|
||||
let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
|
||||
if n % 2 == 0 {
|
||||
box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
|
||||
} else {
|
||||
box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
|
||||
}
|
||||
}
|
||||
// Triangles: one of the reference's tests, a pair as the title's
|
||||
// builder stores it, all four triangles of a full node with turned
|
||||
// ids, random ones.
|
||||
let mut triangle_nodes = Vec::new();
|
||||
let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
|
||||
let pair = s.add(
|
||||
nodes::triangles(
|
||||
&[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
|
||||
9 | 0x80 | 6 << 8,
|
||||
),
|
||||
16,
|
||||
);
|
||||
triangle_nodes.extend([(pair, 0), (pair, 1)]);
|
||||
let five = [
|
||||
[-3.0, -1.0, 6.0],
|
||||
[-1.0, 2.0, 6.5],
|
||||
[1.0, -1.0, 6.0],
|
||||
[3.0, 2.0, 6.5],
|
||||
[5.0, -1.0, 7.0],
|
||||
];
|
||||
// I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
|
||||
let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
|
||||
triangle_nodes.extend((0..4).map(|k| (full, k)));
|
||||
for _ in 0..5 {
|
||||
let c = g.vector(6.0);
|
||||
let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
|
||||
let d = g.vector(3.0);
|
||||
[c[0] + d[0], c[1] + d[1], c[2] + d[2]]
|
||||
});
|
||||
triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
|
||||
}
|
||||
let mut cases: Vec<Case> = Vec::new();
|
||||
// Rays of the reference's tests against the lined-up boxes.
|
||||
for &(n, kind) in &box_nodes[..2] {
|
||||
for (origin, direction, extent) in [
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.5),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.0),
|
||||
([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
|
||||
([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [0.0; 3], 1000.0),
|
||||
] {
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Random rays at every box node, half of them aimed at a box.
|
||||
for &(n, kind) in &box_nodes {
|
||||
let words = s.node(n);
|
||||
let boxes = if kind == 5 {
|
||||
bvh::boxes32(&words)
|
||||
} else {
|
||||
bvh::boxes16(&words)
|
||||
};
|
||||
for k in 0..12 {
|
||||
let origin = g.vector(12.0);
|
||||
let direction = if k % 2 == 0 {
|
||||
let b = boxes[(k / 2) % 4];
|
||||
if b[0].is_nan() {
|
||||
g.vector(1.0)
|
||||
} else {
|
||||
std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
|
||||
}
|
||||
} else {
|
||||
g.vector(1.0)
|
||||
};
|
||||
let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Rays at every triangle: aimed inside, at an edge, at a vertex, past
|
||||
// it, from both sides, along each axis.
|
||||
for &(n, kind) in &triangle_nodes {
|
||||
let p = bvh::triangle_vertices(&s.node(n), kind);
|
||||
let at = |w: [f32; 3]| -> [f32; 3] {
|
||||
std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
|
||||
};
|
||||
for (k, w) in [
|
||||
[0.5, 0.25, 0.25],
|
||||
[0.125, 0.75, 0.125],
|
||||
[0.5, 0.5, 0.0],
|
||||
[0.0, 0.5, 0.5],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.75, 0.75, -0.5],
|
||||
[-0.25, 0.5, 0.75],
|
||||
[0.25, 0.25, 0.5],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let target = at(w);
|
||||
let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
|
||||
let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
|
||||
if k == 7 {
|
||||
// The triangle lies behind.
|
||||
direction = direction.map(|d| -d);
|
||||
}
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
for axis in 0..3 {
|
||||
for sign in [1.0f32, -1.0] {
|
||||
let target = at([0.25, 0.5, 0.25]);
|
||||
let mut origin = target;
|
||||
origin[axis] -= 8.0 * sign;
|
||||
let mut direction = [0.0; 3];
|
||||
direction[axis] = sign;
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Kinds the instruction does not read, and threads masked out.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
cases.extend([
|
||||
Some((triangle_nodes[0].0, 6, ray)),
|
||||
Some((triangle_nodes[0].0, 7, ray)),
|
||||
None,
|
||||
Some((
|
||||
box_nodes[0].0,
|
||||
5,
|
||||
Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
)),
|
||||
None,
|
||||
]);
|
||||
let batches = cases
|
||||
.chunks(THREADS as usize)
|
||||
.map(<[Case]>::to_vec)
|
||||
.collect();
|
||||
(s, batches)
|
||||
}
|
||||
|
||||
/// The buffer for one batch: the threads' records, then the nodes. Node
|
||||
/// pointers count from `base` before the first node, in bytes.
|
||||
fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
|
||||
let mut data = vec![0u32; (NODES / 4) as usize];
|
||||
for (t, case) in batch.iter().enumerate() {
|
||||
let Some((n, kind, ray)) = case else { continue };
|
||||
let r = &mut data[t * (RECORD / 4) as usize..][..13];
|
||||
let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
|
||||
(r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
|
||||
r[2] = ray.extent.to_bits();
|
||||
for a in 0..3 {
|
||||
r[3 + a] = ray.origin[a].to_bits();
|
||||
r[6 + a] = ray.direction[a].to_bits();
|
||||
r[9 + a] = ray.inverse[a].to_bits();
|
||||
}
|
||||
r[12] = 1;
|
||||
}
|
||||
data.extend(&scene.words);
|
||||
data
|
||||
}
|
||||
|
||||
fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
|
||||
match case {
|
||||
Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
|
||||
None => BEFORE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tests' title memory for this thread until dropped.
|
||||
struct Memory;
|
||||
|
||||
impl Memory {
|
||||
fn at(base: u64) -> Self {
|
||||
// Heap slot 0: the buffer of records and nodes.
|
||||
TEST_MEMORY.set(Some((0, base)));
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
TEST_MEMORY.set(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs every batch on the hardware adapter and WARP and compares with
|
||||
/// the reference. `pointers` is what node pointers count from, in bytes
|
||||
/// before the first node.
|
||||
fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
|
||||
let (shader, res) = build(wide, descriptor).expect("the program lowers");
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
let (scene, batches) = scene();
|
||||
// The reference must see a bit of everything, or the comparison
|
||||
// proves little.
|
||||
let all: Vec<&Case> = batches.iter().flatten().collect();
|
||||
let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
|
||||
let boxes = |hits: usize| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 4 | 5, _)))
|
||||
&& r.iter().filter(|&&x| x != bvh::NONE).count() == hits
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let triangles = |hit: bool| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
|
||||
})
|
||||
.count()
|
||||
};
|
||||
assert!(
|
||||
boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
|
||||
"box cases"
|
||||
);
|
||||
assert!(
|
||||
triangles(true) > 30 && triangles(false) > 30,
|
||||
"triangle cases"
|
||||
);
|
||||
// Sorting must matter to some case, or the unsorted run proves nothing.
|
||||
assert!(
|
||||
all.iter()
|
||||
.any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
|
||||
"no case tells sorted from unsorted"
|
||||
);
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = 0;
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
|
||||
for (b, batch) in batches.iter().enumerate() {
|
||||
let data = buffer(&scene, batch, pointers);
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(vec![0; 5]))],
|
||||
views: &[
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::RawUav(4 * THREADS),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
for t in 0..THREADS as usize {
|
||||
let case = batch.get(t).copied().flatten();
|
||||
let want = match batch.get(t) {
|
||||
Some(c) => expected(&scene, c, sort),
|
||||
// A thread past the batch: its record is zeros, so it
|
||||
// is masked out.
|
||||
None => BEFORE,
|
||||
};
|
||||
let got = &out[0][4 * t..4 * t + 4];
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
|
||||
got,
|
||||
got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
|
||||
want,
|
||||
want.map(f32::from_bits),
|
||||
);
|
||||
}
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "no SM 6.6 device available");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
// Pointers count from the buffer's start.
|
||||
run(true, Descriptor::Table, u64::from(NODES), true);
|
||||
assert_eq!(
|
||||
build(true, Descriptor::Table).unwrap().1.bvh[0].1,
|
||||
BvhNodes::Resource
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
run(false, Descriptor::Table, u64::from(NODES), true);
|
||||
}
|
||||
|
||||
/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
|
||||
const BASE: u64 = 0x12_3456_7800;
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's way: one descriptor for all of memory, the structure's
|
||||
// address folded into a 64-bit pointer.
|
||||
let _memory = Memory::at(BASE);
|
||||
run(true, WHOLE, BASE + u64::from(NODES), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's other way: the structure's address in the descriptor
|
||||
// (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
|
||||
// an address past 2^40 bytes, and without box sorting.
|
||||
let base = 0x312_3456_7800u64;
|
||||
let structure = base + u64::from(NODES);
|
||||
let _memory = Memory::at(base);
|
||||
let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
|
||||
run(false, descriptor, 0, false);
|
||||
// And sorted.
|
||||
let descriptor = Descriptor::Numbers(
|
||||
(structure >> 8) as u32,
|
||||
(structure >> 40) as u32 | bvh::BOX_SORT,
|
||||
);
|
||||
run(false, descriptor, 0, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
|
||||
for wide in [true, false] {
|
||||
let native = native(&program(wide, WHOLE));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
// The flags the title sets: sorted boxes, barycentrics, a
|
||||
// ray-tracing structure. No resource is taken for it: the buffer
|
||||
// loads' and the store's descriptors are all there is.
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
assert_eq!(
|
||||
res.bvh[0].1,
|
||||
BvhNodes::Memory {
|
||||
word1: 0x8000_0000,
|
||||
word3: 0x8900_03ff
|
||||
}
|
||||
);
|
||||
assert_eq!(res.descriptors.len(), 5);
|
||||
// Without the tests' stand-in the nodes are read as the title's
|
||||
// programs will read them: through the host's directory of title
|
||||
// memory. The program lowers and validates, and asks the host for
|
||||
// the directory and for the list of pages it found no copy of.
|
||||
let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
|
||||
assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
|
||||
assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
|
||||
// Triangle return mode 0 (bit 24 of dword 3 clear): the last two
|
||||
// result dwords would be a triangle id and a hit status.
|
||||
let mut words = program(true, WHOLE);
|
||||
let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
|
||||
words[flags] = 0x8800_03FF;
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let r = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
match r {
|
||||
Err(ShaderError::Unsupported { what, .. }) => {
|
||||
assert_eq!(what, "a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
other => panic!("{:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,914 @@
|
||||
//! Wave ORs that only steer a loop over each lane's own bits.
|
||||
//!
|
||||
//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and
|
||||
//! the wave walks the set bits of the result together, each lane working only where its own
|
||||
//! mask has the bit:
|
||||
//!
|
||||
//! ```text
|
||||
//! merged = WaveActiveBitOr(mask); // over the lanes that run
|
||||
//! while (merged != 0) {
|
||||
//! bit = firstbitlow(merged);
|
||||
//! if (mask & (1 << bit)) { ... } // the body
|
||||
//! merged ^= 1 << bit;
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not
|
||||
//! every lane runs (a group barrier must be reached by every thread). It does not have to: as
|
||||
//! one thread runs it, the loop visits the bits of `merged` in rising order and does something
|
||||
//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits
|
||||
//! gives that thread the same run. The host wave's own OR is such a value.
|
||||
//!
|
||||
//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the
|
||||
//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no
|
||||
//! instruction sequence taken on trust:
|
||||
//!
|
||||
//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the
|
||||
//! first-lane read of it, the set less the visited bit) are read only by the loop's own
|
||||
//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test
|
||||
//! that ends the loop;
|
||||
//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a
|
||||
//! lane only reaches with that test true in the same round;
|
||||
//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that
|
||||
//! is read after the loop or carried into a later round, and is left only by the test for
|
||||
//! "no bits left";
|
||||
//! - no lane mask that depends on the test is used outside the round that made it.
|
||||
//!
|
||||
//! Anything else is refused there as before ("a wave reduction where not every lane runs") and
|
||||
//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the
|
||||
//! skips left out, the branches around it taken wave-wide), where the halves do exchange.
|
||||
//! `VICTORY_WAVE_OWN_BITS=0` turns this off.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::wave::{self, Op, Shape};
|
||||
use crate::gfx10::{Fields, NULL, Operand};
|
||||
use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
|
||||
type Why = &'static str;
|
||||
|
||||
const USED: Why = "a wave OR used as data";
|
||||
const NO_LOOP: Why = "a wave OR that steers no loop over its bits";
|
||||
const SHAPE: Why = "a loop over a wave OR's bits of another shape";
|
||||
const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit";
|
||||
const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round";
|
||||
const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits";
|
||||
const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits";
|
||||
const EXIT: Why = "a loop over a wave OR's bits left another way";
|
||||
const STALE: Why = "a lane's own-bit test used outside its round";
|
||||
const MASK: Why = "a wave OR over a mask a running lane may be outside";
|
||||
|
||||
/// What [`find`] proved.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct OwnBits {
|
||||
/// Wave ORs (the values their sections leave) a host wave may take over its own lanes.
|
||||
pub totals: HashSet<Value>,
|
||||
/// VGPR values of those loops that every lane of a host wave holds alike (the bits still
|
||||
/// to visit): a first-lane read of one is the lane's own value.
|
||||
pub alike: HashSet<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum User {
|
||||
Inst(usize, usize),
|
||||
Phi(usize, usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Arg {
|
||||
Val(Value),
|
||||
K(u32),
|
||||
Other,
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
p: &'a Program,
|
||||
st: &'a Structured,
|
||||
users: HashMap<Value, Vec<User>>,
|
||||
/// The instruction writing each value.
|
||||
def: HashMap<Value, (usize, usize)>,
|
||||
/// Values an instruction reads, directly or through joins.
|
||||
live: HashSet<Value>,
|
||||
idom: Vec<usize>,
|
||||
sections: Vec<HashMap<usize, wave::Section>>,
|
||||
}
|
||||
|
||||
/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane
|
||||
/// masks are followed as booleans) and without the old value of a VGPR it writes, which only
|
||||
/// lanes outside a guard keep.
|
||||
fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> {
|
||||
let inst = &p.blocks[b].insts[i];
|
||||
let ops = crate::ir::operand_reads(p, inst);
|
||||
let guarded = st.guards[b][i].is_some();
|
||||
inst.reads
|
||||
.iter()
|
||||
.filter(|&&(r, _)| match r {
|
||||
Reg::S(c) if c == EXEC || c == EXEC + 1 => false,
|
||||
Reg::V(_) => ops.contains(&r) || guarded,
|
||||
_ => true,
|
||||
})
|
||||
.map(|r| r.1)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn value(inst: &Inst, op: &Operand) -> Option<Value> {
|
||||
match *op {
|
||||
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
|
||||
Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources of a scalar or unmodified vector operation.
|
||||
fn args(inst: &Inst) -> Vec<Arg> {
|
||||
let src: &[Operand] = match &inst.fields {
|
||||
Fields::Sop { src, .. } => src,
|
||||
Fields::Valu(v)
|
||||
if v.dpp.is_none()
|
||||
&& v.sdwa.is_none()
|
||||
&& v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0 =>
|
||||
{
|
||||
&v.src
|
||||
}
|
||||
_ => &[],
|
||||
};
|
||||
src.iter()
|
||||
.map(|o| match (value(inst, o), o) {
|
||||
(Some(v), _) => Arg::Val(v),
|
||||
(None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K),
|
||||
(None, &Operand::Literal(x)) => Arg::K(x),
|
||||
_ => Arg::Other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The other source of a two-source operation that reads `a`.
|
||||
fn other(inst: &Inst, a: Value) -> Option<Arg> {
|
||||
match args(inst)[..] {
|
||||
[Arg::Val(x), o] if x == a => Some(o),
|
||||
[o, Arg::Val(x)] if x == a => Some(o),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The scalar (not SCC) or vector dword an instruction writes, if it writes one.
|
||||
fn result(inst: &Inst) -> Option<Value> {
|
||||
let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc);
|
||||
match (w.next(), w.next()) {
|
||||
(Some(&(_, v)), None) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program
|
||||
/// sends.
|
||||
fn effect(inst: &Inst) -> bool {
|
||||
let name = inst.name();
|
||||
matches!(inst.fields, Fields::Exp { .. })
|
||||
|| matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
|
||||
|| name.contains("store")
|
||||
|| name.contains("atomic")
|
||||
|| matches!(inst.fields, Fields::Ds { .. })
|
||||
&& !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute"))
|
||||
|| matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt")
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> {
|
||||
let mut users: HashMap<Value, Vec<User>> = HashMap::new();
|
||||
let mut def = HashMap::new();
|
||||
let mut live: HashSet<Value> = HashSet::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (k, phi) in block.phis.iter().enumerate() {
|
||||
for &a in &phi.args {
|
||||
users.entry(a).or_default().push(User::Phi(b, k));
|
||||
}
|
||||
}
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
for v in used(p, st, b, i) {
|
||||
users.entry(v).or_default().push(User::Inst(b, i));
|
||||
live.insert(v);
|
||||
}
|
||||
for &(_, w) in &inst.writes {
|
||||
def.insert(w, (b, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
// through joins
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for block in &p.blocks {
|
||||
for phi in &block.phis {
|
||||
if live.contains(&phi.value) {
|
||||
for &a in &phi.args {
|
||||
changed |= live.insert(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let order = crate::ir::reverse_postorder(&p.blocks);
|
||||
let mut index = vec![usize::MAX; p.blocks.len()];
|
||||
for (n, &b) in order.iter().enumerate() {
|
||||
index[b] = n;
|
||||
}
|
||||
let idom = crate::ir::idoms(&p.blocks, &order, &index);
|
||||
let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect();
|
||||
Ctx {
|
||||
p,
|
||||
st,
|
||||
users,
|
||||
def,
|
||||
live,
|
||||
idom,
|
||||
sections,
|
||||
}
|
||||
}
|
||||
|
||||
fn inst(&self, u: (usize, usize)) -> &Inst {
|
||||
&self.p.blocks[u.0].insts[u.1]
|
||||
}
|
||||
|
||||
fn at(&self, u: (usize, usize)) -> usize {
|
||||
self.inst(u).machine.offset
|
||||
}
|
||||
|
||||
/// Whether block `a` dominates block `b`.
|
||||
fn dominates(&self, a: usize, mut b: usize) -> bool {
|
||||
loop {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
let d = self.idom.get(b).copied().unwrap_or(usize::MAX);
|
||||
if d == b || d == usize::MAX {
|
||||
return false;
|
||||
}
|
||||
b = d;
|
||||
}
|
||||
}
|
||||
|
||||
fn readers(&self, v: Value) -> Vec<(usize, usize)> {
|
||||
let mut out: Vec<(usize, usize)> = self
|
||||
.users
|
||||
.get(&v)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|u| match *u {
|
||||
User::Inst(b, i) => Some((b, i)),
|
||||
User::Phi(..) => None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The joins reading `v` whose value something reads.
|
||||
fn joins(&self, v: Value) -> Vec<(usize, usize)> {
|
||||
let mut out: Vec<(usize, usize)> = self
|
||||
.users
|
||||
.get(&v)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|u| match *u {
|
||||
User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The loop of header `h`: the blocks that reach one of its back edges without passing it.
|
||||
fn natural_loop(&self, h: usize) -> Vec<bool> {
|
||||
let mut inside = vec![false; self.p.blocks.len()];
|
||||
let mut work: Vec<usize> = self.p.blocks[h]
|
||||
.preds
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&q| self.dominates(h, q))
|
||||
.collect();
|
||||
if work.is_empty() {
|
||||
return inside;
|
||||
}
|
||||
inside[h] = true;
|
||||
while let Some(b) = work.pop() {
|
||||
if inside[b] {
|
||||
continue;
|
||||
}
|
||||
inside[b] = true;
|
||||
work.extend(self.p.blocks[b].preds.iter().copied());
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// Whether `b` holds only in lanes where `a` does.
|
||||
fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool {
|
||||
if b == Bool::FALSE {
|
||||
return true;
|
||||
}
|
||||
if let Some(&r) = memo.get(&b) {
|
||||
return r;
|
||||
}
|
||||
let r = match self.st.bools.node(b) {
|
||||
None => false,
|
||||
Some((x, lo, _)) if x == a => lo == Bool::FALSE,
|
||||
Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo),
|
||||
};
|
||||
memo.insert(b, r);
|
||||
r
|
||||
}
|
||||
|
||||
/// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is
|
||||
/// set, the other one).
|
||||
fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> {
|
||||
let [u] = self.readers(scc)[..] else {
|
||||
return None;
|
||||
};
|
||||
let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else {
|
||||
return None;
|
||||
};
|
||||
if u.1 + 1 != self.p.blocks[u.0].insts.len() {
|
||||
return None;
|
||||
}
|
||||
match self.inst(u).name() {
|
||||
"s_cbranch_scc1" => Some((u, taken, not_taken)),
|
||||
"s_cbranch_scc0" => Some((u, not_taken, taken)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the
|
||||
/// VGPR values its loop keeps alike, or where and why it is not such a loop.
|
||||
fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> {
|
||||
let p = self.p;
|
||||
let st = self.st;
|
||||
let n = p.blocks.len();
|
||||
let here = p.blocks[sb].offset;
|
||||
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
|
||||
// every lane that runs the section is one of the lanes ORed
|
||||
let &mb = st.masks.get(&mask).ok_or((here, MASK))?;
|
||||
if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) {
|
||||
return Err((here, MASK));
|
||||
}
|
||||
// ---- the bits still to visit, and the loop's own steps ----
|
||||
let mut rem: HashSet<Value> = HashSet::from([t]);
|
||||
let mut pattern: HashSet<(usize, usize)> = HashSet::new();
|
||||
let mut alike: Vec<Value> = Vec::new();
|
||||
// an unguarded copy
|
||||
let copy = |u: (usize, usize)| -> Option<Value> {
|
||||
let i = self.inst(u);
|
||||
(matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none())
|
||||
.then(|| result(i))
|
||||
.flatten()
|
||||
};
|
||||
let mut init = vec![t];
|
||||
// (SCC, whether it is set when the OR is empty)
|
||||
let mut zero: Option<(Value, bool)> = None;
|
||||
for u in self.readers(t) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
|
||||
&& other(i, t) == Some(Arg::K(0))
|
||||
&& zero.is_none()
|
||||
&& let Some(scc) = i.write(Reg::Scc)
|
||||
{
|
||||
zero = Some((scc, name.contains("_eq_")));
|
||||
rem.insert(scc);
|
||||
} else if let Some(w) = copy(u) {
|
||||
init.push(w);
|
||||
rem.insert(w);
|
||||
if matches!(i.writes[0].0, Reg::V(_)) {
|
||||
alike.push(w);
|
||||
}
|
||||
} else {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
// the loop's join of them
|
||||
let mut join: Option<(usize, usize)> = None;
|
||||
for &v in &init {
|
||||
if v != t
|
||||
&& let Some(&u) = self.readers(v).first()
|
||||
{
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
for j in self.joins(v) {
|
||||
if join.is_some_and(|q| q != j) {
|
||||
return Err((p.blocks[j.0].offset, USED));
|
||||
}
|
||||
join = Some(j);
|
||||
}
|
||||
}
|
||||
let (h, k) = join.ok_or((here, NO_LOOP))?;
|
||||
let phi = &p.blocks[h].phis[k];
|
||||
let r = phi.value;
|
||||
rem.insert(r);
|
||||
let head = p.blocks[h].offset;
|
||||
let lp = self.natural_loop(h);
|
||||
if !lp[h] || lp[sb] {
|
||||
return Err((head, NO_LOOP));
|
||||
}
|
||||
// the set as a scalar: the first lane's copy of it
|
||||
let cur = if matches!(phi.reg, Reg::V(_)) {
|
||||
alike.push(r);
|
||||
let [u] = self.readers(r)[..] else {
|
||||
return Err((head, USED));
|
||||
};
|
||||
let i = self.inst(u);
|
||||
if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
let c = result(i).ok_or((self.at(u), SHAPE))?;
|
||||
if !self.joins(r).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
c
|
||||
} else {
|
||||
r
|
||||
};
|
||||
rem.insert(cur);
|
||||
// its lowest bit, the set without it, the tests for "that was the last"
|
||||
let mut idx: Option<Value> = None;
|
||||
let mut next: Option<(Value, Value)> = None;
|
||||
// (SCC, whether it is set while bits remain)
|
||||
let mut more: Vec<(Value, bool)> = Vec::new();
|
||||
let mut bits: Vec<Value> = Vec::new();
|
||||
for u in self.readers(cur) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if !lp[u.0] {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
match (name, &args(i)[..]) {
|
||||
("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i),
|
||||
("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => {
|
||||
let bit = match (name, &args(i)[..]) {
|
||||
("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b,
|
||||
("s_xor_b32", _) => match other(i, cur) {
|
||||
Some(Arg::Val(b)) if b != cur => b,
|
||||
_ => return Err((self.at(u), USED)),
|
||||
},
|
||||
_ => return Err((self.at(u), USED)),
|
||||
};
|
||||
let w = result(i).ok_or((self.at(u), SHAPE))?;
|
||||
next = Some((w, bit));
|
||||
bits.push(bit);
|
||||
if let Some(scc) = i.write(Reg::Scc) {
|
||||
more.push((scc, true));
|
||||
rem.insert(scc);
|
||||
}
|
||||
}
|
||||
("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => {
|
||||
let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else {
|
||||
return Err((self.at(u), USED));
|
||||
};
|
||||
bits.push(b);
|
||||
more.push((scc, name.contains("_lg_")));
|
||||
rem.insert(scc);
|
||||
}
|
||||
_ => return Err((self.at(u), USED)),
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
if cur != r && !self.joins(cur).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
let (Some(idx), Some((nx, bit))) = (idx, next) else {
|
||||
return Err((head, SHAPE));
|
||||
};
|
||||
if bits.iter().any(|&b| b != bit) {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it)
|
||||
let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u)));
|
||||
let shifted = match made(bit) {
|
||||
Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] {
|
||||
[Arg::K(1), Arg::Val(sh)] => Some(sh),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let by_idx = shifted.is_some_and(|sh| {
|
||||
sh == idx
|
||||
|| made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)))
|
||||
});
|
||||
if !by_idx {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// the set less the bit: back into the join, or tested for empty
|
||||
rem.insert(nx);
|
||||
let mut nexts = vec![nx];
|
||||
for u in self.readers(nx) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
|
||||
&& other(i, nx) == Some(Arg::K(0))
|
||||
&& let Some(scc) = i.write(Reg::Scc)
|
||||
{
|
||||
more.push((scc, name.contains("_lg_")));
|
||||
rem.insert(scc);
|
||||
} else if let Some(w) = copy(u) {
|
||||
nexts.push(w);
|
||||
rem.insert(w);
|
||||
if matches!(i.writes[0].0, Reg::V(_)) {
|
||||
alike.push(w);
|
||||
}
|
||||
} else {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
for &v in &nexts {
|
||||
if v != nx
|
||||
&& let Some(&u) = self.readers(v).first()
|
||||
{
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
if self.joins(v).iter().any(|&j| j != (h, k)) {
|
||||
return Err((head, USED));
|
||||
}
|
||||
}
|
||||
for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) {
|
||||
let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) };
|
||||
if !ok {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
}
|
||||
// the loop goes on while bits remain and is left when none does
|
||||
let mut leaves: HashSet<usize> = HashSet::new();
|
||||
for &(scc, set_while_more) in &more {
|
||||
if !self.joins(scc).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
if self.readers(scc).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (u, set, clear) = self.branch(scc).ok_or((head, USED))?;
|
||||
let (on, out) = if set_while_more { (set, clear) } else { (clear, set) };
|
||||
if !lp[u.0] || !lp[on] || lp[out] {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
leaves.insert(u.0);
|
||||
pattern.insert(u);
|
||||
}
|
||||
if leaves.is_empty() {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// "no bit at all" skips the loop; what lies between that test and the loop runs only
|
||||
// when there is one
|
||||
let mut pre = vec![false; n];
|
||||
if let Some((scc, set_when_empty)) = zero {
|
||||
if !self.joins(scc).is_empty() {
|
||||
return Err((here, USED));
|
||||
}
|
||||
if !self.readers(scc).is_empty() {
|
||||
let (u, set, clear) = self.branch(scc).ok_or((here, USED))?;
|
||||
let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) };
|
||||
if none == some || lp[u.0] {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
if some != h {
|
||||
if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
for b in 0..n {
|
||||
pre[b] = self.dominates(some, b) && !self.dominates(h, b);
|
||||
}
|
||||
for b in (0..n).filter(|&b| pre[b]) {
|
||||
let inside = match p.blocks[b].exit {
|
||||
Exit::End | Exit::Indirect => false,
|
||||
ref e => e.successors().iter().all(|&s| pre[s] || s == h),
|
||||
};
|
||||
if !inside {
|
||||
return Err((p.blocks[b].offset, SHAPE));
|
||||
}
|
||||
}
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
}
|
||||
// ---- the lane's test of its own bit ----
|
||||
// (the atom of the compare, its block, its index)
|
||||
let mut tests: Vec<(Atom, usize, usize)> = Vec::new();
|
||||
for u in self.readers(bit) {
|
||||
let i = self.inst(u);
|
||||
if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(y) = result(i) else { continue };
|
||||
for c in self.readers(y) {
|
||||
let ci = self.inst(c);
|
||||
if matches!(
|
||||
ci.name(),
|
||||
"v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32"
|
||||
| "v_cmp_lg_i32" | "v_cmpx_lg_i32"
|
||||
) && other(ci, y) == Some(Arg::K(0))
|
||||
&& lp[c.0]
|
||||
{
|
||||
tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if tests.is_empty() {
|
||||
return Err((head, TEST));
|
||||
}
|
||||
let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()];
|
||||
// what a lane only reaches with its own bit set, in the round of that test
|
||||
let mut body_block = vec![false; n];
|
||||
for b in (0..n).filter(|&b| lp[b]) {
|
||||
body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| {
|
||||
b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j])
|
||||
});
|
||||
}
|
||||
let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| {
|
||||
body_block[b]
|
||||
|| lp[b]
|
||||
&& st.guards[b][i].is_some_and(|g| {
|
||||
tests.iter().enumerate().any(|(j, &(a, tb, ti))| {
|
||||
(b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j])
|
||||
})
|
||||
})
|
||||
};
|
||||
// ---- a round outside the body leaves nothing behind ----
|
||||
for b in (0..n).filter(|&b| lp[b] || pre[b]) {
|
||||
for (i, inst) in p.blocks[b].insts.iter().enumerate() {
|
||||
if lp[b] && body_inst(b, i, &mut memo) {
|
||||
continue;
|
||||
}
|
||||
let u = (b, i);
|
||||
for &(reg, w) in &inst.writes {
|
||||
if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) {
|
||||
continue;
|
||||
}
|
||||
for user in self.users.get(&w).into_iter().flatten() {
|
||||
let stays = match *user {
|
||||
User::Inst(b2, _) => lp[b2] || pre[b2],
|
||||
User::Phi(b2, k2) => {
|
||||
body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value)
|
||||
}
|
||||
};
|
||||
if !stays {
|
||||
return Err((self.at(u), LEAVES));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.contains(&u) {
|
||||
continue;
|
||||
}
|
||||
if effect(inst) {
|
||||
return Err((self.at(u), EFFECT));
|
||||
}
|
||||
let name = inst.name();
|
||||
let cross = name.starts_with("ds_swizzle")
|
||||
|| name.contains("permute")
|
||||
|| name.starts_with("v_mbcnt")
|
||||
|| name.contains("lane")
|
||||
|| matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some())
|
||||
|| super::lower::reads_mask_as_data(st, inst)
|
||||
|| self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end);
|
||||
if cross {
|
||||
return Err((self.at(u), CROSS));
|
||||
}
|
||||
if used(p, st, b, i).iter().any(|v| rem.contains(v)) {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
}
|
||||
// left only by "no bits left"; the body may leave it as it likes
|
||||
if lp[b] && !body_block[b] {
|
||||
let ok = match p.blocks[b].exit {
|
||||
Exit::End | Exit::Indirect => false,
|
||||
ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]),
|
||||
};
|
||||
if !ok {
|
||||
return Err((p.blocks[b].offset, EXIT));
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---- no mask that depends on the test outlives its round ----
|
||||
let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect();
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (&id, edges) in &st.phi_masks {
|
||||
if !dep.contains(&Atom::Phi(id))
|
||||
&& edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a)))
|
||||
{
|
||||
dep.insert(Atom::Phi(id));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen: HashMap<Bool, bool> = HashMap::new();
|
||||
let mut tainted = |b: Bool| -> bool {
|
||||
*seen
|
||||
.entry(b)
|
||||
.or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a)))
|
||||
};
|
||||
for b in 0..n {
|
||||
if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) {
|
||||
continue;
|
||||
}
|
||||
let stale = st.guards[b].iter().flatten().any(|&g| tainted(g))
|
||||
|| matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when));
|
||||
if stale {
|
||||
return Err((p.blocks[b].offset, STALE));
|
||||
}
|
||||
}
|
||||
for (&v, &m) in &st.masks {
|
||||
if !tainted(m) {
|
||||
continue;
|
||||
}
|
||||
for user in self.users.get(&v).into_iter().flatten() {
|
||||
let outside = match *user {
|
||||
User::Inst(b2, _) => !lp[b2],
|
||||
User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value),
|
||||
};
|
||||
if outside {
|
||||
return Err((head, STALE));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(alike)
|
||||
}
|
||||
}
|
||||
|
||||
/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module
|
||||
/// notes). `why`: one line on stderr for each wave OR that is not one.
|
||||
pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits {
|
||||
let mut out = OwnBits::default();
|
||||
let mut ctx: Option<Ctx> = None;
|
||||
for b in 0..p.blocks.len() {
|
||||
let sections = wave::sections(p, b);
|
||||
let mut starts: Vec<_> = sections.keys().copied().collect();
|
||||
starts.sort_unstable();
|
||||
for s in starts {
|
||||
let sec = §ions[&s];
|
||||
let mut left: Vec<_> = sec.shapes.iter().collect();
|
||||
left.sort_unstable_by_key(|(v, _)| v.0);
|
||||
for (&t, &shape) in left {
|
||||
let Shape::Active(Op::Or, x, mask, 0) = shape else {
|
||||
continue;
|
||||
};
|
||||
let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st));
|
||||
// (values only the section itself reads are not results)
|
||||
let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end);
|
||||
if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) {
|
||||
continue;
|
||||
}
|
||||
match ctx.site(b, t, x, mask) {
|
||||
Ok(alike) => {
|
||||
out.totals.insert(t);
|
||||
out.alike.extend(alike);
|
||||
}
|
||||
Err((offset, what)) => {
|
||||
if why {
|
||||
eprintln!(
|
||||
"WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}",
|
||||
p.blocks[b].insts[s].machine.offset
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::emit::wave::WAVE_OR_V7_TO_S7;
|
||||
|
||||
const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5
|
||||
|
||||
/// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`,
|
||||
/// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest
|
||||
/// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit
|
||||
/// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after
|
||||
/// the loop.
|
||||
fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program {
|
||||
let mut w = WAVE_OR_V7_TO_S7.to_vec();
|
||||
let test: &[u32] = if own {
|
||||
&[
|
||||
0x3608_0E0B, // v_and_b32 v4, s11, v7
|
||||
0xBE8C_047E, // s_mov_b64 s[12:13], exec
|
||||
0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4
|
||||
]
|
||||
} else {
|
||||
&[0xBE8C_047E] // s_mov_b64 s[12:13], exec
|
||||
};
|
||||
// from the loop's head to its last branch
|
||||
let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3;
|
||||
w.extend_from_slice(&[
|
||||
0xBF06_8007, // s_cmp_eq_u32 s7, 0
|
||||
0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop
|
||||
0x7E06_0207, // v_mov_b32 v3, s7
|
||||
0xBF82_0001, // s_branch to the loop's head
|
||||
0x7E06_0209, // again: v_mov_b32 v3, s9
|
||||
0x7E10_0503, // head: v_readfirstlane_b32 s8, v3
|
||||
0xBE8A_1308, // s_ff1_i32_b32 s10, s8
|
||||
0x8F0B_0A81, // s_lshl_b32 s11, 1, s10
|
||||
]);
|
||||
w.extend_from_slice(test);
|
||||
if own {
|
||||
w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body
|
||||
}
|
||||
w.extend_from_slice(body);
|
||||
w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
|
||||
w.extend_from_slice(latch);
|
||||
w.extend_from_slice(&[
|
||||
0x8909_080B, // s_xor_b32 s9, s11, s8
|
||||
0xBF06_0B08, // s_cmp_eq_u32 s8, s11
|
||||
0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again
|
||||
]);
|
||||
w.extend_from_slice(after);
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
crate::ir::build(&code, true, 256).unwrap()
|
||||
}
|
||||
|
||||
fn found(p: &Program) -> OwnBits {
|
||||
let st = crate::structure::structure(p).unwrap();
|
||||
find(p, &st, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() {
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]);
|
||||
let insts = || p.blocks.iter().flat_map(|b| &b.insts);
|
||||
let names: Vec<&str> = insts().map(|i| i.name()).collect();
|
||||
for n in [
|
||||
"s_ff1_i32_b32",
|
||||
"s_lshl_b32",
|
||||
"v_and_b32",
|
||||
"v_cmpx_ne_u32",
|
||||
"s_xor_b32",
|
||||
"v_readfirstlane_b32",
|
||||
"s_cbranch_execz",
|
||||
] {
|
||||
assert!(names.contains(&n), "{n} in {names:?}");
|
||||
}
|
||||
// a loop: its last branch goes back to the copy of the bits still to visit
|
||||
assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b)));
|
||||
let own = found(&p);
|
||||
// the OR is the section's last lane read, and the bits still to visit (v3) are alike
|
||||
let total = insts()
|
||||
.rfind(|i| i.name() == "v_readlane_b32")
|
||||
.and_then(|i| i.write(Reg::S(7)))
|
||||
.unwrap();
|
||||
assert_eq!(own.totals, HashSet::from([total]));
|
||||
let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap();
|
||||
assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() {
|
||||
// (the same title's volume loops, 0xa668 on: no test of the lane's own mask)
|
||||
let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() {
|
||||
// v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() {
|
||||
// v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too
|
||||
let p = light_loop(true, &[0x4A0A_0A08], &[], &[]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_of_the_rounds_is_not_the_lanes_own() {
|
||||
// s_add_i32 s14, s14, 1 where every lane passes, read after the loop
|
||||
// (v_mov_b32 v6, s14): one round for each bit any lane has
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]);
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32"));
|
||||
assert!(found(&p).totals.is_empty());
|
||||
// (reading s14 there without counting in it is nothing of the loop's)
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]);
|
||||
assert_eq!(found(&p).totals.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_where_every_lane_passes_is_not_the_lanes_own() {
|
||||
// ds_write_b32 v5, v5 after the body: once for each bit any lane has
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]);
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32"));
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! The geometry shader that completes the console's rectangle lists (list
|
||||
//! topology 17, pipeline topology type 19). A rectangle comes as three
|
||||
//! vertices, three corners of a screen-aligned rectangle; the hardware
|
||||
//! draws the whole rectangle and continues every vertex shader output
|
||||
//! linearly into the fourth corner. The host has no such topology: the
|
||||
//! draw goes out as a triangle list with this shader behind the translated
|
||||
//! vertex shader, so vertex counts, vertex numbers, indices and indirect
|
||||
//! arguments stay the title's, and each rectangle arrives here as one
|
||||
//! triangle.
|
||||
//!
|
||||
//! Which vertex is the corner between the other two varies:
|
||||
//! the title's full-screen rectangles come as top left, bottom left, bottom
|
||||
//! right (the second), its tiled lighting as top left, bottom left, top
|
||||
//! right (the first). The corner is the vertex that shares x with one of
|
||||
//! the others and y with the other; the fourth vertex lies opposite it,
|
||||
//! `a + b - corner` for the position and every float output. That holds
|
||||
//! for three vertices with one positive w (then it is the same in clip
|
||||
//! space and on the screen, whatever the interpolation mode); three that
|
||||
//! differ in w, or are not such corners, stay the triangle they make.
|
||||
//!
|
||||
//! Flat values are the first vertex's: both triangles start with it (the
|
||||
//! halves on either side of the diagonal through it, turning as the three
|
||||
//! vertices do), which is the vertex the host takes a flat input from, and
|
||||
//! the fourth vertex's integer outputs are the first vertex's.
|
||||
//!
|
||||
//! shortcut: that the console takes a rectangle's flat values from its
|
||||
//! first vertex follows from the hardware's provoking-vertex setting for
|
||||
//! triangles; it is not measured on a rectangle.
|
||||
|
||||
use super::bitcode::{Attr, Bin, Term, V, pred};
|
||||
use super::container::SigElement;
|
||||
use super::shader::{Geometry, Shader};
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::{Container, FourCC};
|
||||
|
||||
/// Vertices emitted per rectangle: two triangles.
|
||||
const VERTICES: u32 = 6;
|
||||
|
||||
/// The scalars a geometry shader may emit per invocation (vertices times
|
||||
/// output components).
|
||||
const MAX_SCALARS: u32 = 1024;
|
||||
|
||||
/// The geometry shader (a DXIL container) for rectangle lists drawn with
|
||||
/// the translated vertex shader `vs` and, if the pipeline has one, the
|
||||
/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its
|
||||
/// inputs and outputs are the vertex shader's outputs, register for
|
||||
/// register, so it links with both. A pixel shader that declares a
|
||||
/// primitive id gets the rectangle's number, which the host leaves to the
|
||||
/// geometry stage when there is one.
|
||||
pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
|
||||
let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> {
|
||||
let c = Container::parse(dxil)?;
|
||||
match c.part(fourcc) {
|
||||
Some(part) => super::signature(part.data),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
};
|
||||
let outputs = sig(vs, FourCC::OSG1)?;
|
||||
let wanted = match ps {
|
||||
Some(ps) => sig(ps, FourCC::ISG1)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
build(outputs, &wanted)
|
||||
}
|
||||
|
||||
/// [`rect_list_gs`] from the vertex shader's outputs and the pixel
|
||||
/// shader's inputs.
|
||||
fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> {
|
||||
let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
|
||||
if outputs.iter().any(|e| e.row.is_none()) {
|
||||
return Err(unsupported("a rectangle list output without a register"));
|
||||
}
|
||||
let Some(position) = outputs
|
||||
.iter()
|
||||
.position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4)
|
||||
else {
|
||||
return Err(unsupported("a rectangle list without a four-component position"));
|
||||
};
|
||||
for e in &mut outputs {
|
||||
// Interpolation as `emit_program` declares a vertex shader's
|
||||
// outputs; a geometry shader's inputs carry the same modes.
|
||||
e.interp = match (e.kind, e.comp) {
|
||||
(3, _) => 4,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
e.usage = (1 << e.cols) - 1;
|
||||
}
|
||||
let mut s = Shader::new(false);
|
||||
s.geometry = Some(Geometry {
|
||||
max_vertices: VERTICES,
|
||||
});
|
||||
s.inputs = outputs.clone();
|
||||
// The primitive id the pixel shader declares, as one more output.
|
||||
let wanted = ps_inputs
|
||||
.iter()
|
||||
.find(|e| e.kind == 10 && e.row.is_some())
|
||||
.filter(|_| !outputs.iter().any(|o| o.kind == 10));
|
||||
let primitive = match wanted {
|
||||
Some(e) => {
|
||||
// Alone in its columns, and in a row of constant elements.
|
||||
let clash = outputs.iter().any(|o| {
|
||||
let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols;
|
||||
o.row == e.row && (o.interp != 1 || overlap)
|
||||
});
|
||||
if clash {
|
||||
return Err(unsupported(
|
||||
"a rectangle list whose primitive id shares a register with a vertex output",
|
||||
));
|
||||
}
|
||||
outputs.push(SigElement {
|
||||
interp: 1,
|
||||
usage: (1 << e.cols) - 1,
|
||||
..e.clone()
|
||||
});
|
||||
Some(outputs.len() - 1)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum();
|
||||
if scalars * VERTICES > MAX_SCALARS {
|
||||
return Err(unsupported(
|
||||
"a rectangle list with more output components than a geometry shader emits",
|
||||
));
|
||||
}
|
||||
s.outputs = outputs;
|
||||
let b = s.entry;
|
||||
|
||||
// Every input of the three vertices: [element][column][vertex].
|
||||
let mut corners: Vec<Vec<[V; 3]>> = Vec::new();
|
||||
for id in 0..s.inputs.len() {
|
||||
let mut columns = Vec::new();
|
||||
for col in 0..s.inputs[id].cols {
|
||||
columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex)));
|
||||
}
|
||||
corners.push(columns);
|
||||
}
|
||||
|
||||
// One positive w, and no two vertices in one place.
|
||||
let (x, y, w) = (
|
||||
corners[position][0],
|
||||
corners[position][1],
|
||||
corners[position][3],
|
||||
);
|
||||
let zero = s.m.f32(0);
|
||||
let mut plain = s.m.cmp(b, pred::OGT, w[0], zero);
|
||||
for &other in &w[1..] {
|
||||
let one_w = same(&mut s, other, w[0]);
|
||||
plain = both(&mut s, plain, one_w);
|
||||
}
|
||||
for (i, j) in [(0, 1), (0, 2), (1, 2)] {
|
||||
let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j]));
|
||||
let together = both(&mut s, same_x, same_y);
|
||||
let apart = not(&mut s, together);
|
||||
plain = both(&mut s, plain, apart);
|
||||
}
|
||||
// corner[i]: vertex i is the corner between the other two (the first
|
||||
// that shares x with one of them and y with the other).
|
||||
let mut corner: Vec<V> = Vec::new();
|
||||
for i in 0..3 {
|
||||
let (a, c) = ((i + 1) % 3, (i + 2) % 3);
|
||||
let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c]));
|
||||
let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a]));
|
||||
let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya));
|
||||
let shares = either(&mut s, one, other);
|
||||
let mut here = both(&mut s, shares, plain);
|
||||
for &found in &corner {
|
||||
let earlier = not(&mut s, found);
|
||||
here = both(&mut s, here, earlier);
|
||||
}
|
||||
corner.push(here);
|
||||
}
|
||||
|
||||
// What the six emitted vertices carry: [element][column][vertex].
|
||||
let mut emitted: Vec<Vec<[V; 6]>> = Vec::new();
|
||||
for (id, columns) in corners.iter().enumerate() {
|
||||
let float = s.inputs[id].comp == 9;
|
||||
let mut out = Vec::new();
|
||||
for &[p0, p1, p2] in columns {
|
||||
// The fourth vertex: `a + b - corner`. Integers (flat), and
|
||||
// three vertices without a corner, keep the first vertex's
|
||||
// value; the second triangle of the latter is then empty.
|
||||
let mut fourth = p0;
|
||||
if float {
|
||||
for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let sum = s.m.bin(b, Bin::Add, a, c);
|
||||
let opposite = s.m.bin(b, Bin::Sub, sum, at);
|
||||
fourth = s.m.select(b, corner[k], opposite, fourth);
|
||||
}
|
||||
}
|
||||
// Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1,
|
||||
// v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1).
|
||||
let third = s.m.select(b, corner[0], fourth, p2);
|
||||
let fifth = s.m.select(b, corner[1], p2, fourth);
|
||||
let sixth = s.m.select(b, corner[0], p2, p1);
|
||||
let sixth = s.m.select(b, corner[1], fourth, sixth);
|
||||
out.push([p0, p1, third, p0, fifth, sixth]);
|
||||
}
|
||||
emitted.push(out);
|
||||
}
|
||||
|
||||
// The rectangle's number: the triangle's, three vertices a rectangle.
|
||||
let mut number = None;
|
||||
if let Some(id) = primitive {
|
||||
let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]);
|
||||
number = Some((id, n));
|
||||
}
|
||||
let stream = s.m.i8(0);
|
||||
for vertex in 0..VERTICES as usize {
|
||||
for (id, columns) in emitted.iter().enumerate() {
|
||||
let name = if s.outputs[id].comp == 9 {
|
||||
"storeOutput.f32"
|
||||
} else {
|
||||
"storeOutput.i32"
|
||||
};
|
||||
for (col, values) in columns.iter().enumerate() {
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col as u8),
|
||||
values[vertex],
|
||||
];
|
||||
s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
if let Some((id, n)) = number {
|
||||
let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n];
|
||||
s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]);
|
||||
// The strip ends after the first triangle.
|
||||
if vertex == 2 {
|
||||
s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
Ok(s.finish())
|
||||
}
|
||||
|
||||
/// Column `col` of input `id` at vertex `vertex` of the triangle.
|
||||
fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V {
|
||||
let (name, ty) = if s.inputs[id].comp == 9 {
|
||||
("loadInput.f32", s.t.f32)
|
||||
} else {
|
||||
("loadInput.i32", s.t.i32)
|
||||
};
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col),
|
||||
s.m.i32(vertex),
|
||||
];
|
||||
let entry = s.entry;
|
||||
s.op(entry, name, Attr::ReadNone, ty, 4, &args)
|
||||
}
|
||||
|
||||
/// Two floats are equal.
|
||||
fn same(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.cmp(entry, pred::OEQ, a, b)
|
||||
}
|
||||
|
||||
fn both(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::And, a, b)
|
||||
}
|
||||
|
||||
fn either(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::Or, a, b)
|
||||
}
|
||||
|
||||
fn not(s: &mut Shader, a: V) -> V {
|
||||
let (entry, on) = (s.entry, s.m.bool(true));
|
||||
s.m.bin(entry, Bin::Xor, a, on)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index,
|
||||
kind,
|
||||
comp,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A position, a float interpolant and an integer one.
|
||||
fn outputs() -> Vec<SigElement> {
|
||||
vec![
|
||||
element("SV_Position", 0, 3, 9, 0, 4),
|
||||
element("TEXCOORD", 0, 0, 9, 1, 4),
|
||||
element("TEXCOORD", 1, 0, 5, 2, 2),
|
||||
]
|
||||
}
|
||||
|
||||
/// The stage is a geometry shader of triangles in and six strip
|
||||
/// vertices out, with the vertex shader's outputs on both sides and
|
||||
/// the primitive id the pixel shader declares; the validator, where
|
||||
/// there is one, accepts it.
|
||||
#[test]
|
||||
fn the_rectangle_stage_is_a_geometry_shader() {
|
||||
let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)];
|
||||
let gs = build(outputs(), &wanted).unwrap();
|
||||
let c = Container::parse(&gs).unwrap();
|
||||
// Program version: geometry (2), shader model 6.6.
|
||||
assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]);
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
// Triangles in, triangle strips out, stream 0, a position.
|
||||
assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]);
|
||||
// Geometry stage, six vertices, three inputs, four outputs.
|
||||
assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]);
|
||||
let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap();
|
||||
let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1));
|
||||
assert_eq!(ins.len(), 3);
|
||||
assert_eq!(outs.len(), 4);
|
||||
for (i, o) in ins.iter().zip(&outs) {
|
||||
assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row));
|
||||
assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp));
|
||||
}
|
||||
assert_eq!((outs[3].kind, outs[3].row), (10, Some(3)));
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut gs.clone()).unwrap();
|
||||
let plain = build(outputs(), &[]).unwrap();
|
||||
v.validate(&mut plain.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused with a reason: no position, a primitive id in a register a
|
||||
/// vertex output has, more components than six vertices may carry.
|
||||
#[test]
|
||||
fn rectangle_stages_that_cannot_be_made_are_refused() {
|
||||
assert!(build(outputs()[1..].to_vec(), &[]).is_err());
|
||||
let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)];
|
||||
assert!(build(outputs(), &taken).is_err());
|
||||
let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)];
|
||||
many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4)));
|
||||
assert!(build(many, &[]).is_err());
|
||||
}
|
||||
|
||||
/// A vertex shader that passes a position and a float4 through, and a
|
||||
/// pixel shader that writes the float4.
|
||||
#[cfg(windows)]
|
||||
fn pass_through() -> (super::super::HostShader, super::super::HostShader) {
|
||||
let position = SigElement {
|
||||
interp: 4,
|
||||
usage: 15,
|
||||
..element("SV_Position", 0, 3, 9, 0, 4)
|
||||
};
|
||||
let coord = SigElement {
|
||||
interp: 2,
|
||||
usage: 15,
|
||||
..element("TEXCOORD", 0, 0, 9, 1, 4)
|
||||
};
|
||||
let mut vs = Shader::new(false);
|
||||
vs.inputs = vec![
|
||||
SigElement {
|
||||
usage: 15,
|
||||
..element("POSITION", 0, 0, 9, 0, 4)
|
||||
},
|
||||
SigElement {
|
||||
interp: 0,
|
||||
..coord.clone()
|
||||
},
|
||||
];
|
||||
vs.outputs = vec![position.clone(), coord.clone()];
|
||||
let mut ps = Shader::new(true);
|
||||
ps.inputs = vec![
|
||||
SigElement {
|
||||
usage: 0,
|
||||
..position
|
||||
},
|
||||
coord,
|
||||
];
|
||||
ps.outputs = vec![SigElement {
|
||||
usage: 15,
|
||||
..element("SV_Target", 0, 16, 9, 0, 4)
|
||||
}];
|
||||
// Vertex: output id from input id. Pixel: target 0 from input 1.
|
||||
for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] {
|
||||
let b = s.entry;
|
||||
for &(from, to) in copies {
|
||||
for col in 0..4 {
|
||||
let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
|
||||
let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
|
||||
let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v];
|
||||
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
}
|
||||
let host = |stage, s: Shader| super::super::HostShader {
|
||||
stage,
|
||||
dxil: s.finish(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
(
|
||||
host(crate::native::HwStage::Vs, vs),
|
||||
host(crate::native::HwStage::Ps, ps),
|
||||
)
|
||||
}
|
||||
|
||||
/// Three corners of the whole target, the corner between the other two
|
||||
/// first (as the tiled lighting sends its tiles), second (as
|
||||
/// full-screen rectangles come) or third: with the stage every texel
|
||||
/// is drawn and the interpolant continues into the fourth corner's
|
||||
/// half; without it part of the target is not drawn.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn rectangles_are_drawn_whole() {
|
||||
use super::super::host::{Draw, Host};
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 device; skipped");
|
||||
return;
|
||||
};
|
||||
let (vs, ps) = pass_through();
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut vs.dxil.clone()).unwrap();
|
||||
v.validate(&mut ps.dxil.clone()).unwrap();
|
||||
}
|
||||
let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap();
|
||||
let root = host.root_signature(&vs, &ps).unwrap();
|
||||
// Position (z 0.5, w 1) and an interpolant that is the position.
|
||||
let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0];
|
||||
for (name, corners) in [
|
||||
("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]),
|
||||
("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]),
|
||||
("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]),
|
||||
] {
|
||||
let vertices = corners.map(vertex).concat();
|
||||
let draw = |gs: Option<&[u8]>| {
|
||||
let pso = host
|
||||
.pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil)
|
||||
.unwrap();
|
||||
let d = Draw {
|
||||
roots: Vec::new(),
|
||||
textures: &[],
|
||||
samplers: &[],
|
||||
vertices: &vertices,
|
||||
stride: 32,
|
||||
size: (8, 8),
|
||||
mesh_groups: 0,
|
||||
};
|
||||
host.draw(&root, &pso, &d).unwrap()
|
||||
};
|
||||
let whole = draw(Some(&gs[..]));
|
||||
for (i, texel) in whole.iter().enumerate() {
|
||||
let (x, y) = ((i % 8) as f32, (i / 8) as f32);
|
||||
let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0];
|
||||
assert!(
|
||||
texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4),
|
||||
"{name}: texel {i} is {texel:?}, not {want:?}"
|
||||
);
|
||||
}
|
||||
let half = draw(None);
|
||||
let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count();
|
||||
assert!(missing >= 24, "{name}: only {missing} texels need the stage");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Immediate samplers: the console's four sampler words (the GPU's public
|
||||
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
|
||||
//!
|
||||
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
|
||||
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
|
||||
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
|
||||
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
|
||||
//! magnification and minification filters (20-21, 22-23: point, linear,
|
||||
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
|
||||
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
|
||||
//! opaque white, custom).
|
||||
//!
|
||||
//! Comparison is the sampling instruction's, not the sampler's: the console
|
||||
//! encodes a comparison function in every sampler (D3D's default, less or
|
||||
//! equal, when unused).
|
||||
|
||||
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
|
||||
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
|
||||
/// `D3D12_STATIC_BORDER_COLOR` values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct StaticSampler {
|
||||
pub filter: u32,
|
||||
/// U, V, W.
|
||||
pub address: [u32; 3],
|
||||
pub mip_lod_bias: f32,
|
||||
pub max_anisotropy: u32,
|
||||
pub comparison: u32,
|
||||
pub border: u32,
|
||||
pub min_lod: f32,
|
||||
pub max_lod: f32,
|
||||
}
|
||||
|
||||
// The floats come from fixed-point fields: never NaN.
|
||||
impl Eq for StaticSampler {}
|
||||
|
||||
impl StaticSampler {
|
||||
/// Decodes the four sampler words.
|
||||
pub fn from_words(w: [u32; 4]) -> Self {
|
||||
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
|
||||
// wrap, mirror, clamp, mirror once; the half-border modes have no
|
||||
// D3D form and become their nearest.
|
||||
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
|
||||
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
|
||||
let reduction = match bits(w[0], 29, 2) {
|
||||
1 => 2,
|
||||
2 => 3,
|
||||
_ => 0,
|
||||
};
|
||||
let filter = if mag >= 2 || min >= 2 {
|
||||
0x55 | reduction << 7
|
||||
} else {
|
||||
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
|
||||
};
|
||||
let lod = |v: u32| v as f32 / 256.0;
|
||||
// Without a mip filter the base level is sampled.
|
||||
let (min_lod, max_lod) = if mip == 0 {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
|
||||
};
|
||||
StaticSampler {
|
||||
filter,
|
||||
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
|
||||
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
|
||||
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
|
||||
comparison: bits(w[0], 12, 3) + 1,
|
||||
// shortcut: a custom border colour (type 3, a table entry) becomes
|
||||
// transparent black; upgrade when a title uses one.
|
||||
border: bits(w[3], 30, 2) % 3,
|
||||
min_lod,
|
||||
max_lod,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn console_compiled_samplers_decode() {
|
||||
// Words the console compiler wrote for static samplers of known
|
||||
// descriptions.
|
||||
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
point,
|
||||
StaticSampler {
|
||||
filter: 0,
|
||||
address: [1, 2, 3],
|
||||
mip_lod_bias: 0.5,
|
||||
max_anisotropy: 1,
|
||||
comparison: 4,
|
||||
border: 2,
|
||||
min_lod: 1.0,
|
||||
max_lod: 5.25,
|
||||
}
|
||||
);
|
||||
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(aniso.filter, aniso.address, aniso.max_anisotropy),
|
||||
(0x55, [4, 5, 3], 8)
|
||||
);
|
||||
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
|
||||
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
|
||||
assert_eq!(
|
||||
(compare.filter, compare.address, compare.border),
|
||||
(0x14, [4, 1, 1], 1)
|
||||
);
|
||||
let minimum =
|
||||
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
|
||||
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
|
||||
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
|
||||
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
|
||||
let max_aniso =
|
||||
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(
|
||||
max_aniso.filter,
|
||||
max_aniso.max_anisotropy,
|
||||
max_aniso.mip_lod_bias
|
||||
),
|
||||
(0x1D5, 16, 15.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
|
||||
//! the `dx.op` declarations it calls, its signatures and bound resources,
|
||||
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
|
||||
|
||||
use super::bitcode::{Attr, Md, Module, Ty, V};
|
||||
use super::container::{self, Binding, Psv, SigElement};
|
||||
|
||||
/// Where the shader reads its user data: `b0` in this space.
|
||||
pub const USER_DATA_SPACE: u32 = 0;
|
||||
/// Where immediate samplers are bound: `s<n>` in this space.
|
||||
pub const SAMPLER_SPACE: u32 = 0;
|
||||
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
|
||||
/// `t<root parameter index>` in this space.
|
||||
pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
|
||||
/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
|
||||
/// reads buffers through descriptors it picks from the view heap at an
|
||||
/// index it computes (SM 6.6 dynamic resources): a raw buffer of
|
||||
/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
|
||||
/// element of the buffer view at heap slot `i` (0: none or not a buffer).
|
||||
/// The console's descriptor holds that stride and its hardware multiplies
|
||||
/// the element index by it; the program's code does not say it, and the
|
||||
/// used-resource list only names what tables hold. A shader that has this
|
||||
/// root SRV also tells the host that the buffer views of the whole heap
|
||||
/// must be ready when it runs, not only those its tables name.
|
||||
pub const SLOT_STRIDES: u8 = 255;
|
||||
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
|
||||
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
|
||||
|
||||
/// Title memory by address (`resource::MEMORY`): console code reads and
|
||||
/// writes through raw 40-bit addresses it takes from root constants,
|
||||
/// descriptors and other memory (the ray-tracing structure builder and the
|
||||
/// programs that walk its structures). The host keeps copies of the title
|
||||
/// memory shaders use; a shader with such an access finds the copy by the
|
||||
/// address:
|
||||
///
|
||||
/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
|
||||
/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
|
||||
/// address space: the number of the host copy holding that page (0: none
|
||||
/// yet) and the page's byte offset in that copy;
|
||||
/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
|
||||
/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
|
||||
/// reads zeros and drops writes;
|
||||
/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
|
||||
/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
|
||||
/// host reads afterwards to make those copies for the frames to come.
|
||||
pub const SLOT_MEMORY: u8 = 254;
|
||||
/// See [`SLOT_MEMORY`].
|
||||
pub const SLOT_FAULTS: u8 = 253;
|
||||
/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
|
||||
pub const MEMORY_PAGES: u32 = 1 << 21;
|
||||
/// Dwords of the [`SLOT_FAULTS`] buffer.
|
||||
pub const MEMORY_FAULTS: u32 = 4096;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the view
|
||||
/// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
|
||||
pub const USER_MEMORY_BASE: u32 = 0x100;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the low
|
||||
/// 32 bits of the title address of the buffer view at dword `dword` of the
|
||||
/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
|
||||
/// its bits from 32 up. (Console code reads the address out of a buffer
|
||||
/// descriptor and uses it as a pointer.)
|
||||
pub const USER_VIEW_ADDRESS: u32 = 0x101;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the
|
||||
/// bytes (0 to 15) by which the raw view the host binds for the root view
|
||||
/// of root parameter `slot` begins before the title's address. A raw view
|
||||
/// begins on 16 bytes of its host buffer; the console's root views begin
|
||||
/// anywhere (the structure builder's counters sit at addresses ending in
|
||||
/// 4 and c). The shader adds the dword to every byte offset through that
|
||||
/// view. Asked for every root UAV, and for the root SRVs of programs with
|
||||
/// a spilled user-data table.
|
||||
pub const USER_VIEW_BIAS: u32 = 0x103;
|
||||
|
||||
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
|
||||
pub(crate) mod flags {
|
||||
pub const RAW_BUFFERS: u64 = 1 << 4;
|
||||
pub const DOUBLES: u64 = 1 << 2;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
pub const ATOMIC_TYPED64: u64 = 1 << 27;
|
||||
pub const ATOMIC_HEAP64: u64 = 1 << 32;
|
||||
pub const RESOURCE_HEAP: u64 = 1 << 30;
|
||||
pub const SAMPLER_HEAP: u64 = 1 << 31;
|
||||
pub const ROVS: u64 = 1 << 18;
|
||||
}
|
||||
|
||||
pub(crate) struct Types {
|
||||
pub void: Ty,
|
||||
pub i1: Ty,
|
||||
pub i32: Ty,
|
||||
pub f32: Ty,
|
||||
pub handle: Ty,
|
||||
pub props: Ty,
|
||||
pub bind: Ty,
|
||||
pub cbuf_ret: Ty,
|
||||
pub res_ret: Ty,
|
||||
}
|
||||
|
||||
/// What a mesh shader declares beyond its thread-group size.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Mesh {
|
||||
pub max_vertices: u32,
|
||||
pub max_primitives: u32,
|
||||
/// 1 lines, 2 triangles.
|
||||
pub topology: u8,
|
||||
}
|
||||
|
||||
/// What a geometry shader declares: triangles in, triangle strips out on
|
||||
/// stream 0, one instance.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Geometry {
|
||||
pub max_vertices: u32,
|
||||
}
|
||||
|
||||
/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while
|
||||
/// it is set read that slot for any view index at or past it. A read past a heap's end is
|
||||
/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
|
||||
/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD
|
||||
/// RDNA3 took a page fault and removed the device.
|
||||
static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
|
||||
pub fn set_view_heap_limit(null_slot: u32) {
|
||||
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
|
||||
pub fn view_heap_limit() -> u32 {
|
||||
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) struct Shader {
|
||||
pub m: Module,
|
||||
pub t: Types,
|
||||
pub pixel: bool,
|
||||
pub inputs: Vec<SigElement>,
|
||||
pub outputs: Vec<SigElement>,
|
||||
/// A mesh shader's per-primitive outputs.
|
||||
pub prims: Vec<SigElement>,
|
||||
/// A mesh shader (`threads` is its thread-group size).
|
||||
pub mesh: Option<Mesh>,
|
||||
/// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
|
||||
pub geometry: Option<Geometry>,
|
||||
/// Dwords of user data the shader reads (0: no user-data buffer).
|
||||
pub user_data: u32,
|
||||
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
|
||||
pub samplers: u32,
|
||||
/// Bit n: immediate sampler n is a comparison sampler.
|
||||
pub cmp_samplers: u64,
|
||||
/// Root CBVs read, by root parameter index, with their handles.
|
||||
pub root_cbvs: Vec<(u8, V)>,
|
||||
/// Root SRVs (raw buffers) read, likewise.
|
||||
pub root_srvs: Vec<(u8, V)>,
|
||||
/// Root UAVs (raw buffers) read or written, likewise.
|
||||
pub root_uavs: Vec<(u8, V)>,
|
||||
pub flags: u64,
|
||||
/// Every UAV the shader opens is rasterizer ordered ([`Self::annotate`]).
|
||||
pub rov: bool,
|
||||
/// Heap handles made with a non-uniform index.
|
||||
pub nonuniform_handles: u32,
|
||||
/// A compute shader with this thread-group size.
|
||||
pub threads: Option<[u32; 3]>,
|
||||
/// The wave size a compute shader requires (`WaveSize`).
|
||||
pub wave_size: Option<u32>,
|
||||
/// Thread-group shared memory, in dwords.
|
||||
pub lds_dwords: u32,
|
||||
lds: Option<V>,
|
||||
main: V,
|
||||
pub entry: usize,
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
pub fn new(pixel: bool) -> Self {
|
||||
let mut m = Module::default();
|
||||
let void = m.void();
|
||||
let i1 = m.int(1);
|
||||
let i8 = m.int(8);
|
||||
let i32 = m.int(32);
|
||||
let f32 = m.float();
|
||||
let i8p = m.ptr(i8);
|
||||
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
|
||||
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
|
||||
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
|
||||
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
|
||||
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
|
||||
let main_ty = m.func_ty(void, vec![]);
|
||||
m.ptr(main_ty);
|
||||
let main = m.function("main", main_ty, None, true);
|
||||
let entry = m.new_block();
|
||||
Shader {
|
||||
m,
|
||||
t: Types {
|
||||
void,
|
||||
i1,
|
||||
i32,
|
||||
f32,
|
||||
handle,
|
||||
props,
|
||||
bind,
|
||||
cbuf_ret,
|
||||
res_ret,
|
||||
},
|
||||
pixel,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh: None,
|
||||
geometry: None,
|
||||
user_data: 0,
|
||||
samplers: 0,
|
||||
cmp_samplers: 0,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
flags: 0,
|
||||
rov: false,
|
||||
nonuniform_handles: 0,
|
||||
threads: None,
|
||||
wave_size: None,
|
||||
lds_dwords: 0,
|
||||
lds: None,
|
||||
main,
|
||||
entry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread-group shared memory: `[lds_dwords x i32]` in address
|
||||
/// space 3.
|
||||
pub fn lds(&mut self) -> V {
|
||||
if let Some(g) = self.lds {
|
||||
return g;
|
||||
}
|
||||
let arr = self.m.array(self.lds_dwords, self.t.i32);
|
||||
let g = self.m.global("lds", arr, 3);
|
||||
self.lds = Some(g);
|
||||
g
|
||||
}
|
||||
|
||||
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
|
||||
pub fn op(
|
||||
&mut self,
|
||||
block: usize,
|
||||
name: &str,
|
||||
attr: Attr,
|
||||
ret: Ty,
|
||||
opcode: u32,
|
||||
args: &[V],
|
||||
) -> V {
|
||||
let mut params = vec![self.t.i32];
|
||||
params.extend(args.iter().map(|&a| self.m.type_of(a)));
|
||||
let fty = self.m.func_ty(ret, params);
|
||||
self.m.ptr(fty);
|
||||
let f = self
|
||||
.m
|
||||
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
|
||||
let mut all = vec![self.m.i32(opcode)];
|
||||
all.extend(args);
|
||||
self.m.call(block, f, all)
|
||||
}
|
||||
|
||||
/// The handle of the user-data constant buffer, made in the entry block.
|
||||
pub fn user_data_handle(&mut self) -> V {
|
||||
let bind = [
|
||||
self.m.i32(0),
|
||||
self.m.i32(0),
|
||||
self.m.i32(USER_DATA_SPACE),
|
||||
self.m.i8(2), // CBV
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let block = self.entry;
|
||||
let (i, f) = (self.m.i32(0), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
// The size is known in `finish`, which fixes this placeholder.
|
||||
self.annotate(block, h, 13, u32::MAX)
|
||||
}
|
||||
|
||||
/// The handle of the root CBV of root parameter `slot`, made in the
|
||||
/// entry block.
|
||||
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 13, 65536);
|
||||
self.root_cbvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
|
||||
pub fn root_srv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_srvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root UAV (a raw buffer) of root parameter `slot`:
|
||||
/// `u<slot>` in [`ROOT_CBV_SPACE`].
|
||||
pub fn root_uav_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11 | 0x1000, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_uavs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of immediate sampler `n` (a comparison sampler when its
|
||||
/// bit in `cmp_samplers` is set).
|
||||
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
|
||||
let bind = [
|
||||
self.m.i32(n),
|
||||
self.m.i32(n),
|
||||
self.m.i32(SAMPLER_SPACE),
|
||||
self.m.i8(3), // sampler
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let (i, f) = (self.m.i32(n), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
let cmp = if self.cmp_samplers >> n & 1 != 0 {
|
||||
0x8000
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.annotate(block, h, 14 | cmp, 0)
|
||||
}
|
||||
|
||||
/// Annotates a handle with its resource properties. Bit 12 of `props0` is
|
||||
/// "UAV"; with `rov` set a UAV also gets bit 13, rasterizer ordered.
|
||||
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
|
||||
let props0 = if self.rov && props0 & 0x1000 != 0 {
|
||||
self.flags |= flags::ROVS;
|
||||
props0 | 0x2000
|
||||
} else {
|
||||
props0
|
||||
};
|
||||
let p = [self.m.i32(props0), self.m.i32(props1)];
|
||||
let p = self.m.aggregate(self.t.props, &p);
|
||||
self.op(
|
||||
block,
|
||||
"annotateHandle",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
216,
|
||||
&[h, p],
|
||||
)
|
||||
}
|
||||
|
||||
/// A descriptor heap handle, annotated with `props`; `nonuniform` when
|
||||
/// the index may differ between lanes (`NonUniformResourceIndex`).
|
||||
pub fn heap_handle(
|
||||
&mut self,
|
||||
block: usize,
|
||||
index: V,
|
||||
sampler: bool,
|
||||
nonuniform: bool,
|
||||
props: (u32, u32),
|
||||
) -> V {
|
||||
// a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
|
||||
let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
// (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
|
||||
let index = if !sampler && limit != 0 {
|
||||
let null = self.m.i32(limit);
|
||||
let i32t = self.t.i32;
|
||||
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]);
|
||||
self.m.tag(v, super::bitcode::Tag::Clamp);
|
||||
v
|
||||
} else if sampler {
|
||||
// A sampler heap has at most 2,048 samplers on any host: an
|
||||
// index past that (a number read from memory the host has not
|
||||
// got yet) stays inside the largest heap there is.
|
||||
// shortcut: not the bound heap's own count, which a title
|
||||
// heap smaller than 2,048 would need.
|
||||
let last = self.m.i32(2047);
|
||||
let i32t = self.t.i32;
|
||||
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
|
||||
self.m.tag(v, super::bitcode::Tag::Clamp);
|
||||
v
|
||||
} else {
|
||||
index
|
||||
};
|
||||
self.flags |= if sampler {
|
||||
flags::SAMPLER_HEAP
|
||||
} else {
|
||||
flags::RESOURCE_HEAP
|
||||
};
|
||||
self.nonuniform_handles += u32::from(nonuniform);
|
||||
let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromHeap",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
218,
|
||||
&[index, s, n],
|
||||
);
|
||||
self.annotate(block, h, props.0, props.1)
|
||||
}
|
||||
|
||||
/// The finished container.
|
||||
pub fn finish(mut self) -> Vec<u8> {
|
||||
let ud_size = (self.user_data * 4).next_multiple_of(16);
|
||||
self.fix_user_data_size(ud_size);
|
||||
// The clean-up, before anything is declared about the code: a
|
||||
// feature whose last use it removed must not be declared (the
|
||||
// validator compares the flags with what the code uses).
|
||||
let passes = super::shader_opt() & super::bitcode::opt::MODULE;
|
||||
if passes != 0 {
|
||||
self.m.optimise(passes);
|
||||
let used = self.m.usage();
|
||||
for (flag, used) in [
|
||||
(flags::WAVE_OPS, used.wave_ops),
|
||||
(flags::ROVS, used.rov),
|
||||
(flags::INT64, used.int64),
|
||||
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
|
||||
(flags::RESOURCE_HEAP, used.heap_views),
|
||||
(flags::SAMPLER_HEAP, used.heap_samplers),
|
||||
(flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64),
|
||||
] {
|
||||
if !used {
|
||||
self.flags &= !flag;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut resources = None;
|
||||
let mut bindings = Vec::new();
|
||||
let i32c = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
s.m.md_value(c)
|
||||
};
|
||||
if self.user_data > 0
|
||||
|| self.samplers > 0
|
||||
|| !self.root_cbvs.is_empty()
|
||||
|| !self.root_srvs.is_empty()
|
||||
|| !self.root_uavs.is_empty()
|
||||
{
|
||||
let empty = self.m.md_str("");
|
||||
let mut cbvs = None;
|
||||
let mut cbv_list = Vec::new();
|
||||
if self.user_data > 0 {
|
||||
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
|
||||
let ty = self.m.named_struct("UserData", vec![arr]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, USER_DATA_SPACE)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, ud_size)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: USER_DATA_SPACE,
|
||||
register: 0,
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
let blob = self.m.array(16384, self.t.i32);
|
||||
let ty = self.m.named_struct("RootCbv", vec![blob]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
for (slot, _) in self.root_cbvs.clone() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, cbv_list.len() as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 65536)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
if !cbv_list.is_empty() {
|
||||
cbvs = Some(self.m.md_node(cbv_list));
|
||||
}
|
||||
let mut srvs = None;
|
||||
if !self.root_srvs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 4,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
srvs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut uavs = None;
|
||||
if !self.root_uavs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let no = self.m.bool(false);
|
||||
let no = self.m.md_value(no);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
|
||||
// Id, variable, name, space, lower bound, range size,
|
||||
// shape (11: raw buffer), globally coherent, counter,
|
||||
// rasterizer ordered, no extra properties.
|
||||
let ordered = self.m.bool(self.rov);
|
||||
let ordered = self.m.md_value(ordered);
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(no),
|
||||
Some(no),
|
||||
Some(ordered),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 7,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
uavs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut samplers = None;
|
||||
if self.samplers > 0 {
|
||||
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for n in 0..self.samplers {
|
||||
let kind = (self.cmp_samplers >> n & 1) as u32;
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, SAMPLER_SPACE)),
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
// Sampler kind: 1 comparison.
|
||||
Some(i32c(&mut self, kind)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 1,
|
||||
space: SAMPLER_SPACE,
|
||||
register: n,
|
||||
dxil_kind: 14,
|
||||
});
|
||||
}
|
||||
samplers = Some(self.m.md_node(list));
|
||||
}
|
||||
resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
|
||||
bindings.sort_by_key(|b| match b.kind {
|
||||
2 => 0,
|
||||
1 => 1,
|
||||
7 => 3,
|
||||
_ => 2,
|
||||
});
|
||||
}
|
||||
if let Some(r) = resources {
|
||||
self.m.named_md("dx.resources", vec![r]);
|
||||
}
|
||||
|
||||
let graphics = self.threads.is_none() || self.mesh.is_some();
|
||||
if graphics {
|
||||
// shortcut: every output is declared to depend on every input; the
|
||||
// exact sets need a dependence pass. Drivers read this state.
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
|
||||
let mut view = vec![ni, no];
|
||||
// Mesh shaders have no inputs: then the primitive outputs' count.
|
||||
if self.mesh.is_some() {
|
||||
view.push(scalars(&self.prims));
|
||||
}
|
||||
for _ in 0..ni {
|
||||
for k in 0..no.div_ceil(32) {
|
||||
let bits = (no - 32 * k).min(32);
|
||||
view.push(if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1 << bits) - 1
|
||||
});
|
||||
}
|
||||
}
|
||||
// A geometry shader lists four streams: the other three have
|
||||
// no outputs.
|
||||
if self.geometry.is_some() {
|
||||
view.extend([0, 0, 0]);
|
||||
}
|
||||
let arr = self.m.array(view.len() as u32, self.t.i32);
|
||||
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
|
||||
let arr = self.m.aggregate(arr, &elems);
|
||||
let arr = self.m.md_value(arr);
|
||||
let view_node = self.m.md_node(vec![Some(arr)]);
|
||||
self.m.named_md("dx.viewIdState", vec![view_node]);
|
||||
}
|
||||
|
||||
let sigs = if graphics {
|
||||
let ins = self.signature_md(self.inputs.clone());
|
||||
let outs = self.signature_md(self.outputs.clone());
|
||||
let prims = self.signature_md(self.prims.clone());
|
||||
Some(self.m.md_node(vec![ins, outs, prims]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A pixel shader with an SV_StencilRef output (as DXC collects it).
|
||||
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
|
||||
self.flags |= flags::STENCIL_REF;
|
||||
}
|
||||
// Entry properties: shader flags (tag 0), geometry state (1),
|
||||
// thread-group size (4), wave size (11).
|
||||
let mut props = Vec::new();
|
||||
if self.flags != 0 {
|
||||
props.push(i32c(&mut self, 0));
|
||||
let i64t = self.m.int(64);
|
||||
let f = self.m.int_const(i64t, self.flags as i64);
|
||||
props.push(self.m.md_value(f));
|
||||
}
|
||||
if let Some(g) = self.geometry {
|
||||
// Input primitive (3: triangles), maximum vertices, stream
|
||||
// mask, output topology (5: triangle strips), instances.
|
||||
props.push(i32c(&mut self, 1));
|
||||
let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
|
||||
props.push(self.m.md_node(state.to_vec()));
|
||||
}
|
||||
if let Some(threads) = self.threads {
|
||||
let t = threads.map(|n| Some(i32c(&mut self, n)));
|
||||
let t = self.m.md_node(t.to_vec());
|
||||
match self.mesh {
|
||||
// Mesh state (tag 9): threads, maximum vertices and
|
||||
// primitives, topology, payload bytes.
|
||||
Some(mesh) => {
|
||||
props.push(i32c(&mut self, 9));
|
||||
let state = [
|
||||
mesh.max_vertices,
|
||||
mesh.max_primitives,
|
||||
mesh.topology.into(),
|
||||
0,
|
||||
]
|
||||
.map(|n| Some(i32c(&mut self, n)));
|
||||
let mut node = vec![Some(t)];
|
||||
node.extend(state);
|
||||
props.push(self.m.md_node(node));
|
||||
}
|
||||
None => {
|
||||
props.push(i32c(&mut self, 4));
|
||||
props.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(n) = self.wave_size {
|
||||
props.push(i32c(&mut self, 11));
|
||||
let n = Some(i32c(&mut self, n));
|
||||
props.push(self.m.md_node(vec![n]));
|
||||
}
|
||||
let props =
|
||||
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
|
||||
let main = self.m.md_value(self.main);
|
||||
let name = self.m.md_str("main");
|
||||
let entry = self
|
||||
.m
|
||||
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
|
||||
|
||||
let ident = self.m.md_str("victory");
|
||||
let ident = self.m.md_node(vec![Some(ident)]);
|
||||
self.m.named_md("llvm.ident", vec![ident]);
|
||||
let one = i32c(&mut self, 1);
|
||||
let six = i32c(&mut self, 6);
|
||||
let version = self.m.md_node(vec![Some(one), Some(six)]);
|
||||
self.m.named_md("dx.version", vec![version]);
|
||||
self.m.named_md("dx.valver", vec![version]);
|
||||
// Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
|
||||
let (name, kind) = match (self.threads, self.pixel) {
|
||||
_ if self.mesh.is_some() => ("ms", 13u32),
|
||||
_ if self.geometry.is_some() => ("gs", 2),
|
||||
(Some(_), _) => ("cs", 5u32),
|
||||
(None, true) => ("ps", 0),
|
||||
(None, false) => ("vs", 1),
|
||||
};
|
||||
let name = self.m.md_str(name);
|
||||
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
|
||||
self.m.named_md("dx.shaderModel", vec![sm]);
|
||||
self.m.named_md("dx.entryPoints", vec![entry]);
|
||||
|
||||
let bitcode = self.m.write();
|
||||
super::bitcode::census::note(&self.m, &bitcode);
|
||||
let mut dxil = Vec::with_capacity(24 + bitcode.len());
|
||||
dxil.extend((kind << 16 | 0x66).to_le_bytes());
|
||||
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
|
||||
dxil.extend(b"DXIL");
|
||||
dxil.extend(0x106u32.to_le_bytes());
|
||||
dxil.extend(16u32.to_le_bytes());
|
||||
dxil.extend((bitcode.len() as u32).to_le_bytes());
|
||||
dxil.extend(&bitcode);
|
||||
|
||||
let mut features = 0u64;
|
||||
if self.flags & flags::DOUBLES != 0 {
|
||||
features |= 0x1;
|
||||
}
|
||||
if self.flags & flags::STENCIL_REF != 0 {
|
||||
features |= 0x200;
|
||||
}
|
||||
if self.flags & flags::TYPED_UAV_LOADS != 0 {
|
||||
features |= 0x800;
|
||||
}
|
||||
if self.flags & flags::ROVS != 0 {
|
||||
features |= 0x1000;
|
||||
}
|
||||
if self.flags & flags::WAVE_OPS != 0 {
|
||||
features |= 0x4000;
|
||||
}
|
||||
if self.flags & flags::INT64 != 0 {
|
||||
features |= 0x8000;
|
||||
}
|
||||
if self.flags & flags::BARYCENTRICS != 0 {
|
||||
features |= 0x2_0000;
|
||||
}
|
||||
if self.flags & flags::RESOURCE_HEAP != 0 {
|
||||
features |= 0x200_0000;
|
||||
}
|
||||
if self.flags & flags::SAMPLER_HEAP != 0 {
|
||||
features |= 0x400_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_TYPED64 != 0 {
|
||||
features |= 0x40_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_HEAP64 != 0 {
|
||||
features |= 0x1000_0000;
|
||||
}
|
||||
let sfi0 = features.to_le_bytes();
|
||||
let isg1 = container::signature(&self.inputs, true);
|
||||
let osg1 = container::signature(&self.outputs, false);
|
||||
let flag = if self.pixel {
|
||||
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
|
||||
} else {
|
||||
self.outputs.iter().any(|o| o.kind == 3)
|
||||
};
|
||||
let psv0 = container::psv(&Psv {
|
||||
stage: kind as u8,
|
||||
flag: flag && self.threads.is_none(),
|
||||
inputs: &self.inputs,
|
||||
outputs: &self.outputs,
|
||||
prims: &self.prims,
|
||||
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
|
||||
geometry: self.geometry.map(|g| g.max_vertices),
|
||||
bindings: &bindings,
|
||||
threads: self.threads.unwrap_or_default(),
|
||||
wave_size: self.wave_size,
|
||||
});
|
||||
let hash = [0u8; 20];
|
||||
let psg1 = container::signature(&self.prims, false);
|
||||
let mut parts: Vec<(&[u8; 4], &[u8])> =
|
||||
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
|
||||
if self.mesh.is_some() {
|
||||
parts.push((b"PSG1", &psg1));
|
||||
}
|
||||
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
|
||||
container::build(&parts)
|
||||
}
|
||||
|
||||
/// The user-data buffer's annotation carries its size, known only now.
|
||||
fn fix_user_data_size(&mut self, size: u32) {
|
||||
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
|
||||
let old = self.m.aggregate(self.t.props, &old);
|
||||
let new = [self.m.i32(13), self.m.i32(size)];
|
||||
let new = self.m.aggregate(self.t.props, &new);
|
||||
self.m.replace_const(old, new);
|
||||
}
|
||||
|
||||
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
|
||||
if elements.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut list = Vec::new();
|
||||
for (id, e) in elements.iter().enumerate() {
|
||||
let c32 = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let c8 = |s: &mut Self, v: u8| {
|
||||
let c = s.m.i8(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let idx = c32(self, e.index);
|
||||
let indices = Some(self.m.md_node(vec![idx]));
|
||||
let usage = if e.usage != 0 {
|
||||
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
|
||||
Some(self.m.md_node(vec![tag, mask]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ops = vec![
|
||||
c32(self, id as u32),
|
||||
Some(self.m.md_str(&e.name)),
|
||||
c8(self, e.comp),
|
||||
c8(self, e.kind),
|
||||
indices,
|
||||
c8(self, e.interp),
|
||||
c32(self, 1),
|
||||
c8(self, e.cols),
|
||||
c32(self, e.row.unwrap_or(u32::MAX)),
|
||||
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
|
||||
usage,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
}
|
||||
Some(self.m.md_node(list))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Jump threading for uniform diamonds. One arm can set a flag that fixes
|
||||
//! the join's next branch. Registers recycled on that arm then never reach
|
||||
//! the other successor, even if an ordinary SSA phi joins their values.
|
||||
use crate::gfx10::{Fields, Operand, Valu};
|
||||
use crate::ir::{Exit, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn plain(v: &Valu) -> bool {
|
||||
v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& v.opsel == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0
|
||||
&& v.sdwa.is_none()
|
||||
&& v.dpp.is_none()
|
||||
}
|
||||
|
||||
fn immediate(op: Operand) -> Option<u32> {
|
||||
match op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(n) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
|
||||
let mut constants = HashMap::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if inst.name() == "v_mov_b32"
|
||||
&& st.guards[b][i].is_none()
|
||||
&& let Fields::Valu(v) = &inst.fields
|
||||
&& plain(v)
|
||||
&& let [src] = v.src.as_slice()
|
||||
&& let Some(word) = immediate(*src)
|
||||
&& let [(_, dst)] = inst.writes.as_slice()
|
||||
{
|
||||
constants.insert(*dst, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges = Vec::new();
|
||||
for (join, block) in p.blocks.iter().enumerate() {
|
||||
let LaneExit::Branch {
|
||||
when,
|
||||
taken,
|
||||
not_taken,
|
||||
} = st.exits[join]
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if when == Bool::TRUE || when == Bool::FALSE {
|
||||
continue;
|
||||
}
|
||||
// Keep memory accesses and wave operations at their original
|
||||
// reconvergence point. Only duplicate scalar ALU and comparisons.
|
||||
if !block.insts.iter().all(|i| match &i.fields {
|
||||
Fields::Sop { .. } => true,
|
||||
Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
|
||||
Fields::Valu(_) => i.name().starts_with("v_cmp_"),
|
||||
_ => false,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = block.preds.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
// A triangle has a direct edge from the fork to the join. A full
|
||||
// diamond has an unconditional jump at the end of each arm.
|
||||
let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
|
||||
&[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
|
||||
_ => None,
|
||||
};
|
||||
let fork = match (arm_from(*a), arm_from(*b)) {
|
||||
(Some(f), Some(g)) if f == g => f,
|
||||
(_, Some(f)) if f == *a => f,
|
||||
(Some(f), _) if f == *b => f,
|
||||
_ => continue,
|
||||
};
|
||||
if fork == join || a == b {
|
||||
continue;
|
||||
}
|
||||
let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
|
||||
continue;
|
||||
};
|
||||
if !st
|
||||
.bools
|
||||
.support(entry)
|
||||
.iter()
|
||||
.all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (edge, &pred) in block.preds.iter().enumerate() {
|
||||
let value = |v: Value| {
|
||||
let input = block
|
||||
.phis
|
||||
.iter()
|
||||
.find(|p| p.value == v)
|
||||
.map_or(v, |p| p.args[edge]);
|
||||
constants.get(&input).copied()
|
||||
};
|
||||
// Restrict the branch's decision diagram to known comparisons.
|
||||
// Unknown tests stop the proof. Keep the original join for the
|
||||
// other arm, which may still go either way.
|
||||
let mut cond = when;
|
||||
while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
|
||||
let Some(inst) = block
|
||||
.insts
|
||||
.iter()
|
||||
.find(|i| i.writes.iter().any(|&(_, v)| v == id))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let Fields::Valu(v) = &inst.fields else { break };
|
||||
let [left, right] = v.src.as_slice() else {
|
||||
break;
|
||||
};
|
||||
let operand = |op| match op {
|
||||
Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
|
||||
_ => immediate(op),
|
||||
};
|
||||
let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
|
||||
break;
|
||||
};
|
||||
if !plain(v) {
|
||||
break;
|
||||
}
|
||||
let yes = match inst.name() {
|
||||
"v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
|
||||
"v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
|
||||
_ => break,
|
||||
};
|
||||
cond = if yes { hi } else { lo };
|
||||
}
|
||||
if cond == Bool::TRUE || cond == Bool::FALSE {
|
||||
edges.push((
|
||||
pred,
|
||||
join,
|
||||
if cond == Bool::TRUE { taken } else { not_taken },
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ir;
|
||||
use crate::structure;
|
||||
|
||||
// s8 initially holds a descriptor address. One arm overwrites it with
|
||||
// a buffer load and sets v1. Only that arm can use s8 as the stored value.
|
||||
const WORDS: [u32; 19] = [
|
||||
0xbe810380, // s1 = 0 (table address high)
|
||||
0xf4080200, 0xfa000000, // load SRV into s[8:11]
|
||||
0xf4080300, 0xfa000020, // load UAV into s[12:15]
|
||||
0x7e020280, // v1 = 0
|
||||
0xbf068002, 0xbf850003, // if s2 == 0, jump to join
|
||||
0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
|
||||
0x7e020281, // v1 = 1
|
||||
0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
|
||||
0x7e060208, 0xbf820001, // v3 = s8, jump to store
|
||||
0x7e060293, // constant: v3 = 19
|
||||
0xe0700000, 0x80030300, // store v3 at byte 0
|
||||
0xbf810000, // end
|
||||
];
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
ir::build(
|
||||
&words
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect::<Vec<_>>(),
|
||||
false,
|
||||
4,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_buffer_load_reaches_the_numeric_read() {
|
||||
let p = program(&WORDS);
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let edges = constant_edges(&p, &st);
|
||||
assert_eq!(edges, [(0, 2, 4)]);
|
||||
let p = ir::thread_edges(&p, &edges).unwrap();
|
||||
let load = &p.blocks[1].insts[0];
|
||||
assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
|
||||
assert_eq!(
|
||||
p.blocks[0].exit,
|
||||
Exit::Branch {
|
||||
taken: 6,
|
||||
not_taken: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(p.blocks[6].exit, Exit::Jump(4));
|
||||
assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_unknown_flags_and_divergent_forks_alone() {
|
||||
let mut words = WORDS;
|
||||
words[5] = 0x7e020202; // v1 = s2
|
||||
words[10] = 0x7e020203; // v1 = s3
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
let mut words = WORDS;
|
||||
words[6] = 0x7d840080; // compare 0 with lane-dependent v0
|
||||
words[7] = 0xbf870003; // branch on VCC
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
|
||||
//! offline batch. Translated shaders do not need it: they carry the
|
||||
//! container hash we compute (`container::hash`).
|
||||
//!
|
||||
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
|
||||
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
|
||||
|
||||
type Hresult = i32;
|
||||
|
||||
#[repr(C)]
|
||||
struct Guid(u32, u16, u16, [u8; 8]);
|
||||
|
||||
const CLSID_DXC_VALIDATOR: Guid = Guid(
|
||||
0x8ca3_e215,
|
||||
0xf728,
|
||||
0x4cf3,
|
||||
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
|
||||
);
|
||||
const IID_IDXC_VALIDATOR: Guid = Guid(
|
||||
0xa6e8_2bd2,
|
||||
0x1fd7,
|
||||
0x4826,
|
||||
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
|
||||
);
|
||||
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
|
||||
const IN_PLACE_EDIT: u32 = 1;
|
||||
|
||||
type CreateInstance =
|
||||
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
|
||||
|
||||
/// COM object: a pointer to a table of method pointers.
|
||||
type Object = *mut *const usize;
|
||||
|
||||
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
|
||||
// SAFETY: the caller names a slot of the object's interface.
|
||||
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
|
||||
}
|
||||
|
||||
unsafe fn release(obj: Object) {
|
||||
if !obj.is_null() {
|
||||
// SAFETY: slot 2 of every COM interface is Release.
|
||||
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
|
||||
}
|
||||
}
|
||||
|
||||
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
|
||||
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
|
||||
#[repr(C)]
|
||||
struct Blob {
|
||||
vtable: *const BlobVtable,
|
||||
data: *mut u8,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
/// IUnknown and IDxcBlob, as raw GUID bytes.
|
||||
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
|
||||
const IDXC_BLOB: [u8; 16] = [
|
||||
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
|
||||
];
|
||||
|
||||
unsafe extern "system" fn blob_qi(
|
||||
this: *mut Blob,
|
||||
iid: *const [u8; 16],
|
||||
out: *mut *mut c_void,
|
||||
) -> Hresult {
|
||||
// SAFETY: the validator passes valid pointers.
|
||||
unsafe {
|
||||
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
|
||||
*out = this.cast();
|
||||
0
|
||||
} else {
|
||||
*out = std::ptr::null_mut();
|
||||
0x8000_4002_u32 as i32 // E_NOINTERFACE
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
|
||||
1
|
||||
}
|
||||
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).data }
|
||||
}
|
||||
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).len }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct BlobVtable {
|
||||
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
|
||||
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
release: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
|
||||
len: unsafe extern "system" fn(*mut Blob) -> usize,
|
||||
}
|
||||
|
||||
static BLOB_VTABLE: BlobVtable = BlobVtable {
|
||||
qi: blob_qi,
|
||||
add_ref: blob_ref,
|
||||
release: blob_ref,
|
||||
ptr: blob_ptr,
|
||||
len: blob_len,
|
||||
};
|
||||
|
||||
pub struct Validator {
|
||||
object: Object,
|
||||
}
|
||||
|
||||
// SAFETY: the validator object is free-threaded (DXC's validator has no
|
||||
// thread affinity); calls are serialised by `&mut self`.
|
||||
unsafe impl Send for Validator {}
|
||||
|
||||
impl Validator {
|
||||
/// Where `dxil.dll` is looked for.
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
|
||||
return Some(p.into());
|
||||
}
|
||||
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
|
||||
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path().join(r"x64\dxil.dll"))
|
||||
.filter(|p| p.exists())
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.pop()
|
||||
}
|
||||
|
||||
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
|
||||
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
|
||||
let name: Vec<u16> = path
|
||||
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
|
||||
.to_string_lossy()
|
||||
.encode_utf16()
|
||||
.chain([0])
|
||||
.collect();
|
||||
// SAFETY: plain Win32 calls with a NUL-terminated name.
|
||||
unsafe {
|
||||
let module = LoadLibraryW(name.as_ptr());
|
||||
if module.is_null() {
|
||||
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
|
||||
}
|
||||
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
|
||||
.ok_or("dxil.dll lacks DxcCreateInstance")?;
|
||||
let create: CreateInstance = std::mem::transmute(create);
|
||||
let mut object = std::ptr::null_mut();
|
||||
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
|
||||
if hr < 0 || object.is_null() {
|
||||
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
|
||||
}
|
||||
Ok(Validator {
|
||||
object: object.cast(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates `container` and signs it in place; the error text if it
|
||||
/// is rejected.
|
||||
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
|
||||
let mut blob = Blob {
|
||||
vtable: &BLOB_VTABLE,
|
||||
data: container.as_mut_ptr(),
|
||||
len: container.len(),
|
||||
};
|
||||
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
|
||||
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
|
||||
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
|
||||
unsafe {
|
||||
let mut result: Object = std::ptr::null_mut();
|
||||
let validate: unsafe extern "system" fn(
|
||||
Object,
|
||||
*mut Blob,
|
||||
u32,
|
||||
*mut Object,
|
||||
) -> Hresult = method(self.object, 3);
|
||||
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
|
||||
if hr < 0 || result.is_null() {
|
||||
return Err(format!("Validate failed: {hr:#x}"));
|
||||
}
|
||||
let mut status = 0;
|
||||
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
|
||||
method(result, 3);
|
||||
get_status(result, &mut status);
|
||||
let mut text = String::new();
|
||||
if status < 0 {
|
||||
let mut errors: Object = std::ptr::null_mut();
|
||||
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
|
||||
method(result, 5);
|
||||
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
|
||||
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
|
||||
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
|
||||
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
|
||||
text = String::from_utf8_lossy(bytes)
|
||||
.trim_end_matches('\0')
|
||||
.trim()
|
||||
.into();
|
||||
release(errors);
|
||||
}
|
||||
if text.is_empty() {
|
||||
text = format!("rejected ({status:#x})");
|
||||
}
|
||||
}
|
||||
release(result);
|
||||
if status < 0 { Err(text) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Validator {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: we own one reference.
|
||||
unsafe { release(self.object) };
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,435 @@
|
||||
//! End-to-end tests of waterfall loops over per-lane descriptors: the
|
||||
//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated
|
||||
//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane
|
||||
//! reading the resource its own descriptor names.
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{io, ir, resource, structure};
|
||||
|
||||
/// Lowers a wave32 compute program of 32 threads with the table of views at
|
||||
/// s0 (textures, or with `buffers` structured buffers of dwords, at entries
|
||||
/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1.
|
||||
fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
let table = |user_data: u8| RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot: user_data,
|
||||
};
|
||||
let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride,
|
||||
dwords,
|
||||
user_data,
|
||||
slot: user_data,
|
||||
};
|
||||
let views = if buffers {
|
||||
range(ResourceType::Srv, 0, 4, 4, 0)
|
||||
} else {
|
||||
range(ResourceType::Srv, 0, 8, 0, 0)
|
||||
};
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![table(0), table(1)],
|
||||
used: vec![
|
||||
views,
|
||||
range(ResourceType::Uav, 16, 4, 0, 0),
|
||||
range(ResourceType::Sampler, 0, 4, 0, 1),
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [32, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.expect("lower");
|
||||
// One access with each lane's own heap index, no wave operation.
|
||||
assert_eq!(lowered.nonuniform_handles, 1);
|
||||
assert!(!lowered.wave_ops);
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
.expect("DXIL validation failed");
|
||||
} else {
|
||||
eprintln!("no dxil.dll; validation skipped");
|
||||
}
|
||||
shader
|
||||
}
|
||||
|
||||
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
|
||||
/// hardware GPU and on WARP (each skipped without a device) and returns,
|
||||
/// per one that ran, the UAV's 32 dwords.
|
||||
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
let samplers = [D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
MaxAnisotropy: 1,
|
||||
MaxLOD: f32::MAX,
|
||||
..Default::default()
|
||||
}];
|
||||
let mut out = Vec::new();
|
||||
// One GPU test at a time, with the VALU tests: in parallel on the
|
||||
// hardware adapter and WARP the test process sometimes died of an
|
||||
// access violation (7 of 24 runs of these four tests).
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(shader) {
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{label}: compute_pipeline failed: {e}"),
|
||||
};
|
||||
// Both tables start at heap index 0.
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
assert_eq!(u.root, RootType::Table, "{u:?}");
|
||||
ud[u.index as usize] = 0;
|
||||
}
|
||||
let words = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views,
|
||||
samplers: &samplers,
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
out.push((label, words[0].clone()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The red channel each lane sampled from two 1x1 textures, red 1.0 at
|
||||
/// heap index 0 and 2.0 at 1.
|
||||
fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec<f32>)> {
|
||||
let first = [[1.0f32, 0.0, 0.0, 1.0]];
|
||||
let second = [[2.0f32, 0.0, 0.0, 1.0]];
|
||||
let views = [
|
||||
View::Texture(1, 1, &first),
|
||||
View::Texture(1, 1, &second),
|
||||
View::RawUav(32),
|
||||
];
|
||||
run(shader, &views)
|
||||
.into_iter()
|
||||
.map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_texture_their_if_else_arm_chose() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_WAVE32, false);
|
||||
for (label, red) in sampled(&shader) {
|
||||
// Lanes below 16 took the first texture, the others the second.
|
||||
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_texture_their_arm_loaded_or_picked() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false);
|
||||
for (label, red) in sampled(&shader) {
|
||||
// Lanes below 16 loaded entry (lane & 1); of the others, lanes
|
||||
// below 24 picked the first, the rest the second.
|
||||
let want: Vec<f32> = (0..32)
|
||||
.map(|l| match l {
|
||||
0..16 => [1.0, 2.0][l & 1],
|
||||
16..24 => 1.0,
|
||||
_ => 2.0,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_load_from_the_buffer_their_nested_arms_chose() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true);
|
||||
let first: Vec<u32> = (0..32).map(|i| 100 + i).collect();
|
||||
let second: Vec<u32> = (0..32).map(|i| 200 + i).collect();
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &first,
|
||||
stride: Stride::Structured(4),
|
||||
},
|
||||
View::Buffer {
|
||||
data: &second,
|
||||
stride: Stride::Structured(4),
|
||||
},
|
||||
View::RawUav(32),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
// Dword `lane` of the first buffer below 16, of the second from 16
|
||||
// to 23; lanes from 24 on load and store nothing.
|
||||
let want: Vec<u32> = (0..32)
|
||||
.map(|l| match l {
|
||||
0..16 => 100 + l,
|
||||
16..24 => 200 + l,
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(got, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() {
|
||||
use crate::resource::tests::WATERFALL_INDEXED_WAVE32;
|
||||
let shader = build(WATERFALL_INDEXED_WAVE32, false);
|
||||
let results = sampled(&shader);
|
||||
assert!(!results.is_empty());
|
||||
for (label, red) in results {
|
||||
// Even lanes hold entry 0's offset, odd lanes entry 1's.
|
||||
let want: Vec<f32> = (0..32).map(|l| [1.0, 2.0][l & 1]).collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() {
|
||||
use crate::resource::tests::cmpx_waterfall;
|
||||
// Lanes below 16 hold the first descriptor, the others the second.
|
||||
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
|
||||
for folded in [false, true] {
|
||||
let shader = build(&cmpx_waterfall(false, folded), false);
|
||||
let results = sampled(&shader);
|
||||
assert!(!results.is_empty());
|
||||
for (label, red) in results {
|
||||
assert_eq!(red, want, "{label}, folded {folded}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_sampler_chosen_by_control_flow() {
|
||||
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
|
||||
let s_mov_zero = |dst: u8| 0xBE80_0380 | (dst as u32) << 16;
|
||||
let s_load_x8 = |dst: u8, base: u8| [0x3D << 26 | 0x03 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25];
|
||||
let s_load_x4_off = |dst: u8, base: u8, off: u32| [0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25 | off];
|
||||
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
let image_sample_lz: [u32; 2] = [
|
||||
0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, // dmask=1, dim=2D(1)
|
||||
(16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2,
|
||||
];
|
||||
// buffer_store_dword v4, off, s[20:23], 0
|
||||
let buf_store: [u32; 2] = [0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8];
|
||||
|
||||
// Two distinct valid immediate sampler descriptors (different wrap/filter bits).
|
||||
let samp_a: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0000, 0];
|
||||
let samp_b: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0001, 0];
|
||||
|
||||
for (case_name, alt) in [("same_sampler", samp_a), ("different_samplers", samp_b)] {
|
||||
let mut words = Vec::new();
|
||||
// s[2:3] = view table base (s0, 0).
|
||||
words.push(0xBE80_0300 | (2 << 16)); // s_mov_b32 s2, s0
|
||||
words.push(s_mov_zero(3));
|
||||
words.extend_from_slice(&s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0)
|
||||
words.extend_from_slice(&s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B)
|
||||
// v2 = 0.5, v3 = 0.5 (sample coordinates).
|
||||
words.push(0x7E00_02F0 | (2 << 17)); // v_mov_b32 v2, 0.5
|
||||
words.push(0x7E00_02F0 | (3 << 17)); // v_mov_b32 v3, 0.5
|
||||
// s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm
|
||||
words.push(0xBF00_8001); // s_cmp_eq_u32 s1, 0 (const 128)
|
||||
let br_else = words.len();
|
||||
words.push(0); // placeholder s_cbranch_scc0
|
||||
// then arm: load samp_a into s[16:19]
|
||||
for (i, &w) in samp_a.iter().enumerate() {
|
||||
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
|
||||
}
|
||||
let br_join = words.len();
|
||||
words.push(0); // placeholder s_branch
|
||||
let else_pc = words.len();
|
||||
// else arm: load alt into s[16:19]
|
||||
for (i, &w) in alt.iter().enumerate() {
|
||||
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
|
||||
}
|
||||
let join_pc = words.len();
|
||||
words[br_else] = 0xBF84_0000 | ((else_pc - br_else - 1) as u32 & 0xFFFF);
|
||||
words[br_join] = 0xBF82_0000 | ((join_pc - br_join - 1) as u32 & 0xFFFF);
|
||||
words.extend_from_slice(&image_sample_lz);
|
||||
words.extend_from_slice(&buf_store);
|
||||
words.push(0xBF81_0000); // s_endpgm
|
||||
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 1,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![
|
||||
UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 8,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 16,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
|
||||
let p = ir::build(&native.code, false, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}"));
|
||||
|
||||
let static_samplers = lowered
|
||||
.samplers
|
||||
.iter()
|
||||
.map(|&w| super::StaticSampler::from_words(w))
|
||||
.collect();
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers,
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{case_name}/{label}: compute_pipeline failed: {e}"));
|
||||
for branch in [0u32, 1u32] {
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
ud[u.index as usize] = match (u.root, u.slot) {
|
||||
(RootType::Table, 0) => 0,
|
||||
(RootType::Constants, 1) => branch,
|
||||
other => panic!("unexpected user data {other:?}"),
|
||||
};
|
||||
}
|
||||
let texels = [[1.0f32, 0.0, 0.0, 1.0]];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[
|
||||
View::Texture(1, 1, &texels),
|
||||
View::Texture(1, 1, &texels),
|
||||
View::RawUav(1),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{case_name}/{label}: dispatch failed: {e}"));
|
||||
let got = f32::from_bits(out[0][0]);
|
||||
assert_eq!(got, 1.0, "{case_name}/{label} branch={branch}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,549 @@
|
||||
//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a
|
||||
//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`])
|
||||
//! so that the two host waves can exchange their halves inside it. Lowered, validated by
|
||||
//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::host::{Dispatch, Host, Root, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads
|
||||
/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store
|
||||
/// the result to dword 0 of the raw UAV.
|
||||
/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or
|
||||
/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left").
|
||||
fn program(skip: u32) -> NativeProgram {
|
||||
let mut words = vec![
|
||||
0x7E0A_0281, // v_mov_b32 v5, 1
|
||||
0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0
|
||||
0x340E_0B06, // v_lshlrev_b32 v7, v6, v5
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
|
||||
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
|
||||
skip | 23, // the branch to the restore of EXEC
|
||||
];
|
||||
words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7);
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
|
||||
]);
|
||||
native(&words)
|
||||
}
|
||||
|
||||
/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4
|
||||
/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`.
|
||||
fn native(body: &[u32]) -> NativeProgram {
|
||||
native_of(body, true, 64)
|
||||
}
|
||||
|
||||
/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads.
|
||||
fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
|
||||
let mut words = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0x3D << 26 | 0x02 << 18 | 8 << 6 | 2,
|
||||
125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0
|
||||
];
|
||||
words.extend_from_slice(body);
|
||||
words.push(S_ENDPGM);
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64,
|
||||
vgprs: 16,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
|
||||
threads: [threads, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
|
||||
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
|
||||
lowered_on(native, p, wide, 32)
|
||||
}
|
||||
|
||||
/// [`lowered`] for a host whose waves have at most `host_wave` lanes.
|
||||
fn lowered_on(
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
wide: &HashSet<usize>,
|
||||
host_wave: u32,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let st = structure::structure_wide(p, wide).expect("structure");
|
||||
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
|
||||
let io = io::raise(p, native).expect("io::raise");
|
||||
let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
lower::TEST_HOST_WAVE.set(was);
|
||||
let lowered = lowered?;
|
||||
Ok(HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
|
||||
// thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd
|
||||
// mantissas, so that additions round); all of them store the wave's sum
|
||||
let mut words = vec![
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
];
|
||||
// (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28)
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
]);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6);
|
||||
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
// the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits
|
||||
// (to nearest, ties to even); values here are normal numbers
|
||||
let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13);
|
||||
let narrow = |f: f32| {
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
|
||||
let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect();
|
||||
let mut tree = terms.clone();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
|
||||
}
|
||||
let in_a_row = terms.iter().copied().reduce(add).unwrap();
|
||||
assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order");
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(&shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
// (the high half is lane 0's term's: zero)
|
||||
assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]);
|
||||
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
|
||||
}
|
||||
|
||||
/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a
|
||||
/// thread past the end of the data): on the console they add +0, and after each step of the
|
||||
/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the
|
||||
/// lanes that are here read each partner run's sum from a lane of it that is here.
|
||||
#[test]
|
||||
fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
|
||||
let mut words = vec![
|
||||
0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay
|
||||
0, // s_cbranch_execz to the end (filled in below)
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
];
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
]);
|
||||
// past every word after it, to the program's end
|
||||
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
// BetterXen correction (research/shader-wave-semantics): this program is lowered for a host
|
||||
// of 64-lane waves. A device whose waves are narrower cannot run that lowering: its lanes 32
|
||||
// and up do not exist, and the observed result was 0 instead of the tree. Such a device
|
||||
// must be offered the lowering for its own width instead, which the recompiler refuses for
|
||||
// this program ("a wave sum of 16-bit floats where not every lane runs"): the test then
|
||||
// asserts that refusal, which is the correct behaviour, rather than reporting a failure
|
||||
// or silently skipping.
|
||||
if let Some(w) = Host::hardware().ok().and_then(|h| h.wave_lane_count_max()).filter(|&w| w < 64) {
|
||||
let refused = lowered_on(&native, &p, &HashSet::new(), w);
|
||||
assert!(
|
||||
matches!(&refused, Err(ShaderError::Unsupported { what, .. }) if what.contains("16-bit floats where not every lane runs")),
|
||||
"a {w}-lane device must be refused this program, got {:?}",
|
||||
refused.as_ref().map(|_| "a shader")
|
||||
);
|
||||
eprintln!("device waves are {w} lanes; refused for that width as expected; not run on the device");
|
||||
return;
|
||||
}
|
||||
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let wide = |h: u16| {
|
||||
if h == 0 {
|
||||
0.0
|
||||
} else {
|
||||
f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13)
|
||||
}
|
||||
};
|
||||
let narrow = |f: f32| {
|
||||
if f == 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = false;
|
||||
for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] {
|
||||
let terms: Vec<u16> = (0..64u32)
|
||||
.map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 })
|
||||
.collect();
|
||||
let mut tree = terms.clone();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
|
||||
}
|
||||
let Some(got) = on_the_card(&shader, [stay, 0]) else {
|
||||
return;
|
||||
};
|
||||
ran = true;
|
||||
// (the high half is lane 0's term's: zero)
|
||||
assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]);
|
||||
}
|
||||
if ran {
|
||||
eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case");
|
||||
}
|
||||
}
|
||||
|
||||
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
|
||||
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
|
||||
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
|
||||
/// translation gives the console's whatever the host does.
|
||||
#[test]
|
||||
fn a_16_bit_sum_rounds_to_nearest_when_asked_to() {
|
||||
let words = [
|
||||
0x7E0E_02FF,
|
||||
0x0000_3C03, // v_mov_b32 v7, 0x3c03
|
||||
0x7E0C_02FF,
|
||||
0x0000_4000, // v_mov_b32 v6, 0x4000
|
||||
0x6400_0D07, // v_add_f16 v0, v7, v6
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
];
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16"));
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for nearest in [false, true] {
|
||||
let was = lower::TEST_F16_NEAREST.replace(Some(nearest));
|
||||
let shader = lowered(&native, &p, &HashSet::new());
|
||||
lower::TEST_F16_NEAREST.set(was);
|
||||
let shader = shader.expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let Ok((root, pso)) = host.compute_pipeline(&shader) else {
|
||||
eprintln!("the hardware device does not take this program; not run");
|
||||
return;
|
||||
};
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
let got = out[0][0] & 0xFFFF;
|
||||
eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}");
|
||||
if nearest {
|
||||
assert_eq!(got, 0x4202);
|
||||
} else {
|
||||
assert!(got == 0x4201 || got == 0x4202, "{got:#x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() {
|
||||
for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] {
|
||||
a_wave_or_inside(skip, name);
|
||||
}
|
||||
}
|
||||
|
||||
fn a_wave_or_inside(skip: u32, name: &str) {
|
||||
let native = program(skip);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let branch = (0..p.blocks.len())
|
||||
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name))
|
||||
.expect("the branch");
|
||||
// per lane, the two host waves cannot meet inside the branch
|
||||
lower::take_needs();
|
||||
let per_lane = lowered(&native, &p, &HashSet::new());
|
||||
assert!(
|
||||
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"),
|
||||
"{:?}",
|
||||
per_lane.err()
|
||||
);
|
||||
// ... and the lowering names the block, around which that branch is the one to widen
|
||||
let needs = lower::take_needs();
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch]));
|
||||
// (taken, past the body, when every lane's bit is clear)
|
||||
assert_eq!(st.wave_any[branch], Some(false));
|
||||
// wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there)
|
||||
let wide = HashSet::from([branch]);
|
||||
let st = structure::structure_wide(&p, &wide).expect("structure");
|
||||
let inside = match p.blocks[branch].exit {
|
||||
ir::Exit::Branch { not_taken, .. } => not_taken,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(st.guards[inside].iter().any(Option::is_some));
|
||||
let shader = lowered(&native, &p, &wide).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
// On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of
|
||||
// both halves, whichever half's lanes take the branch.
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(&shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// (threads below s0 take the branch; thread t gives bit t >> 1)
|
||||
for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] {
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) {
|
||||
ud[u.index as usize] = below;
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch");
|
||||
}
|
||||
eprintln!("ran on the hardware device ({name}): the OR of both halves in every case");
|
||||
}
|
||||
|
||||
/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0
|
||||
/// of the UAV; None (and a line) without a device that takes it.
|
||||
fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> {
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return None;
|
||||
};
|
||||
let Ok((root, pso)) = host.compute_pipeline(shader) else {
|
||||
eprintln!("the hardware device does not take this program; not run");
|
||||
return None;
|
||||
};
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) {
|
||||
ud[u.index as usize] = constants[d as usize];
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
Some(out[0][0])
|
||||
}
|
||||
|
||||
/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0)
|
||||
/// and a number on the other, and is read as a number after the join, as the trace programs
|
||||
/// keep their lanes' masks and their node numbers on one stack
|
||||
/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The
|
||||
/// mask arrives as the ballot of its lanes.
|
||||
#[test]
|
||||
fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() {
|
||||
let words = [
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
|
||||
0xBE94_036A, // s_mov_b32 s20, vcc_lo
|
||||
0xBF06_8001, // s_cmp_eq_u32 s1, 0
|
||||
0xBF85_0001, // s_cbranch_scc1 over the next
|
||||
0xBE94_0385, // s_mov_b32 s20, 5
|
||||
0x7E00_0214, // v_mov_b32 v0, s20
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
];
|
||||
let native = native_of(&words, false, 32);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] {
|
||||
let Some(got) = on_the_card(&shader, [below, other]) else { return };
|
||||
assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}");
|
||||
}
|
||||
eprintln!("ran on the hardware device: the mask's bits, or the number");
|
||||
}
|
||||
|
||||
/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after
|
||||
/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along
|
||||
/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console
|
||||
/// the skip is taken by the wave, so with some lane inside every lane sees the inner test.
|
||||
/// A lane that skipped on its own would see "some lane is left" instead: refused per lane,
|
||||
/// right with the branch taken wave-wide. Lane 31 stores what it saw.
|
||||
#[test]
|
||||
fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() {
|
||||
let words = [
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
|
||||
0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo
|
||||
0xBF88_0001, // s_cbranch_execz over the next
|
||||
0xBF06_8701, // s_cmp_eq_u32 s1, 7
|
||||
0xBEFE_030D, // s_mov_b32 exec_lo, s13
|
||||
0xBF85_0002, // s_cbranch_scc1 to "seven"
|
||||
0x7E0A_0281, // v_mov_b32 v5, 1
|
||||
0xBF82_0001, // s_branch over the next
|
||||
0x7E0A_0282, // seven: v_mov_b32 v5, 2
|
||||
0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0
|
||||
];
|
||||
let native = native_of(&words, false, 32);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let branch = (0..p.blocks.len())
|
||||
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
|
||||
.expect("the skip");
|
||||
lower::take_needs();
|
||||
let per_lane = lowered(&native, &p, &HashSet::new());
|
||||
assert!(
|
||||
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"),
|
||||
"{:?}",
|
||||
per_lane.err()
|
||||
);
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch]));
|
||||
let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch
|
||||
for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] {
|
||||
let Some(got) = on_the_card(&shader, [below, s1]) else { return };
|
||||
assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}");
|
||||
}
|
||||
eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
|
||||
}
|
||||
@@ -0,0 +1,815 @@
|
||||
//! Operand fields of GFX10 instructions, by encoding.
|
||||
//!
|
||||
//! Layouts follow AMD's RDNA ISA reference. Register ranges carry their size
|
||||
//! in dwords, which depends on the opcode (read from its name) and, for lane
|
||||
//! masks (VCC, EXEC, compare results), on the wave size.
|
||||
|
||||
use super::{Encoding, Instruction};
|
||||
|
||||
/// A source or destination of an instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Operand {
|
||||
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
|
||||
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
|
||||
/// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the
|
||||
/// IR names scalars parked in VGPR lanes by the codes from 128 up
|
||||
/// (`crate::ir::PARKED`).
|
||||
Scalar {
|
||||
code: u8,
|
||||
dwords: u8,
|
||||
},
|
||||
Vector {
|
||||
reg: u8,
|
||||
dwords: u8,
|
||||
},
|
||||
/// Inline constant or read-only special source, by operand code
|
||||
/// (128-192: 0-64, 193-208: -1 to -16, 240-248: floats, 251-254: vccz,
|
||||
/// execz, scc, lds_direct).
|
||||
Const(u8),
|
||||
/// The 32-bit literal that follows the instruction.
|
||||
Literal(u32),
|
||||
/// Interpolation attribute and channel (0-3 = x-w); `high` selects the
|
||||
/// upper f16 half.
|
||||
Attr {
|
||||
index: u8,
|
||||
chan: u8,
|
||||
high: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Operand code of `null` (no register; reads as 0).
|
||||
pub const NULL: u8 = 125;
|
||||
const VCC: u8 = 106;
|
||||
const EXEC: u8 = 126;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Cache {
|
||||
pub glc: bool,
|
||||
pub slc: bool,
|
||||
pub dlc: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Fields {
|
||||
/// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate.
|
||||
Sop {
|
||||
dst: Option<Operand>,
|
||||
src: Vec<Operand>,
|
||||
imm: Option<u16>,
|
||||
},
|
||||
/// The 16-bit immediate: branch offset in dwords, wait counts, message...
|
||||
Sopp {
|
||||
imm: u16,
|
||||
},
|
||||
Smem {
|
||||
data: Option<Operand>,
|
||||
base: Operand,
|
||||
/// Signed byte offset, added to `soffset`.
|
||||
offset: i32,
|
||||
soffset: Operand,
|
||||
cache: Cache,
|
||||
},
|
||||
Valu(Valu),
|
||||
Vintrp {
|
||||
dst: Operand,
|
||||
/// The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`,
|
||||
/// 1 `p20`, 2 `p0`) as [`Operand::Const`].
|
||||
src: Operand,
|
||||
attr: Operand,
|
||||
},
|
||||
Ds {
|
||||
dst: Option<Operand>,
|
||||
addr: Option<Operand>,
|
||||
data: Vec<Operand>,
|
||||
offset0: u8,
|
||||
offset1: u8,
|
||||
gds: bool,
|
||||
},
|
||||
/// MUBUF, and MTBUF with `format` set.
|
||||
Buffer {
|
||||
/// Loaded, stored, or the atomic operand (and result with `glc`).
|
||||
data: Option<Operand>,
|
||||
addr: Operand,
|
||||
rsrc: Operand,
|
||||
soffset: Operand,
|
||||
offset: u16,
|
||||
offen: bool,
|
||||
idxen: bool,
|
||||
format: Option<u8>,
|
||||
lds: bool,
|
||||
tfe: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
Image {
|
||||
data: Operand,
|
||||
/// One range, or one VGPR per address with the NSA form.
|
||||
addr: Vec<Operand>,
|
||||
rsrc: Operand,
|
||||
sampler: Option<Operand>,
|
||||
dmask: u8,
|
||||
dim: u8,
|
||||
unorm: bool,
|
||||
r128: bool,
|
||||
a16: bool,
|
||||
d16: bool,
|
||||
tfe: bool,
|
||||
lwe: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
/// FLAT, GLOBAL and SCRATCH.
|
||||
Flat {
|
||||
dst: Option<Operand>,
|
||||
addr: Option<Operand>,
|
||||
data: Option<Operand>,
|
||||
saddr: Option<Operand>,
|
||||
offset: i16,
|
||||
lds: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
Exp {
|
||||
target: u8,
|
||||
/// Per channel; `None` when disabled.
|
||||
src: [Option<Operand>; 4],
|
||||
compr: bool,
|
||||
done: bool,
|
||||
vm: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Valu {
|
||||
/// A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares).
|
||||
pub dst: Option<Operand>,
|
||||
/// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...).
|
||||
pub carry: Option<Operand>,
|
||||
/// In operand order, including the implicit VCC of VOP2 `v_cndmask_b32`
|
||||
/// and carry-in, and the literal of `v_madmk`/`v_madak` forms.
|
||||
pub src: Vec<Operand>,
|
||||
/// Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's.
|
||||
pub neg: u8,
|
||||
pub abs: u8,
|
||||
/// VOP3P: negate the high half (`v_fma_mix*`: absolute value).
|
||||
pub neg_hi: u8,
|
||||
/// VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used.
|
||||
pub opsel: u8,
|
||||
pub opsel_hi: u8,
|
||||
pub clamp: bool,
|
||||
/// Output modifier: 1 ×2, 2 ×4, 3 ÷2.
|
||||
pub omod: u8,
|
||||
pub sdwa: Option<Sdwa>,
|
||||
pub dpp: Option<Dpp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Sdwa {
|
||||
/// Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`.
|
||||
pub dst_sel: u8,
|
||||
/// 0 pad with zeros, 1 sign-extend, 2 preserve.
|
||||
pub dst_unused: u8,
|
||||
pub src_sel: [u8; 2],
|
||||
/// Bit i sign-extends `src[i]`.
|
||||
pub sext: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Dpp {
|
||||
/// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...).
|
||||
Row {
|
||||
ctrl: u16,
|
||||
row_mask: u8,
|
||||
bank_mask: u8,
|
||||
bound_ctrl: bool,
|
||||
fi: bool,
|
||||
},
|
||||
/// DPP8: eight 3-bit lane selects.
|
||||
Lanes { sel: u32, fi: bool },
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// Decodes the operand fields. `wave64` sizes lane masks.
|
||||
pub fn fields(&self, wave64: bool) -> Fields {
|
||||
let name = self.name().unwrap_or("");
|
||||
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
|
||||
let (w0, w1) = (w(0), w(1));
|
||||
let bit = |word: u32, n: u32| word >> n & 1 != 0;
|
||||
let cache = |glc, slc, dlc| Cache { glc, slc, dlc };
|
||||
match self.encoding {
|
||||
Encoding::Sop2 | Encoding::Sop1 | Encoding::Sopc => {
|
||||
let (dst, src0, src1) = salu_dwords(name);
|
||||
let sdst = scalar((w0 >> 16 & 0x7F) as u8, dst);
|
||||
let ssrc = |shift: u32, dwords| source(w0 >> shift & 0xFF, dwords, w1);
|
||||
let (dst, src) = match self.encoding {
|
||||
Encoding::Sop2 => (Some(sdst), vec![ssrc(0, src0), ssrc(8, src1)]),
|
||||
Encoding::Sopc => (None, vec![ssrc(0, src0), ssrc(8, src1)]),
|
||||
_ => match name {
|
||||
"s_getpc_b64" => (Some(sdst), vec![]),
|
||||
"s_setpc_b64" | "s_rfe_b64" => (None, vec![ssrc(0, src0)]),
|
||||
_ => (Some(sdst), vec![ssrc(0, src0)]),
|
||||
},
|
||||
};
|
||||
Fields::Sop {
|
||||
dst,
|
||||
src,
|
||||
imm: None,
|
||||
}
|
||||
}
|
||||
Encoding::Sopk => {
|
||||
let sdst = scalar((w0 >> 16 & 0x7F) as u8, 1 + u8::from(name == "s_call_b64"));
|
||||
let (dst, src) = match name {
|
||||
"s_setreg_imm32_b32" => (None, vec![Operand::Literal(w1)]),
|
||||
"s_version" => (None, vec![]),
|
||||
n if n.starts_with("s_cmpk_")
|
||||
|| n.starts_with("s_waitcnt_")
|
||||
|| n == "s_setreg_b32" =>
|
||||
{
|
||||
(None, vec![sdst])
|
||||
}
|
||||
_ => (Some(sdst), vec![]),
|
||||
};
|
||||
Fields::Sop {
|
||||
dst,
|
||||
src,
|
||||
imm: Some(w0 as u16),
|
||||
}
|
||||
}
|
||||
Encoding::Sopp => Fields::Sopp { imm: w0 as u16 },
|
||||
Encoding::Smem => {
|
||||
let data = match name {
|
||||
"s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None,
|
||||
n if n.starts_with("s_dcache_discard") => None,
|
||||
"s_memtime" | "s_memrealtime" => Some(2),
|
||||
_ => Some(data_dwords(name)),
|
||||
};
|
||||
let base = 2 + 2 * u8::from(name.starts_with("s_buffer_"));
|
||||
Fields::Smem {
|
||||
data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)),
|
||||
base: scalar(((w0 & 0x3F) << 1) as u8, base),
|
||||
offset: (w1 << 11) as i32 >> 11,
|
||||
soffset: scalar((w1 >> 25) as u8, 1),
|
||||
cache: cache(bit(w0, 16), false, bit(w0, 14)),
|
||||
}
|
||||
}
|
||||
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => {
|
||||
Fields::Valu(self.valu(name, if wave64 { 2 } else { 1 }))
|
||||
}
|
||||
Encoding::Vintrp => {
|
||||
let vsrc = (w0 & 0xFF) as u8;
|
||||
Fields::Vintrp {
|
||||
dst: vector(w0 >> 18, 1),
|
||||
src: if name == "v_interp_mov_f32" {
|
||||
Operand::Const(vsrc)
|
||||
} else {
|
||||
vector(vsrc.into(), 1)
|
||||
},
|
||||
attr: Operand::Attr {
|
||||
index: (w0 >> 10 & 0x3F) as u8,
|
||||
chan: (w0 >> 8 & 3) as u8,
|
||||
high: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
Encoding::Ds => {
|
||||
let ty = data_dwords(name);
|
||||
let pair = ds_pair(name);
|
||||
let returns = name.contains("read")
|
||||
|| name.contains("_rtn")
|
||||
|| matches!(
|
||||
name,
|
||||
"ds_swizzle_b32"
|
||||
| "ds_permute_b32"
|
||||
| "ds_bpermute_b32"
|
||||
| "ds_append"
|
||||
| "ds_consume"
|
||||
| "ds_ordered_count"
|
||||
);
|
||||
let no_addr = name.starts_with("ds_gws")
|
||||
|| name.contains("addtid")
|
||||
|| matches!(name, "ds_nop" | "ds_append" | "ds_consume");
|
||||
let data = if name.contains("read")
|
||||
|| name.contains("src2")
|
||||
|| matches!(
|
||||
name,
|
||||
"ds_swizzle_b32"
|
||||
| "ds_nop"
|
||||
| "ds_append"
|
||||
| "ds_consume"
|
||||
| "ds_ordered_count"
|
||||
| "ds_gws_sema_v"
|
||||
| "ds_gws_sema_p"
|
||||
| "ds_gws_sema_release_all"
|
||||
) {
|
||||
0
|
||||
} else if pair || name.contains("cmpst") || name.contains("mskor") {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
Fields::Ds {
|
||||
dst: returns.then(|| vector(w1 >> 24, ty * (1 + u8::from(pair)))),
|
||||
addr: (!no_addr).then(|| vector(w1 & 0xFF, 1)),
|
||||
data: (0..data)
|
||||
.map(|i| vector(w1 >> (8 + 8 * i) & 0xFF, ty))
|
||||
.collect(),
|
||||
offset0: w0 as u8,
|
||||
offset1: (w0 >> 8) as u8,
|
||||
gds: bit(w0, 17),
|
||||
}
|
||||
}
|
||||
Encoding::Mubuf | Encoding::Mtbuf => {
|
||||
let (offen, idxen, tfe) = (bit(w0, 12), bit(w0, 13), bit(w1, 23));
|
||||
let mtbuf = self.encoding == Encoding::Mtbuf;
|
||||
Fields::Buffer {
|
||||
data: (!name.ends_with("_inv"))
|
||||
.then(|| vector(w1 >> 8 & 0xFF, data_dwords(name) + u8::from(tfe))),
|
||||
addr: vector(w1 & 0xFF, 1 + u8::from(offen && idxen)),
|
||||
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, 4),
|
||||
soffset: source(w1 >> 24, 1, 0),
|
||||
offset: (w0 & 0xFFF) as u16,
|
||||
offen,
|
||||
idxen,
|
||||
format: mtbuf.then_some((w0 >> 19 & 0x7F) as u8),
|
||||
lds: !mtbuf && bit(w0, 16),
|
||||
tfe,
|
||||
cache: cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)),
|
||||
}
|
||||
}
|
||||
Encoding::Mimg => {
|
||||
let (dim, dmask, a16, d16) = (
|
||||
(w0 >> 3 & 7) as u8,
|
||||
(w0 >> 8 & 0xF) as u8,
|
||||
bit(w1, 30),
|
||||
bit(w1, 31),
|
||||
);
|
||||
let (r128, tfe, lwe) = (bit(w0, 15), bit(w0, 16), bit(w0, 17));
|
||||
let mut data = if name.starts_with("image_gather4") {
|
||||
4
|
||||
} else {
|
||||
dmask.count_ones().max(1) as u8
|
||||
};
|
||||
if d16 {
|
||||
data = data.div_ceil(2);
|
||||
}
|
||||
let count = image_addr_dwords(name, dim, a16);
|
||||
let addr = if w0 >> 1 & 3 == 0 {
|
||||
vec![vector(w1 & 0xFF, count)]
|
||||
} else {
|
||||
// NSA: one VGPR per address, the first in dword 1, the rest
|
||||
// in the extra dwords.
|
||||
(0..usize::from(count))
|
||||
.map(|i| match i {
|
||||
0 => vector(w1 & 0xFF, 1),
|
||||
i => vector(w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4)) & 0xFF, 1),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let sampled = ["image_sample", "image_gather4", "image_get_lod"]
|
||||
.iter()
|
||||
.any(|p| name.starts_with(p));
|
||||
Fields::Image {
|
||||
data: vector(w1 >> 8 & 0xFF, data + u8::from(tfe || lwe)),
|
||||
addr,
|
||||
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, if r128 { 4 } else { 8 }),
|
||||
sampler: sampled.then(|| scalar(((w1 >> 21 & 0x1F) << 2) as u8, 4)),
|
||||
dmask,
|
||||
dim,
|
||||
unorm: bit(w0, 12),
|
||||
r128,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
cache: cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)),
|
||||
}
|
||||
}
|
||||
Encoding::Flat | Encoding::Global | Encoding::Scratch => {
|
||||
let saddr = (w1 >> 16 & 0x7F) as u8;
|
||||
let glc = bit(w0, 16);
|
||||
let n = data_dwords(name);
|
||||
let (load, atomic) = (name.contains("_load_"), name.contains("_atomic_"));
|
||||
let addr = match self.encoding {
|
||||
Encoding::Flat => Some(vector(w1 & 0xFF, 2)),
|
||||
Encoding::Global => Some(vector(w1 & 0xFF, 1 + u8::from(saddr == NULL))),
|
||||
// With an SGPR base, scratch takes no VGPR.
|
||||
_ => (saddr == NULL).then(|| vector(w1 & 0xFF, 1)),
|
||||
};
|
||||
let ret = if atomic && name.contains("cmpswap") {
|
||||
n / 2
|
||||
} else {
|
||||
n
|
||||
};
|
||||
Fields::Flat {
|
||||
dst: (load || atomic && glc).then(|| vector(w1 >> 24, ret)),
|
||||
addr,
|
||||
data: (!load).then(|| vector(w1 >> 8 & 0xFF, n)),
|
||||
saddr: (self.encoding != Encoding::Flat)
|
||||
.then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))),
|
||||
offset: match self.encoding {
|
||||
Encoding::Flat => (w0 & 0x7FF) as i16,
|
||||
_ => ((w0 << 4) as i16) >> 4,
|
||||
},
|
||||
lds: bit(w0, 13),
|
||||
cache: cache(glc, bit(w0, 17), bit(w0, 12)),
|
||||
}
|
||||
}
|
||||
Encoding::Exp => {
|
||||
let compr = bit(w0, 10);
|
||||
Fields::Exp {
|
||||
target: (w0 >> 4 & 0x3F) as u8,
|
||||
src: std::array::from_fn(|i| {
|
||||
let slot = if compr { i / 2 } else { i };
|
||||
bit(w0, i as u32).then(|| vector(w1 >> (8 * slot) & 0xFF, 1))
|
||||
}),
|
||||
compr,
|
||||
done: bit(w0, 11),
|
||||
vm: bit(w0, 12),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valu(&self, name: &str, lanes: u8) -> Valu {
|
||||
// No operands; the console compiler stores a shader hash in their fields.
|
||||
if matches!(name, "v_nop" | "v_pipeflush" | "v_clrexcp") {
|
||||
return Valu::default();
|
||||
}
|
||||
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
|
||||
let w0 = w(0);
|
||||
let (dst_n, src_n) = valu_dwords(name);
|
||||
let compare = match self.encoding {
|
||||
Encoding::Vopc => true,
|
||||
Encoding::Vop3 => self.opcode < 0x100,
|
||||
_ => false,
|
||||
};
|
||||
let vop3b = VOP3B.contains(&name);
|
||||
let carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32";
|
||||
let mut v = Valu::default();
|
||||
match self.encoding {
|
||||
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc => {
|
||||
let ext = w(1);
|
||||
let mut src0 = w0 & 0x1FF;
|
||||
let vsrc1 = 256 + (w0 >> 9 & 0xFF);
|
||||
let mut src1 = vsrc1;
|
||||
match src0 {
|
||||
0xF9 => {
|
||||
let sdwa = Sdwa {
|
||||
dst_sel: (ext >> 8 & 7) as u8,
|
||||
dst_unused: (ext >> 11 & 3) as u8,
|
||||
src_sel: [(ext >> 16 & 7) as u8, (ext >> 24 & 7) as u8],
|
||||
sext: (ext >> 19 & 1 | ext >> 26 & 2) as u8,
|
||||
};
|
||||
// The s0/s1 bits select an SGPR or constant instead of a VGPR.
|
||||
src0 = (ext & 0xFF) | if ext >> 23 & 1 == 0 { 256 } else { 0 };
|
||||
if ext >> 31 == 1 {
|
||||
src1 = vsrc1 - 256;
|
||||
}
|
||||
v.neg = (ext >> 20 & 1 | ext >> 27 & 2) as u8;
|
||||
v.abs = (ext >> 21 & 1 | ext >> 28 & 2) as u8;
|
||||
if compare {
|
||||
if ext >> 15 & 1 == 1 {
|
||||
v.dst = Some(scalar((ext >> 8 & 0x7F) as u8, lanes));
|
||||
}
|
||||
v.sdwa = Some(Sdwa {
|
||||
dst_sel: 6,
|
||||
dst_unused: 0,
|
||||
..sdwa
|
||||
});
|
||||
} else {
|
||||
v.clamp = ext >> 13 & 1 == 1;
|
||||
v.omod = (ext >> 14 & 3) as u8;
|
||||
v.sdwa = Some(sdwa);
|
||||
}
|
||||
}
|
||||
0xFA => {
|
||||
src0 = 256 + (ext & 0xFF);
|
||||
v.neg = (ext >> 20 & 1 | ext >> 21 & 2) as u8;
|
||||
v.abs = (ext >> 21 & 1 | ext >> 22 & 2) as u8;
|
||||
v.dpp = Some(Dpp::Row {
|
||||
ctrl: (ext >> 8 & 0x1FF) as u16,
|
||||
row_mask: (ext >> 28) as u8,
|
||||
bank_mask: (ext >> 24 & 0xF) as u8,
|
||||
bound_ctrl: ext >> 19 & 1 == 1,
|
||||
fi: ext >> 18 & 1 == 1,
|
||||
});
|
||||
}
|
||||
0xE9 | 0xEA => {
|
||||
v.dpp = Some(Dpp::Lanes {
|
||||
sel: ext >> 8,
|
||||
fi: src0 == 0xEA,
|
||||
});
|
||||
src0 = 256 + (ext & 0xFF);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let op0 = source(src0, src_n[0], ext);
|
||||
let op1 = source(src1, src_n[1], ext);
|
||||
match self.encoding {
|
||||
Encoding::Vopc => {
|
||||
let mask = if name.starts_with("v_cmpx") {
|
||||
EXEC
|
||||
} else {
|
||||
VCC
|
||||
};
|
||||
v.dst = v.dst.or(Some(scalar(mask, lanes)));
|
||||
v.src = vec![op0, op1];
|
||||
}
|
||||
Encoding::Vop1 => {
|
||||
v.dst = Some(valu_dst(name, w0 >> 17 & 0xFF, dst_n));
|
||||
v.src = vec![op0];
|
||||
}
|
||||
_ => {
|
||||
v.dst = Some(vector(w0 >> 17 & 0xFF, dst_n));
|
||||
v.src = match name {
|
||||
n if n.ends_with("mk_f32") || n.ends_with("mk_f16") => {
|
||||
vec![op0, Operand::Literal(ext), op1]
|
||||
}
|
||||
n if n.ends_with("ak_f32") || n.ends_with("ak_f16") => {
|
||||
vec![op0, op1, Operand::Literal(ext)]
|
||||
}
|
||||
_ => vec![op0, op1],
|
||||
};
|
||||
if carry_in {
|
||||
v.src.push(scalar(VCC, lanes));
|
||||
}
|
||||
if name.ends_with("_co_ci_u32") {
|
||||
v.carry = Some(scalar(VCC, lanes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Encoding::Vop3 | Encoding::Vop3p => {
|
||||
let w1 = w(1);
|
||||
let field = |i: u32| w1 >> (9 * i) & 0x1FF;
|
||||
let count = match self.opcode {
|
||||
_ if self.encoding == Encoding::Vop3p => {
|
||||
if name.starts_with("v_pk_")
|
||||
&& !name.contains("_fma_")
|
||||
&& !name.contains("_mad_")
|
||||
{
|
||||
2
|
||||
} else {
|
||||
3
|
||||
}
|
||||
}
|
||||
0x000..0x100 => 2,
|
||||
0x100..0x140 => 2 + usize::from(carry_in),
|
||||
0x180..0x200 => 1,
|
||||
_ if VOP3_TWO_SOURCES.contains(&name) => 2,
|
||||
_ => 3,
|
||||
};
|
||||
v.src = (0..count)
|
||||
.map(|i| {
|
||||
let code = field(i as u32);
|
||||
if i == 0 && name.starts_with("v_interp_") {
|
||||
Operand::Attr {
|
||||
index: (code & 0x3F) as u8,
|
||||
chan: (code >> 6 & 3) as u8,
|
||||
high: code >> 8 & 1 == 1,
|
||||
}
|
||||
} else if i == 2 && carry_in {
|
||||
source(code, lanes, w(2))
|
||||
} else {
|
||||
source(code, src_n[i], w(2))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
v.clamp = w0 >> 15 & 1 == 1;
|
||||
v.neg = (w1 >> 29) as u8;
|
||||
if self.encoding == Encoding::Vop3p {
|
||||
v.neg_hi = (w0 >> 8 & 7) as u8;
|
||||
v.opsel = (w0 >> 11 & 7) as u8;
|
||||
v.opsel_hi = (w1 >> 27 & 3 | w0 >> 12 & 4) as u8;
|
||||
} else {
|
||||
v.omod = (w1 >> 27 & 3) as u8;
|
||||
if vop3b {
|
||||
v.carry = Some(scalar((w0 >> 8 & 0x7F) as u8, lanes));
|
||||
} else {
|
||||
v.abs = (w0 >> 8 & 7) as u8;
|
||||
v.opsel = (w0 >> 11 & 0xF) as u8;
|
||||
}
|
||||
}
|
||||
let vdst = w0 & 0xFF;
|
||||
v.dst = Some(if compare {
|
||||
scalar(vdst as u8, lanes)
|
||||
} else {
|
||||
valu_dst(name, vdst, dst_n)
|
||||
});
|
||||
}
|
||||
_ => unreachable!("not a VALU encoding"),
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// VOP3-only opcodes that take two sources (the rest take three).
|
||||
const VOP3_TWO_SOURCES: &[&str] = &[
|
||||
"v_add_f64",
|
||||
"v_mul_f64",
|
||||
"v_min_f64",
|
||||
"v_max_f64",
|
||||
"v_ldexp_f64",
|
||||
"v_mul_lo_u32",
|
||||
"v_mul_hi_u32",
|
||||
"v_mul_lo_i32",
|
||||
"v_mul_hi_i32",
|
||||
"v_trig_preop_f64",
|
||||
"v_lshlrev_b64",
|
||||
"v_lshrrev_b64",
|
||||
"v_ashrrev_i64",
|
||||
"v_add_nc_u16",
|
||||
"v_sub_nc_u16",
|
||||
"v_mul_lo_u16",
|
||||
"v_lshrrev_b16",
|
||||
"v_ashrrev_i16",
|
||||
"v_max_u16",
|
||||
"v_max_i16",
|
||||
"v_min_u16",
|
||||
"v_min_i16",
|
||||
"v_add_nc_i16",
|
||||
"v_sub_nc_i16",
|
||||
"v_add_co_u32",
|
||||
"v_sub_co_u32",
|
||||
"v_subrev_co_u32",
|
||||
"v_pack_b32_f16",
|
||||
"v_cvt_pknorm_i16_f16",
|
||||
"v_cvt_pknorm_u16_f16",
|
||||
"v_lshlrev_b16",
|
||||
"v_interp_p1ll_f16",
|
||||
"v_readlane_b32",
|
||||
"v_writelane_b32",
|
||||
"v_ldexp_f32",
|
||||
"v_bfm_b32",
|
||||
"v_bcnt_u32_b32",
|
||||
"v_mbcnt_lo_u32_b32",
|
||||
"v_mbcnt_hi_u32_b32",
|
||||
"v_cvt_pknorm_i16_f32",
|
||||
"v_cvt_pknorm_u16_f32",
|
||||
"v_cvt_pk_u16_u32",
|
||||
"v_cvt_pk_i16_i32",
|
||||
"v_sub_nc_i32",
|
||||
"v_add_nc_i32",
|
||||
];
|
||||
|
||||
/// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`.
|
||||
const VOP3B: &[&str] = &[
|
||||
"v_add_co_u32",
|
||||
"v_sub_co_u32",
|
||||
"v_subrev_co_u32",
|
||||
"v_add_co_ci_u32",
|
||||
"v_sub_co_ci_u32",
|
||||
"v_subrev_co_ci_u32",
|
||||
"v_div_scale_f32",
|
||||
"v_div_scale_f64",
|
||||
"v_mad_u64_u32",
|
||||
"v_mad_i64_i32",
|
||||
];
|
||||
|
||||
fn scalar(code: u8, dwords: u8) -> Operand {
|
||||
Operand::Scalar { code, dwords }
|
||||
}
|
||||
|
||||
fn vector(reg: u32, dwords: u8) -> Operand {
|
||||
Operand::Vector {
|
||||
reg: reg as u8,
|
||||
dwords,
|
||||
}
|
||||
}
|
||||
|
||||
/// A 9-bit source field (8-bit scalar fields are the same codes below 256).
|
||||
fn source(code: u32, dwords: u8, literal: u32) -> Operand {
|
||||
match code {
|
||||
0..=127 => scalar(code as u8, dwords),
|
||||
255 => Operand::Literal(literal),
|
||||
256.. => vector(code - 256, dwords),
|
||||
_ => Operand::Const(code as u8),
|
||||
}
|
||||
}
|
||||
|
||||
/// VALU destinations that are SGPRs.
|
||||
fn valu_dst(name: &str, field: u32, dwords: u8) -> Operand {
|
||||
match name {
|
||||
"v_readlane_b32" | "v_readfirstlane_b32" => scalar(field as u8, 1),
|
||||
_ => vector(field, dwords),
|
||||
}
|
||||
}
|
||||
|
||||
/// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1`.
|
||||
pub(super) fn ds_pair(name: &str) -> bool {
|
||||
name.split('_').any(|t| {
|
||||
["read2", "write2", "wrxchg2"]
|
||||
.iter()
|
||||
.any(|p| t.starts_with(p))
|
||||
})
|
||||
}
|
||||
|
||||
/// Dwords of a type suffix such as `b64` or `f32`.
|
||||
fn type_dwords(token: &str) -> u8 {
|
||||
match token {
|
||||
"b64" | "u64" | "i64" | "f64" => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode.
|
||||
fn salu_dwords(name: &str) -> (u8, u8, u8) {
|
||||
match name {
|
||||
"s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" | "s_bfe_u64" | "s_bfe_i64"
|
||||
| "s_bitcmp0_b64" | "s_bitcmp1_b64" => (2, 2, 1),
|
||||
"s_bfm_b64" | "s_bitset0_b64" | "s_bitset1_b64" | "s_bitreplicate_b64_b32" => (2, 1, 1),
|
||||
"s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64"
|
||||
| "s_flbit_i32_b64" | "s_flbit_i32_i64" => (1, 2, 2),
|
||||
_ => {
|
||||
let n = type_dwords(name.rsplit('_').next().unwrap_or(""));
|
||||
(n, n, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// (vdst, [src0, src1, src2]) dwords of a VALU opcode.
|
||||
fn valu_dwords(name: &str) -> (u8, [u8; 3]) {
|
||||
let parts: Vec<&str> = name.split('_').collect();
|
||||
match name {
|
||||
"v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => (2, [1, 2, 2]),
|
||||
"v_ldexp_f64" | "v_trig_preop_f64" | "v_cmp_class_f64" | "v_cmpx_class_f64" => {
|
||||
(2, [2, 1, 2])
|
||||
}
|
||||
"v_mad_u64_u32" | "v_mad_i64_i32" => (2, [1, 1, 2]),
|
||||
"v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" => (2, [2, 1, 2]),
|
||||
"v_mqsad_u32_u8" => (4, [2, 1, 4]),
|
||||
"v_frexp_exp_i32_f64" => (1, [2; 3]),
|
||||
_ if parts.len() == 4 && parts[1] == "cvt" => {
|
||||
(type_dwords(parts[2]), [type_dwords(parts[3]); 3])
|
||||
}
|
||||
_ => {
|
||||
let n = type_dwords(parts.last().copied().unwrap_or(""));
|
||||
(n, [n; 3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dwords of loaded, stored or atomic data, from the opcode name.
|
||||
fn data_dwords(name: &str) -> u8 {
|
||||
let mut n: u8 = 1;
|
||||
for token in name.split('_') {
|
||||
n = match token {
|
||||
"dwordx2" | "x2" | "xy" | "b64" | "u64" | "i64" | "f64" => 2,
|
||||
"dwordx3" | "xyz" | "b96" => 3,
|
||||
"dwordx4" | "xyzw" | "b128" => 4,
|
||||
"dwordx8" => 8,
|
||||
"dwordx16" => 16,
|
||||
_ => n,
|
||||
};
|
||||
}
|
||||
if name.contains("cmpswap") {
|
||||
n *= 2;
|
||||
}
|
||||
if name.contains("format_d16") {
|
||||
n = n.div_ceil(2);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Address dwords of an image opcode: offset, bias, compare, derivatives,
|
||||
/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`.
|
||||
fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 {
|
||||
// (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY
|
||||
// 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY.
|
||||
const DIMS: [(u8, u8); 8] = [
|
||||
(1, 1),
|
||||
(2, 2),
|
||||
(3, 3),
|
||||
(3, 2),
|
||||
(2, 1),
|
||||
(3, 2),
|
||||
(3, 2),
|
||||
(4, 2),
|
||||
];
|
||||
let (coords, grads) = DIMS[usize::from(dim & 7)];
|
||||
match name {
|
||||
"image_bvh_intersect_ray" => return if a16 { 8 } else { 11 },
|
||||
"image_bvh64_intersect_ray" => return if a16 { 9 } else { 12 },
|
||||
"image_get_resinfo" => return 1,
|
||||
_ => {}
|
||||
}
|
||||
let (mut whole, mut derivs, mut packed): (u8, u8, u8) = (0, 0, coords);
|
||||
if let Some(rest) = name
|
||||
.strip_prefix("image_sample")
|
||||
.or_else(|| name.strip_prefix("image_gather4"))
|
||||
{
|
||||
for token in rest.split('_') {
|
||||
match token {
|
||||
"o" | "b" | "c" => whole += 1,
|
||||
"d" | "cd" => derivs = grads,
|
||||
"l" | "cl" => packed += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else if name.contains("_mip") {
|
||||
packed += 1;
|
||||
}
|
||||
if a16 {
|
||||
whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2)
|
||||
} else {
|
||||
whole + 2 * derivs + packed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
//! GFX10 machine code: instruction boundaries, encodings and opcodes.
|
||||
//!
|
||||
//! Instructions are found by following control flow from offset 0, not by a
|
||||
//! linear sweep: compilers place data (constant tables) in the code region
|
||||
//! after the end of the program. [`Instruction::fields`] decodes the operand
|
||||
//! fields and [`Instruction::text`] prints them in AMD's SP3 syntax.
|
||||
//!
|
||||
//! Encodings by the top bits of the first dword:
|
||||
//!
|
||||
//! ```text
|
||||
//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
|
||||
//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
|
||||
//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
|
||||
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
|
||||
//! ```
|
||||
|
||||
mod fields;
|
||||
mod opcodes;
|
||||
mod sp3;
|
||||
|
||||
pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::ShaderError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Encoding {
|
||||
Sop2,
|
||||
Sopk,
|
||||
Sop1,
|
||||
Sopc,
|
||||
Sopp,
|
||||
Smem,
|
||||
Vop2,
|
||||
Vop1,
|
||||
Vopc,
|
||||
Vop3,
|
||||
Vop3p,
|
||||
Vintrp,
|
||||
Ds,
|
||||
Mubuf,
|
||||
Mtbuf,
|
||||
Mimg,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Scratch,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Instruction {
|
||||
/// Byte offset in the program.
|
||||
pub offset: usize,
|
||||
pub encoding: Encoding,
|
||||
pub opcode: u16,
|
||||
/// Every dword of the instruction, including literals and extra dwords.
|
||||
pub words: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// AMD's name for the opcode, if it is in our table.
|
||||
pub fn name(&self) -> Option<&'static str> {
|
||||
name(self.encoding, self.opcode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes every instruction reachable from offset 0, sorted by offset.
|
||||
pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
|
||||
if !code.len().is_multiple_of(4) {
|
||||
return Err(isa(code.len(), "code size is not a multiple of 4"));
|
||||
}
|
||||
let mut found = BTreeMap::new();
|
||||
let mut pending = vec![0usize];
|
||||
while let Some(mut offset) = pending.pop() {
|
||||
while !found.contains_key(&offset) {
|
||||
let inst = instruction(code, offset)?;
|
||||
let next = offset + 4 * inst.words.len();
|
||||
let flow = control(&inst, code.len(), |at| {
|
||||
found.range(..at).next_back().map(|(_, i)| i)
|
||||
})?;
|
||||
found.insert(offset, inst);
|
||||
match flow {
|
||||
Flow::Next => offset = next,
|
||||
Flow::Stop => break,
|
||||
Flow::Jump(target) => offset = target,
|
||||
Flow::Branch(target) => {
|
||||
pending.push(target);
|
||||
offset = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let list: Vec<Instruction> = found.into_values().collect();
|
||||
if let Some(w) = list
|
||||
.windows(2)
|
||||
.find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
|
||||
{
|
||||
return Err(isa(w[1].offset, "a branch lands inside an instruction"));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Where execution goes after an instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Flow {
|
||||
Next,
|
||||
/// End of the program, or an indirect jump that is not a far jump.
|
||||
Stop,
|
||||
Jump(usize),
|
||||
/// Conditional: to the target or the next instruction.
|
||||
Branch(usize),
|
||||
}
|
||||
|
||||
/// Control flow after `inst`, resolving far jumps. `before(at)` returns the
|
||||
/// decoded instruction with the highest offset below `at`, if any.
|
||||
pub(crate) fn control<'a>(
|
||||
inst: &Instruction,
|
||||
len: usize,
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
) -> Result<Flow, ShaderError> {
|
||||
Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? {
|
||||
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
|
||||
far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump)
|
||||
}
|
||||
flow => flow,
|
||||
})
|
||||
}
|
||||
|
||||
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
|
||||
let target = || {
|
||||
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
|
||||
usize::try_from(next as i64 + delta)
|
||||
.ok()
|
||||
.filter(|&t| t < len)
|
||||
.ok_or(isa(inst.offset, "branch target outside the code"))
|
||||
};
|
||||
Ok(match (inst.encoding, inst.name().unwrap_or("")) {
|
||||
(
|
||||
Encoding::Sopp,
|
||||
"s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
|
||||
) => Flow::Stop,
|
||||
(Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
|
||||
(Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
|
||||
(Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
|
||||
// Indirect jump; `decode` resolves the compiler's far-jump form.
|
||||
(Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
|
||||
_ => Flow::Next,
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the far jump compilers emit beyond the reach of a branch offset:
|
||||
/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
|
||||
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
|
||||
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
|
||||
/// merged stage through registers) gives `None`.
|
||||
fn far_jump<'a>(
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
setpc: &Instruction,
|
||||
len: usize,
|
||||
) -> Result<Option<usize>, ShaderError> {
|
||||
let n = setpc.words[0] & 0xFF;
|
||||
let mut delta = None;
|
||||
let mut at = setpc.offset;
|
||||
for _ in 0..4 {
|
||||
let Some(prev) = before(at) else {
|
||||
break;
|
||||
};
|
||||
if prev.offset + 4 * prev.words.len() != at {
|
||||
break;
|
||||
}
|
||||
let w = prev.words[0];
|
||||
let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
|
||||
match (prev.encoding, prev.name()) {
|
||||
(Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
|
||||
if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
|
||||
{
|
||||
// The low dword of a signed 64-bit offset: a backward jump
|
||||
// adds a negative one (its high dword is -1).
|
||||
let literal = i64::from(prev.words[1] as i32);
|
||||
delta = Some(if op == "s_add_u32" { literal } else { -literal });
|
||||
}
|
||||
(Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
|
||||
let Some(delta) = delta else { break };
|
||||
// s_getpc_b64 yields the address of the instruction after it.
|
||||
return usize::try_from(prev.offset as i64 + 4 + delta)
|
||||
.ok()
|
||||
.filter(|&t| t < len)
|
||||
.map(Some)
|
||||
.ok_or(isa(setpc.offset, "far jump target outside the code"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
at = prev.offset;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
|
||||
let word = |i: usize| {
|
||||
code.get(offset + 4 * i..offset + 4 * i + 4)
|
||||
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
|
||||
.ok_or(isa(offset, "instruction runs past the end of the code"))
|
||||
};
|
||||
let w = word(0)?;
|
||||
let (encoding, opcode, len) = if w >> 31 == 0 {
|
||||
let src0 = w & 0x1FF;
|
||||
// Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
|
||||
let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
|
||||
match w >> 25 {
|
||||
0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
|
||||
0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
|
||||
op => {
|
||||
let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
|
||||
matches!(
|
||||
n,
|
||||
"v_madmk_f32"
|
||||
| "v_madak_f32"
|
||||
| "v_fmamk_f32"
|
||||
| "v_fmaak_f32"
|
||||
| "v_madmk_f16"
|
||||
| "v_madak_f16"
|
||||
| "v_fmamk_f16"
|
||||
| "v_fmaak_f16"
|
||||
)
|
||||
});
|
||||
(Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
|
||||
}
|
||||
}
|
||||
} else if w >> 30 == 0b10 {
|
||||
let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
|
||||
match w >> 23 {
|
||||
0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
|
||||
0x17E => (
|
||||
Encoding::Sopc,
|
||||
(w >> 16) & 0x7F,
|
||||
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
|
||||
),
|
||||
0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
|
||||
_ if w >> 28 == 0b1011 => {
|
||||
let op = (w >> 23) & 0x1F;
|
||||
let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
|
||||
(Encoding::Sopk, op, 1 + usize::from(imm32))
|
||||
}
|
||||
_ => (
|
||||
Encoding::Sop2,
|
||||
(w >> 23) & 0x7F,
|
||||
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
let vop3 =
|
||||
|w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
|
||||
match w >> 26 {
|
||||
0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
|
||||
0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
|
||||
0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
|
||||
0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
|
||||
0x37 => {
|
||||
let encoding = match (w >> 14) & 3 {
|
||||
0 => Encoding::Flat,
|
||||
1 => Encoding::Scratch,
|
||||
2 => Encoding::Global,
|
||||
_ => return Err(isa(offset, "reserved FLAT segment")),
|
||||
};
|
||||
(encoding, (w >> 18) & 0x7F, 2)
|
||||
}
|
||||
0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
|
||||
0x3A => (
|
||||
Encoding::Mtbuf,
|
||||
(w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
|
||||
2,
|
||||
),
|
||||
// Bits 2:1 count extra dwords of non-sequential address registers.
|
||||
0x3C => (
|
||||
Encoding::Mimg,
|
||||
(w >> 18) & 0x7F | (w & 1) << 7,
|
||||
2 + (w as usize >> 1 & 3),
|
||||
),
|
||||
0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
|
||||
0x3E => (Encoding::Exp, 0, 2),
|
||||
_ => return Err(isa(offset, "unknown encoding")),
|
||||
}
|
||||
};
|
||||
Ok(Instruction {
|
||||
offset,
|
||||
encoding,
|
||||
opcode: opcode as u16,
|
||||
words: (0..len).map(word).collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
|
||||
use opcodes as t;
|
||||
let (table, op) = match encoding {
|
||||
Encoding::Sop2 => (t::SOP2, opcode),
|
||||
Encoding::Sopk => (t::SOPK, opcode),
|
||||
Encoding::Sop1 => (t::SOP1, opcode),
|
||||
Encoding::Sopc => (t::SOPC, opcode),
|
||||
Encoding::Sopp => (t::SOPP, opcode),
|
||||
Encoding::Smem => (t::SMEM, opcode),
|
||||
Encoding::Vop2 => (t::VOP2, opcode),
|
||||
Encoding::Vop1 => (t::VOP1, opcode),
|
||||
Encoding::Vopc => (t::VOPC, opcode),
|
||||
// VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
|
||||
Encoding::Vop3 => match opcode {
|
||||
0x000..0x100 => (t::VOPC, opcode),
|
||||
0x100..0x140 => (t::VOP2, opcode - 0x100),
|
||||
0x180..0x200 => (t::VOP1, opcode - 0x180),
|
||||
_ => (t::VOP3, opcode),
|
||||
},
|
||||
Encoding::Vop3p => (t::VOP3P, opcode),
|
||||
Encoding::Vintrp => (t::VINTRP, opcode),
|
||||
Encoding::Ds => (t::DS, opcode),
|
||||
Encoding::Mubuf => (t::MUBUF, opcode),
|
||||
Encoding::Mtbuf => (t::MTBUF, opcode),
|
||||
Encoding::Mimg => (t::MIMG, opcode),
|
||||
Encoding::Exp => return Some("exp"),
|
||||
Encoding::Flat => (t::FLAT, opcode),
|
||||
Encoding::Global => (t::GLOBAL, opcode),
|
||||
Encoding::Scratch => (t::SCRATCH, opcode),
|
||||
};
|
||||
table
|
||||
.binary_search_by_key(&op, |&(o, _)| o)
|
||||
.ok()
|
||||
.map(|i| table[i].1)
|
||||
}
|
||||
|
||||
fn isa(offset: usize, reason: &'static str) -> ShaderError {
|
||||
ShaderError::Isa { offset, reason }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
/// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
|
||||
const fn sopp(op: u32, simm16: i16) -> u32 {
|
||||
0xBF80_0000 | op << 16 | simm16 as u16 as u32
|
||||
}
|
||||
|
||||
fn bytes(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
|
||||
decode(&bytes(code))
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_sorted() {
|
||||
for t in [
|
||||
opcodes::SOP2,
|
||||
opcodes::SOPK,
|
||||
opcodes::SOP1,
|
||||
opcodes::SOPC,
|
||||
opcodes::SOPP,
|
||||
opcodes::SMEM,
|
||||
opcodes::VOP2,
|
||||
opcodes::VOP1,
|
||||
opcodes::VOPC,
|
||||
opcodes::VOP3,
|
||||
opcodes::VOP3P,
|
||||
opcodes::VINTRP,
|
||||
opcodes::DS,
|
||||
opcodes::MUBUF,
|
||||
opcodes::MTBUF,
|
||||
opcodes::MIMG,
|
||||
opcodes::FLAT,
|
||||
opcodes::GLOBAL,
|
||||
opcodes::SCRATCH,
|
||||
] {
|
||||
assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_and_names() {
|
||||
let code = [
|
||||
0xBE80_03FF,
|
||||
0x3F80_0000, // s_mov_b32 s0, literal
|
||||
0x0600_0000, // v_add_f32 v0, s0, v0
|
||||
0xD54B_0000,
|
||||
0x03FE_0000,
|
||||
0x4000_0000, // v_fma_f32 with a literal src2
|
||||
0xF080_0F0A,
|
||||
0,
|
||||
0, // image_sample (2D) with one extra address dword
|
||||
0xF800_080F,
|
||||
0, // exp
|
||||
S_ENDPGM,
|
||||
];
|
||||
assert_eq!(
|
||||
summary(&code),
|
||||
[
|
||||
(0, 2, "s_mov_b32"),
|
||||
(8, 1, "v_add_f32"),
|
||||
(12, 3, "v_fma_f32"),
|
||||
(24, 3, "image_sample"),
|
||||
(36, 2, "exp"),
|
||||
(44, 1, "s_endpgm"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_branches_and_skips_data() {
|
||||
let code = [
|
||||
sopp(0x04, 1), // s_cbranch_scc0 -> 8
|
||||
sopp(0x02, 1), // s_branch -> 12
|
||||
S_ENDPGM,
|
||||
S_ENDPGM,
|
||||
S_ENDPGM, // data follows the program end
|
||||
0xFFFF_FFFF,
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
|
||||
assert_eq!(found, [0, 4, 8, 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_far_jumps() {
|
||||
let code = [
|
||||
0xBE88_1F00, // s_getpc_b64 s[8:9]
|
||||
0x8008_FF08,
|
||||
20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
|
||||
0x8209_8009, // s_addc_u32 s9, s9, 0
|
||||
0xBE80_2008, // s_setpc_b64 s[8:9]
|
||||
0xFFFF_FFFF, // not code
|
||||
S_ENDPGM,
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(0, "s_getpc_b64"),
|
||||
(4, "s_add_u32"),
|
||||
(12, "s_addc_u32"),
|
||||
(16, "s_setpc_b64"),
|
||||
(24, "s_endpgm"),
|
||||
]
|
||||
);
|
||||
// Through other registers (a handover to another stage): the path ends.
|
||||
assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_far_jumps_backward() {
|
||||
// The compiler's backward far jump adds a negative offset: the low
|
||||
// dword as a 32-bit literal, the high dword as -1 with the carry.
|
||||
let code = [
|
||||
sopp(0x02, 1), // s_branch -> 8, past the jump target
|
||||
S_ENDPGM, // the far jump's target: only it reaches here
|
||||
0xBE88_1F00, // s_getpc_b64 s[8:9]
|
||||
0x8008_FF08,
|
||||
0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4
|
||||
0x8209_C109, // s_addc_u32 s9, s9, -1
|
||||
0xBE80_2008, // s_setpc_b64 s[8:9]
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(0, "s_branch"),
|
||||
(4, "s_endpgm"),
|
||||
(8, "s_getpc_b64"),
|
||||
(12, "s_add_u32"),
|
||||
(20, "s_addc_u32"),
|
||||
(24, "s_setpc_b64"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_code() {
|
||||
assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
|
||||
assert!(
|
||||
decode(&bytes(&[sopp(0x02, 100)])).is_err(),
|
||||
"branch out of range"
|
||||
);
|
||||
assert!(
|
||||
decode(&bytes(&[0xBE80_03FF])).is_err(),
|
||||
"literal past the end"
|
||||
);
|
||||
assert!(
|
||||
decode(&bytes(&[0xE400_0000, 0])).is_err(),
|
||||
"unknown encoding"
|
||||
);
|
||||
// s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
|
||||
assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,784 @@
|
||||
//! Instruction text in AMD's SP3 assembly syntax.
|
||||
|
||||
use std::fmt::{self, Display, Write};
|
||||
|
||||
use super::fields::{Cache, Dpp, Fields, NULL, Operand, Valu};
|
||||
use super::{Encoding, Instruction};
|
||||
|
||||
impl Instruction {
|
||||
/// The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`.
|
||||
/// Branch targets are written `label_<byte offset>`.
|
||||
pub fn text(&self, wave64: bool) -> String {
|
||||
let name = self.name().unwrap_or("?");
|
||||
let ops = operands(self, name, &self.fields(wave64));
|
||||
if ops.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name} {ops}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Operand {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Operand::Scalar { code, dwords: 1 } => f.write_str(&scalar_name(code)),
|
||||
Operand::Scalar {
|
||||
code: 106,
|
||||
dwords: 2,
|
||||
} => f.write_str("vcc"),
|
||||
Operand::Scalar {
|
||||
code: 126,
|
||||
dwords: 2,
|
||||
} => f.write_str("exec"),
|
||||
Operand::Scalar { code, dwords } if code < 106 => {
|
||||
write!(f, "s[{code}:{}]", code + dwords - 1)
|
||||
}
|
||||
Operand::Scalar { code, dwords } if (108..124).contains(&code) => {
|
||||
write!(f, "ttmp[{}:{}]", code - 108, code - 108 + dwords - 1)
|
||||
}
|
||||
Operand::Scalar { code, .. } => f.write_str(&scalar_name(code)),
|
||||
Operand::Vector { reg, dwords: 1 } => write!(f, "v{reg}"),
|
||||
Operand::Vector { reg, dwords } => {
|
||||
write!(f, "v[{reg}:{}]", reg as u32 + dwords as u32 - 1)
|
||||
}
|
||||
Operand::Const(code) => f.write_str(&const_name(code)),
|
||||
Operand::Literal(value) => write!(f, "lit(0x{value:08x})"),
|
||||
Operand::Attr { index, chan, .. } => write!(
|
||||
f,
|
||||
"attr{index}.{}",
|
||||
['x', 'y', 'z', 'w'][usize::from(chan & 3)]
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_name(code: u8) -> String {
|
||||
match code {
|
||||
0..=105 => format!("s{code}"),
|
||||
106 => "vcc_lo".into(),
|
||||
107 => "vcc_hi".into(),
|
||||
108..=123 => format!("ttmp{}", code - 108),
|
||||
124 => "m0".into(),
|
||||
125 => "null".into(),
|
||||
126 => "exec_lo".into(),
|
||||
_ => "exec_hi".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn const_name(code: u8) -> String {
|
||||
match code {
|
||||
128..=192 => (i32::from(code) - 128).to_string(),
|
||||
193..=208 => (192 - i32::from(code)).to_string(),
|
||||
240 => "0.5".into(),
|
||||
241 => "-0.5".into(),
|
||||
242 => "1.0".into(),
|
||||
243 => "-1.0".into(),
|
||||
244 => "2.0".into(),
|
||||
245 => "-2.0".into(),
|
||||
246 => "4.0".into(),
|
||||
247 => "-4.0".into(),
|
||||
248 => "0.15915494".into(),
|
||||
235 => "src_shared_base".into(),
|
||||
236 => "src_shared_limit".into(),
|
||||
237 => "src_private_base".into(),
|
||||
238 => "src_private_limit".into(),
|
||||
239 => "src_pops_exiting_wave_id".into(),
|
||||
251 => "src_vccz".into(),
|
||||
252 => "src_execz".into(),
|
||||
253 => "src_scc".into(),
|
||||
254 => "src_lds_direct".into(),
|
||||
_ => format!("<src {code}>"),
|
||||
}
|
||||
}
|
||||
|
||||
fn join(ops: impl IntoIterator<Item = String>) -> String {
|
||||
ops.into_iter().collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String {
|
||||
let mut out = String::new();
|
||||
match fields {
|
||||
Fields::Sop { dst, src, imm } => {
|
||||
let regs = join(dst.iter().chain(src).map(|o| o.to_string()));
|
||||
out = match (name, imm) {
|
||||
("s_getreg_b32", Some(imm)) => format!("{regs}, {}", hwreg(*imm)),
|
||||
("s_setreg_b32" | "s_setreg_imm32_b32", Some(imm)) => {
|
||||
format!("{}, {regs}", hwreg(*imm))
|
||||
}
|
||||
("s_call_b64", Some(imm)) => format!("{regs}, {}", label(inst, *imm)),
|
||||
(_, Some(imm)) if regs.is_empty() => format!("0x{imm:04x}"),
|
||||
(_, Some(imm)) => format!("{regs}, 0x{imm:04x}"),
|
||||
(_, None) => regs,
|
||||
};
|
||||
}
|
||||
Fields::Sopp { imm } => {
|
||||
out = match name {
|
||||
"s_endpgm"
|
||||
| "s_barrier"
|
||||
| "s_code_end"
|
||||
| "s_endpgm_saved"
|
||||
| "s_endpgm_ordered_ps_done"
|
||||
| "s_wakeup"
|
||||
| "s_icache_inv"
|
||||
| "s_ttracedata" => String::new(),
|
||||
"s_branch" => label(inst, *imm),
|
||||
n if n.starts_with("s_cbranch_") => label(inst, *imm),
|
||||
"s_waitcnt" => waitcnt(*imm),
|
||||
"s_sendmsg" | "s_sendmsghalt" => sendmsg(*imm),
|
||||
_ => format!("0x{imm:04x}"),
|
||||
};
|
||||
}
|
||||
Fields::Smem {
|
||||
data,
|
||||
base,
|
||||
offset,
|
||||
soffset,
|
||||
cache,
|
||||
} => {
|
||||
if let Some(data) = data {
|
||||
let off = match (soffset, offset) {
|
||||
(Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(),
|
||||
(Operand::Scalar { code: NULL, .. }, _) => {
|
||||
format!("0x{:06x}", offset & 0x1F_FFFF)
|
||||
}
|
||||
(_, 0) => soffset.to_string(),
|
||||
_ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF),
|
||||
};
|
||||
out = format!("{data}, {base}, {off}");
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
}
|
||||
Fields::Valu(v) => out = valu(name, v, inst.encoding),
|
||||
Fields::Vintrp { dst, src, attr } => {
|
||||
let src = match (name, src) {
|
||||
("v_interp_mov_f32", Operand::Const(p)) => ["p10", "p20", "p0"]
|
||||
.get(usize::from(*p))
|
||||
.map_or("p?".into(), |p| p.to_string()),
|
||||
_ => src.to_string(),
|
||||
};
|
||||
out = format!("{dst}, {src}, {attr}");
|
||||
}
|
||||
Fields::Ds {
|
||||
dst,
|
||||
addr,
|
||||
data,
|
||||
offset0,
|
||||
offset1,
|
||||
gds,
|
||||
} => {
|
||||
out = join(dst.iter().chain(addr).chain(data).map(|o| o.to_string()));
|
||||
if super::fields::ds_pair(name) {
|
||||
if *offset0 != 0 {
|
||||
let _ = write!(out, " offset0:{offset0}");
|
||||
}
|
||||
if *offset1 != 0 {
|
||||
let _ = write!(out, " offset1:{offset1}");
|
||||
}
|
||||
} else {
|
||||
let offset = u16::from(*offset1) << 8 | u16::from(*offset0);
|
||||
if offset != 0 {
|
||||
let _ = write!(out, " offset:{offset}");
|
||||
}
|
||||
}
|
||||
if *gds {
|
||||
out.push_str(" gds");
|
||||
}
|
||||
}
|
||||
Fields::Buffer {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
soffset,
|
||||
offset,
|
||||
offen,
|
||||
idxen,
|
||||
format,
|
||||
lds,
|
||||
tfe,
|
||||
cache,
|
||||
} => {
|
||||
if let Some(data) = data {
|
||||
out = format!("{data}, {addr}, {rsrc}, {soffset}");
|
||||
if *idxen {
|
||||
out.push_str(" idxen");
|
||||
}
|
||||
if *offen {
|
||||
out.push_str(" offen");
|
||||
}
|
||||
if *offset != 0 {
|
||||
let _ = write!(out, " offset:{offset}");
|
||||
}
|
||||
if let Some(format) = format {
|
||||
let _ = write!(out, " format:[{}]", buffer_format(*format));
|
||||
}
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
if *lds {
|
||||
out.push_str(" lds");
|
||||
}
|
||||
if *tfe {
|
||||
out.push_str(" tfe");
|
||||
}
|
||||
}
|
||||
Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
sampler,
|
||||
dmask,
|
||||
dim,
|
||||
unorm,
|
||||
r128,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
cache,
|
||||
} => {
|
||||
let addr = match addr.as_slice() {
|
||||
[one] => one.to_string(),
|
||||
many => format!(
|
||||
"[{}]",
|
||||
many.iter()
|
||||
.map(|o| o.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
),
|
||||
};
|
||||
out = join(
|
||||
[data.to_string(), addr, rsrc.to_string()]
|
||||
.into_iter()
|
||||
.chain(sampler.map(|s| s.to_string())),
|
||||
);
|
||||
if *dmask != 1 {
|
||||
let _ = write!(out, " dmask:0x{dmask:x}");
|
||||
}
|
||||
let dims = [
|
||||
"1D",
|
||||
"2D",
|
||||
"3D",
|
||||
"CUBE",
|
||||
"1D_ARRAY",
|
||||
"2D_ARRAY",
|
||||
"2D_MSAA",
|
||||
"2D_MSAA_ARRAY",
|
||||
];
|
||||
let _ = write!(out, " dim:SQ_RSRC_IMG_{}", dims[usize::from(*dim & 7)]);
|
||||
for (on, text) in [(*r128, "r128"), (*unorm, "unorm")] {
|
||||
if on {
|
||||
out.push(' ');
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
flags(&mut out, cache, true);
|
||||
for (on, text) in [(*a16, "a16"), (*d16, "d16"), (*tfe, "tfe"), (*lwe, "lwe")] {
|
||||
if on {
|
||||
out.push(' ');
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
Fields::Flat {
|
||||
dst,
|
||||
addr,
|
||||
data,
|
||||
saddr,
|
||||
offset,
|
||||
lds,
|
||||
cache,
|
||||
} => {
|
||||
let addr = addr.map_or("off".into(), |a| a.to_string());
|
||||
out = join(
|
||||
dst.iter()
|
||||
.map(|o| o.to_string())
|
||||
.chain([addr])
|
||||
.chain(data.iter().chain(saddr).map(|o| o.to_string())),
|
||||
);
|
||||
if *offset != 0 {
|
||||
let _ = write!(out, " inst_offset:{offset}");
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
if *lds {
|
||||
out.push_str(" lds");
|
||||
}
|
||||
}
|
||||
Fields::Exp {
|
||||
target,
|
||||
src,
|
||||
compr,
|
||||
done,
|
||||
vm,
|
||||
} => {
|
||||
let target = match *target {
|
||||
0..=7 => format!("mrt{target}"),
|
||||
8 => "mrtz".into(),
|
||||
9 => "null".into(),
|
||||
12..=15 => format!("pos{}", target - 12),
|
||||
20 => "prim".into(),
|
||||
32..=63 => format!("param{}", target - 32),
|
||||
_ => format!("<target {target}>"),
|
||||
};
|
||||
out = join(
|
||||
[target].into_iter().chain(
|
||||
src.iter()
|
||||
.map(|s| s.map_or("off".into(), |o| o.to_string())),
|
||||
),
|
||||
);
|
||||
for (on, text) in [(*done, " done"), (*compr, " compr"), (*vm, " vm")] {
|
||||
if on {
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Cache flags; images write `dlc` first.
|
||||
fn flags(out: &mut String, cache: &Cache, dlc_first: bool) {
|
||||
let dlc = (cache.dlc, " dlc");
|
||||
let (first, last) = if dlc_first {
|
||||
(dlc, (false, ""))
|
||||
} else {
|
||||
((false, ""), dlc)
|
||||
};
|
||||
for (on, text) in [first, (cache.glc, " glc"), (cache.slc, " slc"), last] {
|
||||
if on {
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
if out.starts_with(' ') {
|
||||
out.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn label(inst: &Instruction, imm: u16) -> String {
|
||||
let target = inst.offset as i64 + 4 * inst.words.len() as i64 + 4 * i64::from(imm as i16);
|
||||
format!("label_{target:04X}")
|
||||
}
|
||||
|
||||
fn hwreg(imm: u16) -> String {
|
||||
let (id, offset, size) = (imm & 0x3F, imm >> 6 & 0x1F, (imm >> 11 & 0x1F) + 1);
|
||||
let name = match id {
|
||||
1 => "HW_REG_MODE".into(),
|
||||
20 => "HW_REG_SHADER_FLAT_SCRATCH_LO".into(),
|
||||
21 => "HW_REG_SHADER_FLAT_SCRATCH_HI".into(),
|
||||
25 => "HW_REG_POPS_PACKER".into(),
|
||||
_ => id.to_string(),
|
||||
};
|
||||
if offset == 0 && size == 32 {
|
||||
format!("hwreg({name})")
|
||||
} else {
|
||||
format!("hwreg({name}, {offset}, {size})")
|
||||
}
|
||||
}
|
||||
|
||||
fn waitcnt(imm: u16) -> String {
|
||||
let vm = imm & 0xF | (imm >> 14) << 4;
|
||||
let exp = imm >> 4 & 7;
|
||||
let lgkm = imm >> 8 & 0x3F;
|
||||
let mut parts = Vec::new();
|
||||
if vm != 0x3F {
|
||||
parts.push(format!("vmcnt({vm})"));
|
||||
}
|
||||
if exp != 7 {
|
||||
parts.push(format!("expcnt({exp})"));
|
||||
}
|
||||
if lgkm != 0x3F {
|
||||
parts.push(format!("lgkmcnt({lgkm})"));
|
||||
}
|
||||
if matches!(parts.len(), 0 | 3) {
|
||||
return format!("0x{imm:04x}");
|
||||
}
|
||||
parts.join(" & ")
|
||||
}
|
||||
|
||||
fn sendmsg(imm: u16) -> String {
|
||||
let (msg, op, stream) = (imm & 0xF, imm >> 4 & 7, imm >> 8 & 3);
|
||||
let msg_name = match msg {
|
||||
2 => "MSG_GS".into(),
|
||||
3 => "MSG_GS_DONE".into(),
|
||||
7 => "MSG_ORDERED_PS_DONE".into(),
|
||||
9 => "MSG_GS_ALLOC_REQ".into(),
|
||||
_ => msg.to_string(),
|
||||
};
|
||||
let op_name = ["GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"]
|
||||
.get(usize::from(op))
|
||||
.map_or(op.to_string(), |s| s.to_string());
|
||||
if msg == 3 && op == 0 {
|
||||
format!("sendmsg({msg_name}, {op_name})")
|
||||
} else {
|
||||
format!("sendmsg({msg_name}, {op_name}, {stream})")
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_format(format: u8) -> String {
|
||||
const NAMES: [&str; 78] = [
|
||||
"INVALID",
|
||||
"8_UNORM",
|
||||
"8_SNORM",
|
||||
"8_USCALED",
|
||||
"8_SSCALED",
|
||||
"8_UINT",
|
||||
"8_SINT",
|
||||
"16_UNORM",
|
||||
"16_SNORM",
|
||||
"16_USCALED",
|
||||
"16_SSCALED",
|
||||
"16_UINT",
|
||||
"16_SINT",
|
||||
"16_FLOAT",
|
||||
"8_8_UNORM",
|
||||
"8_8_SNORM",
|
||||
"8_8_USCALED",
|
||||
"8_8_SSCALED",
|
||||
"8_8_UINT",
|
||||
"8_8_SINT",
|
||||
"32_UINT",
|
||||
"32_SINT",
|
||||
"32_FLOAT",
|
||||
"16_16_UNORM",
|
||||
"16_16_SNORM",
|
||||
"16_16_USCALED",
|
||||
"16_16_SSCALED",
|
||||
"16_16_UINT",
|
||||
"16_16_SINT",
|
||||
"16_16_FLOAT",
|
||||
"10_11_11_UNORM",
|
||||
"10_11_11_SNORM",
|
||||
"10_11_11_USCALED",
|
||||
"10_11_11_SSCALED",
|
||||
"10_11_11_UINT",
|
||||
"10_11_11_SINT",
|
||||
"10_11_11_FLOAT",
|
||||
"11_11_10_UNORM",
|
||||
"11_11_10_SNORM",
|
||||
"11_11_10_USCALED",
|
||||
"11_11_10_SSCALED",
|
||||
"11_11_10_UINT",
|
||||
"11_11_10_SINT",
|
||||
"11_11_10_FLOAT",
|
||||
"10_10_10_2_UNORM",
|
||||
"10_10_10_2_SNORM",
|
||||
"10_10_10_2_USCALED",
|
||||
"10_10_10_2_SSCALED",
|
||||
"10_10_10_2_UINT",
|
||||
"10_10_10_2_SINT",
|
||||
"2_10_10_10_UNORM",
|
||||
"2_10_10_10_SNORM",
|
||||
"2_10_10_10_USCALED",
|
||||
"2_10_10_10_SSCALED",
|
||||
"2_10_10_10_UINT",
|
||||
"2_10_10_10_SINT",
|
||||
"8_8_8_8_UNORM",
|
||||
"8_8_8_8_SNORM",
|
||||
"8_8_8_8_USCALED",
|
||||
"8_8_8_8_SSCALED",
|
||||
"8_8_8_8_UINT",
|
||||
"8_8_8_8_SINT",
|
||||
"32_32_UINT",
|
||||
"32_32_SINT",
|
||||
"32_32_FLOAT",
|
||||
"16_16_16_16_UNORM",
|
||||
"16_16_16_16_SNORM",
|
||||
"16_16_16_16_USCALED",
|
||||
"16_16_16_16_SSCALED",
|
||||
"16_16_16_16_UINT",
|
||||
"16_16_16_16_SINT",
|
||||
"16_16_16_16_FLOAT",
|
||||
"32_32_32_UINT",
|
||||
"32_32_32_SINT",
|
||||
"32_32_32_FLOAT",
|
||||
"32_32_32_32_UINT",
|
||||
"32_32_32_32_SINT",
|
||||
"32_32_32_32_FLOAT",
|
||||
];
|
||||
NAMES
|
||||
.get(usize::from(format))
|
||||
.map_or(format!("{format}"), |n| format!("BUF_FMT_{n}"))
|
||||
}
|
||||
|
||||
fn valu(name: &str, v: &Valu, encoding: Encoding) -> String {
|
||||
let bit = |mask: u8, i: usize| mask >> i & 1 != 0;
|
||||
let mix = name.starts_with("v_fma_mix");
|
||||
let src = |i: usize| {
|
||||
let o = v.src[i];
|
||||
let mut s = o.to_string();
|
||||
if let Some(sdwa) = v.sdwa
|
||||
&& bit(sdwa.sext, i)
|
||||
{
|
||||
s = format!("sext({s})");
|
||||
}
|
||||
if encoding == Encoding::Vop3p {
|
||||
if mix {
|
||||
if bit(v.opsel_hi, i) {
|
||||
s = format!("{}({s})", if bit(v.opsel, i) { "sel_hi" } else { "sel_lo" });
|
||||
}
|
||||
if bit(v.neg_hi, i) {
|
||||
s = format!("abs({s})");
|
||||
}
|
||||
if bit(v.neg, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
} else {
|
||||
if bit(v.neg, i) && bit(v.neg_hi, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
match (bit(v.opsel, i), bit(v.opsel_hi, i)) {
|
||||
(false, true) => {}
|
||||
(false, false) => s = format!("sel_lo({s})"),
|
||||
(true, true) => s = format!("sel_hi({s})"),
|
||||
(true, false) => s = format!("sel_hi_lo({s})"),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if bit(v.abs, i) {
|
||||
s = format!("abs({s})");
|
||||
}
|
||||
if bit(v.neg, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
// v_permlane*: the opsel bits are fi and bound_ctrl.
|
||||
if bit(v.opsel, i) && !name.starts_with("v_permlane") {
|
||||
s = format!("sel_hi({s})");
|
||||
}
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut ops: Vec<String> = v
|
||||
.dst
|
||||
.iter()
|
||||
.chain(&v.carry)
|
||||
.map(|o| o.to_string())
|
||||
.collect();
|
||||
let mut order: Vec<usize> = (0..v.src.len()).collect();
|
||||
if name.starts_with("v_interp_") && order.len() > 1 {
|
||||
// dst, i/j, attribute, then the p1 result for p2.
|
||||
order.swap(0, 1);
|
||||
}
|
||||
ops.extend(order.into_iter().map(src));
|
||||
let mut out = ops.join(", ");
|
||||
let mut suffix = |s: &str| {
|
||||
out.push(' ');
|
||||
out.push_str(s);
|
||||
};
|
||||
if let Some(Operand::Attr { high: true, .. }) = v.src.first() {
|
||||
suffix("high");
|
||||
}
|
||||
let omod = ["", "mul:2", "mul:4", "div:2"][usize::from(v.omod & 3)];
|
||||
if name.starts_with("v_permlane") {
|
||||
if v.opsel & 1 != 0 {
|
||||
suffix("fi:1");
|
||||
}
|
||||
if v.opsel & 2 != 0 {
|
||||
suffix("bound_ctrl:1");
|
||||
}
|
||||
}
|
||||
if let Some(sdwa) = v.sdwa {
|
||||
if v.clamp {
|
||||
suffix("clamp");
|
||||
}
|
||||
if !omod.is_empty() {
|
||||
suffix(omod);
|
||||
}
|
||||
let sel = [
|
||||
"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?",
|
||||
];
|
||||
if sdwa.dst_sel != 6 {
|
||||
suffix(&format!("dst_sel:{}", sel[usize::from(sdwa.dst_sel & 7)]));
|
||||
}
|
||||
if sdwa.dst_unused != 0 {
|
||||
let unused = ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"];
|
||||
suffix(&format!(
|
||||
"dst_unused:{}",
|
||||
unused[usize::from(sdwa.dst_unused & 3)]
|
||||
));
|
||||
}
|
||||
for (i, s) in sdwa.src_sel.iter().enumerate() {
|
||||
if *s != 6 {
|
||||
suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !omod.is_empty() {
|
||||
suffix(omod);
|
||||
}
|
||||
if v.clamp {
|
||||
suffix("clamp");
|
||||
}
|
||||
}
|
||||
match v.dpp {
|
||||
Some(Dpp::Row {
|
||||
ctrl,
|
||||
row_mask,
|
||||
bank_mask,
|
||||
bound_ctrl,
|
||||
fi,
|
||||
}) => {
|
||||
suffix(&match ctrl {
|
||||
0x000..=0x0FF => format!(
|
||||
"quad_perm:[{},{},{},{}]",
|
||||
ctrl & 3,
|
||||
ctrl >> 2 & 3,
|
||||
ctrl >> 4 & 3,
|
||||
ctrl >> 6 & 3
|
||||
),
|
||||
0x101..=0x10F => format!("row_shl:{}", ctrl & 0xF),
|
||||
0x111..=0x11F => format!("row_shr:{}", ctrl & 0xF),
|
||||
0x121..=0x12F => format!("row_ror:{}", ctrl & 0xF),
|
||||
0x140 => "row_mirror".into(),
|
||||
0x141 => "row_half_mirror".into(),
|
||||
0x150..=0x15F => format!("row_share:{}", ctrl & 0xF),
|
||||
0x160..=0x16F => format!("row_xmask:{}", ctrl & 0xF),
|
||||
_ => format!("dpp_ctrl:0x{ctrl:x}"),
|
||||
});
|
||||
if row_mask != 0xF {
|
||||
suffix(&format!("row_mask:0x{row_mask:x}"));
|
||||
}
|
||||
if bank_mask != 0xF {
|
||||
suffix(&format!("bank_mask:0x{bank_mask:x}"));
|
||||
}
|
||||
if bound_ctrl {
|
||||
suffix("bound_ctrl:1");
|
||||
}
|
||||
if fi {
|
||||
suffix("fi:1");
|
||||
}
|
||||
}
|
||||
Some(Dpp::Lanes { sel, fi }) => {
|
||||
let lanes: Vec<String> = (0..8).map(|i| (sel >> (3 * i) & 7).to_string()).collect();
|
||||
suffix(&format!("dpp8:[{}]", lanes.join(",")));
|
||||
if fi {
|
||||
suffix("fi:1");
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::gfx10::{Fields, Operand, decode};
|
||||
|
||||
/// Text of each instruction in `words` (a straight-line program).
|
||||
fn texts(words: &[u32], wave64: bool) -> Vec<String> {
|
||||
let mut code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
code.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm
|
||||
let insts = decode(&code).unwrap();
|
||||
insts[..insts.len() - 1]
|
||||
.iter()
|
||||
.map(|i| i.text(wave64))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn one(words: &[u32], wave64: bool) -> String {
|
||||
let t = texts(words, wave64);
|
||||
assert_eq!(t.len(), 1, "{t:?}");
|
||||
t[0].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar() {
|
||||
assert_eq!(
|
||||
texts(&[0xBF88_0001, 0xBF8C_0070, 0xBE80_03FF, 0x1234_5678], true),
|
||||
[
|
||||
"s_cbranch_execz label_0008",
|
||||
"s_waitcnt vmcnt(0) & lgkmcnt(0)",
|
||||
"s_mov_b32 s0, lit(0x12345678)",
|
||||
]
|
||||
);
|
||||
assert_eq!(one(&[0x8782_027E], true), "s_and_b64 s[2:3], exec, s[2:3]");
|
||||
assert_eq!(
|
||||
one(&[0xF408_0501, 0xFA00_0040], true),
|
||||
"s_load_dwordx4 s[20:23], s[2:3], 0x000040"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xF420_0144, 0x0400_0000], true),
|
||||
"s_buffer_load_dword s5, s[8:11], s2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lane_masks_follow_the_wave_size() {
|
||||
let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3
|
||||
assert_eq!(one(&cmp, false), "v_cmp_gt_f32 vcc_lo, 0.5, v3");
|
||||
assert_eq!(one(&cmp, true), "v_cmp_gt_f32 vcc, 0.5, v3");
|
||||
let vop3 = [0xD401_0106, 0x0001_E501]; // v_cmp_lt_f32 to s6, |v1| < 1.0
|
||||
assert_eq!(one(&vop3, false), "v_cmp_lt_f32 s6, abs(v1), 1.0");
|
||||
assert_eq!(one(&vop3, true), "v_cmp_lt_f32 s[6:7], abs(v1), 1.0");
|
||||
assert_eq!(
|
||||
one(&[0x0202_0480], false),
|
||||
"v_cndmask_b32 v1, 0, v2, vcc_lo"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x5006_0801], true),
|
||||
"v_add_co_ci_u32 v3, vcc, s1, v4, vcc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_modifiers() {
|
||||
assert_eq!(
|
||||
one(&[0x1004_0AFF, 0x3F00_0001], true),
|
||||
"v_mul_f32 v2, lit(0x3f000001), v5"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xD54B_8004, 0x2BC0_0501], true),
|
||||
"v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E02_16F9, 0x0605_0602], true),
|
||||
"v_cvt_f32_f16 v1, v2 src0_sel:WORD_1"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E06_02E9, 0x0539_7701], true),
|
||||
"v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E0A_02FA, 0xFF08_B106], true),
|
||||
"v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xCC20_0C01, 0x2C10_0702], true),
|
||||
"v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_and_export() {
|
||||
assert_eq!(
|
||||
one(&[0xE034_7010, 0x0102_0402], true),
|
||||
"buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xD8DC_0302, 0x0600_0001], true),
|
||||
"ds_read2_b32 v[6:7], v1 offset0:2 offset1:3"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xF800_1C0F, 0x0000_0302], true),
|
||||
"exp mrt0, v2, v2, v3, v3 done compr vm"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_d16_data_is_packed() {
|
||||
// Three f16 channels occupy two VGPRs; NSA lists the addresses.
|
||||
let words = [0xF09C_070A, 0x8024_0801, 0x0000_0005];
|
||||
assert_eq!(
|
||||
one(&words, true),
|
||||
"image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16"
|
||||
);
|
||||
let code: Vec<u8> = words
|
||||
.iter()
|
||||
.chain(&[0xBF81_0000])
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect();
|
||||
let Fields::Image { data, addr, .. } = decode(&code).unwrap()[0].fields(true) else {
|
||||
panic!("not an image instruction");
|
||||
};
|
||||
assert_eq!(data, Operand::Vector { reg: 8, dwords: 2 });
|
||||
assert_eq!(addr.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,826 @@
|
||||
//! I/O raising (decision 0003): what a program's input registers, its
|
||||
//! interpolation and its exports mean.
|
||||
//!
|
||||
//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
|
||||
//! order (barycentrics, then position, front face...). `v_interp_p1` and
|
||||
//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
|
||||
//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
|
||||
//! export patch ([`NativeProgram::patched_code`]) exports carry plain
|
||||
//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
|
||||
//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
|
||||
//! export that ends the program (`done`) is discarded: that export's guard
|
||||
//! after structurisation.
|
||||
//!
|
||||
//! Vertex shaders that run as the hardware VS get the vertex id in v0, the
|
||||
//! primitive id in v2 and the instance id in v3; the fetch shader loads
|
||||
//! channel k of each attribute into its VGPR + k. `exp pos0` is the
|
||||
//! position, `exp param<n>` the output with parameter n.
|
||||
//!
|
||||
//! Attributes and outputs are named by their row: a register of the
|
||||
//! container's signature part.
|
||||
//!
|
||||
//! Compute programs get the thread id in the group in v0-v2 and the group
|
||||
//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
|
||||
//!
|
||||
//! Mesh programs run as one NGG stage. The program computes its thread
|
||||
//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
|
||||
//! its group id from v5 of the first lane (`v_readfirstlane`: the group
|
||||
//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
|
||||
//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
|
||||
//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
|
||||
//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
|
||||
//! primitives << 12).
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, Operand};
|
||||
use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
|
||||
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
|
||||
use crate::resource::Site;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Input {
|
||||
VertexId,
|
||||
PrimitiveId,
|
||||
InstanceId,
|
||||
/// A vertex attribute the fetch shader loads.
|
||||
Attribute {
|
||||
row: u8,
|
||||
channel: u8,
|
||||
},
|
||||
/// `index` 0 is i, 1 is j (2 the pull model's w).
|
||||
Barycentric {
|
||||
kind: Barycentric,
|
||||
index: u8,
|
||||
},
|
||||
/// Pixel position channel (0-3: x, y, z, w).
|
||||
Position(u8),
|
||||
FrontFace,
|
||||
/// Sample id and other bits.
|
||||
Ancillary,
|
||||
SampleCoverage,
|
||||
FixedPosition,
|
||||
LineStipple,
|
||||
/// Compute: thread-group id component (an SGPR).
|
||||
GroupId(u8),
|
||||
/// Compute: thread id within the group, component (a VGPR).
|
||||
ThreadIdInGroup(u8),
|
||||
/// Compute: the thread-group info SGPR (wave index and count).
|
||||
GroupInfo,
|
||||
/// Mesh: v5, the group id times the group size (read as uniform).
|
||||
MeshGroup,
|
||||
/// Mesh: s3, the wave's index in the group in bits 24-27.
|
||||
MergedWaveInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Barycentric {
|
||||
PerspectiveSample,
|
||||
PerspectiveCenter,
|
||||
PerspectiveCentroid,
|
||||
PerspectivePullModel,
|
||||
LinearSample,
|
||||
LinearCenter,
|
||||
LinearCentroid,
|
||||
}
|
||||
|
||||
/// The pixel input VGPRs in hardware order: one entry per
|
||||
/// `SPI_PS_INPUT_ADDR` bit.
|
||||
const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
|
||||
(2, Some(Barycentric::PerspectiveSample)),
|
||||
(2, Some(Barycentric::PerspectiveCenter)),
|
||||
(2, Some(Barycentric::PerspectiveCentroid)),
|
||||
(3, Some(Barycentric::PerspectivePullModel)),
|
||||
(2, Some(Barycentric::LinearSample)),
|
||||
(2, Some(Barycentric::LinearCenter)),
|
||||
(2, Some(Barycentric::LinearCentroid)),
|
||||
(1, None), // line stipple
|
||||
(1, None), // position x
|
||||
(1, None), // y
|
||||
(1, None), // z
|
||||
(1, None), // w
|
||||
(1, None), // front face
|
||||
(1, None), // ancillary
|
||||
(1, None), // sample coverage
|
||||
(1, None), // fixed-point position
|
||||
];
|
||||
|
||||
fn ps_system(bit: usize) -> Input {
|
||||
match bit {
|
||||
7 => Input::LineStipple,
|
||||
8..=11 => Input::Position(bit as u8 - 8),
|
||||
12 => Input::FrontFace,
|
||||
13 => Input::Ancillary,
|
||||
14 => Input::SampleCoverage,
|
||||
_ => Input::FixedPosition,
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute channel of the input signature.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Attribute {
|
||||
pub usage: Usage,
|
||||
pub row: u8,
|
||||
pub channel: u8,
|
||||
/// The upper f16 half of the channel (packed fp16 inputs).
|
||||
pub high: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Interp {
|
||||
/// This site's result (`v_interp_p2*`) is the attribute interpolated
|
||||
/// with `barycentric`; `first` are the `v_interp_p1*` halves it
|
||||
/// completes (one per path where the compiler shares a first half).
|
||||
Interpolated {
|
||||
attribute: Attribute,
|
||||
barycentric: Barycentric,
|
||||
first: Vec<Site>,
|
||||
},
|
||||
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
|
||||
/// 1 for P20, 2 for P0 (the provoking vertex).
|
||||
Vertex { attribute: Attribute, vertex: u8 },
|
||||
/// A half of an interpolation whose i or j is computed rather than
|
||||
/// loaded: each half evaluates as the hardware does, from the
|
||||
/// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
|
||||
/// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
|
||||
Weighted { attribute: Attribute },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
Color(u8),
|
||||
/// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
|
||||
Depth,
|
||||
Null,
|
||||
Position(u8),
|
||||
Param {
|
||||
usage: Usage,
|
||||
row: u8,
|
||||
},
|
||||
/// `param0` of a vertex shader without outputs: the hardware wants one
|
||||
/// parameter export regardless.
|
||||
Unread,
|
||||
/// The primitive export of a merged or mesh stage.
|
||||
Primitive,
|
||||
/// A mesh program's per-primitive output (a row of `PSG1`).
|
||||
PrimitiveParam {
|
||||
usage: Usage,
|
||||
row: u8,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Export {
|
||||
pub site: Site,
|
||||
pub target: Target,
|
||||
/// Per channel, as the instruction enables them.
|
||||
pub values: [Option<Value>; 4],
|
||||
/// Two f16 values per dword.
|
||||
pub compressed: bool,
|
||||
/// The program's last export (for pixels: kills the lanes not in EXEC).
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Io {
|
||||
/// Input values the hardware loads, with their meaning; other VGPRs
|
||||
/// read before written hold undefined values.
|
||||
pub inputs: Vec<(Value, Input)>,
|
||||
pub interps: Vec<(Site, Interp)>,
|
||||
pub exports: Vec<Export>,
|
||||
/// Compute: how many SGPRs the hardware initializes
|
||||
/// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)).
|
||||
pub initialized_sgprs: Option<u8>,
|
||||
}
|
||||
|
||||
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
|
||||
/// stages whose stage data is not read and on constructs not covered yet.
|
||||
pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
|
||||
let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
|
||||
let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
|
||||
(
|
||||
StageIo::Ps {
|
||||
inputs, input_addr, ..
|
||||
},
|
||||
HwStage::Ps,
|
||||
) => {
|
||||
// A pixel shader exports no parameters; `[]` never reaches `Unread`.
|
||||
let loaded = ps_vgprs(*input_addr)
|
||||
.into_iter()
|
||||
.map(|(r, i)| (Reg::V(r), i))
|
||||
.collect();
|
||||
(loaded, &inputs[..], &[][..])
|
||||
}
|
||||
(StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
|
||||
let mut loaded = vec![
|
||||
(Reg::V(0), Input::VertexId),
|
||||
(Reg::V(2), Input::PrimitiveId),
|
||||
(Reg::V(3), Input::InstanceId),
|
||||
];
|
||||
for i in inputs {
|
||||
for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
|
||||
let input = Input::Attribute {
|
||||
row: i.row,
|
||||
channel,
|
||||
};
|
||||
loaded.push((Reg::V(i.vgpr + channel), input));
|
||||
}
|
||||
}
|
||||
(loaded, &[][..], &outputs[..])
|
||||
}
|
||||
// Compute: thread ids in v0-v2, group ids and the group info in the
|
||||
// SGPRs after the user data.
|
||||
(StageIo::Cs(cs), HwStage::Cs) => {
|
||||
let (ids, info) = cs.system_sgprs();
|
||||
let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
|
||||
.map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
|
||||
.collect();
|
||||
for (c, s) in ids.into_iter().enumerate() {
|
||||
if let Some(s) = s {
|
||||
loaded.push((Reg::S(s), Input::GroupId(c as u8)));
|
||||
}
|
||||
}
|
||||
loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
|
||||
(loaded, &[][..], &[][..])
|
||||
}
|
||||
(StageIo::Ms(ms), HwStage::Ms) => {
|
||||
// The group input, and the phis that may carry it past a join.
|
||||
let mut group: Vec<Value> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|i| i.0 == Reg::V(5))
|
||||
.map(|i| i.1)
|
||||
.collect();
|
||||
// No lane is active over the EXEC-zero edge of s_cbranch_execz or
|
||||
// _execnz, the same case as a partial-EXEC write below.
|
||||
let no_lanes = |q: usize, b: usize| match (
|
||||
p.blocks[q].insts.last().map(Inst::name),
|
||||
p.blocks[q].exit,
|
||||
) {
|
||||
(Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
|
||||
taken == b && not_taken != b
|
||||
}
|
||||
(Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
|
||||
not_taken == b && taken != b
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
while let Some(v) = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
|
||||
.find_map(|(b, f)| {
|
||||
let mut args = f.args.iter().zip(&p.blocks[b].preds);
|
||||
let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
|
||||
(carried && !group.contains(&f.value)).then_some(f.value)
|
||||
})
|
||||
{
|
||||
group.push(v);
|
||||
}
|
||||
// The group input holds the same value in every lane only as the
|
||||
// first lane reads it. A write to v5 reads its old value too, which
|
||||
// only lanes outside EXEC keep.
|
||||
// shortcut: writes that may keep the old v5 in active lanes
|
||||
// (v_fmac_f32's accumulator, a 16-bit half or d16 load,
|
||||
// v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
|
||||
// partial-EXEC writes pass; check those too if a mesh program
|
||||
// writes v5 that way.
|
||||
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
|
||||
i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
|
||||
&& i.name() != "v_readfirstlane_b32"
|
||||
&& (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
|
||||
});
|
||||
if let Some(i) = per_lane {
|
||||
return Err(unsupported(
|
||||
i.machine.offset,
|
||||
"the mesh group input read per lane",
|
||||
));
|
||||
}
|
||||
let loaded = vec![
|
||||
(Reg::V(5), Input::MeshGroup),
|
||||
(Reg::S(3), Input::MergedWaveInfo),
|
||||
];
|
||||
(loaded, &[][..], &ms.outputs[..])
|
||||
}
|
||||
_ => return Err(unsupported(0, "I/O of this stage")),
|
||||
};
|
||||
let inputs: Vec<(Value, Input)> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
|
||||
.collect();
|
||||
let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
|
||||
let attribute = |inst: &Inst, attr: &Operand| match *attr {
|
||||
Operand::Attr { index, chan, high } => ps_inputs
|
||||
.iter()
|
||||
.find(|i: &&PsInput| i.attr == index)
|
||||
.map(|i| Attribute {
|
||||
usage: i.usage,
|
||||
row: i.row,
|
||||
channel: chan,
|
||||
high,
|
||||
})
|
||||
.ok_or(unsupported(
|
||||
inst.machine.offset,
|
||||
"an interpolated attribute the stage data does not list",
|
||||
)),
|
||||
_ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
|
||||
};
|
||||
// A VGPR value's barycentric kind and index, if it is one as loaded.
|
||||
let barycentric = |v: Option<Value>| match v.and_then(input_of) {
|
||||
Some(Input::Barycentric { kind, index }) => Some((kind, index)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut io = Io {
|
||||
inputs: inputs.clone(),
|
||||
initialized_sgprs: match &native.io {
|
||||
StageIo::Cs(cs) => Some(cs.initialized_sgprs()),
|
||||
_ => None,
|
||||
},
|
||||
..Io::default()
|
||||
};
|
||||
let defs: std::collections::HashMap<Value, Site> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
block
|
||||
.insts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
|
||||
})
|
||||
.collect();
|
||||
let phis: std::collections::HashMap<Value, (usize, usize)> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
block
|
||||
.phis
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(move |(i, phi)| (phi.value, (b, i)))
|
||||
})
|
||||
.collect();
|
||||
let halves = Halves {
|
||||
p,
|
||||
defs: &defs,
|
||||
phis: &phis,
|
||||
};
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let site = (b, i);
|
||||
let at = inst.machine.offset;
|
||||
let name = inst.name();
|
||||
match &inst.fields {
|
||||
Fields::Vintrp { dst, src, attr } => {
|
||||
let attribute = attribute(inst, attr)?;
|
||||
match (name, *src) {
|
||||
("v_interp_mov_f32", Operand::Const(vertex)) => {
|
||||
io.interps
|
||||
.push((site, Interp::Vertex { attribute, vertex }));
|
||||
}
|
||||
("v_interp_p1_f32", _) => {}
|
||||
("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
|
||||
let Operand::Vector { reg: d, .. } = *dst else {
|
||||
return Err(unsupported(at, "an interpolation operand"));
|
||||
};
|
||||
// The first half's result is this one's old dst.
|
||||
let interp = halves
|
||||
.pair(
|
||||
attr,
|
||||
inst.read(Reg::V(d)),
|
||||
inst.read(Reg::V(reg)),
|
||||
&barycentric,
|
||||
)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
}
|
||||
}
|
||||
Fields::Valu(v) if name.starts_with("v_interp_") => match name {
|
||||
"v_interp_p1ll_f16" => {}
|
||||
"v_interp_p2_f16" => {
|
||||
let attribute = attribute(inst, &v.src[0])?;
|
||||
let read = |k: usize| match v.src.get(k) {
|
||||
Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
};
|
||||
let interp = halves
|
||||
.pair(&v.src[0], read(2), read(1), &barycentric)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
},
|
||||
Fields::Exp {
|
||||
target,
|
||||
src,
|
||||
compr,
|
||||
done,
|
||||
..
|
||||
} => {
|
||||
let target = match *target {
|
||||
t @ 0..=7 => Target::Color(t),
|
||||
8 => Target::Depth,
|
||||
9 => Target::Null,
|
||||
t @ 12..=16 => Target::Position(t - 12),
|
||||
20 => Target::Primitive,
|
||||
32 if params.is_empty() => Target::Unread,
|
||||
t @ 32..=63 => {
|
||||
// Bit 7: a mesh program's per-primitive output.
|
||||
let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
|
||||
unsupported(at, "a parameter export the stage data does not list"),
|
||||
)?;
|
||||
let (usage, row) = (o.usage, o.row);
|
||||
if o.param & 0x80 != 0 {
|
||||
Target::PrimitiveParam { usage, row }
|
||||
} else {
|
||||
Target::Param { usage, row }
|
||||
}
|
||||
}
|
||||
_ => return Err(unsupported(at, "an export target")),
|
||||
};
|
||||
let values = src.map(|s| match s {
|
||||
Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
});
|
||||
io.exports.push(Export {
|
||||
site,
|
||||
target,
|
||||
values,
|
||||
compressed: *compr,
|
||||
done: *done,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(io)
|
||||
}
|
||||
|
||||
/// The pixel input VGPRs that `addr` enables, with their meaning.
|
||||
fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = 0u8;
|
||||
for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
|
||||
if addr >> bit & 1 == 0 {
|
||||
continue;
|
||||
}
|
||||
for index in 0..count {
|
||||
let input = match kind {
|
||||
Some(kind) => Input::Barycentric { kind, index },
|
||||
None => ps_system(bit),
|
||||
};
|
||||
out.push((next + index, input));
|
||||
}
|
||||
next += count;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An interpolation before its attribute is known: `barycentric` none
|
||||
/// when i or j is computed.
|
||||
struct Pair {
|
||||
barycentric: Option<Barycentric>,
|
||||
first: Vec<Site>,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
fn with(self, attribute: Attribute) -> Interp {
|
||||
match self.barycentric {
|
||||
Some(barycentric) => Interp::Interpolated {
|
||||
attribute,
|
||||
barycentric,
|
||||
first: self.first,
|
||||
},
|
||||
None => Interp::Weighted { attribute },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records interpolation `pair` at `site`, and its first halves too when
|
||||
/// they evaluate on their own (computed barycentrics).
|
||||
fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
|
||||
if pair.barycentric.is_none() {
|
||||
for &f in &pair.first {
|
||||
if !io.interps.iter().any(|(s, _)| *s == f) {
|
||||
io.interps.push((f, Interp::Weighted { attribute }));
|
||||
}
|
||||
}
|
||||
}
|
||||
io.interps.push((site, pair.with(attribute)));
|
||||
}
|
||||
|
||||
/// Finds the first halves of interpolations.
|
||||
struct Halves<'a> {
|
||||
p: &'a Program,
|
||||
defs: &'a std::collections::HashMap<Value, Site>,
|
||||
phis: &'a std::collections::HashMap<Value, (usize, usize)>,
|
||||
}
|
||||
|
||||
impl Halves<'_> {
|
||||
/// The interpolation whose second half reads the first half's result
|
||||
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
|
||||
/// must read the same attribute channel. With j and every first half's
|
||||
/// i loaded as one kind's, the pair interpolates with that kind;
|
||||
/// otherwise each half evaluates on its own (`Interp::Weighted`).
|
||||
fn pair(
|
||||
&self,
|
||||
attr: &Operand,
|
||||
acc: Option<Value>,
|
||||
j: Option<Value>,
|
||||
barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
|
||||
) -> Result<Pair, &'static str> {
|
||||
let mut first = Vec::new();
|
||||
self.sites(
|
||||
acc.ok_or("an interpolation without its first half")?,
|
||||
&mut Vec::new(),
|
||||
&mut first,
|
||||
)?;
|
||||
let mut kind = match barycentric(j) {
|
||||
Some((kind, 1)) => Some(kind),
|
||||
_ => None,
|
||||
};
|
||||
for &(b, i) in &first {
|
||||
let inst = &self.p.blocks[b].insts[i];
|
||||
let (a, i) = match &inst.fields {
|
||||
Fields::Vintrp {
|
||||
src: Operand::Vector { reg, .. },
|
||||
attr,
|
||||
..
|
||||
} if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
|
||||
Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
|
||||
Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
|
||||
_ => return Err("an interpolation without its first half"),
|
||||
},
|
||||
_ => return Err("an interpolation without its first half"),
|
||||
};
|
||||
if a != *attr {
|
||||
return Err("interpolation halves of different attributes");
|
||||
}
|
||||
if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
|
||||
kind = None;
|
||||
}
|
||||
}
|
||||
Ok(Pair {
|
||||
barycentric: kind,
|
||||
first,
|
||||
})
|
||||
}
|
||||
|
||||
/// The instructions `v` comes from, through phis (`seen`: phis on the
|
||||
/// way; a loop back to one adds nothing).
|
||||
fn sites(
|
||||
&self,
|
||||
v: Value,
|
||||
seen: &mut Vec<Value>,
|
||||
out: &mut Vec<Site>,
|
||||
) -> Result<(), &'static str> {
|
||||
if let Some(&site) = self.defs.get(&v) {
|
||||
if !out.contains(&site) {
|
||||
out.push(site);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let &(b, i) = self
|
||||
.phis
|
||||
.get(&v)
|
||||
.ok_or("an interpolation without its first half")?;
|
||||
if !seen.contains(&v) {
|
||||
seen.push(v);
|
||||
for &a in &self.p.blocks[b].phis[i].args {
|
||||
self.sites(a, seen, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::ExportPatch;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
crate::ir::build(&code, false, 256).unwrap()
|
||||
}
|
||||
|
||||
fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
|
||||
NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 256,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ps {
|
||||
inputs,
|
||||
input_addr,
|
||||
db_shader_control: 0,
|
||||
patches: Vec::<ExportPatch>::new(),
|
||||
},
|
||||
code: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
const TEXCOORD: PsInput = PsInput {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
mask: 3,
|
||||
attr: 0,
|
||||
flat: false,
|
||||
fp16: false,
|
||||
pack2: false,
|
||||
row2: 1,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn interpolation_pairs_and_color_exports() {
|
||||
// Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
|
||||
// in v0/v1, then exported unconverted to MRT0.
|
||||
let p = program(&[
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
0xF800_180F,
|
||||
0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
|
||||
S_ENDPGM,
|
||||
]);
|
||||
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
|
||||
let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
|
||||
let center = |index| Input::Barycentric {
|
||||
kind: Barycentric::PerspectiveCenter,
|
||||
index,
|
||||
};
|
||||
assert!(io.inputs.contains(&(input(0), center(0))));
|
||||
assert!(io.inputs.contains(&(input(1), center(1))));
|
||||
// v2 and v3 are read before written but hold nothing.
|
||||
assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
|
||||
assert_eq!(
|
||||
io.interps,
|
||||
[(
|
||||
(0, 1),
|
||||
Interp::Interpolated {
|
||||
attribute: Attribute {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
channel: 0,
|
||||
high: false
|
||||
},
|
||||
barycentric: Barycentric::PerspectiveCenter,
|
||||
first: vec![(0, 0)],
|
||||
}
|
||||
)]
|
||||
);
|
||||
let [e] = &io.exports[..] else {
|
||||
panic!("{:?}", io.exports)
|
||||
};
|
||||
assert_eq!(
|
||||
(e.target, e.done, e.compressed),
|
||||
(Target::Color(0), true, false)
|
||||
);
|
||||
assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpaired_or_unknown_interpolation_fails() {
|
||||
// p2 alone: its old dst is no p1's result.
|
||||
let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
|
||||
assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
|
||||
// attr1 is not in the stage data.
|
||||
let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
|
||||
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computed_barycentrics_evaluate_each_half() {
|
||||
// i scaled before the first half: both halves stand on their own.
|
||||
let p = program(&[
|
||||
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
S_ENDPGM,
|
||||
]);
|
||||
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
|
||||
let attribute = Attribute {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
channel: 0,
|
||||
high: false,
|
||||
};
|
||||
let mut interps = io.interps.clone();
|
||||
interps.sort_by_key(|i| i.0);
|
||||
assert_eq!(
|
||||
interps,
|
||||
[
|
||||
((0, 1), Interp::Weighted { attribute }),
|
||||
((0, 2), Interp::Weighted { attribute }),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_inputs_and_primitive_export() {
|
||||
let mesh = |words: &[u32]| {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 256).unwrap();
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ms,
|
||||
wave64: true,
|
||||
vgprs: 256,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ms(crate::native::MeshIo {
|
||||
outputs: vec![],
|
||||
clip_cntl: 0,
|
||||
threads: 128,
|
||||
max_vertices: 128,
|
||||
max_primitives: 128,
|
||||
topology: 2,
|
||||
lds_bytes: 0,
|
||||
}),
|
||||
code,
|
||||
};
|
||||
raise(&p, &native)
|
||||
};
|
||||
let io = mesh(&[
|
||||
0x7E04_0505, // v_readfirstlane_b32 s2, v5
|
||||
0xF800_0941,
|
||||
0x0000_0009, // exp prim, v9, off, off, off done
|
||||
S_ENDPGM,
|
||||
])
|
||||
.unwrap();
|
||||
assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
|
||||
assert_eq!(io.exports[0].target, Target::Primitive);
|
||||
// The group input is uniform only as the first lane reads it.
|
||||
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
|
||||
// Also as an operand of a write to v5, or after a join.
|
||||
let per_lane: [&[u32]; 5] = [
|
||||
&[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
|
||||
&[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
|
||||
&[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
|
||||
&[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
|
||||
&[
|
||||
0xBF06_8001, // s_cmp_eq_u32 s1, 0
|
||||
0xBF85_0001, // s_cbranch_scc1 -> 0xc
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x7E02_0305, // 0xc: v_mov_b32 v1, v5
|
||||
S_ENDPGM,
|
||||
],
|
||||
];
|
||||
let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
|
||||
assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
|
||||
// Overwriting v5 reads the group input only for lanes outside EXEC:
|
||||
// v_mov_b32 v5, 0; v_mov_b32 v1, v5.
|
||||
assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
|
||||
// Skipping that write with s_cbranch_execz is the same case: under the
|
||||
// same mask, the read sees only the 0.
|
||||
let reuse = [
|
||||
0x7E04_0505, // v_readfirstlane_b32 s2, v5
|
||||
0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x14
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x24
|
||||
0x7E02_0305, // v_mov_b32 v1, v5
|
||||
0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
|
||||
S_ENDPGM,
|
||||
];
|
||||
assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_vgprs_follow_the_input_address() {
|
||||
// Linear center (bit 5), then position x and y (bits 8, 9).
|
||||
let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
|
||||
assert_eq!(
|
||||
v,
|
||||
[
|
||||
(
|
||||
0,
|
||||
Input::Barycentric {
|
||||
kind: Barycentric::LinearCenter,
|
||||
index: 0
|
||||
}
|
||||
),
|
||||
(
|
||||
1,
|
||||
Input::Barycentric {
|
||||
kind: Barycentric::LinearCenter,
|
||||
index: 1
|
||||
}
|
||||
),
|
||||
(2, Input::Position(0)),
|
||||
(3, Input::Position(1)),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
//! Xbox Series shaders to host shaders.
|
||||
//!
|
||||
//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL`
|
||||
//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an
|
||||
//! `XDAT` table before it indexing blobs after it, among them `xbop`
|
||||
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
|
||||
//! console-only intrinsics, so the GFX10 code is translated in general.
|
||||
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod bvh;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod dxbc;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod dxil;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod emit;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod gfx10;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod io;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod ir;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod native;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod resource;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod spill;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod structure;
|
||||
|
||||
pub use dxbc::{Container, FourCC, Part};
|
||||
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
|
||||
pub use native::{
|
||||
HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ShaderError {
|
||||
#[error("not a DXBC container")]
|
||||
NotDxbc,
|
||||
#[error("malformed shader: {0}")]
|
||||
Malformed(&'static str),
|
||||
#[error("GFX10 code at {offset:#x}: {reason}")]
|
||||
Isa { offset: usize, reason: &'static str },
|
||||
/// Valid code the translator cannot handle yet: an opcode name or a construct.
|
||||
#[error("GFX10 code at {offset:#x}: {what} is not supported")]
|
||||
Unsupported { offset: usize, what: &'static str },
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,380 @@
|
||||
//! The spilled user-data table of a compute program.
|
||||
//!
|
||||
//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
|
||||
//! root signature that needs more dwords than that keeps none of its
|
||||
//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
|
||||
//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
|
||||
//! the parameter the layout declares at user-data index N (16 or above) is
|
||||
//! at byte `4 * (N - 16)` of that table. The code reads it with
|
||||
//! `s_load_dword*` through that pointer. (Every compute program of the
|
||||
//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
|
||||
//! kind; measured there: 118 of 118 such loads land on a declared parameter.)
|
||||
//!
|
||||
//! [`user_data`] rewrites those loads away: each dword they read becomes the
|
||||
//! entry value of the SGPR its user-data index names, as if the parameter
|
||||
//! had arrived in a register. Resource tracking and lowering then treat a
|
||||
//! spilled parameter like any other (the host binds user data by root slot
|
||||
//! and dword, not by register).
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, NULL, Operand};
|
||||
use crate::ir::{self, Program, Reg, Value};
|
||||
use crate::native::{HwStage, NativeProgram, StageIo};
|
||||
|
||||
/// The user-data index of the table's first dword.
|
||||
const FIRST: u32 = 16;
|
||||
|
||||
/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
|
||||
/// of a spilled user-data table rewritten ([`user_data`]).
|
||||
pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
|
||||
let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
user_data(&mut p, native);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Whether `native` is a compute program that keeps its root parameters in
|
||||
/// a spilled user-data table (see the module): the entries no register
|
||||
/// holds, as (first user-data index, dwords), if the table starts at index
|
||||
/// 16 and the program has the two registers of its address.
|
||||
fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
|
||||
let StageIo::Cs(cs) = &native.io else {
|
||||
return None;
|
||||
};
|
||||
if native.stage != HwStage::Cs {
|
||||
return None;
|
||||
}
|
||||
let registers = u32::from(cs.user_sgprs());
|
||||
let spilled: Vec<(u32, u32)> = native
|
||||
.layout
|
||||
.iter()
|
||||
.filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
|
||||
.map(|e| (u32::from(e.user_data), e.sgprs))
|
||||
.collect();
|
||||
// Only the one arrangement seen: the table starts at index 16.
|
||||
(spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
|
||||
}
|
||||
|
||||
/// Whether `native` reads its root parameters from a spilled user-data
|
||||
/// table. (In the title exactly the compute programs of the
|
||||
/// console's ray-tracing structure builder do.)
|
||||
pub fn is_spilled(native: &NativeProgram) -> bool {
|
||||
spilled(native).is_some()
|
||||
}
|
||||
|
||||
/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
|
||||
/// how many loads it replaced. Nothing changes unless the program is a
|
||||
/// compute program whose layout has entries past its user SGPRs, the first
|
||||
/// at index 16. A load is left alone (and resource tracking then refuses it
|
||||
/// as before) when its offset is not a constant on a dword, or when a dword
|
||||
/// it reads and the program uses is in no layout entry.
|
||||
pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
|
||||
let Some(spilled) = spilled(native) else {
|
||||
return 0;
|
||||
};
|
||||
let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
|
||||
let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
// The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
|
||||
let mut lows = vec![low];
|
||||
let mut highs: Vec<Value> = Vec::new();
|
||||
let mut raw_highs = vec![high];
|
||||
// Instructions that only form the pointer: dropped when nothing reads
|
||||
// them any more.
|
||||
let mut forming: Vec<(usize, usize)> = Vec::new();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Sop { dst, src, .. } = &inst.fields else {
|
||||
continue;
|
||||
};
|
||||
let Some(Operand::Scalar { code: d, .. }) = *dst else {
|
||||
continue;
|
||||
};
|
||||
let Some(out) = inst.write(Reg::S(d)) else {
|
||||
continue;
|
||||
};
|
||||
let read = |op: &Operand| match *op {
|
||||
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
|
||||
_ => None,
|
||||
};
|
||||
let found = match (inst.name(), &src[..]) {
|
||||
("s_mov_b32", [s]) => match read(s) {
|
||||
Some(v) if lows.contains(&v) => Some(&mut lows),
|
||||
Some(v) if highs.contains(&v) => Some(&mut highs),
|
||||
Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
|
||||
_ => None,
|
||||
},
|
||||
("s_and_b32", [x, y]) => {
|
||||
let masked = |a: &Operand, m: &Operand| {
|
||||
matches!(*m, Operand::Literal(0xff))
|
||||
&& read(a).is_some_and(|v| raw_highs.contains(&v))
|
||||
};
|
||||
(masked(x, y) || masked(y, x)).then_some(&mut highs)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(set) = found
|
||||
&& !set.contains(&out)
|
||||
{
|
||||
set.push(out);
|
||||
forming.push((b, i));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if highs.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Values some instruction or phi reads.
|
||||
let mut read_somewhere = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
let mut next = p
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| i.1)
|
||||
.chain(p.blocks.iter().flat_map(|b| {
|
||||
b.phis
|
||||
.iter()
|
||||
.map(|phi| phi.value)
|
||||
.chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
|
||||
}))
|
||||
.map(|v| v.0 + 1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Each load through the pointer: its dwords become entry values.
|
||||
let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
|
||||
let mut gone: Vec<(usize, usize)> = Vec::new();
|
||||
let mut inputs = p.inputs.clone();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
'insts: for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Smem {
|
||||
data: Some(Operand::Scalar { code: first, .. }),
|
||||
base: Operand::Scalar { code: base, .. },
|
||||
offset,
|
||||
soffset,
|
||||
..
|
||||
} = inst.fields
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !inst.name().starts_with("s_load_dword")
|
||||
|| !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
|
||||
|| offset < 0
|
||||
|| offset % 4 != 0
|
||||
|| !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
|
||||
|| !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut dwords = Vec::new();
|
||||
for &(reg, v) in &inst.writes {
|
||||
let Reg::S(code) = reg else {
|
||||
continue 'insts;
|
||||
};
|
||||
let Some(k) = code.checked_sub(first) else {
|
||||
continue 'insts;
|
||||
};
|
||||
let index = FIRST + offset as u32 / 4 + u32::from(k);
|
||||
let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
|
||||
if !declared {
|
||||
if read_somewhere.contains(&v) {
|
||||
continue 'insts;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// SGPR codes end at 105; no root signature reaches there.
|
||||
let Ok(code) = u8::try_from(index) else {
|
||||
continue 'insts;
|
||||
};
|
||||
if code > 105 {
|
||||
continue 'insts;
|
||||
}
|
||||
dwords.push((Reg::S(code), v));
|
||||
}
|
||||
for (reg, v) in dwords {
|
||||
let value = match inputs.iter().find(|e| e.0 == reg) {
|
||||
Some(e) => e.1,
|
||||
None => {
|
||||
let value = Value(next);
|
||||
next += 1;
|
||||
inputs.push((reg, value));
|
||||
value
|
||||
}
|
||||
};
|
||||
replaced.insert(v, value);
|
||||
}
|
||||
gone.push((b, i));
|
||||
}
|
||||
}
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
p.inputs = inputs;
|
||||
let renamed = |v: &mut Value| {
|
||||
if let Some(&to) = replaced.get(v) {
|
||||
*v = to;
|
||||
}
|
||||
};
|
||||
for block in &mut p.blocks {
|
||||
for phi in &mut block.phis {
|
||||
phi.args.iter_mut().for_each(renamed);
|
||||
}
|
||||
for inst in &mut block.insts {
|
||||
inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
|
||||
}
|
||||
}
|
||||
// The loads go, then what only formed the pointer (last first, so a
|
||||
// copy goes before what it copied).
|
||||
let mut drop = gone.clone();
|
||||
loop {
|
||||
let read_somewhere = {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if !drop.contains(&(b, i)) {
|
||||
used.extend(inst.reads.iter().map(|r| r.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
used
|
||||
};
|
||||
let before = drop.len();
|
||||
for &site in &forming {
|
||||
let inst = &p.blocks[site.0].insts[site.1];
|
||||
if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
|
||||
drop.push(site);
|
||||
}
|
||||
}
|
||||
if drop.len() == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (b, block) in p.blocks.iter_mut().enumerate() {
|
||||
let mut i = 0;
|
||||
block.insts.retain(|_| {
|
||||
i += 1;
|
||||
!drop.contains(&(b, i - 1))
|
||||
});
|
||||
}
|
||||
// The pointer's registers are no inputs once nothing reads them.
|
||||
let mut read = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
p.inputs
|
||||
.retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
|
||||
gone.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::{ComputeIo, RootParam, RootType};
|
||||
|
||||
fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
|
||||
RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A compute program with `registers` user SGPRs and the group id after
|
||||
/// them.
|
||||
fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 256,
|
||||
layout,
|
||||
used: vec![],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: registers << 1 | 1 << 7,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
|
||||
// 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
|
||||
const TABLE: [u32; 8] = [
|
||||
0x8703_FF01,
|
||||
0x0000_00FF,
|
||||
0xBE82_0300,
|
||||
0xF400_0141,
|
||||
0xFA00_0010,
|
||||
0xF404_0001,
|
||||
0xFA00_0000,
|
||||
0xBF81_0000,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn loads_of_the_spilled_table_become_entry_registers() {
|
||||
let n = native(
|
||||
&TABLE,
|
||||
4,
|
||||
vec![
|
||||
param(RootType::Descriptor, 16, 2, 0),
|
||||
param(RootType::Descriptor, 18, 2, 1),
|
||||
param(RootType::Constants, 20, 16, 2),
|
||||
],
|
||||
);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 2);
|
||||
let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
|
||||
assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
|
||||
// The pointer is gone with the loads; byte 0x10 is index 20, the
|
||||
// first root constant, and bytes 0-7 are the first root view.
|
||||
let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
|
||||
regs.sort();
|
||||
assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_in_registers_are_left_alone() {
|
||||
// The same code where s0 and s1 are a root view the layout declares.
|
||||
let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
let before = p.clone();
|
||||
assert_eq!(user_data(&mut p, &n), 0);
|
||||
assert_eq!(p, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_used_dword_no_parameter_declares_keeps_its_load() {
|
||||
// As above with `s_mov_b32 s6, s5` before the end: the dword at
|
||||
// byte 0x10 (index 20) is read, and here nothing declares it.
|
||||
let mut words = TABLE.to_vec();
|
||||
words.insert(7, 0xBE86_0305);
|
||||
let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 1);
|
||||
let loads = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.insts)
|
||||
.filter(|i| i.name().starts_with("s_load_"))
|
||||
.count();
|
||||
assert_eq!(loads, 1);
|
||||
// The pointer is still read, by the load that stays.
|
||||
assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -68,6 +68,9 @@ checkpoints retain their original evidence scope.
|
||||
|
||||
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
|
||||
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
|
||||
- [victory-shader provenance review](research/victory-shader-provenance.md) — Per-file licence and origin record for the proposed import; not approved, maintainer decision pending.
|
||||
- [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified.
|
||||
- [Shader wave-semantics investigation](research/shader-wave-semantics.md) — Why two upstream wave tests failed under D3DMetal: device capabilities, independent probes, the fix and its limits.
|
||||
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
|
||||
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
|
||||
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
|
||||
|
||||
@@ -12,6 +12,9 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa
|
||||
| bitflags | 2.13.2, `80ce9b545acb0bd42150695fc351889cac1d8eb4` | MIT from MIT OR Apache-2.0 | Runtime transitive dependency |
|
||||
| AMD RDNA 2 ISA XML | 2026-02-20, schema 1.1.1 | MIT | Source for generated decoder constants |
|
||||
| LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked |
|
||||
| victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md |
|
||||
| thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited |
|
||||
| DirectX Shader Compiler | v1.9.2609, `dxc_2026_09_29.zip` (sha256 `ad31b1fc…a7e7f1`) | University of Illinois/NCSA plus MIT components (per its licence files) | External tool for compiling HLSL probes under CrossOver; not vendored, not distributed |
|
||||
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
|
||||
|
||||
## Runtime redistribution review
|
||||
|
||||
@@ -14,6 +14,7 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
|
||||
| Vulkan on Metal | MoltenVK | **Evaluate** | Apache-2.0 (compatible with GPLv3). Subset of Vulkan; coverage vs consumers unknown. |
|
||||
| Shader compiler / runtime | VIctory, VIctory-macOS | **Rejected for reuse** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
|
||||
| GFX10 to DXIL recompiler | victory-mac `crates/victory-shader` (VIctory family) | **Not approved: maintainer decision pending** (the rejection above stands until then) | PR #394 proposes vendoring it. The [per-file review](victory-shader-provenance.md) finds GPL-3.0 licensing but development against one commercial title's shaders; read plainly, the engineering rules exclude it. |
|
||||
| Project discovery | PortWatch VI | Reference only | Editorial tracker; not engineering evidence; nothing imported. |
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Shader wave-operation failures under D3DMetal: investigation
|
||||
|
||||
Part of the shader integration PR (#394). It began as the separate investigation PR #392, whose content is carried here. Evidence class B (runs on one machine: Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, default backend), not independently reproduced. The two failures are the ones recorded in `victory-shader-integration.md`. This note separates what is **established** from what is **a hypothesis**.
|
||||
|
||||
## Device capabilities (measured with BetterXen's own host, `workloads/d3d12-wave-probe/d3d12_run.c caps`)
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Adapter reported | "AMD Compatibility Mode", vendor 0x1002, 18,186 MB (D3DMetal's reported identity; the hardware is the M4) |
|
||||
| Device created at feature level | 12_1 |
|
||||
| Highest shader model | 6.6 |
|
||||
| `WaveOps` | supported |
|
||||
| `WaveLaneCountMin` / `Max` | 32 / 32 (waves are exactly 32 lanes; `TotalLaneCount` 1024) |
|
||||
| `DoublePrecisionFloatShaderOps` | **0** (no double-precision shader operations) |
|
||||
| `Int64ShaderOps` | supported |
|
||||
| Min-precision support | 0x2 (16-bit) |
|
||||
|
||||
## Failure 2: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (established)
|
||||
|
||||
**Cause: a wrong test precondition (a subgroup-size assumption), not a translation error.**
|
||||
|
||||
1. The test lowers the program with `lowered_on(.., 64)`, "for a host of 64-lane waves (AMD)" per its own comment, then dispatches it on the default device without asking that device's wave width.
|
||||
2. The device's waves are exactly 32 lanes (table above). A program written for 64-lane waves reads lanes 32 to 63, which do not exist; the observed result was `0x0` against the expected tree `0x5914`.
|
||||
3. It is the only test in that file that lowers for 64 lanes (line 238); the sibling `a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit` lowers for 32 (line 160) and passes on the same device.
|
||||
4. Lowering this same program for a 32-lane host does not produce a wrong shader: the recompiler refuses it with `Unsupported: a wave sum of 16-bit floats where not every lane runs`. So the recompiler already behaves correctly; it states a limit instead of emitting something wrong.
|
||||
5. The expected value `0x5914` is derived on the host by integer 16-bit float arithmetic in the test itself, independent of the recompiler.
|
||||
|
||||
**Correction made (test, not recompiler):** `Host::wave_lane_count_max()` (new, from `D3D12_OPTIONS1`), and the test now checks the device first. On a device narrower than 64 lanes it asserts the refusal above and returns, printing why; on a 64-lane device it runs the original hardware comparison unchanged. After the change the test passes on this device, and what it verifies there is "the recompiler refuses a 64-lane-only program for a 32-lane host", not "the sum is correct on the GPU". The correct-sum claim stays **unverified on 32-lane hardware** and has not been run on a 64-lane device.
|
||||
|
||||
## Failure 1: `whole_wave_f64_sum_and_cvt_f32_f64` (established: unsupported double-precision operations in D3DMetal; fixed in the recompiler)
|
||||
|
||||
Observed: a Wave32 program with 4 launched threads, each contributing 1.25, should store 5.0; it stored `0x00000000`. It is a Wave32 program on a 32-lane device, so wave width was never the cause.
|
||||
|
||||
**Independent evidence** (Microsoft's DXC compiled original HLSL, BetterXen's own host dispatched it; expected values derived by hand before running; DXC v1.9.2609 digest-verified and run under CrossOver 26.3):
|
||||
|
||||
| Probe (`workloads/d3d12-wave-probe/hlsl/`) | Expected | Observed |
|
||||
| --- | --- | --- |
|
||||
| `lanes4`: wave size and lane index, 4 threads | `0x2000`..`0x2003` (wave of 32) | exactly that |
|
||||
| `sum_f32_4`: `WaveActiveSum(1.25f)`, 4 threads | `0x40a00000` in every lane | exactly that |
|
||||
| `add_f32_4`: control, run-time load, float add, store | `0x40000000`, `0` per thread | exactly that |
|
||||
| `add_f64_4`: a `double` add of run-time operands (DXIL contains `fadd fast double`) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
| `sum_f64_4`: `WaveActiveSum` over a run-time `double` (DXIL `waveActiveOp.f64`) | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
|
||||
An earlier version of `add_f64_4` used constant operands: the compiler folded the addition to `splitDouble(2.0)` with no `fadd` (reviewer finding by atesahmet0, confirmed with `dxc -dumpbin`), so it did not show a double *addition* failing. The probes above take their operands from the buffer at run time and were rerun; the result is the same.
|
||||
|
||||
So wave operations, wave width and partial waves are fine on this device. Any shader that uses a `double` runs without effect: pipeline creation succeeds, the dispatch completes, and nothing is stored. That matches the capability record (`DoublePrecisionFloatShaderOps = 0`; Metal has no fp64). Upstream's test harness zero-fills its output buffer, which is why it saw `0` instead of the sentinel. **Conclusion:** the failure comes from unsupported double-precision operations in the backend, combined with the recompiler emitting a native `double` in one place (`active_f64_sum`) while using integer emulation everywhere else. It is not a mistranslation of the wave operation and not a wave-semantics problem.
|
||||
|
||||
**Fix (recompiler, `active_f64_sum`):** the existing integer fp64 add (`add_f64`, checked upstream against the CPU's doubles) is reused to build the console's sum, which is the balanced tree over the lanes in their order. Each lane adds its partner run's partial sum, read through `waveReadLaneAt` from the first lane of that run that is present (found with a ballot, as `half_sum_present` already does for 16-bit sums), `+0.0` where none is, which is what a lane outside EXEC adds on the console. No `double` type is emitted and the doubles feature flag is no longer set. The same code covers the console wave64 on two host waves of 32 (an integer add for the last step).
|
||||
|
||||
**Validation** (M4, CrossOver 26.3, default backend; one machine, not independently reproduced):
|
||||
- Whole suite under CrossOver: **232 passed, 0 failed, 3 ignored** (229 before the review's sampler tests) (was 224 passed, 2 failed). macOS: 179 + new tests pass (`cargo test -p victory-shader`).
|
||||
- New test `f64_wave_sums_match_the_cpu_tree_bit_for_bit`: 24 cases (1, 4, 20 and 32 launched threads; six values including ones that round: 0.1, 123456.789, a value one ulp above 1.0, -3.75e10, 1e-300), comparing all 64 bits with a CPU model of the balanced tree using the CPU's own f64 additions and `+0.0` for lanes that are not launched. All 24 match. The model is independent of the recompiler.
|
||||
- Negative controls: against the **original** lowering this GPU test fails (`got 0x0000000000000000, want 0x3ff4000000000000`) and the new `the_f64_wave_sum_is_lowered_without_native_doubles` test (the container's feature word must declare wave operations but not doubles) fails too; both pass with the fix.
|
||||
|
||||
**Limits:** (1) the tree order is what the recompiler's recognizer claims the console program computes (`wave::buddies`); this was not independently simulated from the DPP instructions, so bit-for-bit fidelity to the console for rounding values is only as good as that recognition. (2) The cost of the integer version was not measured and no performance claim is made. (3) Other fp64 wave operations (products, min/max) were not examined; only this one site emitted native doubles. (4) On a device with real fp64 the old native operation would work and is no longer used. (5) DXC is an external tool (University of Illinois/NCSA licence plus MIT components per its licence files), used only to compile probes; nothing from it is in the repository.
|
||||
|
||||
## Reproduce
|
||||
```sh
|
||||
scripts/hybrid/run-shader-gpu-tests.sh <llvm-mingw-dir> betterxen-test all # the runner script is in PR #395; or run the cross-built test executable with wine directly # expect: 0 failures with the fix in this branch (the vendored original has 2)
|
||||
# probes: compile hlsl/*.hlsl with DXC under CrossOver, then d3d12_run.exe run <file>.dxil 1 <dwords>
|
||||
# capabilities (needs the d3d12_run.exe built from workloads/d3d12-wave-probe/d3d12_run.c with llvm-mingw):
|
||||
# x86_64-w64-mingw32-clang -O2 -o d3d12_run.exe d3d12_run.c -ld3d12 -ldxgi -ldxguid
|
||||
# CrossOver bin/wine --bottle <bottle> ./d3d12_run.exe caps
|
||||
```
|
||||
@@ -15,6 +15,10 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in [portwatch-native-macos.md](portwatch-native-macos.md)). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
|
||||
## victory-shader import under review
|
||||
|
||||
`skakwy/victory-mac` `crates/victory-shader` at `22b3f8e45a59` is proposed for vendoring in PR #394. **Not approved.** See the [per-file provenance and licence review](victory-shader-provenance.md); the provenance decision below stands until a maintainer changes it.
|
||||
|
||||
## Additional candidates found by search (not reviewed)
|
||||
|
||||
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# victory-shader integration (GFX10 to DXIL recompiler)
|
||||
|
||||
Evidence: classes noted per row. Everything ran on one machine (Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, bottle `betterxen-test`, default backend) and has **not been independently reproduced**. BetterXen's runs used no game files or leaked material. **The vendored code itself was developed against one commercial title's shaders** and is not approved for merge: see [victory-shader-provenance.md](victory-shader-provenance.md).
|
||||
|
||||
## What was integrated
|
||||
|
||||
`crates/victory-shader` is a snapshot of `crates/victory-shader/` from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (head `22b3f8e45a59`). It translates GFX10 (RDNA 2) machine code to PC DXIL, shader model 6.6, in pure Rust: a GFX10 decoder with an SP3 printer, control-flow structurizer, register spilling, wave emulation, fp64 by integer operations, its own LLVM 3.7 bitcode writer and DXIL container writer. About 43,500 lines against 4,022 in BetterXen's native `xenora-shader`. The native RDNA-to-Metal compiler is untouched and still paused; the two are different targets (DXIL for D3D12 under CrossOver versus MSL) and nothing was replaced. Provenance, authors, licences and the 19 changed lines are in [`crates/victory-shader/UPSTREAM.md`](../../crates/victory-shader/UPSTREAM.md). Licensing: GPL-3.0 upstream, GPL-3.0-or-later here, one MIT Mesa-derived table with its notice kept.
|
||||
|
||||
Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game-specific code (one console title's runtime) and their provenance questions; the console shader containers the crate can also parse were not exercised, because no authorized container exists.
|
||||
|
||||
## How it connects to BetterXen
|
||||
|
||||
- `emit::translate_native` (BetterXen addition, `emit/betterxen.rs`): the crate only accepted shaders inside console containers; this entry point takes a compute program as machine code plus root layout, which is what BetterXen has.
|
||||
- `emit/betterxen_tests.rs`: BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled with LLVM's `llvm-mc`) are wrapped in a short descriptor-table prologue, translated to DXIL, and compared with the expected words in `fixtures/manifest.toml`. Those expectations were derived by hand in the manifest and are checked by BetterXen's independent reference; none comes from the recompiler. Six of the eleven manifest fixtures have input and expected words (add, float-exact, bitwise-branch, or, shifts, ashr); the five graphics-stage fixtures (`x9-*`) have none and are not bridged.
|
||||
- Running the cross-built Windows test executable under CrossOver is done by `scripts/hybrid/run-shader-gpu-tests.sh` through `betterxen-hybrid run`. Those live in separate pull requests (the hybrid runner, and the script on top of it); the GPU results below were produced with them.
|
||||
|
||||
## Results
|
||||
|
||||
| Check | Result | Notes |
|
||||
| --- | --- | --- |
|
||||
| Native build, aarch64-apple-darwin, Rust 1.100.0 | builds; fmt, `clippy -D warnings` clean | upstream also builds for Windows targets |
|
||||
| Upstream tests that run on macOS (CPU-side: decode, structurize, lower, emit) | 177 passed, 2 ignored | The Windows-only GPU modules are not compiled here |
|
||||
| BetterXen fixtures to DXIL on macOS | 6 of 6 translate to a DXBC container | `translate_native` |
|
||||
| BetterXen fixtures run on the GPU: D3D12 under CrossOver 26.3 (D3DMetal) | **6 of 6 output words match the manifest** | via `betterxen-hybrid run`, 2.3 to 2.6 s including bottle start; the GPU is a D3D12 device with shader model 6.6 as upstream's host layer requires |
|
||||
| Negative control | a flipped expected word is rejected; the output is not the zeroed buffer | `a_wrong_expectation_is_detected` |
|
||||
| Same GPU tests on DXMT, DXVK and wined3d (no D3D12) | fail with "no SM 6.6 D3D12 hardware device: not verified" | confirms they cannot pass by skipping; upstream's own tests print "skipped" instead |
|
||||
| Whole upstream suite, vendored unchanged, under CrossOver (default backend), 229 tests | 224 passed, **2 failed**, 3 ignored | the two failures are explained in `shader-wave-semantics.md` |
|
||||
| Whole suite with the fixes in this PR, under CrossOver | **232 tests: 229 passed, 0 failed, 3 ignored** | the 3 additional tests are BetterXen's f64 tests; see below |
|
||||
| Upstream suite on a backend without D3D12 (DXMT) | 201 passed, 25 failed, 3 ignored | see the classification below |
|
||||
|
||||
The two failures are `whole_wave_f64_sum_and_cvt_f32_f64` (a wave-wide fp64 sum returned 0, expected `0x40a00000`) and `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (64 lanes: got 0, expected `0x5914`). Both are cross-lane wave reductions of the console's 64-lane waves. Hypothesis, **not verified**: the host's waves are 32 lanes wide (Apple GPU) and D3DMetal does not honour the required wave size or wave operation semantics. The cause, and whether upstream passes them on a Windows GPU, were not investigated.
|
||||
|
||||
## Which tests actually executed on the GPU
|
||||
|
||||
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each test was therefore run on the default backend (D3D12 via D3DMetal) and on DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. Final content of this PR (232 tests: 225 upstream, 7 BetterXen):
|
||||
|
||||
| Group | Tests |
|
||||
| --- | --- |
|
||||
| Executed on the D3D12 hardware device and passed | **31** (26 of them fail without D3D12; 5 pass only by skipping there) |
|
||||
| Executed on the D3D12 hardware device and failed | **0** |
|
||||
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 201, including 3 ignored |
|
||||
| Total | 232 |
|
||||
|
||||
For the vendored upstream code before the fixes in this PR the same method gave 229 tests: 32 GPU-dependent, 30 passed on the device and 2 failed (they "passed" without D3D12 by skipping, which hid the failures), see `shader-wave-semantics.md`. Three of the 31 are BetterXen's GPU tests (fixtures, negative control, bit-exact f64 sums). Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
|
||||
|
||||
## Limits
|
||||
|
||||
- Microsoft's `dxil.dll` is not present, so upstream's DXIL validation is skipped in six tests. DXIL is accepted unsigned by D3DMetal under Wine (upstream's code states this; the passing runs agree).
|
||||
- Many upstream tests also run on WARP (a software adapter) and print "no SM 6.6 warp device; skipped" because Wine has none. Those skips are expected and are not counted as GPU runs.
|
||||
- Only compute fixtures with one input and one output buffer are bridged. Graphics stages, textures, samplers, wave64 and LDS programs are exercised only by upstream's own tests.
|
||||
- No performance was measured: a six-fixture dispatch says nothing about speed or about real shaders.
|
||||
- Correctness is shown for these original fixtures, not for console shaders; the crate's real inputs (console shader containers) were not used.
|
||||
- Upstream is a snapshot; later upstream fixes must be merged by hand against the pinned commit.
|
||||
@@ -0,0 +1,66 @@
|
||||
# victory-shader: per-file provenance and licence review
|
||||
|
||||
**Status: NOT APPROVED. A maintainer decision is required before PR #394 can merge.** This is the review the engineering rules require for VIctory-family code. It records facts; it does not grant approval, and its author is the person who proposed the import, so it is not an independent review.
|
||||
|
||||
Upstream: <https://github.com/skakwy/victory-mac>, revision `22b3f8e45a59f7d11fef7718988c58d0b3f1d0f9`. Method: every tracked file of `crates/victory-shader/` at that revision; authors from `git shortlog`; licence from the repository `LICENSE` and a search of each file for other notices; title references by searching for shader names of the form `module:CS_Name` and the words title, titles, game, games. The search finds references, not every dependence: a file without one may still have been developed against the same title.
|
||||
|
||||
## Findings
|
||||
|
||||
1. **Licence:** GPL-3.0, compatible with BetterXen's GPL-3.0-or-later. One third-party notice (Mesa-derived opcode names, MIT, Valve) in `src/gfx10/opcodes.rs`, kept. Some comments cite Mesa behaviour and LLVM definitions. skakwy and the VIctory-macOS maintainer authorized reuse of their own contributions (relayed by the maintainer); other authors' lines rest on the repository licence.
|
||||
2. **The crate was developed against one commercial title's shaders.** 17 of 36 files refer to "the title" or "the game"; comments describe that title's programs, layouts and structures, and four places cite its shaders by name (`wave64_tests.rs`, `wave.rs`, `own_bits.rs`). The upstream project's stated purpose is to run that title's Xbox Series build; this registry and PortWatch record that build as leaked.
|
||||
3. **What is not in the crate:** a search found no shader binaries, shader dumps, game assets, keys or decryption code. The references are in comments, test descriptions and handling of shader constructs.
|
||||
4. **Earlier statements that were wrong:** the integration record and PR descriptions said the crate had nothing game-specific. That claim came from searching only for the game's and publisher's names. It is withdrawn.
|
||||
|
||||
## How this meets the engineering rules (`AGENTS.md`)
|
||||
|
||||
| Rule | Assessment |
|
||||
| --- | --- |
|
||||
| "Projects whose stated purpose depends on leaked or unauthorized builds ... are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry." | This file is that record. Recording it does not by itself approve adoption. |
|
||||
| "Game-specific, asset-specific and decryption-related code is never adopted." | Handling written for and documented against one title's shaders is present in at least some files. Whether that makes a file "game-specific code" is the decision to make; it is a general GFX10 recompiler in structure, with title-driven behaviour inside it. |
|
||||
| "Provenance first: exclude anything derived from leaked proprietary material or unauthorized software." | Layouts "as observed in shipped titles" (`native.rs`) and behaviour tuned to the title's programs are plausibly derived from that material. |
|
||||
| "Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material." | Read plainly, this applies to this import. Author permission does not change it. |
|
||||
|
||||
**Reviewer's recommendation to the maintainer:** under the rules as written, do not merge the import. Either decline it (keep the crate as a documentation-level reference; BetterXen's own fixtures, probes and findings stand on their own), or change the rule explicitly in `AGENTS.md` with the legal question considered, and then decide file by file. This is not legal advice.
|
||||
|
||||
## Per-file record
|
||||
|
||||
| File (under `crates/victory-shader/`) | Lines | Upstream authors (commits) | Licence and third-party notes | Shader names of a title | Lines saying title/game |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `Cargo.toml` | 40 | Marvis (2), fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/bvh.rs` | 696 | fxceless (2) | GPL-3.0 (repository licence) | - | 5 |
|
||||
| `src/dxbc.rs` | 181 | Marvis (2) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/dxil.rs` | 211 | Marvis (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/emit/bitcode.rs` | 1240 | Marvis (3), fxceless (2), Lyrnc (1) +2 more | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/emit/bitcode/census.rs` | 174 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/bitcode/opt.rs` | 2140 | armin (1), fxceless (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/emit/container.rs` | 419 | Duff (1), Marvis (1), fxceless (1) +1 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/diff_tests.rs` | 1287 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence) | - | 5 |
|
||||
| `src/emit/f64.rs` | 409 | skakwy (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/host.rs` | 1472 | fxceless (3), Marvis (1), skakwy (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/intersect.rs` | 557 | fxceless (1) | GPL-3.0 (repository licence) | - | 12 |
|
||||
| `src/emit/intersect_tests.rs` | 690 | fxceless (1) | GPL-3.0 (repository licence) | - | 15 |
|
||||
| `src/emit/lower.rs` | 12268 | Marvis (21), skakwy (9), fxceless (6) +23 more | GPL-3.0 (repository licence); comment cites Mesa behaviour; cites LLVM | - | 18 |
|
||||
| `src/emit/mod.rs` | 1755 | Marvis (7), fxceless (6), skakwy (4) +8 more | GPL-3.0 (repository licence) | - | 16 |
|
||||
| `src/emit/own_bits.rs` | 914 | fxceless (1) | GPL-3.0 (repository licence) | 1 | 3 |
|
||||
| `src/emit/rect.rs` | 484 | fxceless (2) | GPL-3.0 (repository licence) | - | 2 |
|
||||
| `src/emit/sampler.rs` | 125 | Marvis (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/emit/shader.rs` | 908 | fxceless (4), Claude (1), Duff (1) +4 more | GPL-3.0 (repository licence) | - | 8 |
|
||||
| `src/emit/threading.rs` | 218 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/validator.rs` | 221 | Marvis (1), lameloball2813-ui (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/valu_tests.rs` | 1624 | Marvis (6), r4. (5), fxceless (4) +6 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/waterfall_tests.rs` | 435 | r4. (3), Marvis (1), Noname0202 (1) +1 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/wave.rs` | 1228 | fxceless (3), skakwy (2), AscilCH (1) +1 more | GPL-3.0 (repository licence) | 1 | - |
|
||||
| `src/emit/wave64_tests.rs` | 532 | fxceless (1), triippywhale (1) | GPL-3.0 (repository licence) | 2 | - |
|
||||
| `src/gfx10/fields.rs` | 815 | Marvis (1), fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/gfx10/mod.rs` | 496 | Marvis (3), tedin7 (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/gfx10/opcodes.rs` | 1333 | Duff (1), Marvis (1) | GPL-3.0 (repository licence); Mesa-derived, MIT (Valve), notice in header; cites LLVM | - | - |
|
||||
| `src/gfx10/sp3.rs` | 784 | Marvis (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/io.rs` | 826 | Marvis (1), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/ir.rs` | 1791 | fxceless (4), Marvis (2), Yaekai (1) +1 more | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/lib.rs` | 38 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/native.rs` | 1103 | Marvis (4), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/resource.rs` | 3848 | Claude (3), fxceless (3), Marvis (2) +2 more | GPL-3.0 (repository licence); cites LLVM | - | 10 |
|
||||
| `src/spill.rs` | 380 | fxceless (2) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/structure.rs` | 1899 | Marvis (2), fxceless (2), DexNom (1) +2 more | GPL-3.0 (repository licence) | - | - |
|
||||
|
||||
BetterXen's additions (`src/emit/betterxen.rs`, `src/emit/betterxen_tests.rs`, `Cargo.toml`, `UPSTREAM.md`) are original, GPL-3.0-or-later. Functional edits to upstream files are listed in `crates/victory-shader/UPSTREAM.md`.
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Cross-build the vendored victory-shader test executable for Windows and run it under an
|
||||
# installed CrossOver through `betterxen-hybrid run`, so every GPU test goes through D3D12 on the
|
||||
# host Apple GPU (D3DMetal). Writes JSON run records under artifacts/hybrid-runs/.
|
||||
#
|
||||
# scripts/hybrid/run-shader-gpu-tests.sh <llvm-mingw-dir> [bottle] [fixtures|all]
|
||||
#
|
||||
# `fixtures` (default) runs only BetterXen's own gfx1030 fixtures through the recompiler and
|
||||
# D3D12; `all` runs the whole upstream suite, which currently has two known failures on D3DMetal
|
||||
# (see docs/research/victory-shader-integration.md). Needs: Rust 1.100.0 with the
|
||||
# x86_64-pc-windows-gnullvm target, an unpacked llvm-mingw, CrossOver, and a bottle.
|
||||
set -eu
|
||||
TC=${1:?usage: $0 <llvm-mingw-dir> [bottle] [fixtures|all]}
|
||||
BOTTLE=${2:-betterxen-test}
|
||||
WHICH=${3:-fixtures}
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
cd "$ROOT"
|
||||
# Both executables are taken from the messages of the cargo invocation that built them, and only
|
||||
# when that invocation succeeded: no path is guessed and nothing left over from an earlier build can
|
||||
# be run. (Cargo is not piped into the parser: under /bin/sh a pipeline reports only the parser's
|
||||
# exit status.)
|
||||
LOG=$(mktemp)
|
||||
trap 'rm -f "$LOG"' EXIT
|
||||
# built_exe <target name> <is test: true|false>: the executable named in $LOG.
|
||||
built_exe() {
|
||||
python3 -I -c '
|
||||
import json, sys
|
||||
name, test, exe = sys.argv[1], sys.argv[2] == "true", ""
|
||||
for line in open(sys.argv[3]):
|
||||
try:
|
||||
m = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
t = m.get("target", {})
|
||||
if (m.get("reason") == "compiler-artifact" and m.get("executable")
|
||||
and t.get("name", "").replace("-", "_") == name
|
||||
and bool(m.get("profile", {}).get("test")) == test):
|
||||
exe = m["executable"]
|
||||
print(exe)' "$1" "$2" "$LOG"
|
||||
}
|
||||
|
||||
# The host tool first, before the environment is pointed at the Windows toolchain.
|
||||
rustup run 1.100.0 cargo build -q -p betterxen-hybrid --message-format=json-render-diagnostics >"$LOG" \
|
||||
|| { echo "building betterxen-hybrid failed" >&2; exit 1; }
|
||||
B=$(built_exe betterxen_hybrid false)
|
||||
[ -n "$B" ] && [ -x "$B" ] || { echo "the host build named no betterxen-hybrid executable" >&2; exit 1; }
|
||||
|
||||
export PATH="$TC/bin:$PATH"
|
||||
export CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER="$TC/bin/x86_64-w64-mingw32-clang"
|
||||
export CARGO_TARGET_DIR="$ROOT/artifacts/victory-win"
|
||||
rustup run 1.100.0 cargo test -q -p victory-shader --target x86_64-pc-windows-gnullvm --no-run \
|
||||
--message-format=json-render-diagnostics >"$LOG" \
|
||||
|| { echo "building the victory-shader test executable failed" >&2; exit 1; }
|
||||
EXE=$(built_exe victory_shader true)
|
||||
[ -n "$EXE" ] && [ -f "$EXE" ] || { echo "the build named no victory-shader test executable" >&2; exit 1; }
|
||||
file "$EXE" | grep -q "PE32+ executable.*x86-64" || { echo "not an x86-64 PE: $EXE" >&2; exit 1; }
|
||||
rm -f "$LOG"
|
||||
if [ "$WHICH" = all ]; then
|
||||
exec "$B" run --bottle "$BOTTLE" --timeout 900 --stall-timeout 120 --expect "test result: ok" \
|
||||
--out artifacts/hybrid-runs -- "$EXE" --test-threads=1
|
||||
else
|
||||
# The exact count is deliberate: a looser marker would also accept a filter that matches nothing
|
||||
# ("0 passed"). Update it when BetterXen adds or removes tests in emit/betterxen_tests.rs.
|
||||
exec "$B" run --bottle "$BOTTLE" --timeout 300 --stall-timeout 120 --expect "test result: ok. 10 passed" \
|
||||
--out artifacts/hybrid-runs -- "$EXE" betterxen --test-threads=1
|
||||
fi
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Regression test for run-shader-gpu-tests.sh with a stubbed `rustup`/cargo and a stubbed runner:
|
||||
# no toolchain, CrossOver or GPU is needed. Checks that
|
||||
# 1. a failed Windows test build stops the script and the runner is never invoked, even when an
|
||||
# older test executable is lying in the target directory;
|
||||
# 2. a successful build runs exactly the executable that build named;
|
||||
# 3. the host runner is the one the host build named, also with an inherited CARGO_TARGET_DIR.
|
||||
set -u
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
T=$(mktemp -d)
|
||||
trap 'rm -rf "$T"' EXIT
|
||||
fails=0
|
||||
check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fails=1; fi; }
|
||||
|
||||
# A file `file` reports as an x86-64 PE32+ executable.
|
||||
make_pe() {
|
||||
python3 -I -c '
|
||||
import struct, sys
|
||||
b = bytearray(512); b[0:2] = b"MZ"; struct.pack_into("<I", b, 0x3C, 0x80)
|
||||
b[0x80:0x84] = b"PE\0\0"; struct.pack_into("<HHIIIHH", b, 0x84, 0x8664, 0, 0, 0, 0, 240, 0x22)
|
||||
struct.pack_into("<H", b, 0x98, 0x20B); struct.pack_into("<H", b, 0x98 + 68, 3)
|
||||
open(sys.argv[1], "wb").write(b)' "$1"
|
||||
}
|
||||
|
||||
setup() { # $1 = case directory
|
||||
R=$1/repo
|
||||
mkdir -p "$R/scripts/hybrid" "$1/bin" "$1/tc/bin"
|
||||
cp "$HERE/run-shader-gpu-tests.sh" "$R/scripts/hybrid/"
|
||||
: > "$1/tc/bin/x86_64-w64-mingw32-clang"; chmod +x "$1/tc/bin/x86_64-w64-mingw32-clang"
|
||||
# The stub runner records how it was called.
|
||||
runner() { mkdir -p "$(dirname "$1")"; printf '#!/bin/sh\necho "$0 $*" >> "%s"\n' "$2" > "$1"; chmod +x "$1"; }
|
||||
# A runner left over from an earlier build at the old hard-coded place.
|
||||
runner "$R/target/debug/betterxen-hybrid" "$1/stale-runner.log"
|
||||
# An older test executable lying around in the target directory.
|
||||
old="$R/artifacts/victory-win/x86_64-pc-windows-gnullvm/debug/deps"
|
||||
mkdir -p "$old"; make_pe "$old/victory_shader-0000stale.exe"
|
||||
cat > "$1/bin/rustup" <<STUB
|
||||
#!/bin/sh
|
||||
# stands in for: rustup run 1.100.0 cargo <build|test> ...
|
||||
shift 3
|
||||
cmd=\$1
|
||||
dir=\${CARGO_TARGET_DIR:-$R/target}
|
||||
case "\$cmd" in
|
||||
build)
|
||||
mkdir -p "\$dir/debug"
|
||||
printf '#!/bin/sh\necho "\$0 \$*" >> "%s"\n' "$1/runner.log" > "\$dir/debug/betterxen-hybrid"
|
||||
chmod +x "\$dir/debug/betterxen-hybrid"
|
||||
echo "{\"reason\":\"compiler-artifact\",\"target\":{\"name\":\"betterxen-hybrid\",\"kind\":[\"bin\"]},\"profile\":{\"test\":false},\"executable\":\"\$dir/debug/betterxen-hybrid\"}"
|
||||
;;
|
||||
test)
|
||||
[ "\${STUB_TEST_BUILD_FAILS:-0}" = 1 ] && exit 101
|
||||
mkdir -p "\$dir/fresh"; cp "$old/victory_shader-0000stale.exe" "\$dir/fresh/victory_shader-1111new.exe"
|
||||
echo "{\"reason\":\"compiler-artifact\",\"target\":{\"name\":\"victory_shader\",\"kind\":[\"lib\"]},\"profile\":{\"test\":true},\"executable\":\"\$dir/fresh/victory_shader-1111new.exe\"}"
|
||||
;;
|
||||
esac
|
||||
STUB
|
||||
chmod +x "$1/bin/rustup"
|
||||
}
|
||||
|
||||
# 1. failed test build
|
||||
c=$T/fail; setup "$c"
|
||||
STUB_TEST_BUILD_FAILS=1 PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
|
||||
check "failed build: script exits non-zero (got $rc)" "[ $rc -ne 0 ]"
|
||||
check "failed build: no runner is invoked" "[ ! -e '$c/runner.log' ] && [ ! -e '$c/stale-runner.log' ]"
|
||||
|
||||
# 2. successful build
|
||||
c=$T/ok; setup "$c"
|
||||
PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
|
||||
check "good build: script succeeds (got $rc)" "[ $rc -eq 0 ]"
|
||||
check "good build: runs the executable this build named" "grep -q 'victory_shader-1111new.exe' '$c/runner.log' 2>/dev/null"
|
||||
|
||||
# 3. inherited CARGO_TARGET_DIR
|
||||
c=$T/dir; setup "$c"
|
||||
CARGO_TARGET_DIR="$c/elsewhere" PATH="$c/bin:$PATH" sh "$c/repo/scripts/hybrid/run-shader-gpu-tests.sh" "$c/tc" >/dev/null 2>&1; rc=$?
|
||||
check "inherited target dir: script succeeds (got $rc)" "[ $rc -eq 0 ]"
|
||||
check "inherited target dir: the freshly built runner is used" "grep -q '$c/elsewhere/debug/betterxen-hybrid' '$c/runner.log' 2>/dev/null"
|
||||
check "inherited target dir: the stale runner is not used" "[ ! -e '$c/stale-runner.log' ]"
|
||||
exit $fails
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original BetterXen workload (shader wave-semantics investigation): a minimal Direct3D 12
|
||||
// compute host that is independent of the vendored recompiler.
|
||||
//
|
||||
// d3d12_run.exe caps
|
||||
// Prints the default adapter and the device capabilities relevant to wave operations.
|
||||
// d3d12_run.exe run <shader.dxil> <groups_x> <out_dwords>
|
||||
// Creates a root signature with one root UAV (u0), a compute PSO from the DXIL file,
|
||||
// fills a UAV buffer of <out_dwords> dwords with 0xDEADBEEF, dispatches <groups_x> groups
|
||||
// and prints every dword read back as `out <index> 0x<hex>`. A dword that stays
|
||||
// 0xDEADBEEF was never written.
|
||||
//
|
||||
// Status: `caps` and `run` have both been compiled and run under CrossOver 26.3 on the M4.
|
||||
// Exit codes: 0 ran, 2 no device, 3 pipeline creation failed, 4 other D3D12 failure.
|
||||
#define COBJMACROS
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CK(x, what) do { HRESULT h_ = (x); if (FAILED(h_)) { \
|
||||
printf("FAIL %s hr=0x%08lx\n", what, (unsigned long)h_); return 4; } } while (0)
|
||||
|
||||
static ID3D12Device *make_device(void) {
|
||||
ID3D12Device *dev = NULL;
|
||||
static const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0};
|
||||
for (unsigned i = 0; i < sizeof levels / sizeof *levels; i++) {
|
||||
if (SUCCEEDED(D3D12CreateDevice(NULL, levels[i], &IID_ID3D12Device, (void **)&dev))) {
|
||||
printf("device_created_at_feature_level=0x%x\n", (unsigned)levels[i]);
|
||||
return dev;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int caps(void) {
|
||||
ID3D12Device *dev = make_device();
|
||||
if (!dev) { printf("NO DEVICE\n"); return 2; }
|
||||
LUID luid; dev->lpVtbl->GetAdapterLuid(dev, &luid); // (the C macro cannot return a struct)
|
||||
IDXGIFactory4 *f = NULL;
|
||||
if (SUCCEEDED(CreateDXGIFactory1(&IID_IDXGIFactory4, (void **)&f))) {
|
||||
IDXGIAdapter1 *ad = NULL;
|
||||
if (SUCCEEDED(IDXGIFactory4_EnumAdapterByLuid(f, luid, &IID_IDXGIAdapter1, (void **)&ad))) {
|
||||
DXGI_ADAPTER_DESC1 d; IDXGIAdapter1_GetDesc1(ad, &d);
|
||||
char n[128]; size_t i = 0; for (; d.Description[i] && i < 127; i++) n[i] = (char)d.Description[i]; n[i] = 0;
|
||||
printf("adapter=%s vendor=0x%x device=0x%x vram_mb=%u shared_mb=%u\n", n, d.VendorId, d.DeviceId,
|
||||
(unsigned)(d.DedicatedVideoMemory >> 20), (unsigned)(d.SharedSystemMemory >> 20));
|
||||
}
|
||||
}
|
||||
D3D12_FEATURE_DATA_SHADER_MODEL sm = {D3D_SHADER_MODEL_6_7};
|
||||
HRESULT h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm);
|
||||
if (FAILED(h)) { sm.HighestShaderModel = D3D_SHADER_MODEL_6_6; h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof sm); }
|
||||
printf("highest_shader_model=0x%x (query hr=0x%08lx)\n", (unsigned)sm.HighestShaderModel, (unsigned long)h);
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS o = {0};
|
||||
h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof o);
|
||||
printf("options: hr=0x%08lx double_ops=%d min_precision=0x%x resource_binding_tier=%d\n", (unsigned long)h, o.DoublePrecisionFloatShaderOps, (unsigned)o.MinPrecisionSupport, (int)o.ResourceBindingTier);
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1 = {0};
|
||||
h = ID3D12Device_CheckFeatureSupport(dev, D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof o1);
|
||||
printf("options1: hr=0x%08lx wave_ops=%d wave_lane_count_min=%u wave_lane_count_max=%u total_lane_count=%u expanded_compute_resource_states=%d int64_shader_ops=%d\n",
|
||||
(unsigned long)h, o1.WaveOps, o1.WaveLaneCountMin, o1.WaveLaneCountMax, o1.TotalLaneCount, o1.ExpandedComputeResourceStates, o1.Int64ShaderOps);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int run(const char *path, unsigned groups, unsigned dwords) {
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) { printf("FAIL open %s\n", path); return 4; }
|
||||
fseek(fp, 0, SEEK_END); long n = ftell(fp); fseek(fp, 0, SEEK_SET);
|
||||
void *code = malloc((size_t)n);
|
||||
if (fread(code, 1, (size_t)n, fp) != (size_t)n) { printf("FAIL read\n"); return 4; }
|
||||
fclose(fp);
|
||||
ID3D12Device *dev = make_device();
|
||||
if (!dev) { printf("NO DEVICE\n"); return 2; }
|
||||
|
||||
D3D12_ROOT_PARAMETER rp = {0};
|
||||
rp.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
rp.Descriptor.ShaderRegister = 0;
|
||||
rp.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
D3D12_ROOT_SIGNATURE_DESC rsd = {0};
|
||||
rsd.NumParameters = 1; rsd.pParameters = &rp;
|
||||
ID3DBlob *blob = NULL, *err = NULL;
|
||||
CK(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err), "serialize root signature");
|
||||
ID3D12RootSignature *rs = NULL;
|
||||
CK(ID3D12Device_CreateRootSignature(dev, 0, ID3D10Blob_GetBufferPointer(blob), ID3D10Blob_GetBufferSize(blob), &IID_ID3D12RootSignature, (void **)&rs), "create root signature");
|
||||
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {0};
|
||||
pd.pRootSignature = rs;
|
||||
pd.CS.pShaderBytecode = code; pd.CS.BytecodeLength = (SIZE_T)n;
|
||||
ID3D12PipelineState *pso = NULL;
|
||||
HRESULT h = ID3D12Device_CreateComputePipelineState(dev, &pd, &IID_ID3D12PipelineState, (void **)&pso);
|
||||
if (FAILED(h)) { printf("PSO_FAILED hr=0x%08lx\n", (unsigned long)h); return 3; }
|
||||
|
||||
UINT64 bytes = (UINT64)dwords * 4;
|
||||
D3D12_HEAP_PROPERTIES hp_def = {0}, hp_up = {0}, hp_rb = {0};
|
||||
hp_def.Type = D3D12_HEAP_TYPE_DEFAULT; hp_up.Type = D3D12_HEAP_TYPE_UPLOAD; hp_rb.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC rd = {0};
|
||||
rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; rd.Width = bytes; rd.Height = 1; rd.DepthOrArraySize = 1; rd.MipLevels = 1;
|
||||
rd.Format = DXGI_FORMAT_UNKNOWN; rd.SampleDesc.Count = 1; rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource *def, *up, *rb;
|
||||
D3D12_RESOURCE_DESC rdu = rd; rdu.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
CK(ID3D12Device_CreateCommittedResource(dev, &hp_def, D3D12_HEAP_FLAG_NONE, &rdu, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&def), "create default");
|
||||
CK(ID3D12Device_CreateCommittedResource(dev, &hp_up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &IID_ID3D12Resource, (void **)&up), "create upload");
|
||||
CK(ID3D12Device_CreateCommittedResource(dev, &hp_rb, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, (void **)&rb), "create readback");
|
||||
unsigned *p; CK(ID3D12Resource_Map(up, 0, NULL, (void **)&p), "map upload");
|
||||
for (unsigned i = 0; i < dwords; i++) p[i] = 0xDEADBEEFu;
|
||||
ID3D12Resource_Unmap(up, 0, NULL);
|
||||
|
||||
D3D12_COMMAND_QUEUE_DESC qd = {0};
|
||||
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
ID3D12CommandQueue *q; CK(ID3D12Device_CreateCommandQueue(dev, &qd, &IID_ID3D12CommandQueue, (void **)&q), "queue");
|
||||
ID3D12CommandAllocator *al; CK(ID3D12Device_CreateCommandAllocator(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator, (void **)&al), "allocator");
|
||||
ID3D12GraphicsCommandList *cl; CK(ID3D12Device_CreateCommandList(dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, al, pso, &IID_ID3D12GraphicsCommandList, (void **)&cl), "list");
|
||||
ID3D12GraphicsCommandList_CopyBufferRegion(cl, def, 0, up, 0, bytes);
|
||||
D3D12_RESOURCE_BARRIER b = {0};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = def; b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b);
|
||||
ID3D12GraphicsCommandList_SetComputeRootSignature(cl, rs);
|
||||
ID3D12GraphicsCommandList_SetComputeRootUnorderedAccessView(cl, 0, ID3D12Resource_GetGPUVirtualAddress(def));
|
||||
ID3D12GraphicsCommandList_Dispatch(cl, groups, 1, 1);
|
||||
b.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
ID3D12GraphicsCommandList_ResourceBarrier(cl, 1, &b);
|
||||
ID3D12GraphicsCommandList_CopyBufferRegion(cl, rb, 0, def, 0, bytes);
|
||||
CK(ID3D12GraphicsCommandList_Close(cl), "close");
|
||||
ID3D12CommandList *lists[1] = {(ID3D12CommandList *)cl};
|
||||
ID3D12CommandQueue_ExecuteCommandLists(q, 1, lists);
|
||||
ID3D12Fence *fence; CK(ID3D12Device_CreateFence(dev, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, (void **)&fence), "fence");
|
||||
HANDLE ev = CreateEventA(NULL, FALSE, FALSE, NULL);
|
||||
CK(ID3D12CommandQueue_Signal(q, fence, 1), "signal");
|
||||
ID3D12Fence_SetEventOnCompletion(fence, 1, ev);
|
||||
if (WaitForSingleObject(ev, 30000) != WAIT_OBJECT_0) { printf("FAIL timeout waiting for the GPU\n"); return 4; }
|
||||
CK(ID3D12Resource_Map(rb, 0, NULL, (void **)&p), "map readback");
|
||||
for (unsigned i = 0; i < dwords; i++) printf("out %u 0x%08x\n", i, p[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc == 2 && !strcmp(argv[1], "caps")) return caps();
|
||||
if (argc == 5 && !strcmp(argv[1], "run")) return run(argv[2], (unsigned)atoi(argv[3]), (unsigned)atoi(argv[4]));
|
||||
printf("usage: d3d12_run caps | run <shader.dxil> <groups_x> <out_dwords>\n");
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# Wave-semantics HLSL probes
|
||||
|
||||
Original BetterXen sources, GPL-3.0-or-later. They are compiled with Microsoft's open-source DXC
|
||||
(`dxc -T cs_6_6 -E main`; release v1.9.2609, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc...a7e7f1`, equal to
|
||||
the release digest; an external tool, not vendored) and dispatched with `d3d12_run.exe run <shader.dxil> 1 <dwords>`
|
||||
under CrossOver. Expected values were worked out by hand before running. Results and what they show:
|
||||
`docs/research/shader-wave-semantics.md`.
|
||||
|
||||
```sh
|
||||
wine --bottle <bottle> ./dxc.exe -T cs_6_6 -E main -Fo sum_f64_4.dxil sum_f64_4.hlsl # dxcompiler.dll and dxil.dll beside it
|
||||
wine --bottle <bottle> ./d3d12_run.exe run sum_f64_4.dxil 1 8
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Control for add_f64_4: the same run-time load, add and store in single precision. If this writes
|
||||
// and the double version does not, the load/store path is not the cause.
|
||||
// Expected (by hand): word 0 = 2.0f (0x40000000), word 1 = 0 for each of the 4 threads.
|
||||
RWByteAddressBuffer o : register(u0);
|
||||
[numthreads(4, 1, 1)]
|
||||
void main(uint t : SV_GroupIndex) {
|
||||
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
|
||||
float s = asfloat(z ^ 0x3FA00000) + asfloat(z ^ 0x3F400000); // 1.25 + 0.75
|
||||
o.Store2(t * 8, uint2(asuint(s), z));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// No wave operation: a double addition 1.25 + 0.75 = 2.0 (0x4000000000000000) whose operands are
|
||||
// only known at run time, so the compiler cannot fold it. The host fills the buffer with
|
||||
// 0xDEADBEEF; `z` is therefore 0 when the shader runs, but not at compile time. The compiled DXIL
|
||||
// must contain `fadd ... double` (check with `dxc -dumpbin`). Separates "doubles unsupported" from
|
||||
// "wave operations on doubles unsupported".
|
||||
// Expected (by hand): low word 0x00000000, high word 0x40000000 for each of the 4 threads.
|
||||
RWByteAddressBuffer o : register(u0);
|
||||
[numthreads(4, 1, 1)]
|
||||
void main(uint t : SV_GroupIndex) {
|
||||
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
|
||||
double a = asdouble(z, z ^ 0x3FF40000); // 1.25
|
||||
double b = asdouble(z, z ^ 0x3FE80000); // 0.75
|
||||
double s = a + b;
|
||||
uint lo, hi;
|
||||
asuint(s, lo, hi);
|
||||
o.Store2(t * 8, uint2(lo, hi));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Expected (by hand): each launched thread t stores (laneCount << 8) | t, where laneCount is the
|
||||
// device's wave width (32 per the capability record), so 0x2000, 0x2001, 0x2002, 0x2003.
|
||||
RWByteAddressBuffer o : register(u0);
|
||||
[numthreads(4, 1, 1)]
|
||||
void main(uint t : SV_GroupIndex) { o.Store(t * 4, (WaveGetLaneCount() << 8) | WaveGetLaneIndex()); }
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Expected (by hand): 4 threads each add 1.25f, every launched lane reads 5.0 = 0x40a00000.
|
||||
RWByteAddressBuffer o : register(u0);
|
||||
[numthreads(4, 1, 1)]
|
||||
void main(uint t : SV_GroupIndex) { o.Store(t * 4, asuint(WaveActiveSum(1.25f))); }
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// A wave sum over a double that is only known at run time (see add_f64_4.hlsl).
|
||||
// Expected (by hand): 4 threads each add 1.25, sum 5.0 = 0x4014000000000000, so each stores low
|
||||
// word 0x00000000 and high word 0x40140000.
|
||||
// The device reports DoublePrecisionFloatShaderOps = 0; this probe shows what actually happens.
|
||||
RWByteAddressBuffer o : register(u0);
|
||||
[numthreads(4, 1, 1)]
|
||||
void main(uint t : SV_GroupIndex) {
|
||||
uint z = o.Load(t * 8) ^ 0xDEADBEEF;
|
||||
double s = WaveActiveSum(asdouble(z, z ^ 0x3FF40000));
|
||||
uint lo, hi;
|
||||
asuint(s, lo, hi);
|
||||
o.Store2(t * 8, uint2(lo, hi));
|
||||
}
|
||||
Reference in new issue
Block a user