diff options
| author | NotRexed <therealnothingfn@gmail.com> | 2026-12-01 07:52:21 -0500 |
|---|---|---|
| committer | NotRexed <therealnothingfn@gmail.com> | 2026-12-01 07:52:21 -0500 |
| commit | dd4829ecfc259eebc0e42e3f72d2d61911ee010e (patch) | |
| tree | 607dabec0efef7e5fe71297e2c5f0b512b0859eb | |
| parent | e12f7f9f9a82288ee0424be753d383eb3eb7843f (diff) | |
| parent | 1723dec94510d0aa3d99e795f0a656970c1f00e9 (diff) | |
Merge remote-tracking branch 'origin/main' into push/main-1130
# Conflicts:
# d3d12/docs/switches.md
154 files changed, 9426 insertions, 704 deletions
diff --git a/.github/workflows/d3d12.yml b/.github/workflows/d3d12.yml new file mode 100644 index 000000000..3cf56fa81 --- /dev/null +++ b/.github/workflows/d3d12.yml | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | # Builds and tests the D3D12 runtime (d3d12/, Rust: leonida.exe and its crates) when it changes. Until now no workflow | ||
| 2 | # ran its tests, so a change that broke one of them reached main unseen. It needs no GPU and no game files: the tests | ||
| 3 | # that need a device or the title skip themselves. | ||
| 4 | # | ||
| 5 | # Measured on main 060c47160 (Windows 11, toolchain from d3d12/rust-toolchain.toml): the workspace builds in about | ||
| 6 | # 4 minutes and its tests take about 11; 1441 pass, 58 are ignored, and one fails, the xtask asset-policy test, because | ||
| 7 | # two sources are over its 640 KiB limit (crates/leonida-gpu/src/host.rs, crates/leonida-shader/src/emit/lower.rs). | ||
| 8 | # `cargo clippy -D warnings` also fails on main (about 25 findings in five crates) and `cargo fmt --check` would | ||
| 9 | # reformat most of the tree. So the tests are the gate; the policy test and clippy run as reports until those are fixed, | ||
| 10 | # and formatting is left out so it does not collide with the open d3d12 pull requests. | ||
| 11 | name: D3D12 runtime | ||
| 12 | |||
| 13 | on: | ||
| 14 | push: | ||
| 15 | branches: [main] | ||
| 16 | paths: | ||
| 17 | - "d3d12/**" | ||
| 18 | # leonida-lua's tests read mods/example_lua. | ||
| 19 | - "mods/**" | ||
| 20 | - ".github/workflows/d3d12.yml" | ||
| 21 | pull_request: | ||
| 22 | paths: | ||
| 23 | - "d3d12/**" | ||
| 24 | # leonida-lua's tests read mods/example_lua. | ||
| 25 | - "mods/**" | ||
| 26 | - ".github/workflows/d3d12.yml" | ||
| 27 | workflow_dispatch: | ||
| 28 | |||
| 29 | permissions: | ||
| 30 | contents: read | ||
| 31 | |||
| 32 | concurrency: | ||
| 33 | # Each non-PR run has its own group so a queued push or dispatch cannot replace it. | ||
| 34 | group: d3d12-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} | ||
| 35 | cancel-in-progress: ${{ github.event_name == 'pull_request' }} | ||
| 36 | |||
| 37 | jobs: | ||
| 38 | d3d12: | ||
| 39 | name: d3d12 (windows-latest) | ||
| 40 | # The crates are Windows-only today (leonida-gpu does not build on macOS); Linux follows #2577 if it lands. | ||
| 41 | runs-on: windows-latest | ||
| 42 | timeout-minutes: 70 | ||
| 43 | defaults: | ||
| 44 | run: | ||
| 45 | working-directory: d3d12 | ||
| 46 | shell: bash | ||
| 47 | steps: | ||
| 48 | - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 | ||
| 49 | with: | ||
| 50 | persist-credentials: false | ||
| 51 | # The runner's own rustup installs the toolchain pinned in d3d12/rust-toolchain.toml, no third-party action. | ||
| 52 | - name: Rust toolchain | ||
| 53 | run: | | ||
| 54 | rustup show active-toolchain || rustup toolchain install | ||
| 55 | rustc --version | ||
| 56 | echo "RUSTC_HASH=$(rustc -vV | tr -d '\r' | awk '/^commit-hash: /{print $2}')" >> "$GITHUB_ENV" | ||
| 57 | - name: Cache Cargo downloads | ||
| 58 | uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 | ||
| 59 | with: | ||
| 60 | path: | | ||
| 61 | ~/.cargo/registry | ||
| 62 | ~/.cargo/git | ||
| 63 | key: d3d12-windows-cargo-${{ env.RUSTC_HASH }}-${{ hashFiles('d3d12/Cargo.lock') }} | ||
| 64 | restore-keys: | | ||
| 65 | d3d12-windows-cargo-${{ env.RUSTC_HASH }}- | ||
| 66 | d3d12-windows-cargo- | ||
| 67 | - name: Build | ||
| 68 | run: cargo build --workspace --all-targets --locked | ||
| 69 | # The features of the executable people run (d3d12/scripts/build-nvidia.ps1, without dlss); no other step builds them. | ||
| 70 | - name: Build as shipped (diagnostics, mimalloc) | ||
| 71 | run: cargo build -p leonida --features diagnostics,mimalloc --locked | ||
| 72 | # The software adapter of the runner does not do the depth bounds test as this one expects, and #2663 fixes that | ||
| 73 | # in the renderer; drop the --skip with it. A failing test here also stops the crates after leonida-gpu. | ||
| 74 | - name: Tests (no GPU, no game data) | ||
| 75 | timeout-minutes: 30 | ||
| 76 | run: cargo test --workspace --exclude xtask --locked -- --skip depth_bounds_pipeline_loads_and_filters_draws | ||
| 77 | # tests/replay.rs is compiled only with the diagnostics feature. | ||
| 78 | - name: Replay test (diagnostics) | ||
| 79 | timeout-minutes: 15 | ||
| 80 | run: cargo test -p leonida-gpu --features diagnostics --test replay --locked | ||
| 81 | # Report only until host.rs and lower.rs are split under the limit; make it blocking then. | ||
| 82 | - name: Asset policy (report) | ||
| 83 | continue-on-error: true | ||
| 84 | run: cargo test -p xtask --locked | ||
| 85 | # Report only until the existing findings are fixed; make it blocking (-D warnings) then. | ||
| 86 | - name: Clippy (report) | ||
| 87 | continue-on-error: true | ||
| 88 | run: cargo clippy --workspace --all-targets --locked -- -D warnings | ||
diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index c732b27e0..a6b1e0346 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml | |||
| @@ -41,6 +41,7 @@ on: | |||
| 41 | - "tools/gfx10_formats.json" | 41 | - "tools/gfx10_formats.json" |
| 42 | - "tools/heap_index_census.py" | 42 | - "tools/heap_index_census.py" |
| 43 | - "tools/lane_masks.py" | 43 | - "tools/lane_masks.py" |
| 44 | - "tools/lod_bias_probe.py" | ||
| 44 | - "tools/mc_command.py" | 45 | - "tools/mc_command.py" |
| 45 | - "tools/mesh_compute_vs.py" | 46 | - "tools/mesh_compute_vs.py" |
| 46 | - "tools/native_pso_hashes.py" | 47 | - "tools/native_pso_hashes.py" |
| @@ -61,6 +62,7 @@ on: | |||
| 61 | - "tools/spirv_loop_guard.py" | 62 | - "tools/spirv_loop_guard.py" |
| 62 | - "tools/spirv_opt.py" | 63 | - "tools/spirv_opt.py" |
| 63 | - "tools/spirv_stubs.py" | 64 | - "tools/spirv_stubs.py" |
| 65 | - "tools/vk_lod_bias.py" | ||
| 64 | - "tools/vk_subgroup_info.py" | 66 | - "tools/vk_subgroup_info.py" |
| 65 | - "tools/wave64_emulate_opt.py" | 67 | - "tools/wave64_emulate_opt.py" |
| 66 | - "tools/wave64_halves.py" | 68 | - "tools/wave64_halves.py" |
| @@ -95,6 +97,7 @@ on: | |||
| 95 | - "tools/gfx10_formats.json" | 97 | - "tools/gfx10_formats.json" |
| 96 | - "tools/heap_index_census.py" | 98 | - "tools/heap_index_census.py" |
| 97 | - "tools/lane_masks.py" | 99 | - "tools/lane_masks.py" |
| 100 | - "tools/lod_bias_probe.py" | ||
| 98 | - "tools/mc_command.py" | 101 | - "tools/mc_command.py" |
| 99 | - "tools/mesh_compute_vs.py" | 102 | - "tools/mesh_compute_vs.py" |
| 100 | - "tools/native_pso_hashes.py" | 103 | - "tools/native_pso_hashes.py" |
| @@ -115,6 +118,7 @@ on: | |||
| 115 | - "tools/spirv_loop_guard.py" | 118 | - "tools/spirv_loop_guard.py" |
| 116 | - "tools/spirv_opt.py" | 119 | - "tools/spirv_opt.py" |
| 117 | - "tools/spirv_stubs.py" | 120 | - "tools/spirv_stubs.py" |
| 121 | - "tools/vk_lod_bias.py" | ||
| 118 | - "tools/vk_subgroup_info.py" | 122 | - "tools/vk_subgroup_info.py" |
| 119 | - "tools/wave64_emulate_opt.py" | 123 | - "tools/wave64_emulate_opt.py" |
| 120 | - "tools/wave64_halves.py" | 124 | - "tools/wave64_halves.py" |
| @@ -70,6 +70,12 @@ loader that maps the game's executable and resolves its imports to shims. Nothin | |||
| 70 | - Frame rates of the D3D12 runtime (`d3d12/`): search [d3d12/docs/findings.md](d3d12/docs/findings.md) for the switch or | 70 | - Frame rates of the D3D12 runtime (`d3d12/`): search [d3d12/docs/findings.md](d3d12/docs/findings.md) for the switch or |
| 71 | function before measuring it, and measure as [docs/measuring_fps.md](docs/measuring_fps.md) says (a switch by turns | 71 | function before measuring it, and measure as [docs/measuring_fps.md](docs/measuring_fps.md) says (a switch by turns |
| 72 | inside one run). The variables are listed in [d3d12/docs/switches.md](d3d12/docs/switches.md). | 72 | inside one run). The variables are listed in [d3d12/docs/switches.md](d3d12/docs/switches.md). |
| 73 | - Show the test **fails without the fix**, not just that it passes with it. Run the new case on `main`, or revert | ||
| 74 | only the source the change touches and run again: a test that has never seen the old behaviour proves the test | ||
| 75 | compiles, nothing about the fix. Say which of the two you did. | ||
| 76 | - Check the instrument before trusting the number: rebuild before `ctest` after switching branches (a stale binary | ||
| 77 | is indistinguishable from a bug), compare the **change** between two branches rather than the file (a file diff | ||
| 78 | carries their different bases), and read the test's own header before describing what it proves. | ||
| 73 | 79 | ||
| 74 | ## Test without the game first | 80 | ## Test without the game first |
| 75 | 81 | ||
diff --git a/d3d12/.github/workflows/ci.yml b/d3d12/.github/workflows/ci.yml deleted file mode 100644 index 80e6a359e..000000000 --- a/d3d12/.github/workflows/ci.yml +++ /dev/null | |||
| @@ -1,33 +0,0 @@ | |||
| 1 | name: CI | ||
| 2 | |||
| 3 | on: | ||
| 4 | pull_request: | ||
| 5 | push: | ||
| 6 | branches: [main] | ||
| 7 | |||
| 8 | permissions: | ||
| 9 | contents: read | ||
| 10 | |||
| 11 | concurrency: | ||
| 12 | group: ci-${{ github.ref }} | ||
| 13 | cancel-in-progress: true | ||
| 14 | |||
| 15 | env: | ||
| 16 | CARGO_TERM_COLOR: always | ||
| 17 | |||
| 18 | jobs: | ||
| 19 | check: | ||
| 20 | runs-on: windows-latest | ||
| 21 | timeout-minutes: 60 | ||
| 22 | steps: | ||
| 23 | - uses: actions/checkout@v5 | ||
| 24 | # The version and components pinned in rust-toolchain.toml. | ||
| 25 | - run: rustup toolchain install | ||
| 26 | - uses: Swatinem/rust-cache@v2 | ||
| 27 | - name: Clippy | ||
| 28 | run: cargo clippy --workspace --all-targets --locked -- -D warnings | ||
| 29 | - name: Clippy, diagnostics build | ||
| 30 | run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings | ||
| 31 | # Includes xtask's repository_passes_policy, the asset-policy check. | ||
| 32 | - name: Tests | ||
| 33 | run: cargo test --workspace --locked | ||
diff --git a/d3d12/apps/leonida/src/game_actions.rs b/d3d12/apps/leonida/src/game_actions.rs index 9cd298de3..8f675218d 100644 --- a/d3d12/apps/leonida/src/game_actions.rs +++ b/d3d12/apps/leonida/src/game_actions.rs | |||
| @@ -1328,7 +1328,7 @@ mod tests { | |||
| 1328 | #[test] | 1328 | #[test] |
| 1329 | fn the_spawn_items_are_the_nine_vehicle_cheats() { | 1329 | fn the_spawn_items_are_the_nine_vehicle_cheats() { |
| 1330 | assert_eq!(SPAWNS.len() as u32, places::CHEATS - CHEAT_VEHICLES); | 1330 | assert_eq!(SPAWNS.len() as u32, places::CHEATS - CHEAT_VEHICLES); |
| 1331 | assert!(CHEAT_HEALTH < CHEAT_VEHICLES); | 1331 | const { assert!(CHEAT_HEALTH < CHEAT_VEHICLES) }; |
| 1332 | // The menu's own ids, each once. | 1332 | // The menu's own ids, each once. |
| 1333 | let pages = leonida_menu::tree::pages(); | 1333 | let pages = leonida_menu::tree::pages(); |
| 1334 | let ids: Vec<&str> = pages.iter().flat_map(|p| p.items.iter().map(|i| i.id)).collect(); | 1334 | let ids: Vec<&str> = pages.iter().flat_map(|p| p.items.iter().map(|i| i.id)).collect(); |
diff --git a/d3d12/apps/leonida/src/player.rs b/d3d12/apps/leonida/src/player.rs index d924af563..c9dc7b5ce 100644 --- a/d3d12/apps/leonida/src/player.rs +++ b/d3d12/apps/leonida/src/player.rs | |||
| @@ -567,15 +567,14 @@ pub fn install(base: usize, size: usize) { | |||
| 567 | let file = std::env::var_os("LEONIDA_PLAYER_PATHS") | 567 | let file = std::env::var_os("LEONIDA_PLAYER_PATHS") |
| 568 | .map(PathBuf::from) | 568 | .map(PathBuf::from) |
| 569 | .unwrap_or_else(|| out_dir().join("paths.txt")); | 569 | .unwrap_or_else(|| out_dir().join("paths.txt")); |
| 570 | match std::fs::read_to_string(&file) { | 570 | if let Ok(text) = std::fs::read_to_string(&file) { |
| 571 | Ok(text) => match Known::parse(&text, size) { | 571 | match Known::parse(&text, size) { |
| 572 | Ok(k) => { | 572 | Ok(k) => { |
| 573 | eprintln!("Leonida: player paths: {} group(s) from {}", k.groups.len(), file.display()); | 573 | eprintln!("Leonida: player paths: {} group(s) from {}", k.groups.len(), file.display()); |
| 574 | set_known(k); | 574 | set_known(k); |
| 575 | } | 575 | } |
| 576 | Err(e) => eprintln!("Leonida: player paths in {} not used: {e}", file.display()), | 576 | Err(e) => eprintln!("Leonida: player paths in {} not used: {e}", file.display()), |
| 577 | }, | 577 | } |
| 578 | Err(_) => {} | ||
| 579 | } | 578 | } |
| 580 | leonida_menu::knobs::provide_player(leonida_menu::knobs::PlayerHook { | 579 | leonida_menu::knobs::provide_player(leonida_menu::knobs::PlayerHook { |
| 581 | ready, | 580 | ready, |
diff --git a/d3d12/apps/leonida/src/warm.rs b/d3d12/apps/leonida/src/warm.rs index 5158b08fe..b07789148 100644 --- a/d3d12/apps/leonida/src/warm.rs +++ b/d3d12/apps/leonida/src/warm.rs | |||
| @@ -99,7 +99,7 @@ pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, t | |||
| 99 | state.0.push(ms); | 99 | state.0.push(ms); |
| 100 | state.1 += usize::from(!there); | 100 | state.1 += usize::from(!there); |
| 101 | let count = state.0.len(); | 101 | let count = state.0.len(); |
| 102 | if count % 1000 == 0 { | 102 | if count.is_multiple_of(1000) { |
| 103 | println!("{count} of {}, {:.0} s", all.len(), began.elapsed().as_secs_f64()); | 103 | println!("{count} of {}, {:.0} s", all.len(), began.elapsed().as_secs_f64()); |
| 104 | } | 104 | } |
| 105 | drop(state); | 105 | drop(state); |
diff --git a/d3d12/crates/leonida-formats/src/bcpack.rs b/d3d12/crates/leonida-formats/src/bcpack.rs index 287e86f72..7069440ea 100644 --- a/d3d12/crates/leonida-formats/src/bcpack.rs +++ b/d3d12/crates/leonida-formats/src/bcpack.rs | |||
| @@ -77,8 +77,36 @@ struct Bc7Ix { | |||
| 77 | ix: [[i16; 16]; 2], | 77 | ix: [[i16; 16]; 2], |
| 78 | } | 78 | } |
| 79 | 79 | ||
| 80 | /// Per-model precomputed rANS decode parameters packed for cache locality and | ||
| 81 | /// branchless bucket + symbol decoding (`b == 0` uses `adj_start[0] = 1`, | ||
| 82 | /// `adj_freq[0] = freq[0] - 1`, `adj_recip[0] = 0`, `base_sym[0] = 0`). | ||
| 83 | #[repr(C, align(64))] | ||
| 84 | #[derive(Clone, Copy)] | ||
| 85 | struct Model { | ||
| 86 | /// `start[1..9]` as signed 32-bit integers (`0..=65536`) for single-register | ||
| 87 | /// AVX2 `vpcmpgtd` bucket lookup. | ||
| 88 | start_1_8: [i32; 8], | ||
| 89 | adj_start: [u32; BUCKETS], | ||
| 90 | adj_freq: [u32; BUCKETS], | ||
| 91 | base_sym: [u32; BUCKETS], | ||
| 92 | adj_recip: [u64; BUCKETS], | ||
| 93 | } | ||
| 94 | |||
| 95 | impl Default for Model { | ||
| 96 | fn default() -> Self { | ||
| 97 | Self { | ||
| 98 | start_1_8: [0; 8], | ||
| 99 | adj_start: [0; BUCKETS], | ||
| 100 | adj_freq: [0; BUCKETS], | ||
| 101 | base_sym: [0; BUCKETS], | ||
| 102 | adj_recip: [0; BUCKETS], | ||
| 103 | } | ||
| 104 | } | ||
| 105 | } | ||
| 106 | |||
| 80 | /// The format's constant tables. | 107 | /// The format's constant tables. |
| 81 | pub struct Tables { | 108 | pub struct Tables { |
| 109 | #[cfg(test)] | ||
| 82 | freq: [[u32; BUCKETS]; MODELS], | 110 | freq: [[u32; BUCKETS]; MODELS], |
| 83 | /// Each bucket's first slot; 65536 past the model's last, and one more | 111 | /// Each bucket's first slot; 65536 past the model's last, and one more |
| 84 | /// 65536 at the end so a bucket always has a next start. | 112 | /// 65536 at the end so a bucket always has a next start. |
| @@ -86,8 +114,8 @@ pub struct Tables { | |||
| 86 | /// Per model, the bucket of the first slot of each 256-slot window: the | 114 | /// Per model, the bucket of the first slot of each 256-slot window: the |
| 87 | /// search for a slot's bucket starts there and seldom moves on. | 115 | /// search for a slot's bucket starts there and seldom moves on. |
| 88 | bucket: Box<[[u8; 256]; MODELS]>, | 116 | bucket: Box<[[u8; 256]; MODELS]>, |
| 89 | /// ceil(2^32 / freq): exact division for the offsets inside a bucket. | 117 | /// Precomputed per-model decode tables for branchless lane decoding. |
| 90 | recip: [[u64; BUCKETS]; MODELS], | 118 | models: Box<[Model; MODELS]>, |
| 91 | rank1: [u8; 256], | 119 | rank1: [u8; 256], |
| 92 | rank3a: [u8; 64], | 120 | rank3a: [u8; 64], |
| 93 | rank3c: [u8; 256], | 121 | rank3c: [u8; 256], |
| @@ -141,7 +169,7 @@ impl Tables { | |||
| 141 | let mut freq = [[0u32; BUCKETS]; MODELS]; | 169 | let mut freq = [[0u32; BUCKETS]; MODELS]; |
| 142 | let mut start = [[0u32; BUCKETS + 1]; MODELS]; | 170 | let mut start = [[0u32; BUCKETS + 1]; MODELS]; |
| 143 | let mut bucket = Box::new([[0u8; 256]; MODELS]); | 171 | let mut bucket = Box::new([[0u8; 256]; MODELS]); |
| 144 | let mut recip = [[0u64; BUCKETS]; MODELS]; | 172 | let mut models = Box::new([Model::default(); MODELS]); |
| 145 | for m in 0..MODELS { | 173 | for m in 0..MODELS { |
| 146 | for f in &mut freq[m] { | 174 | for f in &mut freq[m] { |
| 147 | *f = u32::from(r.u16()); | 175 | *f = u32::from(r.u16()); |
| @@ -154,7 +182,6 @@ impl Tables { | |||
| 154 | return Err(Error("a model has an empty bucket")); | 182 | return Err(Error("a model has an empty bucket")); |
| 155 | } | 183 | } |
| 156 | start[m][b] = at; | 184 | start[m][b] = at; |
| 157 | recip[m][b] = (1u64 << 32).div_ceil(u64::from(freq[m][b])); | ||
| 158 | at += freq[m][b] << b.saturating_sub(1); | 185 | at += freq[m][b] << b.saturating_sub(1); |
| 159 | } | 186 | } |
| 160 | if at != 1 << 16 { | 187 | if at != 1 << 16 { |
| @@ -165,6 +192,20 @@ impl Tables { | |||
| 165 | let first = (window as u32) << 8; | 192 | let first = (window as u32) << 8; |
| 166 | *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; | 193 | *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; |
| 167 | } | 194 | } |
| 195 | let md = &mut models[m]; | ||
| 196 | for k in 0..8 { | ||
| 197 | md.start_1_8[k] = start[m][k + 1] as i32; | ||
| 198 | } | ||
| 199 | md.adj_start[0] = 1; | ||
| 200 | md.adj_freq[0] = freq[m][0] - 1; | ||
| 201 | md.base_sym[0] = 0; | ||
| 202 | md.adj_recip[0] = 0; | ||
| 203 | for b in 1..used { | ||
| 204 | md.adj_start[b] = start[m][b]; | ||
| 205 | md.adj_freq[b] = freq[m][b]; | ||
| 206 | md.base_sym[b] = 1u32 << (b - 1); | ||
| 207 | md.adj_recip[b] = (1u64 << 32).div_ceil(u64::from(freq[m][b])); | ||
| 208 | } | ||
| 168 | } | 209 | } |
| 169 | let rank1 = r.bytes(); | 210 | let rank1 = r.bytes(); |
| 170 | let rank3a = r.bytes(); | 211 | let rank3a = r.bytes(); |
| @@ -240,10 +281,11 @@ impl Tables { | |||
| 240 | }) | 281 | }) |
| 241 | .collect(); | 282 | .collect(); |
| 242 | Ok(Tables { | 283 | Ok(Tables { |
| 284 | #[cfg(test)] | ||
| 243 | freq, | 285 | freq, |
| 244 | start, | 286 | start, |
| 245 | bucket, | 287 | bucket, |
| 246 | recip, | 288 | models, |
| 247 | rank1, | 289 | rank1, |
| 248 | rank3a, | 290 | rank3a, |
| 249 | rank3c, | 291 | rank3c, |
| @@ -320,10 +362,11 @@ struct Lane { | |||
| 320 | impl Lane { | 362 | impl Lane { |
| 321 | /// One step: take the latched byte (header, length or payload) and | 363 | /// One step: take the latched byte (header, length or payload) and |
| 322 | /// decode at most one symbol. | 364 | /// decode at most one symbol. |
| 323 | fn step(&mut self, t: &Tables) -> Result<(), Error> { | 365 | #[inline(always)] |
| 366 | fn step(&mut self, t: &Tables, bucket_fn: impl FnOnce(&Tables, u8, u32) -> usize) { | ||
| 324 | if self.phase != 3 { | 367 | if self.phase != 3 { |
| 325 | let Some(b) = self.latch.take() else { | 368 | let Some(b) = self.latch.take() else { |
| 326 | return Ok(()); | 369 | return; |
| 327 | }; | 370 | }; |
| 328 | self.need = true; | 371 | self.need = true; |
| 329 | match self.phase { | 372 | match self.phase { |
| @@ -349,7 +392,7 @@ impl Lane { | |||
| 349 | self.phase = 3; | 392 | self.phase = 3; |
| 350 | } | 393 | } |
| 351 | } | 394 | } |
| 352 | return Ok(()); | 395 | return; |
| 353 | } | 396 | } |
| 354 | let mut x = self.x; | 397 | let mut x = self.x; |
| 355 | if x < LOW | 398 | if x < LOW |
| @@ -360,22 +403,14 @@ impl Lane { | |||
| 360 | } | 403 | } |
| 361 | self.need = self.left != 0 && self.latch.is_none(); | 404 | self.need = self.left != 0 && self.latch.is_none(); |
| 362 | if x > LOW { | 405 | if x > LOW { |
| 363 | let freq = &t.freq[usize::from(self.model)]; | ||
| 364 | let start = &t.start[usize::from(self.model)]; | ||
| 365 | let slot = x & 0xffff; | 406 | let slot = x & 0xffff; |
| 366 | // The bucket: starts are ascending, and 65536 past the model's last. | 407 | let b = bucket_fn(t, self.model, slot); |
| 367 | let b = bucket_of(t, self.model, slot); | 408 | let md = &t.models[usize::from(self.model)]; |
| 368 | // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 | 409 | let offset = slot.wrapping_sub(md.adj_start[b]); |
| 369 | // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency | 410 | let q = ((u64::from(offset) * md.adj_recip[b]) >> 32) as u32; |
| 370 | // f[b] from start[b] on; offset and frequency are below 2^16, where | 411 | let f = md.adj_freq[b]; |
| 371 | // the reciprocal divides exactly. | 412 | let sym = md.base_sym[b] + q; |
| 372 | let (sym, f, rem) = if b == 0 { | 413 | let rem = offset.wrapping_sub(q.wrapping_mul(f)); |
| 373 | (0, freq[0] - 1, slot.wrapping_sub(1)) | ||
| 374 | } else { | ||
| 375 | let offset = slot - start[b]; | ||
| 376 | let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; | ||
| 377 | ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) | ||
| 378 | }; | ||
| 379 | self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); | 414 | self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); |
| 380 | self.out = Some(sym as u8); | 415 | self.out = Some(sym as u8); |
| 381 | } else if self.left != 0 { | 416 | } else if self.left != 0 { |
| @@ -390,14 +425,13 @@ impl Lane { | |||
| 390 | self.x = 0; | 425 | self.x = 0; |
| 391 | } | 426 | } |
| 392 | } | 427 | } |
| 393 | Ok(()) | ||
| 394 | } | 428 | } |
| 395 | } | 429 | } |
| 396 | 430 | ||
| 397 | /// The bucket holding `slot` (below 65536): the last whose start is at or | 431 | /// The bucket holding `slot` (below 65536): the last whose start is at or |
| 398 | /// below it. The window table gives the bucket of the window's first slot; | 432 | /// below it. The window table gives the bucket of the window's first slot; |
| 399 | /// later buckets that start inside the window are stepped over. | 433 | /// later buckets that start inside the window are stepped over. |
| 400 | #[inline] | 434 | #[inline(always)] |
| 401 | fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { | 435 | fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { |
| 402 | let start = &t.start[usize::from(model)]; | 436 | let start = &t.start[usize::from(model)]; |
| 403 | let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); | 437 | let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); |
| @@ -407,20 +441,66 @@ fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { | |||
| 407 | b | 441 | b |
| 408 | } | 442 | } |
| 409 | 443 | ||
| 444 | #[cfg(target_arch = "x86_64")] | ||
| 445 | #[target_feature(enable = "avx2")] | ||
| 446 | #[inline] | ||
| 447 | unsafe fn bucket_of_avx2(t: &Tables, model: u8, slot: u32) -> usize { | ||
| 448 | use std::arch::x86_64::{ | ||
| 449 | __m256i, _mm256_castsi256_ps, _mm256_cmpgt_epi32, _mm256_loadu_si256, _mm256_movemask_ps, | ||
| 450 | _mm256_set1_epi32, | ||
| 451 | }; | ||
| 452 | let ptr = t.models[usize::from(model)].start_1_8.as_ptr() as *const __m256i; | ||
| 453 | // SAFETY: `start_1_8` is `[i32; 8]` (32 bytes), and all entries are in `0..=65536`. | ||
| 454 | let starts = unsafe { _mm256_loadu_si256(ptr) }; | ||
| 455 | let cmp = _mm256_cmpgt_epi32(_mm256_set1_epi32((slot + 1) as i32), starts); | ||
| 456 | (_mm256_movemask_ps(_mm256_castsi256_ps(cmp)) as u32).count_ones() as usize | ||
| 457 | } | ||
| 458 | |||
| 410 | /// Decodes `per` symbols per block on every lane into `records` (one record | 459 | /// Decodes `per` symbols per block on every lane into `records` (one record |
| 411 | /// of `widths.len() * per` symbols per block), taking input from `fetch` | 460 | /// of `widths.len() * per` symbols per block), taking input from `fetch` |
| 412 | /// (given the lane that takes the byte) in the order of the schedule: each | 461 | /// (given the lane that takes the byte) in the order of the schedule: each |
| 413 | /// round the lanes step in order and take at most 8 bytes between them. | 462 | /// round the lanes step in order and take at most 8 bytes between them. |
| 414 | // shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s | ||
| 415 | // on one core); if texture streaming needs more, run the schedule only to | ||
| 416 | // split the input per lane and decode the lanes apart. | ||
| 417 | fn lanes( | 463 | fn lanes( |
| 418 | t: &Tables, | 464 | t: &Tables, |
| 419 | widths: &[u8], | 465 | widths: &[u8], |
| 420 | per: usize, | 466 | per: usize, |
| 421 | blocks: usize, | 467 | blocks: usize, |
| 468 | fetch: impl FnMut(usize) -> Option<u8>, | ||
| 469 | records: &mut [u8], | ||
| 470 | ) -> Result<(), Error> { | ||
| 471 | #[cfg(target_arch = "x86_64")] | ||
| 472 | if std::arch::is_x86_feature_detected!("avx2") { | ||
| 473 | // SAFETY: AVX2 support verified above. | ||
| 474 | return unsafe { lanes_avx2(t, widths, per, blocks, fetch, records) }; | ||
| 475 | } | ||
| 476 | lanes_impl(t, widths, per, blocks, fetch, records, bucket_of) | ||
| 477 | } | ||
| 478 | |||
| 479 | #[cfg(target_arch = "x86_64")] | ||
| 480 | #[target_feature(enable = "avx2")] | ||
| 481 | unsafe fn lanes_avx2( | ||
| 482 | t: &Tables, | ||
| 483 | widths: &[u8], | ||
| 484 | per: usize, | ||
| 485 | blocks: usize, | ||
| 486 | fetch: impl FnMut(usize) -> Option<u8>, | ||
| 487 | records: &mut [u8], | ||
| 488 | ) -> Result<(), Error> { | ||
| 489 | lanes_impl(t, widths, per, blocks, fetch, records, |t, m, s| { | ||
| 490 | // SAFETY: inside `target_feature(enable = "avx2")`. | ||
| 491 | unsafe { bucket_of_avx2(t, m, s) } | ||
| 492 | }) | ||
| 493 | } | ||
| 494 | |||
| 495 | #[inline(always)] | ||
| 496 | fn lanes_impl( | ||
| 497 | t: &Tables, | ||
| 498 | widths: &[u8], | ||
| 499 | per: usize, | ||
| 500 | blocks: usize, | ||
| 422 | mut fetch: impl FnMut(usize) -> Option<u8>, | 501 | mut fetch: impl FnMut(usize) -> Option<u8>, |
| 423 | records: &mut [u8], | 502 | records: &mut [u8], |
| 503 | mut bucket_fn: impl FnMut(&Tables, u8, u32) -> usize, | ||
| 424 | ) -> Result<(), Error> { | 504 | ) -> Result<(), Error> { |
| 425 | let mut lanes = [Lane::default(); 16]; | 505 | let mut lanes = [Lane::default(); 16]; |
| 426 | let lanes = &mut lanes[..widths.len()]; | 506 | let lanes = &mut lanes[..widths.len()]; |
| @@ -433,13 +513,14 @@ fn lanes( | |||
| 433 | let (mut pos, mut done, mut idle) = (0, 0u32, 0); | 513 | let (mut pos, mut done, mut idle) = (0, 0u32, 0); |
| 434 | // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. | 514 | // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. |
| 435 | let mut at = 0; | 515 | let mut at = 0; |
| 436 | while pos < blocks * per { | 516 | let total = blocks * per; |
| 517 | while pos < total { | ||
| 437 | let (mut taken, mut moved) = (0, false); | 518 | let (mut taken, mut moved) = (0, false); |
| 438 | for (j, lane) in lanes.iter_mut().enumerate() { | 519 | for (j, lane) in lanes.iter_mut().enumerate() { |
| 439 | let bit = 1 << j; | 520 | let bit = 1 << j; |
| 440 | let before = taken; | 521 | let before = taken; |
| 441 | if !lane.stalled { | 522 | if !lane.stalled { |
| 442 | lane.step(t)?; | 523 | lane.step(t, &mut bucket_fn); |
| 443 | } | 524 | } |
| 444 | let waiting = lane.out.is_some() && done & bit != 0; | 525 | let waiting = lane.out.is_some() && done & bit != 0; |
| 445 | if lane.need && !waiting && taken < ROUND_BYTES { | 526 | if lane.need && !waiting && taken < ROUND_BYTES { |
| @@ -1602,6 +1683,8 @@ mod tests { | |||
| 1602 | narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); | 1683 | narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); |
| 1603 | } | 1684 | } |
| 1604 | } | 1685 | } |
| 1686 | #[cfg(target_arch = "x86_64")] | ||
| 1687 | let has_avx2 = std::arch::is_x86_feature_detected!("avx2"); | ||
| 1605 | for t in [ | 1688 | for t in [ |
| 1606 | Tables::builtin().unwrap(), | 1689 | Tables::builtin().unwrap(), |
| 1607 | Tables::parse(&tables()).unwrap(), | 1690 | Tables::parse(&tables()).unwrap(), |
| @@ -1616,6 +1699,15 @@ mod tests { | |||
| 1616 | scan, | 1699 | scan, |
| 1617 | "model {model} slot {slot}" | 1700 | "model {model} slot {slot}" |
| 1618 | ); | 1701 | ); |
| 1702 | #[cfg(target_arch = "x86_64")] | ||
| 1703 | if has_avx2 { | ||
| 1704 | // SAFETY: AVX2 support verified above. | ||
| 1705 | assert_eq!( | ||
| 1706 | unsafe { bucket_of_avx2(&t, model, slot) }, | ||
| 1707 | scan, | ||
| 1708 | "avx2 model {model} slot {slot}" | ||
| 1709 | ); | ||
| 1710 | } | ||
| 1619 | } | 1711 | } |
| 1620 | } | 1712 | } |
| 1621 | } | 1713 | } |
| @@ -1670,7 +1762,7 @@ mod tests { | |||
| 1670 | left: 1, | 1762 | left: 1, |
| 1671 | ..Default::default() | 1763 | ..Default::default() |
| 1672 | }; | 1764 | }; |
| 1673 | lane.step(&t).unwrap(); | 1765 | lane.step(&t, bucket_of); |
| 1674 | let (sym, next) = reference_decode(&t, model, x); | 1766 | let (sym, next) = reference_decode(&t, model, x); |
| 1675 | assert_eq!( | 1767 | assert_eq!( |
| 1676 | (lane.out, lane.x), | 1768 | (lane.out, lane.x), |
diff --git a/d3d12/crates/leonida-formats/src/texture.rs b/d3d12/crates/leonida-formats/src/texture.rs index e52d639ed..c49c12228 100644 --- a/d3d12/crates/leonida-formats/src/texture.rs +++ b/d3d12/crates/leonida-formats/src/texture.rs | |||
| @@ -729,9 +729,39 @@ impl Layout { | |||
| 729 | // once so each row can copy them as fixed-size chunks. | 729 | // once so each row can copy them as fixed-size chunks. |
| 730 | let (body, last) = runs.split_at(runs.len().saturating_sub(1)); | 730 | let (body, last) = runs.split_at(runs.len().saturating_sub(1)); |
| 731 | let chunk_size = body.first().map(|run| run.2).filter(|&size| { | 731 | let chunk_size = body.first().map(|run| run.2).filter(|&size| { |
| 732 | body.iter() | 732 | matches!(size, 4 | 8 | 16 | 32 | 64) |
| 733 | .all(|&(offset, _, len)| len == size && offset.is_multiple_of(size)) | 733 | && body.iter().all(|&(offset, _, len)| { |
| 734 | len == size && offset.is_multiple_of(size) && offset / size <= u32::MAX as usize | ||
| 735 | }) | ||
| 734 | }); | 736 | }); |
| 737 | const STACK_CHUNKS: usize = 32; | ||
| 738 | let mut stack_offs = [0u32; STACK_CHUNKS]; | ||
| 739 | let mut heap_offs = Vec::new(); | ||
| 740 | let mut max_chunk_off = 0usize; | ||
| 741 | let chunk_offsets: &[u32] = if let Some(size) = chunk_size { | ||
| 742 | if body.len() <= STACK_CHUNKS { | ||
| 743 | for (dst_off, &(offset, _, _)) in stack_offs[..body.len()].iter_mut().zip(body) { | ||
| 744 | let c = offset / size; | ||
| 745 | if c > max_chunk_off { | ||
| 746 | max_chunk_off = c; | ||
| 747 | } | ||
| 748 | *dst_off = c as u32; | ||
| 749 | } | ||
| 750 | &stack_offs[..body.len()] | ||
| 751 | } else { | ||
| 752 | heap_offs.reserve_exact(body.len()); | ||
| 753 | for &(offset, _, _) in body { | ||
| 754 | let c = offset / size; | ||
| 755 | if c > max_chunk_off { | ||
| 756 | max_chunk_off = c; | ||
| 757 | } | ||
| 758 | heap_offs.push(c as u32); | ||
| 759 | } | ||
| 760 | &heap_offs | ||
| 761 | } | ||
| 762 | } else { | ||
| 763 | &[] | ||
| 764 | }; | ||
| 735 | for z in 0..depth { | 765 | for z in 0..depth { |
| 736 | let (s, inner) = self.split(first + z); | 766 | let (s, inner) = self.split(first + z); |
| 737 | let base = u64::from(s) * self.slice_size + m.offset; | 767 | let base = u64::from(s) * self.slice_size + m.offset; |
| @@ -743,18 +773,24 @@ impl Layout { | |||
| 743 | } else { | 773 | } else { |
| 744 | let tiled_row = (base + self.row(m, y, inner)) as usize; | 774 | let tiled_row = (base + self.row(m, y, inner)) as usize; |
| 745 | match chunk_size { | 775 | match chunk_size { |
| 776 | Some(4) if tiled_row.is_multiple_of(4) => { | ||
| 777 | copy_chunks::<4, DETILE>(src, dst, chunk_offsets, max_chunk_off, tiled_row, linear_row) | ||
| 778 | } | ||
| 746 | Some(8) if tiled_row.is_multiple_of(8) => { | 779 | Some(8) if tiled_row.is_multiple_of(8) => { |
| 747 | copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row) | 780 | copy_chunks::<8, DETILE>(src, dst, chunk_offsets, max_chunk_off, tiled_row, linear_row) |
| 748 | } | 781 | } |
| 749 | Some(16) if tiled_row.is_multiple_of(16) => { | 782 | Some(16) if tiled_row.is_multiple_of(16) => { |
| 750 | copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row) | 783 | copy_chunks::<16, DETILE>(src, dst, chunk_offsets, max_chunk_off, tiled_row, linear_row) |
| 751 | } | 784 | } |
| 752 | Some(32) if tiled_row.is_multiple_of(32) => { | 785 | Some(32) if tiled_row.is_multiple_of(32) => { |
| 753 | copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row) | 786 | copy_chunks::<32, DETILE>(src, dst, chunk_offsets, max_chunk_off, tiled_row, linear_row) |
| 754 | } | 787 | } |
| 755 | _ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row), | 788 | Some(64) if tiled_row.is_multiple_of(64) => { |
| 789 | copy_chunks::<64, DETILE>(src, dst, chunk_offsets, max_chunk_off, tiled_row, linear_row) | ||
| 790 | } | ||
| 791 | _ => copy_runs::<DETILE>(src, dst, body, tiled_row, linear_row), | ||
| 756 | } | 792 | } |
| 757 | copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row); | 793 | copy_runs::<DETILE>(src, dst, last, tiled_row, linear_row); |
| 758 | } | 794 | } |
| 759 | } | 795 | } |
| 760 | } | 796 | } |
| @@ -777,31 +813,51 @@ fn copy_run<const DETILE: bool>( | |||
| 777 | dst[to..][..len].copy_from_slice(&src[from..][..len]); | 813 | dst[to..][..len].copy_from_slice(&src[from..][..len]); |
| 778 | } | 814 | } |
| 779 | 815 | ||
| 780 | /// A row of equal runs is contiguous in linear memory. Treat it as a | 816 | /// Irregular runs and the last run of each row. |
| 781 | /// slice of arrays so only the tiled chunk needs a bounds check per copy. | 817 | fn copy_runs<const DETILE: bool>( |
| 782 | /// Use the byte ranges for irregular runs and the last run of each row. | ||
| 783 | fn copy_runs<const N: usize, const DETILE: bool>( | ||
| 784 | src: &[u8], | 818 | src: &[u8], |
| 785 | dst: &mut [u8], | 819 | dst: &mut [u8], |
| 786 | runs: &[(usize, usize, usize)], | 820 | runs: &[(usize, usize, usize)], |
| 787 | tiled_row: usize, | 821 | tiled_row: usize, |
| 788 | linear_row: usize, | 822 | linear_row: usize, |
| 789 | ) { | 823 | ) { |
| 790 | if N == 0 { | 824 | for &(tiled, linear, len) in runs { |
| 791 | for &(tiled, linear, len) in runs { | 825 | copy_run::<DETILE>(src, dst, tiled_row + tiled, linear_row + linear, len); |
| 792 | copy_run::<DETILE>(src, dst, tiled_row + tiled, linear_row + linear, len); | 826 | } |
| 793 | } | 827 | } |
| 794 | } else if DETILE { | 828 | |
| 829 | /// A row of equal `N`-byte runs is contiguous in linear memory. Pre-divided | ||
| 830 | /// `u32` chunk offsets shrink the offset table 6x (4 B vs 24 B) and a single | ||
| 831 | /// per-row bounds check lets the inner loop copy without per-chunk checks. | ||
| 832 | fn copy_chunks<const N: usize, const DETILE: bool>( | ||
| 833 | src: &[u8], | ||
| 834 | dst: &mut [u8], | ||
| 835 | chunk_offsets: &[u32], | ||
| 836 | max_chunk_off: usize, | ||
| 837 | tiled_row: usize, | ||
| 838 | linear_row: usize, | ||
| 839 | ) { | ||
| 840 | if chunk_offsets.is_empty() { | ||
| 841 | return; | ||
| 842 | } | ||
| 843 | let base = tiled_row / N; | ||
| 844 | if DETILE { | ||
| 795 | let tiled = src.as_chunks::<N>().0; | 845 | let tiled = src.as_chunks::<N>().0; |
| 796 | let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::<N>().0; | 846 | let linear = dst[linear_row..][..chunk_offsets.len() * N].as_chunks_mut::<N>().0; |
| 797 | for (out, &(offset, ..)) in linear.iter_mut().zip(runs) { | 847 | assert!(base + max_chunk_off < tiled.len()); |
| 798 | *out = tiled[(tiled_row + offset) / N]; | 848 | let tiled_base = &tiled[base..]; |
| 849 | for (out, &off) in linear.iter_mut().zip(chunk_offsets) { | ||
| 850 | // SAFETY: `off as usize <= max_chunk_off` and `base + max_chunk_off < tiled.len()`. | ||
| 851 | *out = unsafe { *tiled_base.get_unchecked(off as usize) }; | ||
| 799 | } | 852 | } |
| 800 | } else { | 853 | } else { |
| 801 | let tiled = dst.as_chunks_mut::<N>().0; | 854 | let tiled = dst.as_chunks_mut::<N>().0; |
| 802 | let linear = src[linear_row..][..runs.len() * N].as_chunks::<N>().0; | 855 | let linear = src[linear_row..][..chunk_offsets.len() * N].as_chunks::<N>().0; |
| 803 | for (input, &(offset, ..)) in linear.iter().zip(runs) { | 856 | assert!(base + max_chunk_off < tiled.len()); |
| 804 | tiled[(tiled_row + offset) / N] = *input; | 857 | let tiled_base = &mut tiled[base..]; |
| 858 | for (input, &off) in linear.iter().zip(chunk_offsets) { | ||
| 859 | // SAFETY: `off as usize <= max_chunk_off` and `base + max_chunk_off < tiled.len()`. | ||
| 860 | unsafe { *tiled_base.get_unchecked_mut(off as usize) = *input }; | ||
| 805 | } | 861 | } |
| 806 | } | 862 | } |
| 807 | } | 863 | } |
| @@ -1343,7 +1399,7 @@ mod tests { | |||
| 1343 | let needs: Vec<u64> = (0..9).map(|mip| l.bytes_from(mip)).collect(); | 1399 | let needs: Vec<u64> = (0..9).map(|mip| l.bytes_from(mip)).collect(); |
| 1344 | assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); | 1400 | assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); |
| 1345 | assert!(needs[3] * 4 < l.size, "{needs:?}"); | 1401 | assert!(needs[3] * 4 < l.size, "{needs:?}"); |
| 1346 | let tiled: Vec<u8> = (0..l.size).map(|i| (i * 7 >> 3) as u8).collect(); | 1402 | let tiled: Vec<u8> = (0..l.size).map(|i| ((i * 7) >> 3) as u8).collect(); |
| 1347 | for mip in 1..9 { | 1403 | for mip in 1..9 { |
| 1348 | let m = l.mips[mip as usize]; | 1404 | let m = l.mips[mip as usize]; |
| 1349 | let pitch = m.width as usize * 8; | 1405 | let pitch = m.width as usize * 8; |
| @@ -1510,4 +1566,54 @@ mod tests { | |||
| 1510 | ); | 1566 | ); |
| 1511 | assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); | 1567 | assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); |
| 1512 | } | 1568 | } |
| 1569 | |||
| 1570 | #[test] | ||
| 1571 | #[ignore] | ||
| 1572 | fn texture_walk_bench() { | ||
| 1573 | let cases: &[(&str, u32, u32, u32, u32, Swizzle, u32)] = &[ | ||
| 1574 | ("8x8_4B_64KB_S", 8, 8, 0, 4, Swizzle::SW_64KB_S, 20_000), | ||
| 1575 | ("32x24_4B_64KB_D", 32, 24, 0, 4, Swizzle::SW_64KB_D, 10_000), | ||
| 1576 | ("256x256_4B_64KB_D_m5", 256, 256, 5, 4, Swizzle::SW_64KB_D, 20_000), | ||
| 1577 | ("256x256_4B_64KB_S", 256, 256, 0, 4, Swizzle::SW_64KB_S, 400), | ||
| 1578 | ("256x256_8B_64KB_S", 256, 256, 0, 8, Swizzle::SW_64KB_S, 400), | ||
| 1579 | ("256x256_4B_64KB_D", 256, 256, 0, 4, Swizzle::SW_64KB_D, 400), | ||
| 1580 | ("256x256_8B_64KB_D", 256, 256, 0, 8, Swizzle::SW_64KB_D, 400), | ||
| 1581 | ("512x512_16B_64KB_S", 512, 512, 0, 16, Swizzle::SW_64KB_S, 100), | ||
| 1582 | ("512x512_16B_64KB_D", 512, 512, 0, 16, Swizzle::SW_64KB_D, 100), | ||
| 1583 | ("1024x1024_8B_64KB_S", 1024, 1024, 0, 8, Swizzle::SW_64KB_S, 50), | ||
| 1584 | ("1024x1024_8B_64KB_D", 1024, 1024, 0, 8, Swizzle::SW_64KB_D, 50), | ||
| 1585 | ]; | ||
| 1586 | for &(name, w, h, mip, bpp, swizzle, iters) in cases { | ||
| 1587 | let mips = if mip > 0 { mip + 1 } else { 1 }; | ||
| 1588 | let l = Layout::new(&Desc { mips, ..desc(w, h, 1, bpp, swizzle) }).unwrap(); | ||
| 1589 | let mw = (w >> mip).max(1); | ||
| 1590 | let mh = (h >> mip).max(1); | ||
| 1591 | let mut tiled = vec![0x5Au8; l.size as usize]; | ||
| 1592 | let pitch = (mw * bpp) as usize; | ||
| 1593 | let mut linear = vec![0xA5u8; pitch * mh as usize]; | ||
| 1594 | let bytes = (pitch * mh as usize) as f64 * iters as f64; | ||
| 1595 | // warmup | ||
| 1596 | for _ in 0..4 { | ||
| 1597 | l.detile(&tiled, mip, 0, &mut linear, pitch, 0).unwrap(); | ||
| 1598 | l.tile(&mut tiled, mip, 0, &linear, pitch, 0).unwrap(); | ||
| 1599 | } | ||
| 1600 | let t0 = std::time::Instant::now(); | ||
| 1601 | for _ in 0..iters { | ||
| 1602 | l.detile(std::hint::black_box(&tiled), mip, 0, std::hint::black_box(&mut linear), pitch, 0).unwrap(); | ||
| 1603 | } | ||
| 1604 | let dt_detile = t0.elapsed().as_secs_f64(); | ||
| 1605 | let t1 = std::time::Instant::now(); | ||
| 1606 | for _ in 0..iters { | ||
| 1607 | l.tile(std::hint::black_box(&mut tiled), mip, 0, std::hint::black_box(&linear), pitch, 0).unwrap(); | ||
| 1608 | } | ||
| 1609 | let dt_tile = t1.elapsed().as_secs_f64(); | ||
| 1610 | eprintln!( | ||
| 1611 | "{name:<24} detile={:7.1} MB/s ({:6.3} us) tile={:7.1} MB/s ({:6.3} us)", | ||
| 1612 | bytes / (1024.0 * 1024.0) / dt_detile, | ||
| 1613 | dt_detile * 1e6 / iters as f64, | ||
| 1614 | bytes / (1024.0 * 1024.0) / dt_tile, | ||
| 1615 | dt_tile * 1e6 / iters as f64, | ||
| 1616 | ); | ||
| 1617 | } | ||
| 1618 | } | ||
| 1513 | } | 1619 | } |
diff --git a/d3d12/crates/leonida-gpu/src/aspect.rs b/d3d12/crates/leonida-gpu/src/aspect.rs index 976ee35f9..6b3d4a064 100644 --- a/d3d12/crates/leonida-gpu/src/aspect.rs +++ b/d3d12/crates/leonida-gpu/src/aspect.rs | |||
| @@ -258,7 +258,7 @@ mod tests { | |||
| 258 | for picture in [(3840u32, 2160u32), (2560, 1440), (1920, 1080)] { | 258 | for picture in [(3840u32, 2160u32), (2560, 1440), (1920, 1080)] { |
| 259 | for window in [(1001u32, 333u32), (333, 1001), (3439, 1441), (10000, 10), (10, 10000), (1717, 911)] { | 259 | for window in [(1001u32, 333u32), (333, 1001), (3439, 1441), (10000, 10), (10, 10000), (1717, 911)] { |
| 260 | let f = frame(picture, window); | 260 | let f = frame(picture, window); |
| 261 | assert!(f.width % 2 == 0 && f.height % 2 == 0, "{picture:?} in {window:?}: {f:?}"); | 261 | assert!(f.width.is_multiple_of(2) && f.height.is_multiple_of(2), "{picture:?} in {window:?}: {f:?}"); |
| 262 | assert!(f.width <= MOST && f.height <= MOST, "{f:?}"); | 262 | assert!(f.width <= MOST && f.height <= MOST, "{f:?}"); |
| 263 | assert!(f.left + picture.0 <= f.width && f.top + picture.1 <= f.height, "{f:?}"); | 263 | assert!(f.left + picture.0 <= f.width && f.top + picture.1 <= f.height, "{f:?}"); |
| 264 | // One side is the picture's, and the bars are equal. | 264 | // One side is the picture's, and the bars are equal. |
diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 798db1d8d..0884e6751 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs | |||
| @@ -189,8 +189,7 @@ impl Composer { | |||
| 189 | list: &ID3D12GraphicsCommandList, | 189 | list: &ID3D12GraphicsCommandList, |
| 190 | planes: [(&ID3D12Resource, DXGI_FORMAT); 2], | 190 | planes: [(&ID3D12Resource, DXGI_FORMAT); 2], |
| 191 | back: &ID3D12Resource, | 191 | back: &ID3D12Resource, |
| 192 | (left, top): (u32, u32), | 192 | ((left, top), (width, height)): ((u32, u32), (u32, u32)), |
| 193 | (width, height): (u32, u32), | ||
| 194 | ) -> windows::core::Result<()> { | 193 | ) -> windows::core::Result<()> { |
| 195 | while self.views.len() <= slot { | 194 | while self.views.len() <= slot { |
| 196 | let heap = unsafe { | 195 | let heap = unsafe { |
| @@ -386,8 +385,7 @@ mod tests { | |||
| 386 | cmds, | 385 | cmds, |
| 387 | [(&base, format), (&overlay, format)], | 386 | [(&base, format), (&overlay, format)], |
| 388 | &output, | 387 | &output, |
| 389 | (0, 0), | 388 | ((0, 0), (3, 1)), |
| 390 | (3, 1), | ||
| 391 | ) | 389 | ) |
| 392 | .unwrap(); | 390 | .unwrap(); |
| 393 | cmds.ResourceBarrier(&[crate::host::transition( | 391 | cmds.ResourceBarrier(&[crate::host::transition( |
diff --git a/d3d12/crates/leonida-gpu/src/descriptor.rs b/d3d12/crates/leonida-gpu/src/descriptor.rs index 107880203..f23853061 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor.rs | |||
| @@ -9,6 +9,7 @@ | |||
| 9 | 9 | ||
| 10 | use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; | 10 | use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; |
| 11 | use crate::resource::{Memory, PAGEABLE_IIDS}; | 11 | use crate::resource::{Memory, PAGEABLE_IIDS}; |
| 12 | use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering::{AcqRel, Acquire, Release}}; | ||
| 12 | 13 | ||
| 13 | #[cfg(windows)] | 14 | #[cfg(windows)] |
| 14 | pub(crate) mod host; | 15 | pub(crate) mod host; |
| @@ -1032,6 +1033,8 @@ struct Views { | |||
| 1032 | /// table is looked up here, on several recording threads at once in the | 1033 | /// table is looked up here, on several recording threads at once in the |
| 1033 | /// world. Readers share it; only a view not seen before (a new table entry | 1034 | /// world. Readers share it; only a view not seen before (a new table entry |
| 1034 | /// or shape) and a released resource take it alone. | 1035 | /// or shape) and a released resource take it alone. |
| 1036 | /// (With [`list_lock_fast`] those lookups read [`PUBLISHED`] and take no | ||
| 1037 | /// lock at all.) | ||
| 1035 | static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { | 1038 | static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { |
| 1036 | list: Vec::new(), | 1039 | list: Vec::new(), |
| 1037 | index: std::collections::BTreeMap::new(), | 1040 | index: std::collections::BTreeMap::new(), |
| @@ -1125,6 +1128,16 @@ fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, | |||
| 1125 | ) | 1128 | ) |
| 1126 | } | 1129 | } |
| 1127 | 1130 | ||
| 1131 | /// The view of placed memory with shape `shape` at `address`: what | ||
| 1132 | /// [`shape_of`] took apart. | ||
| 1133 | fn placed_whole(&(unordered, resource, rest): &Shape, address: u64) -> View { | ||
| 1134 | let mut desc = [0u32; 16]; | ||
| 1135 | desc[..10].copy_from_slice(&rest[..10]); | ||
| 1136 | (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); | ||
| 1137 | desc[12..].copy_from_slice(&rest[10..]); | ||
| 1138 | View::Placed(unordered, resource, desc) | ||
| 1139 | } | ||
| 1140 | |||
| 1128 | /// The record words that name the view of placed memory at `address` with | 1141 | /// The record words that name the view of placed memory at `address` with |
| 1129 | /// shape number `shape`. | 1142 | /// shape number `shape`. |
| 1130 | fn placed_words(shape: u32, address: u64) -> [u32; 2] { | 1143 | fn placed_words(shape: u32, address: u64) -> [u32; 2] { |
| @@ -1132,9 +1145,10 @@ fn placed_words(shape: u32, address: u64) -> [u32; 2] { | |||
| 1132 | } | 1145 | } |
| 1133 | 1146 | ||
| 1134 | impl Views { | 1147 | impl Views { |
| 1135 | /// The number of `shape`, a new one if it is not there yet; `None` when | 1148 | /// The number of `shape`, a new one if it is not there yet (`made` is |
| 1136 | /// the shapes are full (the view is then a table entry). | 1149 | /// then told it); `None` when the shapes are full (the view is then a |
| 1137 | fn shape(&mut self, shape: Shape) -> Option<u32> { | 1150 | /// table entry). |
| 1151 | fn shape(&mut self, shape: Shape, made: impl FnOnce(u32, &Shape)) -> Option<u32> { | ||
| 1138 | if let Some(&at) = self.shape_index.get(&shape) { | 1152 | if let Some(&at) = self.shape_index.get(&shape) { |
| 1139 | return Some(at); | 1153 | return Some(at); |
| 1140 | } | 1154 | } |
| @@ -1144,6 +1158,7 @@ impl Views { | |||
| 1144 | let at = self.shapes.len() as u32; | 1158 | let at = self.shapes.len() as u32; |
| 1145 | self.shapes.push(shape); | 1159 | self.shapes.push(shape); |
| 1146 | self.shape_index.insert(shape, at); | 1160 | self.shape_index.insert(shape, at); |
| 1161 | made(at, &shape); | ||
| 1147 | Some(at) | 1162 | Some(at) |
| 1148 | } | 1163 | } |
| 1149 | 1164 | ||
| @@ -1151,12 +1166,8 @@ impl Views { | |||
| 1151 | fn placed_of(&self, i: u32, generation: u32) -> Option<View> { | 1166 | fn placed_of(&self, i: u32, generation: u32) -> Option<View> { |
| 1152 | let payload = payload(i, generation); | 1167 | let payload = payload(i, generation); |
| 1153 | let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); | 1168 | let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); |
| 1154 | let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; | 1169 | let shape = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; |
| 1155 | let mut desc = [0u32; 16]; | 1170 | Some(placed_whole(shape, address)) |
| 1156 | desc[..10].copy_from_slice(&rest[..10]); | ||
| 1157 | (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); | ||
| 1158 | desc[12..].copy_from_slice(&rest[10..]); | ||
| 1159 | Some(View::Placed(unordered, resource, desc)) | ||
| 1160 | } | 1171 | } |
| 1161 | 1172 | ||
| 1162 | /// The record words of `view` as a table entry, if it has one. | 1173 | /// The record words of `view` as a table entry, if it has one. |
| @@ -1166,8 +1177,9 @@ impl Views { | |||
| 1166 | } | 1177 | } |
| 1167 | 1178 | ||
| 1168 | /// The record words of `view` as a table entry: its entry (a new or a | 1179 | /// The record words of `view` as a table entry: its entry (a new or a |
| 1169 | /// freed one if the view is not there yet) and that entry's generation. | 1180 | /// freed one if the view is not there yet; `made` is then told the |
| 1170 | fn entry(&mut self, view: View) -> [u32; 2] { | 1181 | /// entry, its generation and the view) and that entry's generation. |
| 1182 | fn entry(&mut self, view: View, made: impl FnOnce(u32, u32, &View)) -> [u32; 2] { | ||
| 1171 | let i = match self.index.get(&view) { | 1183 | let i = match self.index.get(&view) { |
| 1172 | Some(&i) => i, | 1184 | Some(&i) => i, |
| 1173 | None => { | 1185 | None => { |
| @@ -1186,12 +1198,36 @@ impl Views { | |||
| 1186 | } | 1198 | } |
| 1187 | self.index.insert(view, i); | 1199 | self.index.insert(view, i); |
| 1188 | // (A reused entry keeps the generation `forget` gave it.) | 1200 | // (A reused entry keeps the generation `forget` gave it.) |
| 1189 | view_generation_set(i, self.list[i as usize].1); | 1201 | let (view, generation) = &self.list[i as usize]; |
| 1202 | made(i, *generation, view); | ||
| 1190 | i | 1203 | i |
| 1191 | } | 1204 | } |
| 1192 | }; | 1205 | }; |
| 1193 | [i, self.list[i as usize].1] | 1206 | [i, self.list[i as usize].1] |
| 1194 | } | 1207 | } |
| 1208 | |||
| 1209 | /// `resource` was released: the entries naming it are free for reuse, | ||
| 1210 | /// each under a new generation, which `freed` is told with the entry. | ||
| 1211 | fn forget(&mut self, resource: usize, mut freed: impl FnMut(u32, u32)) { | ||
| 1212 | let Some(entries) = self.by_resource.remove(&resource) else { | ||
| 1213 | return; | ||
| 1214 | }; | ||
| 1215 | for i in entries { | ||
| 1216 | let (view, generation) = self.list[i as usize].clone(); | ||
| 1217 | // Entries freed through a view's other resource may hold another | ||
| 1218 | // view by now. | ||
| 1219 | if self.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { | ||
| 1220 | continue; | ||
| 1221 | } | ||
| 1222 | self.index.remove(&view); | ||
| 1223 | // (Below the bits that say a record is no table entry.) | ||
| 1224 | self.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); | ||
| 1225 | freed(i, self.list[i as usize].1); | ||
| 1226 | // The view's other resource (a counter) keeps a stale entry, which | ||
| 1227 | // `forget` of that resource skips. | ||
| 1228 | self.free.push(i); | ||
| 1229 | } | ||
| 1230 | } | ||
| 1195 | } | 1231 | } |
| 1196 | 1232 | ||
| 1197 | /// The two words that name `view` in a record: the view itself where its | 1233 | /// The two words that name `view` in a record: the view itself where its |
| @@ -1232,8 +1268,388 @@ fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { | |||
| 1232 | VIEWS.read().unwrap_or_else(|e| e.into_inner()) | 1268 | VIEWS.read().unwrap_or_else(|e| e.into_inner()) |
| 1233 | } | 1269 | } |
| 1234 | 1270 | ||
| 1235 | fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { | 1271 | /// [`VIEWS`] held alone. What is made and freed through it is published as well ([`PUBLISHED`]), whatever |
| 1236 | VIEWS.write().unwrap_or_else(|e| e.into_inner()) | 1272 | /// [`list_lock_fast`] says at the time: a reader that takes no lock must find every shape and entry there is |
| 1273 | /// whenever it is switched on. (A table of a test's own is a plain [`Views`], and tells only whom its test names.) | ||
| 1274 | struct ViewsWrite(std::sync::RwLockWriteGuard<'static, Views>); | ||
| 1275 | |||
| 1276 | fn views_write() -> ViewsWrite { | ||
| 1277 | ViewsWrite(VIEWS.write().unwrap_or_else(|e| e.into_inner())) | ||
| 1278 | } | ||
| 1279 | |||
| 1280 | impl ViewsWrite { | ||
| 1281 | /// [`Views::shape`]; a new shape is published. | ||
| 1282 | fn shape(&mut self, shape: Shape) -> Option<u32> { | ||
| 1283 | self.0.shape(shape, |number, made| PUBLISHED.shape_made(number, made)) | ||
| 1284 | } | ||
| 1285 | |||
| 1286 | /// [`Views::entry`]; an entry made for the view is published. | ||
| 1287 | fn entry(&mut self, view: View) -> [u32; 2] { | ||
| 1288 | self.0.entry(view, |i, generation, made| { | ||
| 1289 | view_generation_set(i, generation); | ||
| 1290 | PUBLISHED.entry_made(i, generation, made); | ||
| 1291 | }) | ||
| 1292 | } | ||
| 1293 | |||
| 1294 | /// [`Views::forget`]; every entry it frees is published as free. | ||
| 1295 | fn forget(&mut self, resource: usize) { | ||
| 1296 | self.0.forget(resource, |i, generation| { | ||
| 1297 | view_generation_set(i, generation); | ||
| 1298 | PUBLISHED.entry_freed(i, generation); | ||
| 1299 | }); | ||
| 1300 | } | ||
| 1301 | } | ||
| 1302 | |||
| 1303 | /// Whether the list threads read what a draw looks up most without the locks they took for it. Here that is a | ||
| 1304 | /// view by its record words ([`view_at`]) and the placed R9G9B9E5 views of a table ([`r9_view_at`]): both come | ||
| 1305 | /// from [`PUBLISHED`], which a reader only reads. Before, each took the [`VIEWS`] read lock, two changes of one | ||
| 1306 | /// count that every list thread changes, for every slot a draw reads through a table; [`view_cache`] spares a | ||
| 1307 | /// thread that only for the entries that share none of its 8,192 places with another. `resource.rs` asks the | ||
| 1308 | /// same for its own lookups. Of the list threads' samples `view_at` was 16.7 %, the lock's contended read 4.2 % | ||
| 1309 | /// and the scan of tables for R9G9B9E5 views 2.7 % (issue 2707's profile of a standing run, six list threads). | ||
| 1310 | /// On by default; `LEONIDA_LIST_LOCK_FAST=0` takes the locks as before; by turns under A/B (the table is | ||
| 1311 | /// published either way, so a reader finds all of it whenever this comes on). | ||
| 1312 | pub(crate) fn list_lock_fast() -> bool { | ||
| 1313 | #[cfg(test)] | ||
| 1314 | if let Some(on) = LIST_LOCK_FAST_TEST.get() { | ||
| 1315 | return on; | ||
| 1316 | } | ||
| 1317 | #[cfg(windows)] | ||
| 1318 | { | ||
| 1319 | crate::toggled!("LEONIDA_LIST_LOCK_FAST") | ||
| 1320 | } | ||
| 1321 | #[cfg(not(windows))] | ||
| 1322 | { | ||
| 1323 | static ON: std::sync::LazyLock<bool> = | ||
| 1324 | std::sync::LazyLock::new(|| std::env::var_os("LEONIDA_LIST_LOCK_FAST").is_none_or(|v| v != "0")); | ||
| 1325 | *ON | ||
| 1326 | } | ||
| 1327 | } | ||
| 1328 | |||
| 1329 | #[cfg(test)] | ||
| 1330 | thread_local! { | ||
| 1331 | /// A test's own setting of [`list_lock_fast`] on its thread. | ||
| 1332 | pub(crate) static LIST_LOCK_FAST_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; | ||
| 1333 | } | ||
| 1334 | |||
| 1335 | /// Slots in a page of [`Slots`]. | ||
| 1336 | const SLOT_PAGE: usize = 1 << 10; | ||
| 1337 | |||
| 1338 | /// The table entries [`PUBLISHED`] has slots for: the first so many of [`Views::list`]. An entry past them is | ||
| 1339 | /// read under the lock. | ||
| 1340 | const ENTRIES_PUBLISHED: usize = 1 << 20; | ||
| 1341 | |||
| 1342 | /// A table entry or a shape as a reader that takes no lock reads it: sixteen words, each only ever read and | ||
| 1343 | /// written whole, so that a reader and a writer at once are no data race, and the first of them, the head, tells | ||
| 1344 | /// a reader whether the words it read were one view. | ||
| 1345 | /// | ||
| 1346 | /// The head holds the entry's generation in its low half (a shape has none), then what the other words hold | ||
| 1347 | /// ([`Slot::HELD`]), [`Slot::MARKED`], [`Slot::R9`], and from [`Slot::TURN`] up a count of the views the slot was | ||
| 1348 | /// given. The other words are the view's own, two of them to each ([`Slot::hold`]). | ||
| 1349 | /// | ||
| 1350 | /// The writers (one at a time: they hold the [`VIEWS`] write lock) change those words only between two heads: one | ||
| 1351 | /// that says the slot holds no view, then the one that names the new view, a turn on. A reader looks at the head, | ||
| 1352 | /// reads the words it names and looks at the head again ([`Slot::view`]). The same head both times says that no | ||
| 1353 | /// word changed between the looks: a word changes only after a head that holds nothing was stored, and no head | ||
| 1354 | /// that names a view comes twice (the generations go round in 2^30 - 1 steps and the turns in 2^27, so the same | ||
| 1355 | /// pair comes again after 2^27 * (2^30 - 1) views in the one slot, over 10^17). Every load is `Acquire` and every | ||
| 1356 | /// store `Release`, the words' too: a reader that read a word of a later view has thereby seen the head stored | ||
| 1357 | /// that emptied the slot for it, so its second look cannot find the old head (with `Relaxed` words the memory | ||
| 1358 | /// model would let it). | ||
| 1359 | /// | ||
| 1360 | /// 128 bytes on a 64-byte boundary: the head and a view of a resource object are one cache line, and a writer at | ||
| 1361 | /// the next slot takes none of a reader's. | ||
| 1362 | #[repr(align(64))] | ||
| 1363 | struct Slot([AtomicU64; 16]); | ||
| 1364 | |||
| 1365 | impl Slot { | ||
| 1366 | /// Where the head says what the words hold: 0 nothing, else 1 to 6, the kinds of [`View`] in their order. | ||
| 1367 | const HELD: u32 = 32; | ||
| 1368 | /// In the head: the view has a description of its own (a view of a resource object), or is unordered access | ||
| 1369 | /// (a view of placed memory). | ||
| 1370 | const MARKED: u64 = 1 << 35; | ||
| 1371 | /// In the head: a shader view of a placed R9G9B9E5 texture ([`View::r9_placed`]). | ||
| 1372 | const R9: u64 = 1 << 36; | ||
| 1373 | /// In the head, from this bit up: one more for every view the slot was given. | ||
| 1374 | const TURN: u64 = 1 << 37; | ||
| 1375 | /// The reads of a slot that a writer may overtake before the answer is left to the lock. | ||
| 1376 | const READS: usize = 3; | ||
| 1377 | |||
| 1378 | const fn new() -> Self { | ||
| 1379 | Self([const { AtomicU64::new(0) }; 16]) | ||
| 1380 | } | ||
| 1381 | |||
| 1382 | /// Stores `words` in the slot's words from `at` on, two to each. | ||
| 1383 | fn put(&self, at: usize, words: &[u32]) { | ||
| 1384 | debug_assert!(at >= 1 && at + words.len().div_ceil(2) <= self.0.len()); | ||
| 1385 | for (to, pair) in self.0[at..].iter().zip(words.chunks(2)) { | ||
| 1386 | let high = pair.get(1).copied().map_or(0, u64::from); | ||
| 1387 | to.store(u64::from(pair[0]) | high << 32, Release); | ||
| 1388 | } | ||
| 1389 | } | ||
| 1390 | |||
| 1391 | /// The `N` words [`Slot::put`] stored from `at` on. | ||
| 1392 | fn get<const N: usize>(&self, at: usize) -> [u32; N] { | ||
| 1393 | debug_assert!(at >= 1 && at + N.div_ceil(2) <= self.0.len()); | ||
| 1394 | let mut words = [0; N]; | ||
| 1395 | for (pair, from) in words.chunks_mut(2).zip(&self.0[at..]) { | ||
| 1396 | let both = from.load(Acquire); | ||
| 1397 | pair[0] = both as u32; | ||
| 1398 | if let Some(high) = pair.get_mut(1) { | ||
| 1399 | *high = (both >> 32) as u32; | ||
| 1400 | } | ||
| 1401 | } | ||
| 1402 | words | ||
| 1403 | } | ||
| 1404 | |||
| 1405 | /// The slot holds no view from now on, at `generation`. The turn its head is at. | ||
| 1406 | fn clear(&self, generation: u32) -> u64 { | ||
| 1407 | let turn = self.0[0].load(Acquire) & !(Self::TURN - 1); | ||
| 1408 | self.0[0].store(turn | u64::from(generation), Release); | ||
| 1409 | turn | ||
| 1410 | } | ||
| 1411 | |||
| 1412 | /// Gives the slot `view` at `generation`: the view's words under a head that holds nothing (whatever the | ||
| 1413 | /// slot held), then the head that names them. | ||
| 1414 | fn hold(&self, generation: u32, view: &View) { | ||
| 1415 | let turn = self.clear(generation); | ||
| 1416 | let (kind, marked): (u64, bool) = match view { | ||
| 1417 | View::Constant(address, size) => { | ||
| 1418 | self.0[1].store(*address, Release); | ||
| 1419 | self.0[2].store(u64::from(*size), Release); | ||
| 1420 | (1, false) | ||
| 1421 | } | ||
| 1422 | View::Shader(resource, desc) => { | ||
| 1423 | self.0[1].store(*resource as u64, Release); | ||
| 1424 | if let Some(desc) = desc { | ||
| 1425 | self.put(2, desc); | ||
| 1426 | } | ||
| 1427 | (2, desc.is_some()) | ||
| 1428 | } | ||
| 1429 | View::Unordered(resource, counter, desc) => { | ||
| 1430 | self.0[1].store(*resource as u64, Release); | ||
| 1431 | self.0[2].store(*counter as u64, Release); | ||
| 1432 | if let Some(desc) = desc { | ||
| 1433 | self.put(3, desc); | ||
| 1434 | } | ||
| 1435 | (3, desc.is_some()) | ||
| 1436 | } | ||
| 1437 | View::Sampler(desc) => { | ||
| 1438 | self.put(1, desc); | ||
| 1439 | (4, false) | ||
| 1440 | } | ||
| 1441 | View::ConsoleSampler(desc) => { | ||
| 1442 | self.put(1, desc); | ||
| 1443 | (5, false) | ||
| 1444 | } | ||
| 1445 | View::Placed(unordered, resource, desc) => { | ||
| 1446 | self.put(1, resource); | ||
| 1447 | self.put(8, desc); | ||
| 1448 | (6, *unordered) | ||
| 1449 | } | ||
| 1450 | }; | ||
| 1451 | let mut head = turn.wrapping_add(Self::TURN) | kind << Self::HELD | u64::from(generation); | ||
| 1452 | if marked { | ||
| 1453 | head |= Self::MARKED; | ||
| 1454 | } | ||
| 1455 | if view.r9_placed() { | ||
| 1456 | head |= Self::R9; | ||
| 1457 | } | ||
| 1458 | self.0[0].store(head, Release); | ||
| 1459 | } | ||
| 1460 | |||
| 1461 | /// The view the slot's words hold, as the head `head` names it; `None` if that names none. | ||
| 1462 | fn held(&self, head: u64) -> Option<View> { | ||
| 1463 | let marked = head & Self::MARKED != 0; | ||
| 1464 | Some(match head >> Self::HELD & 7 { | ||
| 1465 | 1 => View::Constant(self.0[1].load(Acquire), self.0[2].load(Acquire) as u32), | ||
| 1466 | 2 => View::Shader(self.0[1].load(Acquire) as usize, marked.then(|| self.get(2))), | ||
| 1467 | 3 => View::Unordered( | ||
| 1468 | self.0[1].load(Acquire) as usize, | ||
| 1469 | self.0[2].load(Acquire) as usize, | ||
| 1470 | marked.then(|| self.get(3)), | ||
| 1471 | ), | ||
| 1472 | 4 => View::Sampler(self.get(1)), | ||
| 1473 | 5 => View::ConsoleSampler(self.get(1)), | ||
| 1474 | 6 => View::Placed(marked, self.get(1), self.get(8)), | ||
| 1475 | _ => return None, | ||
| 1476 | }) | ||
| 1477 | } | ||
| 1478 | |||
| 1479 | /// The view the slot holds at `generation`; with `r9`, only a shader view of a placed R9G9B9E5 texture, which | ||
| 1480 | /// the head says before a word is read. `Some(None)`: it holds no such view at that generation (another | ||
| 1481 | /// generation's, or none: a freed entry names nothing until it is used again). `None`: the slot changed under | ||
| 1482 | /// each of [`Slot::READS`] reads, and the caller asks under the lock. `between` is called between reading the | ||
| 1483 | /// words and the second look at the head (for the tests: a writer there). | ||
| 1484 | fn view(&self, generation: u32, r9: bool, mut between: impl FnMut()) -> Option<Option<View>> { | ||
| 1485 | for _ in 0..Self::READS { | ||
| 1486 | let head = self.0[0].load(Acquire); | ||
| 1487 | if head as u32 != generation || (r9 && head & Self::R9 == 0) { | ||
| 1488 | return Some(None); | ||
| 1489 | } | ||
| 1490 | let Some(view) = self.held(head) else { | ||
| 1491 | return Some(None); | ||
| 1492 | }; | ||
| 1493 | between(); | ||
| 1494 | if self.0[0].load(Acquire) == head { | ||
| 1495 | return Some(Some(view)); | ||
| 1496 | } | ||
| 1497 | } | ||
| 1498 | None | ||
| 1499 | } | ||
| 1500 | } | ||
| 1501 | |||
| 1502 | /// [`Slot`]s by number, in pages of [`SLOT_PAGE`] that are made as their numbers come into use and kept for the | ||
| 1503 | /// run: a slot never moves and is never freed, so a reader keeps it without a lock. | ||
| 1504 | struct Slots<const PAGES: usize>([AtomicPtr<Slot>; PAGES]); | ||
| 1505 | |||
| 1506 | impl<const PAGES: usize> Slots<PAGES> { | ||
| 1507 | const fn new() -> Self { | ||
| 1508 | Self([const { AtomicPtr::<Slot>::new(std::ptr::null_mut()) }; PAGES]) | ||
| 1509 | } | ||
| 1510 | |||
| 1511 | /// Slot `at`, if its page was made. | ||
| 1512 | fn get(&self, at: usize) -> Option<&Slot> { | ||
| 1513 | let page = self.0.get(at / SLOT_PAGE)?.load(Acquire); | ||
| 1514 | if page.is_null() { | ||
| 1515 | return None; | ||
| 1516 | } | ||
| 1517 | // SAFETY: a page that was stored is `SLOT_PAGE` slots, never freed or moved. | ||
| 1518 | Some(unsafe { &*page.add(at % SLOT_PAGE) }) | ||
| 1519 | } | ||
| 1520 | |||
| 1521 | /// Slot `at`, its page made if it was not there; `None` past the last page. | ||
| 1522 | fn make(&self, at: usize) -> Option<&Slot> { | ||
| 1523 | let place = self.0.get(at / SLOT_PAGE)?; | ||
| 1524 | let mut page = place.load(Acquire); | ||
| 1525 | if page.is_null() { | ||
| 1526 | let made = Box::into_raw((0..SLOT_PAGE).map(|_| Slot::new()).collect::<Box<[Slot]>>()); | ||
| 1527 | page = match place.compare_exchange(page, made.cast(), AcqRel, Acquire) { | ||
| 1528 | Ok(_) => made.cast(), | ||
| 1529 | // Another thread's page came first (not in the run: the writers hold a lock). That one it is. | ||
| 1530 | Err(first) => { | ||
| 1531 | // SAFETY: from `Box::into_raw` just above, and stored nowhere. | ||
| 1532 | drop(unsafe { Box::from_raw(made) }); | ||
| 1533 | first | ||
| 1534 | } | ||
| 1535 | }; | ||
| 1536 | } | ||
| 1537 | // SAFETY: as in `get`. | ||
| 1538 | Some(unsafe { &*page.add(at % SLOT_PAGE) }) | ||
| 1539 | } | ||
| 1540 | } | ||
| 1541 | |||
| 1542 | /// What of a table of views a reader finds without its lock, kept by the table's writers: `S` pages of the shapes | ||
| 1543 | /// of placed views by their number, each as the view it gives at address 0 and written once; `E` pages of the | ||
| 1544 | /// table's entries by their index, each with its generation; and whether a shader view of a placed R9G9B9E5 | ||
| 1545 | /// texture was ever among either. Whole cache lines of its own: what every lookup reads here (where the first | ||
| 1546 | /// pages are, that flag) is written a few times in a run, and shares no line with a neighbor written more often. | ||
| 1547 | #[repr(align(64))] | ||
| 1548 | struct Published<const S: usize, const E: usize> { | ||
| 1549 | shapes: Slots<S>, | ||
| 1550 | entries: Slots<E>, | ||
| 1551 | r9: AtomicBool, | ||
| 1552 | } | ||
| 1553 | |||
| 1554 | /// [`VIEWS`] as published ([`ViewsWrite`]): every shape it can number, and its first [`ENTRIES_PUBLISHED`] entries. | ||
| 1555 | static PUBLISHED: Published<{ SHAPES / SLOT_PAGE }, { ENTRIES_PUBLISHED / SLOT_PAGE }> = Published::new(); | ||
| 1556 | |||
| 1557 | impl<const S: usize, const E: usize> Published<S, E> { | ||
| 1558 | const fn new() -> Self { | ||
| 1559 | Self { shapes: Slots::new(), entries: Slots::new(), r9: AtomicBool::new(false) } | ||
| 1560 | } | ||
| 1561 | |||
| 1562 | /// If `view` is a shader view of a placed R9G9B9E5 texture: there is one from now on. Said before the view | ||
| 1563 | /// itself is published, so that whoever has its record words finds it said. | ||
| 1564 | fn r9_made(&self, view: &View) { | ||
| 1565 | if view.r9_placed() && !self.r9.load(Acquire) { | ||
| 1566 | self.r9.store(true, Release); | ||
| 1567 | } | ||
| 1568 | } | ||
| 1569 | |||
| 1570 | /// Whether a shader view of a placed R9G9B9E5 texture was ever made. | ||
| 1571 | #[cfg(any(windows, test))] | ||
| 1572 | fn any_r9(&self) -> bool { | ||
| 1573 | self.r9.load(Acquire) | ||
| 1574 | } | ||
| 1575 | |||
| 1576 | /// Shape `number` is `shape`, for good. | ||
| 1577 | fn shape_made(&self, number: u32, shape: &Shape) { | ||
| 1578 | let view = placed_whole(shape, 0); | ||
| 1579 | self.r9_made(&view); | ||
| 1580 | // (Once: a shape never changes once it has a number.) | ||
| 1581 | if let Some(slot) = self.shapes.make(number as usize) | ||
| 1582 | && slot.0[0].load(Acquire) == 0 | ||
| 1583 | { | ||
| 1584 | slot.hold(0, &view); | ||
| 1585 | } | ||
| 1586 | } | ||
| 1587 | |||
| 1588 | /// Entry `i` holds `view` at `generation` from now on. | ||
| 1589 | fn entry_made(&self, i: u32, generation: u32, view: &View) { | ||
| 1590 | self.r9_made(view); | ||
| 1591 | if let Some(slot) = self.entries.make(i as usize) { | ||
| 1592 | slot.hold(generation, view); | ||
| 1593 | } | ||
| 1594 | } | ||
| 1595 | |||
| 1596 | /// Entry `i` is free, at `generation`: the record words of the view it held name nothing from now on. | ||
| 1597 | fn entry_freed(&self, i: u32, generation: u32) { | ||
| 1598 | if let Some(slot) = self.entries.get(i as usize) { | ||
| 1599 | slot.clear(generation); | ||
| 1600 | } | ||
| 1601 | } | ||
| 1602 | |||
| 1603 | /// The view of placed memory the record words name ([`placed_words`]), from its shape; with `r9`, only a | ||
| 1604 | /// shader view of an R9G9B9E5 texture, which the head says before a word is read. (One look at the head: a | ||
| 1605 | /// shape's slot does not change once written.) | ||
| 1606 | fn placed(&self, i: u32, generation: u32, r9: bool) -> Option<View> { | ||
| 1607 | let payload = payload(i, generation); | ||
| 1608 | let slot = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; | ||
| 1609 | let head = slot.0[0].load(Acquire); | ||
| 1610 | if r9 && head & Slot::R9 == 0 { | ||
| 1611 | return None; | ||
| 1612 | } | ||
| 1613 | let View::Placed(unordered, resource, mut desc) = slot.held(head)? else { | ||
| 1614 | return None; | ||
| 1615 | }; | ||
| 1616 | let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); | ||
| 1617 | (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); | ||
| 1618 | Some(View::Placed(unordered, resource, desc)) | ||
| 1619 | } | ||
| 1620 | |||
| 1621 | /// Entry `i`'s view if `generation` is still its own, as [`Slot::view`] answers; `None` also for an entry | ||
| 1622 | /// past the published ones: the caller asks under the lock. | ||
| 1623 | fn entry(&self, i: u32, generation: u32, r9: bool) -> Option<Option<View>> { | ||
| 1624 | if i as usize >= E * SLOT_PAGE { | ||
| 1625 | return None; | ||
| 1626 | } | ||
| 1627 | match self.entries.get(i as usize) { | ||
| 1628 | Some(slot) => slot.view(generation, r9, || ()), | ||
| 1629 | // No entry of that page was made yet. | ||
| 1630 | None => Some(None), | ||
| 1631 | } | ||
| 1632 | } | ||
| 1633 | } | ||
| 1634 | |||
| 1635 | /// Entry `i`'s view if `generation` is still its own, under the lock. | ||
| 1636 | fn entry_locked(i: u32, generation: u32) -> Option<View> { | ||
| 1637 | let views = views_read(); | ||
| 1638 | let (view, current) = views.list.get(i as usize)?; | ||
| 1639 | (*current == generation).then(|| view.clone()) | ||
| 1640 | } | ||
| 1641 | |||
| 1642 | /// Entry `i`'s view if `generation` is still its own (with `r9`, only a shader view of a placed R9G9B9E5 | ||
| 1643 | /// texture), from `published` ([`PUBLISHED`], or a test's smaller one), and under the lock where that leaves it. | ||
| 1644 | fn entry_at<const S: usize, const E: usize>( | ||
| 1645 | published: &Published<S, E>, | ||
| 1646 | i: u32, | ||
| 1647 | generation: u32, | ||
| 1648 | r9: bool, | ||
| 1649 | ) -> Option<View> { | ||
| 1650 | published | ||
| 1651 | .entry(i, generation, r9) | ||
| 1652 | .unwrap_or_else(|| entry_locked(i, generation).filter(|view| !r9 || view.r9_placed())) | ||
| 1237 | } | 1653 | } |
| 1238 | 1654 | ||
| 1239 | /// Whether [`view_at`] answers from what this thread read before: table entries from [`VIEW_CACHED`] while their | 1655 | /// Whether [`view_at`] answers from what this thread read before: table entries from [`VIEW_CACHED`] while their |
| @@ -1242,6 +1658,7 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { | |||
| 1242 | /// two changes of one count that all the list threads change, `view_at` 2.2 % of their samples on its own (profile | 1658 | /// two changes of one count that all the list threads change, `view_at` 2.2 % of their samples on its own (profile |
| 1243 | /// `listdrs`, 2026-11-29). From ReZOnGithub/VIctory-lap (GPL-3.0-or-later): the cache of table entries checked by | 1659 | /// `listdrs`, 2026-11-29). From ReZOnGithub/VIctory-lap (GPL-3.0-or-later): the cache of table entries checked by |
| 1244 | /// generation and the shapes per thread (242d0c6). Off unless `LEONIDA_VIEW_CACHE=1`; by turns under A/B. | 1660 | /// generation and the shapes per thread (242d0c6). Off unless `LEONIDA_VIEW_CACHE=1`; by turns under A/B. |
| 1661 | /// (Asked only with [`list_lock_fast`] off: with it on, nothing here is read.) | ||
| 1245 | fn view_cache() -> bool { | 1662 | fn view_cache() -> bool { |
| 1246 | #[cfg(windows)] | 1663 | #[cfg(windows)] |
| 1247 | { | 1664 | { |
| @@ -1259,8 +1676,8 @@ const VIEW_GENERATIONS_HELD: usize = 1 << 20; | |||
| 1259 | 1676 | ||
| 1260 | /// The generation of each of the first [`VIEW_GENERATIONS_HELD`] table entries ([`Views::list`]), read without the | 1677 | /// The generation of each of the first [`VIEW_GENERATIONS_HELD`] table entries ([`Views::list`]), read without the |
| 1261 | /// lock by [`view_cached`]. Fixed in size, so it never moves while read. Stored under the write lock wherever an | 1678 | /// lock by [`view_cached`]. Fixed in size, so it never moves while read. Stored under the write lock wherever an |
| 1262 | /// entry's generation is set: [`Views::entry`] when it makes or reuses one, [`forget`] when it gives one a new | 1679 | /// entry's generation is set ([`ViewsWrite`]): when an entry is made or reused, and when [`forget`] gives one a |
| 1263 | /// generation. Kept whether the cache is on or not, so that [`view_cache`] can change by turns. 0: no entry. | 1680 | /// new generation. Kept whether the cache is on or not, so that [`view_cache`] can change by turns. 0: no entry. |
| 1264 | static VIEW_GENERATIONS: std::sync::LazyLock<Box<[std::sync::atomic::AtomicU32]>> = | 1681 | static VIEW_GENERATIONS: std::sync::LazyLock<Box<[std::sync::atomic::AtomicU32]>> = |
| 1265 | std::sync::LazyLock::new(|| (0..VIEW_GENERATIONS_HELD).map(|_| std::sync::atomic::AtomicU32::new(0)).collect()); | 1682 | std::sync::LazyLock::new(|| (0..VIEW_GENERATIONS_HELD).map(|_| std::sync::atomic::AtomicU32::new(0)).collect()); |
| 1266 | 1683 | ||
| @@ -1342,7 +1759,7 @@ fn placed_at(i: u32, generation: u32) -> Option<View> { | |||
| 1342 | let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); | 1759 | let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); |
| 1343 | let number = (payload >> PLACED_ADDRESS_BITS) as usize; | 1760 | let number = (payload >> PLACED_ADDRESS_BITS) as usize; |
| 1344 | let seen = SHAPES_SEEN.with_borrow(|s| s.get(number).copied().flatten()); | 1761 | let seen = SHAPES_SEEN.with_borrow(|s| s.get(number).copied().flatten()); |
| 1345 | let (unordered, resource, rest) = match seen { | 1762 | let shape = match seen { |
| 1346 | Some(shape) => shape, | 1763 | Some(shape) => shape, |
| 1347 | None => { | 1764 | None => { |
| 1348 | let shape = *views_read().shapes.get(number)?; | 1765 | let shape = *views_read().shapes.get(number)?; |
| @@ -1355,11 +1772,7 @@ fn placed_at(i: u32, generation: u32) -> Option<View> { | |||
| 1355 | shape | 1772 | shape |
| 1356 | } | 1773 | } |
| 1357 | }; | 1774 | }; |
| 1358 | let mut desc = [0u32; 16]; | 1775 | Some(placed_whole(&shape, address)) |
| 1359 | desc[..10].copy_from_slice(&rest[..10]); | ||
| 1360 | (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); | ||
| 1361 | desc[12..].copy_from_slice(&rest[10..]); | ||
| 1362 | Some(View::Placed(unordered, resource, desc)) | ||
| 1363 | } | 1776 | } |
| 1364 | 1777 | ||
| 1365 | /// Which of six kinds [`kept`] counts a view under: [`KIND_CONSTANT`], | 1778 | /// Which of six kinds [`kept`] counts a view under: [`KIND_CONSTANT`], |
| @@ -1496,6 +1909,13 @@ impl View { | |||
| 1496 | } | 1909 | } |
| 1497 | } | 1910 | } |
| 1498 | 1911 | ||
| 1912 | /// Whether this is a shader view of a placed R9G9B9E5 texture: of placed | ||
| 1913 | /// memory that is no buffer (dimension 1), in format 67. A draw's table | ||
| 1914 | /// is looked through for these (`host::table_r9g9b9e5_views`). | ||
| 1915 | fn r9_placed(&self) -> bool { | ||
| 1916 | matches!(self, View::Placed(false, resource, _) if resource[0] != 1 && resource[8] == 67) | ||
| 1917 | } | ||
| 1918 | |||
| 1499 | /// The texture object the view is of, if that texture has no host copy | 1919 | /// The texture object the view is of, if that texture has no host copy |
| 1500 | /// yet (`crate::resource::host_waits`): a slot written with such a | 1920 | /// yet (`crate::resource::host_waits`): a slot written with such a |
| 1501 | /// view is left null until the texture is first used. | 1921 | /// view is left null until the texture is first used. |
| @@ -1618,30 +2038,23 @@ pub(crate) fn forget(resource: usize) { | |||
| 1618 | .lock() | 2038 | .lock() |
| 1619 | .unwrap_or_else(|e| e.into_inner()) | 2039 | .unwrap_or_else(|e| e.into_inner()) |
| 1620 | .remove(&resource); | 2040 | .remove(&resource); |
| 1621 | let mut views = views_write(); | 2041 | views_write().forget(resource); |
| 1622 | let Some(entries) = views.by_resource.remove(&resource) else { | ||
| 1623 | return; | ||
| 1624 | }; | ||
| 1625 | for i in entries { | ||
| 1626 | let (view, generation) = views.list[i as usize].clone(); | ||
| 1627 | // Entries freed through a view's other resource may hold another | ||
| 1628 | // view by now. | ||
| 1629 | if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { | ||
| 1630 | continue; | ||
| 1631 | } | ||
| 1632 | views.index.remove(&view); | ||
| 1633 | // (Below the bits that say a record is no table entry.) | ||
| 1634 | views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); | ||
| 1635 | view_generation_set(i, views.list[i as usize].1); | ||
| 1636 | // The view's other resource (a counter) keeps a stale entry, which | ||
| 1637 | // `forget` of that resource skips. | ||
| 1638 | views.free.push(i); | ||
| 1639 | } | ||
| 1640 | } | 2042 | } |
| 1641 | 2043 | ||
| 1642 | /// The view the record words `i` and `generation` name: the one they hold | 2044 | /// The view the record words `i` and `generation` name: the one they hold |
| 1643 | /// whole, or the view of entry `i` if `generation` is still its own. | 2045 | /// whole, or the view of entry `i` if `generation` is still its own. A table |
| 2046 | /// entry and the shape of a view of placed memory are read as published, | ||
| 2047 | /// without a lock ([`list_lock_fast`]; an entry [`PUBLISHED`] leaves to the | ||
| 2048 | /// lock, under it); with that off, under the lock or from this thread's | ||
| 2049 | /// cache as before ([`view_cache`]). | ||
| 1644 | fn view_at(i: u32, generation: u32) -> Option<View> { | 2050 | fn view_at(i: u32, generation: u32) -> Option<View> { |
| 2051 | if list_lock_fast() { | ||
| 2052 | match generation >> KIND_SHIFT { | ||
| 2053 | 0 => return entry_at(&PUBLISHED, i, generation, false), | ||
| 2054 | PLACED => return PUBLISHED.placed(i, generation, false), | ||
| 2055 | _ => {} | ||
| 2056 | } | ||
| 2057 | } | ||
| 1645 | let cache = view_cache(); | 2058 | let cache = view_cache(); |
| 1646 | match generation >> KIND_SHIFT { | 2059 | match generation >> KIND_SHIFT { |
| 1647 | 0 => { | 2060 | 0 => { |
| @@ -1669,6 +2082,26 @@ fn view_at(i: u32, generation: u32) -> Option<View> { | |||
| 1669 | } | 2082 | } |
| 1670 | } | 2083 | } |
| 1671 | 2084 | ||
| 2085 | /// Whether a shader view of a placed R9G9B9E5 texture was ever made, as a shape or as a table entry. While none | ||
| 2086 | /// was, no record names one, and a table need not be looked through for them (`host::table_r9g9b9e5_views`). | ||
| 2087 | /// Not taken back: a view of placed memory has nothing that releases it. | ||
| 2088 | #[cfg(windows)] | ||
| 2089 | fn any_r9_views() -> bool { | ||
| 2090 | PUBLISHED.any_r9() | ||
| 2091 | } | ||
| 2092 | |||
| 2093 | /// The view the record words `i` and `generation` name, if it is a shader view of a placed R9G9B9E5 texture | ||
| 2094 | /// ([`View::r9_placed`]). Read as [`view_at`] reads with [`list_lock_fast`] on, whatever the switch says (what it | ||
| 2095 | /// reads is published either way): the slot's head says whether the view is one before a word of it is read. | ||
| 2096 | #[cfg(windows)] | ||
| 2097 | fn r9_view_at(i: u32, generation: u32) -> Option<View> { | ||
| 2098 | match generation >> KIND_SHIFT { | ||
| 2099 | 0 => entry_at(&PUBLISHED, i, generation, true), | ||
| 2100 | PLACED => PUBLISHED.placed(i, generation, true), | ||
| 2101 | _ => None, | ||
| 2102 | } | ||
| 2103 | } | ||
| 2104 | |||
| 1672 | /// The words of the record at `handle`, if they are a view's. | 2105 | /// The words of the record at `handle`, if they are a view's. |
| 1673 | pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { | 2106 | pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { |
| 1674 | if handle == 0 { | 2107 | if handle == 0 { |
| @@ -2269,7 +2702,7 @@ mod tests { | |||
| 2269 | #[test] | 2702 | #[test] |
| 2270 | fn a_null_constant_view_replaces_the_view_there_before() { | 2703 | fn a_null_constant_view_replaces_the_view_there_before() { |
| 2271 | let null = std::ptr::null(); | 2704 | let null = std::ptr::null(); |
| 2272 | let slots = vec![0u64; 2 * 4]; | 2705 | let slots = [0u64; 2 * 4]; |
| 2273 | let at = slots.as_ptr() as u64; | 2706 | let at = slots.as_ptr() as u64; |
| 2274 | create_cbv(null, &[0x1000, 1, 256, 0], at); | 2707 | create_cbv(null, &[0x1000, 1, 256, 0], at); |
| 2275 | assert_eq!(view(at), Some(View::Constant(0x1_0000_1000, 256))); | 2708 | assert_eq!(view(at), Some(View::Constant(0x1_0000_1000, 256))); |
| @@ -2539,6 +2972,649 @@ mod tests { | |||
| 2539 | } | 2972 | } |
| 2540 | } | 2973 | } |
| 2541 | 2974 | ||
| 2975 | /// A table of a test's own, with nothing in it. | ||
| 2976 | fn no_views() -> Views { | ||
| 2977 | Views { | ||
| 2978 | list: Vec::new(), | ||
| 2979 | index: Default::default(), | ||
| 2980 | by_resource: Default::default(), | ||
| 2981 | free: Vec::new(), | ||
| 2982 | shapes: Vec::new(), | ||
| 2983 | shape_index: Default::default(), | ||
| 2984 | } | ||
| 2985 | } | ||
| 2986 | |||
| 2987 | /// A shader view of a placed 2D texture in `format` (67: R9G9B9E5) at `address`. | ||
| 2988 | fn placed_view(format: u32, address: u64) -> View { | ||
| 2989 | let texture = [3, 0, 0, 0, 8, 0, 8, 0x1_0001, format, 1, 0, 0, 0, 0]; | ||
| 2990 | let desc = [format, 4, 0x1688, 0, 0, 1, 0, 0, 0, 0, address as u32, (address >> 32) as u32, 0, 0, 0, 0]; | ||
| 2991 | View::Placed(false, texture, desc) | ||
| 2992 | } | ||
| 2993 | |||
| 2994 | /// The record words that name `view`, a view of placed memory, by its shape in the real table (whatever | ||
| 2995 | /// `LEONIDA_VIEW_INLINE` says). | ||
| 2996 | fn shape_words(view: &View) -> [u32; 2] { | ||
| 2997 | let View::Placed(unordered, resource, desc) = view else { unreachable!() }; | ||
| 2998 | let (shape, address) = shape_of(*unordered, resource, desc); | ||
| 2999 | placed_words(views_write().shape(shape).expect("room for a shape"), address) | ||
| 3000 | } | ||
| 3001 | |||
| 3002 | /// A view with `n` in every word, of a kind that changes with every other `n`: words of two of them are the | ||
| 3003 | /// view of no `n`. | ||
| 3004 | fn patterned(n: u32) -> View { | ||
| 3005 | fn words<const N: usize>(n: u32) -> [u32; N] { | ||
| 3006 | std::array::from_fn(|k| n.wrapping_mul(0x9e37_79b9) ^ (k as u32) << 24) | ||
| 3007 | } | ||
| 3008 | let [a, b, c] = words(n); | ||
| 3009 | let wide = |low: u32, high: u32| u64::from(high) << 32 | u64::from(low); | ||
| 3010 | match n / 2 % 8 { | ||
| 3011 | 0 => View::Constant(wide(a, b), c), | ||
| 3012 | 1 => View::Shader(wide(a, b) as usize, None), | ||
| 3013 | 2 => View::Shader(wide(a, b) as usize, Some(words(n))), | ||
| 3014 | 3 => View::Unordered(wide(a, b) as usize, wide(b, c) as usize, None), | ||
| 3015 | 4 => View::Unordered(wide(a, b) as usize, wide(b, c) as usize, Some(words(n))), | ||
| 3016 | 5 => View::Sampler(words(n)), | ||
| 3017 | 6 => View::ConsoleSampler(words(n)), | ||
| 3018 | _ => View::Placed(n.is_multiple_of(4), words(n), words(n)), | ||
| 3019 | } | ||
| 3020 | } | ||
| 3021 | |||
| 3022 | /// Says so when it goes, also when its thread panics: the threads that wait to be told then end, and the | ||
| 3023 | /// test fails where a check failed instead of waiting for them. | ||
| 3024 | struct Ended<'a>(&'a AtomicBool); | ||
| 3025 | |||
| 3026 | impl Drop for Ended<'_> { | ||
| 3027 | fn drop(&mut self) { | ||
| 3028 | self.0.store(true, Release); | ||
| 3029 | } | ||
| 3030 | } | ||
| 3031 | |||
| 3032 | /// A slot gives back each kind of view as it was given it, whatever it held before (a small view leaves the | ||
| 3033 | /// words of a larger one behind it), and only at the generation it was given it for. | ||
| 3034 | #[test] | ||
| 3035 | fn a_slot_holds_every_kind_of_view_whole() { | ||
| 3036 | let held = Slot::new(); | ||
| 3037 | assert_eq!(held.view(0, false, || ()), Some(None), "nothing yet"); | ||
| 3038 | let views = [ | ||
| 3039 | View::Placed(true, [u32::MAX; 14], [u32::MAX; 16]), | ||
| 3040 | View::Constant(u64::MAX, u32::MAX), | ||
| 3041 | View::Shader(usize::MAX, Some([u32::MAX; 10])), | ||
| 3042 | View::Shader(1, None), | ||
| 3043 | View::Unordered(usize::MAX, usize::MAX - 1, Some(std::array::from_fn(|k| k as u32))), | ||
| 3044 | View::Unordered(2, 3, None), | ||
| 3045 | View::ConsoleSampler(std::array::from_fn(|k| !(k as u32))), | ||
| 3046 | View::Sampler(std::array::from_fn(|k| 0x8000_0000 | k as u32)), | ||
| 3047 | View::Placed(false, std::array::from_fn(|k| k as u32), std::array::from_fn(|k| 100 + k as u32)), | ||
| 3048 | View::Constant(0, 0), | ||
| 3049 | ]; | ||
| 3050 | for (generation, view) in (1..).zip(views.into_iter().chain((0..64).map(patterned))) { | ||
| 3051 | held.hold(generation, &view); | ||
| 3052 | assert_eq!(held.view(generation, false, || ()), Some(Some(view)), "generation {generation}"); | ||
| 3053 | assert_eq!(held.view(generation - 1, false, || ()), Some(None), "the generation before"); | ||
| 3054 | assert_eq!(held.view(generation + 1, false, || ()), Some(None), "the generation after"); | ||
| 3055 | } | ||
| 3056 | } | ||
| 3057 | |||
| 3058 | /// The record words of a freed entry name nothing: not at the generation it had, and not at its new one | ||
| 3059 | /// until it is used again, whatever words lie in the slot meanwhile; then the new words name the new view, | ||
| 3060 | /// and the old ones still nothing. | ||
| 3061 | #[test] | ||
| 3062 | fn a_freed_slot_names_nothing_until_it_is_used_again() { | ||
| 3063 | let held = Slot::new(); | ||
| 3064 | let (old, new) = (View::Shader(0x7b30_0000, Some([7; 10])), View::Placed(false, [8; 14], [9; 16])); | ||
| 3065 | held.hold(5, &old); | ||
| 3066 | held.clear(6); | ||
| 3067 | assert_eq!(held.view(5, false, || ()), Some(None), "stale once freed"); | ||
| 3068 | assert_eq!(held.view(6, false, || ()), Some(None), "free"); | ||
| 3069 | // As a writer leaves it between its two heads: words of the next view, under a head that holds nothing. | ||
| 3070 | held.put(1, &[8; 14]); | ||
| 3071 | assert_eq!(held.view(5, false, || ()), Some(None)); | ||
| 3072 | assert_eq!(held.view(6, false, || ()), Some(None), "words without their head"); | ||
| 3073 | held.hold(6, &new); | ||
| 3074 | assert_eq!(held.view(5, false, || ()), Some(None), "the old words find nothing"); | ||
| 3075 | assert_eq!(held.view(6, false, || ()), Some(Some(new))); | ||
| 3076 | } | ||
| 3077 | |||
| 3078 | /// A writer that frees an entry and uses it again between a reader's two looks at the head: what the reader | ||
| 3079 | /// read is not its answer (its words could be of both views), and its second read ends at the head. The | ||
| 3080 | /// same with the generation come round to what it was, as after 2^30 - 1 uses, and a view of the same kind: | ||
| 3081 | /// only the turn tells the two heads apart, and the answer is the new view. | ||
| 3082 | #[test] | ||
| 3083 | fn a_read_that_a_reuse_overtakes_is_read_again() { | ||
| 3084 | let held = Slot::new(); | ||
| 3085 | let (old, new) = (patterned(14), patterned(15)); | ||
| 3086 | held.hold(3, &old); | ||
| 3087 | let mut looks = 0; | ||
| 3088 | let found = held.view(3, false, || { | ||
| 3089 | if looks == 0 { | ||
| 3090 | held.clear(4); | ||
| 3091 | held.hold(4, &new); | ||
| 3092 | } | ||
| 3093 | looks += 1; | ||
| 3094 | }); | ||
| 3095 | assert_eq!((found, looks), (Some(None), 1), "freed: the second read ends at the head"); | ||
| 3096 | assert_eq!(held.view(4, false, || ()), Some(Some(new))); | ||
| 3097 | |||
| 3098 | let (old, new) = (patterned(30), patterned(31)); | ||
| 3099 | held.clear(9); | ||
| 3100 | held.hold(9, &old); | ||
| 3101 | let before = held.0[0].load(Acquire); | ||
| 3102 | let mut looks = 0; | ||
| 3103 | let found = held.view(9, false, || { | ||
| 3104 | if looks == 0 { | ||
| 3105 | held.clear(9); | ||
| 3106 | held.hold(9, &new); | ||
| 3107 | } | ||
| 3108 | looks += 1; | ||
| 3109 | }); | ||
| 3110 | assert_eq!(held.0[0].load(Acquire).wrapping_sub(before), Slot::TURN, "a turn on, and nothing else"); | ||
| 3111 | assert_eq!((found, looks), (Some(Some(new)), 2)); | ||
| 3112 | } | ||
| 3113 | |||
| 3114 | /// A slot that changes under every read is left to the lock after [`Slot::READS`] of them. | ||
| 3115 | #[test] | ||
| 3116 | fn a_slot_that_changes_under_every_read_is_left_to_the_lock() { | ||
| 3117 | let held = Slot::new(); | ||
| 3118 | held.hold(9, &patterned(0)); | ||
| 3119 | let mut looks = 0; | ||
| 3120 | let found = held.view(9, false, || { | ||
| 3121 | looks += 1; | ||
| 3122 | held.clear(9); | ||
| 3123 | held.hold(9, &patterned(looks)); | ||
| 3124 | }); | ||
| 3125 | assert_eq!((found, looks as usize), (None, Slot::READS)); | ||
| 3126 | assert_eq!(held.view(9, false, || ()), Some(Some(patterned(looks))), "whole, once it is left alone"); | ||
| 3127 | } | ||
| 3128 | |||
| 3129 | /// Threads that ask for a slot of one page at once get the one page; past the last page there is no slot. | ||
| 3130 | #[test] | ||
| 3131 | fn a_page_of_slots_is_made_once() { | ||
| 3132 | const AT: usize = SLOT_PAGE + 5; | ||
| 3133 | let slots = Slots::<2>::new(); | ||
| 3134 | assert!(slots.get(AT).is_none(), "no page before a slot of it is asked for"); | ||
| 3135 | let made = [const { std::sync::atomic::AtomicUsize::new(0) }; 6]; | ||
| 3136 | let gate = std::sync::Barrier::new(made.len()); | ||
| 3137 | std::thread::scope(|scope| { | ||
| 3138 | let (slots, gate) = (&slots, &gate); | ||
| 3139 | for made in &made { | ||
| 3140 | scope.spawn(move || { | ||
| 3141 | gate.wait(); | ||
| 3142 | made.store(std::ptr::from_ref(slots.make(AT).expect("in the second page")) as usize, Release); | ||
| 3143 | }); | ||
| 3144 | } | ||
| 3145 | }); | ||
| 3146 | let there = std::ptr::from_ref(slots.get(AT).expect("made")) as usize; | ||
| 3147 | assert!(made.iter().all(|made| made.load(Acquire) == there), "more pages than one"); | ||
| 3148 | assert!(slots.get(5).is_none(), "the first page was not asked for"); | ||
| 3149 | assert!(slots.make(2 * SLOT_PAGE).is_none() && slots.get(2 * SLOT_PAGE).is_none(), "past the last page"); | ||
| 3150 | } | ||
| 3151 | |||
| 3152 | /// [`Published::any_r9`] says no until a shader view of a placed R9G9B9E5 texture is made, as a shape or as a | ||
| 3153 | /// table entry (one past the published entries too: it has no slot, and is said all the same). Unordered | ||
| 3154 | /// access to such a texture and a buffer in that format are none. | ||
| 3155 | #[test] | ||
| 3156 | fn a_placed_r9_view_is_said_from_the_first_one_on() { | ||
| 3157 | let shape = |view: &View| { | ||
| 3158 | let View::Placed(unordered, resource, desc) = view else { unreachable!() }; | ||
| 3159 | shape_of(*unordered, resource, desc).0 | ||
| 3160 | }; | ||
| 3161 | let r9 = placed_view(67, 0x2_0000); | ||
| 3162 | let View::Placed(_, texture, desc) = r9.clone() else { unreachable!() }; | ||
| 3163 | let mut buffer = texture; | ||
| 3164 | buffer[0] = 1; | ||
| 3165 | let others = [placed_view(28, 0x2_0000), View::Placed(true, texture, desc), View::Placed(false, buffer, desc)]; | ||
| 3166 | let published = Published::<1, 1>::new(); | ||
| 3167 | assert!(!published.any_r9()); | ||
| 3168 | for (number, view) in (0..).zip(&others) { | ||
| 3169 | published.shape_made(number, &shape(view)); | ||
| 3170 | published.entry_made(number, 1, view); | ||
| 3171 | } | ||
| 3172 | published.entry_made(3, 1, &View::Shader(0x7b40_0000, None)); | ||
| 3173 | assert!(!published.any_r9(), "none of these is one"); | ||
| 3174 | published.shape_made(3, &shape(&r9)); | ||
| 3175 | assert!(published.any_r9(), "a shape of one"); | ||
| 3176 | |||
| 3177 | let published = Published::<1, 1>::new(); | ||
| 3178 | published.entry_made(3, 1, &r9); | ||
| 3179 | assert!(published.any_r9(), "a table entry"); | ||
| 3180 | |||
| 3181 | let published = Published::<1, 1>::new(); | ||
| 3182 | published.entry_made(SLOT_PAGE as u32, 1, &r9); | ||
| 3183 | assert!(published.any_r9(), "an entry past the published ones"); | ||
| 3184 | assert_eq!(published.entry(SLOT_PAGE as u32, 1, true), None, "which the lock answers for"); | ||
| 3185 | } | ||
| 3186 | |||
| 3187 | /// The record words of a released resource's view stay stale when a view of placed memory, which nothing | ||
| 3188 | /// releases, is the next in their entry; the reader of R9G9B9E5 views finds that view by its own words alone. | ||
| 3189 | #[test] | ||
| 3190 | fn old_words_stay_stale_when_a_placed_view_takes_their_entry() { | ||
| 3191 | let published = Published::<1, 1>::new(); | ||
| 3192 | let owned = View::Shader(0x7b50_0000, Some([3; 10])); | ||
| 3193 | let (r9, plain) = (placed_view(67, 0x3_0000), placed_view(28, 0x3_0000)); | ||
| 3194 | assert_eq!(published.entry(40, 1, false), Some(None), "no page yet"); | ||
| 3195 | published.entry_made(40, 1, &owned); | ||
| 3196 | assert_eq!(published.entry(40, 1, false), Some(Some(owned))); | ||
| 3197 | assert_eq!(published.entry(40, 1, true), Some(None), "no placed view"); | ||
| 3198 | assert_eq!(published.entry(41, 1, false), Some(None), "no entry there yet"); | ||
| 3199 | published.entry_freed(40, 2); | ||
| 3200 | for only_r9 in [false, true] { | ||
| 3201 | assert_eq!(published.entry(40, 1, only_r9), Some(None), "stale once freed"); | ||
| 3202 | assert_eq!(published.entry(40, 2, only_r9), Some(None), "free"); | ||
| 3203 | } | ||
| 3204 | published.entry_made(40, 2, &r9); | ||
| 3205 | published.entry_made(41, 1, &plain); | ||
| 3206 | for only_r9 in [false, true] { | ||
| 3207 | assert_eq!(published.entry(40, 1, only_r9), Some(None), "the old words"); | ||
| 3208 | assert_eq!(published.entry(40, 2, only_r9), Some(Some(r9.clone()))); | ||
| 3209 | assert_eq!(published.entry(40, 3, only_r9), Some(None), "a generation it never had"); | ||
| 3210 | } | ||
| 3211 | assert_eq!(published.entry(41, 1, false), Some(Some(plain))); | ||
| 3212 | assert_eq!(published.entry(41, 1, true), Some(None), "no R9G9B9E5 texture"); | ||
| 3213 | } | ||
| 3214 | |||
| 3215 | /// A published shape names the view the table names under its lock, at any address; the reader of R9G9B9E5 | ||
| 3216 | /// views only by the shape of one. A number no shape has names nothing. | ||
| 3217 | #[test] | ||
| 3218 | fn published_shapes_name_the_views_the_table_names() { | ||
| 3219 | let mut views = no_views(); | ||
| 3220 | let published = Published::<1, 1>::new(); | ||
| 3221 | let View::Placed(_, texture, desc) = placed_view(67, 0) else { unreachable!() }; | ||
| 3222 | let cases = [ | ||
| 3223 | (placed_view(28, 0xd_4940_0000), false), | ||
| 3224 | (placed_view(67, 0xff_ffff_ffff), true), | ||
| 3225 | (placed_view(67, 0), true), | ||
| 3226 | (View::Placed(true, texture, desc), false), | ||
| 3227 | ]; | ||
| 3228 | for (view, is_r9) in &cases { | ||
| 3229 | let View::Placed(unordered, resource, desc) = view else { unreachable!() }; | ||
| 3230 | let (shape, address) = shape_of(*unordered, resource, desc); | ||
| 3231 | let number = views.shape(shape, |number, made| published.shape_made(number, made)); | ||
| 3232 | let [i, generation] = placed_words(number.expect("room for a shape"), address); | ||
| 3233 | assert_eq!(views.placed_of(i, generation).as_ref(), Some(view), "the table's own answer"); | ||
| 3234 | assert_eq!(published.placed(i, generation, false).as_ref(), Some(view)); | ||
| 3235 | assert_eq!(published.placed(i, generation, true).as_ref(), is_r9.then_some(view)); | ||
| 3236 | } | ||
| 3237 | assert_eq!(views.shapes.len(), 3, "one shape for the two addresses"); | ||
| 3238 | let [i, generation] = placed_words(3, 0x1000); | ||
| 3239 | assert_eq!(views.placed_of(i, generation), None); | ||
| 3240 | assert_eq!(published.placed(i, generation, false), None, "a shape not made yet"); | ||
| 3241 | let [i, generation] = placed_words(SLOT_PAGE as u32, 0x1000); | ||
| 3242 | assert_eq!(published.placed(i, generation, false), None, "a page not made yet"); | ||
| 3243 | } | ||
| 3244 | |||
| 3245 | /// A table tells what it makes and frees, once each, with the generation its readers must ask at: an entry | ||
| 3246 | /// freed through either resource of its view, and used again for a view of placed memory, which no resource | ||
| 3247 | /// owns and no release frees. (A table of a test's own tells only whom the test names.) | ||
| 3248 | #[test] | ||
| 3249 | fn a_table_tells_what_it_makes_and_frees() { | ||
| 3250 | let mut views = no_views(); | ||
| 3251 | let published = Published::<1, 1>::new(); | ||
| 3252 | let told = std::cell::Cell::new((0, 0)); | ||
| 3253 | let entry = |views: &mut Views, view: View| { | ||
| 3254 | views.entry(view, |i, generation, made| { | ||
| 3255 | told.set((told.get().0 + 1, told.get().1)); | ||
| 3256 | published.entry_made(i, generation, made); | ||
| 3257 | }) | ||
| 3258 | }; | ||
| 3259 | let forget = |views: &mut Views, resource: usize| { | ||
| 3260 | views.forget(resource, |i, generation| { | ||
| 3261 | told.set((told.get().0, told.get().1 + 1)); | ||
| 3262 | published.entry_freed(i, generation); | ||
| 3263 | }); | ||
| 3264 | }; | ||
| 3265 | let (resource, counter) = (0x7b60_0000, 0x7b60_0100); | ||
| 3266 | let owned = View::Unordered(resource, counter, None); | ||
| 3267 | assert_eq!(entry(&mut views, owned.clone()), [0, 1]); | ||
| 3268 | assert_eq!(entry(&mut views, owned.clone()), [0, 1], "the same view again"); | ||
| 3269 | assert_eq!(told.get(), (1, 0), "made once"); | ||
| 3270 | assert_eq!(published.entry(0, 1, false), Some(Some(owned.clone()))); | ||
| 3271 | forget(&mut views, counter); | ||
| 3272 | assert_eq!(told.get(), (1, 1)); | ||
| 3273 | assert_eq!(published.entry(0, 1, false), Some(None), "stale"); | ||
| 3274 | let placed = placed_view(67, 0x100_0000_0000); | ||
| 3275 | assert_eq!(entry(&mut views, placed.clone()), [0, 2], "the freed entry, at the generation `forget` gave it"); | ||
| 3276 | // The first view's other resource still notes the entry, another view's by now. | ||
| 3277 | forget(&mut views, resource); | ||
| 3278 | assert_eq!(told.get(), (2, 1), "the placed view is not freed"); | ||
| 3279 | assert_eq!(published.entry(0, 1, true), Some(None), "the old words"); | ||
| 3280 | assert_eq!(published.entry(0, 2, true), Some(Some(placed))); | ||
| 3281 | assert_eq!(entry(&mut views, owned), [1, 1], "a new entry"); | ||
| 3282 | assert_eq!(told.get(), (3, 1)); | ||
| 3283 | } | ||
| 3284 | |||
| 3285 | /// An entry past the published ones is read under the lock, by the reader of R9G9B9E5 views too. (Published | ||
| 3286 | /// here with one page, in place of [`PUBLISHED`]'s 2^20 entries.) | ||
| 3287 | #[test] | ||
| 3288 | fn entries_past_the_published_ones_are_read_under_the_lock() { | ||
| 3289 | // Resources no other test names. | ||
| 3290 | const BASE: usize = 0x7b70_0000_0000; | ||
| 3291 | let small = Published::<1, 1>::new(); | ||
| 3292 | // Views until one's entry is past the page (other tests free entries and use them meanwhile). | ||
| 3293 | let mut made = 0; | ||
| 3294 | let (i, generation, view) = loop { | ||
| 3295 | assert!(made < 1 << 16, "no entry past the first page"); | ||
| 3296 | let view = View::Shader(BASE + made, None); | ||
| 3297 | made += 1; | ||
| 3298 | let [i, generation] = views_write().entry(view.clone()); | ||
| 3299 | if i as usize >= SLOT_PAGE { | ||
| 3300 | break (i, generation, view); | ||
| 3301 | } | ||
| 3302 | }; | ||
| 3303 | assert_eq!(small.entry(i, generation, false), None, "not for it to say"); | ||
| 3304 | assert_eq!(entry_at(&small, i, generation, false), Some(view.clone())); | ||
| 3305 | assert_eq!(entry_at(&small, i, generation, true), None, "no placed view"); | ||
| 3306 | assert_eq!(entry_at(&PUBLISHED, i, generation, false), Some(view)); | ||
| 3307 | // A placed R9G9B9E5 view in such an entry (nothing frees one: the first that comes past the page). | ||
| 3308 | let (j, placed_generation, r9) = (0..64u64) | ||
| 3309 | .find_map(|n| { | ||
| 3310 | let r9 = placed_view(67, 0x7b71_0000 + n * 0x1_0000); | ||
| 3311 | let [j, generation] = views_write().entry(r9.clone()); | ||
| 3312 | (j as usize >= SLOT_PAGE).then_some((j, generation, r9)) | ||
| 3313 | }) | ||
| 3314 | .expect("an entry past the first page"); | ||
| 3315 | assert_eq!(entry_at(&small, j, placed_generation, true), Some(r9)); | ||
| 3316 | assert_eq!(entry_at(&small, j, placed_generation ^ 1, true), None, "another generation"); | ||
| 3317 | for released in BASE..BASE + made { | ||
| 3318 | forget(released); | ||
| 3319 | } | ||
| 3320 | assert_eq!(entry_at(&small, i, generation, false), None, "released"); | ||
| 3321 | assert_eq!(entry_at(&PUBLISHED, i, generation, false), None); | ||
| 3322 | } | ||
| 3323 | |||
| 3324 | /// Either way the switch is, record words name the same view: of every kind as a table entry, a constant | ||
| 3325 | /// buffer view and a view of placed memory held whole; and nothing once the view's resource is released. | ||
| 3326 | #[test] | ||
| 3327 | fn both_sides_of_the_switch_name_the_same_views() { | ||
| 3328 | let resource = 0x7b20_0000_0000usize; | ||
| 3329 | let views = [ | ||
| 3330 | View::Constant(0x1234_5678_9abc, 0x300), | ||
| 3331 | View::Shader(resource, None), | ||
| 3332 | View::Shader(resource, Some(std::array::from_fn(|k| 0x7b21_0000 + k as u32))), | ||
| 3333 | View::Unordered(resource + 1, 0, None), | ||
| 3334 | View::Unordered(resource + 2, resource + 3, Some([0x7b22_0000; 10])), | ||
| 3335 | View::Sampler(std::array::from_fn(|k| 0x7b23_0000 + k as u32)), | ||
| 3336 | View::ConsoleSampler(std::array::from_fn(|k| 0x7b24_0000 + k as u32)), | ||
| 3337 | placed_view(28, 0x7b25_0000), | ||
| 3338 | placed_view(67, 0x7b25_0000), | ||
| 3339 | ]; | ||
| 3340 | let mut named: Vec<([u32; 2], View)> = | ||
| 3341 | views.iter().map(|view| (views_write().entry(view.clone()), view.clone())).collect(); | ||
| 3342 | named.push((constant_words(0x1234_5678_9abc, 0x300).expect("fits"), views[0].clone())); | ||
| 3343 | named.push((shape_words(&views[8]), views[8].clone())); | ||
| 3344 | let both = |[i, generation]: [u32; 2]| { | ||
| 3345 | let [fast, locked] = [true, false].map(|fast| { | ||
| 3346 | LIST_LOCK_FAST_TEST.set(Some(fast)); | ||
| 3347 | view_at(i, generation) | ||
| 3348 | }); | ||
| 3349 | LIST_LOCK_FAST_TEST.set(None); | ||
| 3350 | assert_eq!(fast, locked, "{i} {generation:#x}"); | ||
| 3351 | fast | ||
| 3352 | }; | ||
| 3353 | for (words, view) in &named { | ||
| 3354 | assert_eq!(both(*words).as_ref(), Some(view)); | ||
| 3355 | } | ||
| 3356 | for released in resource..resource + 4 { | ||
| 3357 | forget(released); | ||
| 3358 | } | ||
| 3359 | for (words, view) in &named { | ||
| 3360 | let kept = view.resources() == [0, 0]; | ||
| 3361 | assert_eq!(both(*words).as_ref(), kept.then_some(view), "{view:?}"); | ||
| 3362 | } | ||
| 3363 | } | ||
| 3364 | |||
| 3365 | /// With the table held alone a reader still reads a table entry and a view of placed memory, from what is | ||
| 3366 | /// published: it waits for no lock. | ||
| 3367 | #[test] | ||
| 3368 | fn views_are_read_while_the_table_is_held_alone() { | ||
| 3369 | let resource = 0x7ba0_0000_0000usize; | ||
| 3370 | let owned = View::Shader(resource, Some([0x7ba0; 10])); | ||
| 3371 | let placed = placed_view(67, 0x7ba1_0000); | ||
| 3372 | let [i, generation] = views_write().entry(owned.clone()); | ||
| 3373 | let [j, kind] = shape_words(&placed); | ||
| 3374 | let (answer, answered) = std::sync::mpsc::channel(); | ||
| 3375 | let alone = views_write(); | ||
| 3376 | let found = std::thread::scope(|scope| { | ||
| 3377 | scope.spawn(move || { | ||
| 3378 | LIST_LOCK_FAST_TEST.set(Some(true)); | ||
| 3379 | #[cfg(windows)] | ||
| 3380 | let r9 = r9_view_at(j, kind); | ||
| 3381 | #[cfg(not(windows))] | ||
| 3382 | let r9 = view_at(j, kind); | ||
| 3383 | let _ = answer.send([view_at(i, generation), view_at(j, kind), r9]); | ||
| 3384 | }); | ||
| 3385 | let found = answered.recv_timeout(std::time::Duration::from_secs(20)); | ||
| 3386 | // (Let go before the scope ends: a reader that waits for the lock after all can then end, and the | ||
| 3387 | // test fail below.) | ||
| 3388 | drop(alone); | ||
| 3389 | found | ||
| 3390 | }); | ||
| 3391 | forget(resource); | ||
| 3392 | let found = found.expect("the reader waited for the table's lock"); | ||
| 3393 | assert_eq!(found, [Some(owned), Some(placed.clone()), Some(placed)]); | ||
| 3394 | } | ||
| 3395 | |||
| 3396 | /// Six readers of one entry that a writer frees and uses again without a pause, for a view of another kind | ||
| 3397 | /// or another view of the same: at a generation's own words a reader finds that generation's view whole, or | ||
| 3398 | /// nothing once the writer has begun to free it; at the words of the generation before, nothing. | ||
| 3399 | #[test] | ||
| 3400 | fn six_readers_of_an_entry_freed_and_reused_read_whole_views() { | ||
| 3401 | use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; | ||
| 3402 | const READERS: usize = 6; | ||
| 3403 | const ROUNDS: u32 = 50_000; | ||
| 3404 | const READS: u64 = 5_000; | ||
| 3405 | const ENTRY: u32 = 77; | ||
| 3406 | let published = Published::<1, 1>::new(); | ||
| 3407 | // The generation whose view the entry holds (`patterned` of it), and the last the writer began to free. | ||
| 3408 | let (current, freeing) = (AtomicU32::new(1), AtomicU32::new(0)); | ||
| 3409 | let reads = [const { AtomicU64::new(0) }; READERS]; | ||
| 3410 | let done = AtomicBool::new(false); | ||
| 3411 | published.entry_made(ENTRY, 1, &patterned(1)); | ||
| 3412 | std::thread::scope(|scope| { | ||
| 3413 | let (published, current, freeing, done) = (&published, ¤t, &freeing, &done); | ||
| 3414 | let _ended = Ended(done); | ||
| 3415 | let readers: Vec<_> = reads | ||
| 3416 | .iter() | ||
| 3417 | .map(|reads| { | ||
| 3418 | scope.spawn(move || { | ||
| 3419 | while !done.load(Acquire) { | ||
| 3420 | let generation = current.load(Acquire); | ||
| 3421 | match published.entry(ENTRY, generation, false) { | ||
| 3422 | Some(Some(view)) => assert_eq!(view, patterned(generation), "generation {generation}"), | ||
| 3423 | // Freed meanwhile: then the writer had begun to. | ||
| 3424 | Some(None) => assert!(freeing.load(Acquire) >= generation, "{generation} not freed"), | ||
| 3425 | None => panic!("a generation is given once: no read is overtaken twice"), | ||
| 3426 | } | ||
| 3427 | assert_eq!(published.entry(ENTRY, generation - 1, false), Some(None), "freed before"); | ||
| 3428 | reads.fetch_add(1, Relaxed); | ||
| 3429 | } | ||
| 3430 | }) | ||
| 3431 | }) | ||
| 3432 | .collect(); | ||
| 3433 | let mut generation = 1; | ||
| 3434 | while readers.iter().all(|reader| !reader.is_finished()) | ||
| 3435 | && (generation < ROUNDS || reads.iter().any(|r| r.load(Relaxed) < READS)) | ||
| 3436 | { | ||
| 3437 | assert!(generation < GENERATIONS - 1, "the readers did not run"); | ||
| 3438 | freeing.store(generation, Release); | ||
| 3439 | generation += 1; | ||
| 3440 | published.entry_freed(ENTRY, generation); | ||
| 3441 | published.entry_made(ENTRY, generation, &patterned(generation)); | ||
| 3442 | // (As long as a read takes, so that a reader finds the view there as often as freed.) | ||
| 3443 | assert_eq!(published.entry(ENTRY, generation, false), Some(Some(patterned(generation)))); | ||
| 3444 | current.store(generation, Release); | ||
| 3445 | } | ||
| 3446 | }); | ||
| 3447 | } | ||
| 3448 | |||
| 3449 | /// The same with the entry at one generation throughout, as when the generations have gone round: only the | ||
| 3450 | /// turn in the head tells a view from the next. A reader finds nothing (between the writer's two heads), or | ||
| 3451 | /// a whole view that is no older than the last it read, or leaves it to the lock. | ||
| 3452 | #[test] | ||
| 3453 | fn six_readers_of_an_entry_rewritten_at_one_generation_read_whole_views() { | ||
| 3454 | use std::sync::atomic::Ordering::Relaxed; | ||
| 3455 | const READERS: usize = 6; | ||
| 3456 | const ROUNDS: u32 = 50_000; | ||
| 3457 | const READS: u64 = 2_000; | ||
| 3458 | const ENTRY: u32 = 78; | ||
| 3459 | // Round `n`'s view: `n` in every word. | ||
| 3460 | let view_of = |n: u32| View::Placed(false, [n; 14], [n; 16]); | ||
| 3461 | let published = Published::<1, 1>::new(); | ||
| 3462 | let whole = [const { AtomicU64::new(0) }; READERS]; | ||
| 3463 | let done = AtomicBool::new(false); | ||
| 3464 | published.entry_made(ENTRY, 1, &view_of(0)); | ||
| 3465 | std::thread::scope(|scope| { | ||
| 3466 | let (published, done) = (&published, &done); | ||
| 3467 | let _ended = Ended(done); | ||
| 3468 | let readers: Vec<_> = whole | ||
| 3469 | .iter() | ||
| 3470 | .map(|whole| { | ||
| 3471 | scope.spawn(move || { | ||
| 3472 | let mut last = 0; | ||
| 3473 | while !done.load(Acquire) { | ||
| 3474 | match published.entry(ENTRY, 1, false) { | ||
| 3475 | Some(Some(View::Placed(false, resource, desc))) => { | ||
| 3476 | let n = resource[0]; | ||
| 3477 | let one = resource.iter().chain(&desc).all(|&word| word == n); | ||
| 3478 | assert!(one, "words of two views: {resource:x?} {desc:x?}"); | ||
| 3479 | assert!(n >= last, "round {n} after round {last}"); | ||
| 3480 | last = n; | ||
| 3481 | whole.fetch_add(1, Relaxed); | ||
| 3482 | } | ||
| 3483 | Some(Some(view)) => panic!("no view the writer gave: {view:?}"), | ||
| 3484 | // Between the writer's two heads, or overtaken at every read. | ||
| 3485 | Some(None) | None => {} | ||
| 3486 | } | ||
| 3487 | } | ||
| 3488 | }) | ||
| 3489 | }) | ||
| 3490 | .collect(); | ||
| 3491 | let mut n = 0; | ||
| 3492 | while readers.iter().all(|reader| !reader.is_finished()) | ||
| 3493 | && (n < ROUNDS || whole.iter().any(|w| w.load(Relaxed) < READS)) | ||
| 3494 | { | ||
| 3495 | assert!(n < u32::MAX, "the readers did not run"); | ||
| 3496 | n += 1; | ||
| 3497 | published.entry_freed(ENTRY, 1); | ||
| 3498 | published.entry_made(ENTRY, 1, &view_of(n)); | ||
| 3499 | // (As long as two reads take, so that a reader finds the view whole as often as not.) | ||
| 3500 | for _ in 0..2 { | ||
| 3501 | assert_eq!(published.entry(ENTRY, 1, false), Some(Some(view_of(n)))); | ||
| 3502 | } | ||
| 3503 | } | ||
| 3504 | }); | ||
| 3505 | } | ||
| 3506 | |||
| 3507 | /// Six readers of the views of resources that a writer makes and releases one after another, mostly in the | ||
| 3508 | /// one entry, each reader with the switch by turns: a view's record words name that view, or nothing once | ||
| 3509 | /// its release has begun, and never the view made in its entry after it; the words of the view before name | ||
| 3510 | /// nothing. The same of what is published, read directly. | ||
| 3511 | #[test] | ||
| 3512 | fn six_readers_of_views_released_under_them_never_read_another_view() { | ||
| 3513 | use std::sync::atomic::Ordering::Relaxed; | ||
| 3514 | const READERS: usize = 6; | ||
| 3515 | const ROUNDS: u64 = 3_000; | ||
| 3516 | const READS: u64 = 1_000; | ||
| 3517 | // Resources no other test names: round `n`'s, and after it the counter of its view. | ||
| 3518 | const BASE: usize = 0x7b90_0000_0000; | ||
| 3519 | let view_of = |n: u64| { | ||
| 3520 | let resource = BASE + 2 * n as usize; | ||
| 3521 | let desc = Some(std::array::from_fn(|k| (n as u32).wrapping_mul(0x9e37_79b9) ^ k as u32)); | ||
| 3522 | if n.is_multiple_of(3) { | ||
| 3523 | View::Unordered(resource, resource + 1, desc) | ||
| 3524 | } else { | ||
| 3525 | View::Shader(resource, desc) | ||
| 3526 | } | ||
| 3527 | }; | ||
| 3528 | // The round under way, the record words of its view and those of the round before's: read and written | ||
| 3529 | // whole (under this lock of the test's own; the table's is not held across a lookup). | ||
| 3530 | let mut words = words_for(view_of(0)); | ||
| 3531 | let shared = std::sync::Mutex::new((0u64, words, [0u32; 2])); | ||
| 3532 | // The rounds below this were released, or are being. | ||
| 3533 | let released = AtomicU64::new(0); | ||
| 3534 | let reads = [const { AtomicU64::new(0) }; READERS]; | ||
| 3535 | let done = AtomicBool::new(false); | ||
| 3536 | std::thread::scope(|scope| { | ||
| 3537 | let (shared, released, done) = (&shared, &released, &done); | ||
| 3538 | let _ended = Ended(done); | ||
| 3539 | let readers: Vec<_> = reads | ||
| 3540 | .iter() | ||
| 3541 | .map(|reads| { | ||
| 3542 | scope.spawn(move || { | ||
| 3543 | let mut fast = false; | ||
| 3544 | while !done.load(Acquire) { | ||
| 3545 | let (n, [i, generation], before) = *shared.lock().unwrap(); | ||
| 3546 | // By turns, as under A/B. | ||
| 3547 | fast = !fast; | ||
| 3548 | LIST_LOCK_FAST_TEST.set(Some(fast)); | ||
| 3549 | match view_at(i, generation) { | ||
| 3550 | Some(view) => assert_eq!(view, view_of(n), "round {n}"), | ||
| 3551 | None => assert!(released.load(Acquire) > n, "round {n} was not released"), | ||
| 3552 | } | ||
| 3553 | match PUBLISHED.entry(i, generation, false).expect("freed once: overtaken once at most") { | ||
| 3554 | Some(view) => assert_eq!(view, view_of(n), "round {n}, as published"), | ||
| 3555 | None => assert!(released.load(Acquire) > n, "round {n} was not released"), | ||
| 3556 | } | ||
| 3557 | if n > 0 { | ||
| 3558 | assert_eq!(view_at(before[0], before[1]), None, "round {} was released", n - 1); | ||
| 3559 | assert_eq!(PUBLISHED.entry(before[0], before[1], false), Some(None)); | ||
| 3560 | } | ||
| 3561 | reads.fetch_add(1, Relaxed); | ||
| 3562 | } | ||
| 3563 | }) | ||
| 3564 | }) | ||
| 3565 | .collect(); | ||
| 3566 | let mut n = 0; | ||
| 3567 | loop { | ||
| 3568 | // (As long as some reads take, so that a reader finds the view there as often as released.) | ||
| 3569 | for _ in 0..4 { | ||
| 3570 | assert_eq!(view_at(words[0], words[1]), Some(view_of(n))); | ||
| 3571 | } | ||
| 3572 | released.store(n + 1, Release); | ||
| 3573 | forget(BASE + 2 * n as usize); | ||
| 3574 | forget(BASE + 2 * n as usize + 1); | ||
| 3575 | assert_eq!(view_at(words[0], words[1]), None, "stale at once"); | ||
| 3576 | let enough = n + 1 >= ROUNDS && reads.iter().all(|r| r.load(Relaxed) >= READS); | ||
| 3577 | if enough || readers.iter().any(|reader| reader.is_finished()) { | ||
| 3578 | break; | ||
| 3579 | } | ||
| 3580 | assert!(n < 1 << 28, "the readers did not run"); | ||
| 3581 | n += 1; | ||
| 3582 | let before = words; | ||
| 3583 | words = words_for(view_of(n)); | ||
| 3584 | *shared.lock().unwrap() = (n, words, before); | ||
| 3585 | } | ||
| 3586 | }); | ||
| 3587 | } | ||
| 3588 | |||
| 3589 | /// [`r9_view_at`] finds a shader view of a placed R9G9B9E5 texture by either kind of record words, and no | ||
| 3590 | /// other view; not by the words of a released resource's view either, whose entry such a view has taken. | ||
| 3591 | /// With one made, [`any_r9_views`] says so. | ||
| 3592 | #[cfg(windows)] | ||
| 3593 | #[test] | ||
| 3594 | fn placed_r9_views_are_found_by_their_record_words() { | ||
| 3595 | let (r9, plain) = (placed_view(67, 0x7b80_0000), placed_view(28, 0x7b80_0000)); | ||
| 3596 | let owner = 0x7b81_0000_0000usize; | ||
| 3597 | let owned = words_for(View::Shader(owner, None)); | ||
| 3598 | forget(owner); | ||
| 3599 | // (With the table to itself, the entry made next is the one just freed.) | ||
| 3600 | let entry = views_write().entry(r9.clone()); | ||
| 3601 | // (Each on its own: the table is held alone until the statement that took it ends.) | ||
| 3602 | let plain_entry = views_write().entry(plain.clone()); | ||
| 3603 | let cases = [ | ||
| 3604 | (entry, Some(&r9)), | ||
| 3605 | (shape_words(&r9), Some(&r9)), | ||
| 3606 | (plain_entry, None), | ||
| 3607 | (shape_words(&plain), None), | ||
| 3608 | (owned, None), | ||
| 3609 | (constant_words(0x7b82_0000, 256).expect("fits"), None), | ||
| 3610 | ]; | ||
| 3611 | assert!(any_r9_views()); | ||
| 3612 | for ([i, generation], view) in cases { | ||
| 3613 | assert_eq!(r9_view_at(i, generation).as_ref(), view, "{i} {generation:#x}"); | ||
| 3614 | } | ||
| 3615 | assert_eq!(r9_view_at(entry[0], entry[1] ^ 1), None, "another generation of its entry"); | ||
| 3616 | } | ||
| 3617 | |||
| 2542 | /// The title places its shader-visible heap in its own memory | 3618 | /// The title places its shader-visible heap in its own memory |
| 2543 | /// and checks that the heap starts there. | 3619 | /// and checks that the heap starts there. |
| 2544 | #[test] | 3620 | #[test] |
diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host.rs b/d3d12/crates/leonida-gpu/src/descriptor/host.rs index b06a80206..24e69d06d 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host.rs | |||
| @@ -504,12 +504,15 @@ pub(crate) fn view_cast_serial(view: &View) -> Option<u64> { | |||
| 504 | crate::resource::cast_alias_serial(*resource as crate::object::This) | 504 | crate::resource::cast_alias_serial(*resource as crate::object::This) |
| 505 | } | 505 | } |
| 506 | 506 | ||
| 507 | /// Collects `(k, View)` for every placed `R9G9B9E5` shader view in the `n` | 507 | /// Collects the placed R9G9B9E5 shader views in a validated table, in slot |
| 508 | /// validated 32-byte descriptor slots starting at `table`, taking `views_read` | 508 | /// order. Until one has been registered there is nothing to read. The |
| 509 | /// at most once for the whole table (zero times when every slot is null or an | 509 | /// negative control takes one registry guard for the whole scan. |
| 510 | /// inline constant buffer). | ||
| 511 | pub(crate) fn table_r9g9b9e5_views(table: u64, n: u32, out: &mut Vec<(u32, View)>) { | 510 | pub(crate) fn table_r9g9b9e5_views(table: u64, n: u32, out: &mut Vec<(u32, View)>) { |
| 512 | out.clear(); | 511 | out.clear(); |
| 512 | let fast = super::list_lock_fast(); | ||
| 513 | if fast && !super::any_r9_views() { | ||
| 514 | return; | ||
| 515 | } | ||
| 513 | let mut views = None; | 516 | let mut views = None; |
| 514 | for k in 0..n { | 517 | for k in 0..n { |
| 515 | // SAFETY: caller verified `[table, table + n * 32)` lies in a bound view heap. | 518 | // SAFETY: caller verified `[table, table + n * 32)` lies in a bound view heap. |
| @@ -517,6 +520,12 @@ pub(crate) fn table_r9g9b9e5_views(table: u64, n: u32, out: &mut Vec<(u32, View) | |||
| 517 | if words[0] != super::VIEW_TAG { | 520 | if words[0] != super::VIEW_TAG { |
| 518 | continue; | 521 | continue; |
| 519 | } | 522 | } |
| 523 | if fast { | ||
| 524 | if let Some(view) = super::r9_view_at(words[1], words[2]) { | ||
| 525 | out.push((k, view)); | ||
| 526 | } | ||
| 527 | continue; | ||
| 528 | } | ||
| 520 | match words[2] >> super::KIND_SHIFT { | 529 | match words[2] >> super::KIND_SHIFT { |
| 521 | super::PLACED => { | 530 | super::PLACED => { |
| 522 | let v = views.get_or_insert_with(super::views_read); | 531 | let v = views.get_or_insert_with(super::views_read); |
| @@ -547,6 +556,167 @@ pub(crate) fn table_r9g9b9e5_views(table: u64, n: u32, out: &mut Vec<(u32, View) | |||
| 547 | } | 556 | } |
| 548 | } | 557 | } |
| 549 | 558 | ||
| 559 | #[cfg(test)] | ||
| 560 | mod list_contention_tests { | ||
| 561 | use super::{placed_texture, table_r9g9b9e5_views}; | ||
| 562 | use crate::descriptor::{self, VIEW_TAG, View}; | ||
| 563 | use crate::resource; | ||
| 564 | |||
| 565 | type Slot = [u32; 8]; | ||
| 566 | |||
| 567 | fn slot([i, generation]: [u32; 2]) -> Slot { | ||
| 568 | [VIEW_TAG, i, generation, 0, 0, 0, 0, 0] | ||
| 569 | } | ||
| 570 | |||
| 571 | fn placed(format: u32, address: u64) -> View { | ||
| 572 | let resource = [3, 0, 0, 0, 32, 0, 32, 0x1_0001, format, 1, 0, 0, 0, 0]; | ||
| 573 | let mut desc = [format, 4, 5768, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; | ||
| 574 | desc[10] = address as u32; | ||
| 575 | desc[11] = (address >> 32) as u32; | ||
| 576 | View::Placed(false, resource, desc) | ||
| 577 | } | ||
| 578 | |||
| 579 | // Force inline and entry records independently of LEONIDA_VIEW_INLINE. | ||
| 580 | fn placed_slot(view: &View, inline: bool) -> Slot { | ||
| 581 | let View::Placed(uav, resource, desc) = view else { unreachable!() }; | ||
| 582 | let mut views = descriptor::views_write(); | ||
| 583 | if inline { | ||
| 584 | let (shape, address) = descriptor::shape_of(*uav, resource, desc); | ||
| 585 | let number = views.shape(shape).unwrap(); | ||
| 586 | slot(descriptor::placed_words(number, address)) | ||
| 587 | } else { | ||
| 588 | slot(views.entry(view.clone())) | ||
| 589 | } | ||
| 590 | } | ||
| 591 | |||
| 592 | #[test] | ||
| 593 | fn r9_scan_filters_both_record_kinds_and_checks_generation() { | ||
| 594 | let plain = placed(28, 0x10000); | ||
| 595 | let mut table = [placed_slot(&plain, true); 32]; | ||
| 596 | let mut found = vec![(99, plain)]; | ||
| 597 | let scan = |table: &[Slot; 32], out: &mut Vec<_>| { | ||
| 598 | table_r9g9b9e5_views(table.as_ptr() as u64, 32, out); | ||
| 599 | }; | ||
| 600 | scan(&table, &mut found); | ||
| 601 | assert!(found.is_empty()); | ||
| 602 | |||
| 603 | let a = placed(67, 0x20000); | ||
| 604 | let b = placed(67, 0x30000); | ||
| 605 | table[4] = placed_slot(&a, true); | ||
| 606 | // Placed views have no owning resource; an old, resource-owned | ||
| 607 | // record must not resolve to an R9 view installed after release. | ||
| 608 | let owner = std::ptr::from_ref(&table) as usize; | ||
| 609 | table[6] = slot(descriptor::words_for(View::Shader(owner, None))); | ||
| 610 | descriptor::forget(owner); | ||
| 611 | table[18] = placed_slot(&b, false); | ||
| 612 | table[7] = table[18]; | ||
| 613 | table[7][2] ^= 1; // Right entry, wrong generation. | ||
| 614 | let View::Placed(_, resource, desc) = &b else { unreachable!() }; | ||
| 615 | table[30] = placed_slot(&View::Placed(true, *resource, *desc), true); | ||
| 616 | let mut buffer = *resource; | ||
| 617 | buffer[0] = 1; | ||
| 618 | table[31] = placed_slot(&View::Placed(false, buffer, *desc), false); | ||
| 619 | scan(&table, &mut found); | ||
| 620 | assert_eq!(found, [(4, a), (18, b)]); | ||
| 621 | } | ||
| 622 | |||
| 623 | /// One op is a synthetic draw: two indexed views 8,192 entries apart, | ||
| 624 | /// an inline placed view, a 32-slot scan, placed lookup/mip demand and | ||
| 625 | /// an owning host-copy lookup. Run each switch value in a fresh process. | ||
| 626 | #[test] | ||
| 627 | #[ignore = "six list threads; release-mode benchmark on a D3D12 adapter"] | ||
| 628 | fn list_threads_descriptor_and_resource_contention_bench() { | ||
| 629 | use std::hint::black_box; | ||
| 630 | use std::sync::Barrier; | ||
| 631 | use std::time::Instant; | ||
| 632 | use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; | ||
| 633 | |||
| 634 | const WORKERS: usize = 6; | ||
| 635 | const ENTRIES: usize = 32_768; | ||
| 636 | const DRAWS: usize = 65_536; | ||
| 637 | assert!(crate::host::host().is_some(), "benchmark requires D3D12"); | ||
| 638 | assert!(!descriptor::any_r9_views(), "run this benchmark alone, in a fresh process"); | ||
| 639 | |||
| 640 | // Placed resources live until process exit; their backing memory | ||
| 641 | // must outlive every call, including any later idle sweep. | ||
| 642 | const TEXTURES: usize = 16; | ||
| 643 | let View::Placed(_, desc, _) = placed(28, 0) else { unreachable!() }; | ||
| 644 | let stride = (resource::placed_bytes(&desc).unwrap() as usize).next_multiple_of(65_536); | ||
| 645 | // SAFETY: reserve and commit private zeroed memory; keep it for the run. | ||
| 646 | let memory = unsafe { VirtualAlloc(std::ptr::null(), stride * TEXTURES, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; | ||
| 647 | assert!(!memory.is_null(), "benchmark texture allocation failed"); | ||
| 648 | let textures: Vec<_> = (0..TEXTURES).map(|i| { | ||
| 649 | let v = placed(28, (memory as usize + i * stride) as u64); | ||
| 650 | let Some(View::Shader(r, _)) = placed_texture(&v) else { panic!("placed texture unavailable") }; | ||
| 651 | assert!(resource::host_copy(r as crate::object::This).is_some()); | ||
| 652 | (v, r) | ||
| 653 | }).collect(); | ||
| 654 | let entries: Vec<_> = { | ||
| 655 | let mut registry = descriptor::views_write(); | ||
| 656 | (0..ENTRIES).map(|i| { | ||
| 657 | let mut desc = [0; 10]; | ||
| 658 | desc[0] = i as u32; | ||
| 659 | slot(registry.entry(View::Shader(textures[i % TEXTURES].1, Some(desc)))) | ||
| 660 | }).collect() | ||
| 661 | }; | ||
| 662 | let inline = placed_slot(&placed(28, 0x40000), true); | ||
| 663 | let mut common = [inline; 32]; | ||
| 664 | for k in (1..32).step_by(2) { common[k] = entries[k]; } | ||
| 665 | let mut rare = common; | ||
| 666 | let mut elapsed = [0.0; 2]; | ||
| 667 | for (phase, seconds) in elapsed.iter_mut().enumerate() { | ||
| 668 | if phase == 1 { | ||
| 669 | let r9 = placed(67, 0x50000); | ||
| 670 | rare[5] = placed_slot(&r9, true); | ||
| 671 | rare[29] = placed_slot(&r9, false); | ||
| 672 | } | ||
| 673 | let gate = Barrier::new(WORKERS); | ||
| 674 | *seconds = std::thread::scope(|scope| { | ||
| 675 | let mut workers = Vec::with_capacity(WORKERS); | ||
| 676 | for worker in 0..WORKERS { | ||
| 677 | let (textures, entries, common, rare, gate) = (&textures, &entries, &common, &rare, &gate); | ||
| 678 | workers.push(scope.spawn(move || { | ||
| 679 | let mut found = Vec::with_capacity(2); | ||
| 680 | let mut draw = |step: usize| { | ||
| 681 | let i = (step * 17 + worker * 131) & (ENTRIES - 1); | ||
| 682 | for s in [&entries[i], &entries[i ^ 8192], &inline] { | ||
| 683 | black_box(descriptor::view(s.as_ptr() as u64).unwrap()); | ||
| 684 | } | ||
| 685 | let hit = phase == 1 && step & 7 == 0; | ||
| 686 | let table = if hit { rare } else { common }; | ||
| 687 | table_r9g9b9e5_views(table.as_ptr() as u64, 32, &mut found); | ||
| 688 | assert_eq!(found.len(), if hit { 2 } else { 0 }); | ||
| 689 | black_box(&found); | ||
| 690 | let index = if step & 1 == 0 { 0 } else { i % TEXTURES }; | ||
| 691 | let Some(View::Shader(r, _)) = placed_texture(&textures[index].0) else { panic!("placed lookup failed") }; | ||
| 692 | black_box(resource::host_copy(r as crate::object::This).unwrap()); | ||
| 693 | }; | ||
| 694 | gate.wait(); | ||
| 695 | for step in 0..1024 { draw(step); } | ||
| 696 | let start = Instant::now(); | ||
| 697 | for step in 0..DRAWS { draw(step); } | ||
| 698 | (start, Instant::now()) | ||
| 699 | })); | ||
| 700 | } | ||
| 701 | // Wall time from the first measured draw to the last; | ||
| 702 | // a failed worker can't strand the others at a finish barrier. | ||
| 703 | let (first, last) = workers.into_iter().map(|w| w.join().unwrap()) | ||
| 704 | .reduce(|(a, b), (c, d)| (a.min(c), b.max(d))).unwrap(); | ||
| 705 | (last - first).as_secs_f64() | ||
| 706 | }); | ||
| 707 | } | ||
| 708 | let ops = (DRAWS * WORKERS) as f64; | ||
| 709 | for (label, seconds, draws) in [ | ||
| 710 | ("no-r9", elapsed[0], ops), | ||
| 711 | ("mixed", elapsed[1], ops), | ||
| 712 | ("combined", elapsed[0] + elapsed[1], 2.0 * ops), | ||
| 713 | ] { | ||
| 714 | eprintln!("list-lock fast={} {label}: {:.2} ns/draw, {:.0} draws/s ({draws} draws)", | ||
| 715 | descriptor::list_lock_fast(), seconds * 1e9 / draws, draws / seconds); | ||
| 716 | } | ||
| 717 | } | ||
| 718 | } | ||
| 719 | |||
| 550 | /// Slots shown late ([`show_after`]), the frames they waited, the longest; | 720 | /// Slots shown late ([`show_after`]), the frames they waited, the longest; |
| 551 | /// those that were given the neutral texture meanwhile; those not shown any | 721 | /// those that were given the neutral texture meanwhile; those not shown any |
| 552 | /// more when their time came. | 722 | /// more when their time came. |
| @@ -2532,6 +2702,7 @@ static STALE_RELEASES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU | |||
| 2532 | 2702 | ||
| 2533 | /// Runs of dynamic slots a release refused since the last call | 2703 | /// Runs of dynamic slots a release refused since the last call |
| 2534 | /// (`LEONIDA_HEAP_ID_GUARD`), logged with the recording line. | 2704 | /// (`LEONIDA_HEAP_ID_GUARD`), logged with the recording line. |
| 2705 | #[cfg(feature = "diagnostics")] | ||
| 2535 | pub(crate) fn stale_releases() -> u64 { | 2706 | pub(crate) fn stale_releases() -> u64 { |
| 2536 | STALE_RELEASES.swap(0, std::sync::atomic::Ordering::Relaxed) | 2707 | STALE_RELEASES.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 2537 | } | 2708 | } |
| @@ -6399,6 +6570,22 @@ impl Copied<'_> { | |||
| 6399 | /// Most of a changed page is as it was: it is looked at sixteen records at a | 6570 | /// Most of a changed page is as it was: it is looked at sixteen records at a |
| 6400 | /// time. | 6571 | /// time. |
| 6401 | fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out: &mut Vec<u32>) { | 6572 | fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out: &mut Vec<u32>) { |
| 6573 | #[cfg(target_arch = "x86_64")] | ||
| 6574 | if step == 32 && last.len() == records.len() && std::arch::is_x86_feature_detected!("avx2") { | ||
| 6575 | // SAFETY: AVX2 is verified above; `last` and `records` have equal length. | ||
| 6576 | unsafe { changed_records_avx2_32(last, records, first, out) }; | ||
| 6577 | return; | ||
| 6578 | } | ||
| 6579 | changed_records_scalar(last, records, step, first, out); | ||
| 6580 | } | ||
| 6581 | |||
| 6582 | fn changed_records_scalar( | ||
| 6583 | last: &mut [u8], | ||
| 6584 | records: &[u8], | ||
| 6585 | step: usize, | ||
| 6586 | first: u32, | ||
| 6587 | out: &mut Vec<u32>, | ||
| 6588 | ) { | ||
| 6402 | const AT_A_TIME: usize = 16; | 6589 | const AT_A_TIME: usize = 16; |
| 6403 | let block = AT_A_TIME * step; | 6590 | let block = AT_A_TIME * step; |
| 6404 | for (b, (old, new)) in last.chunks_mut(block).zip(records.chunks(block)).enumerate() { | 6591 | for (b, (old, new)) in last.chunks_mut(block).zip(records.chunks(block)).enumerate() { |
| @@ -6414,19 +6601,106 @@ fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out | |||
| 6414 | } | 6601 | } |
| 6415 | } | 6602 | } |
| 6416 | 6603 | ||
| 6604 | #[cfg(target_arch = "x86_64")] | ||
| 6605 | #[target_feature(enable = "avx2")] | ||
| 6606 | unsafe fn changed_records_avx2_32( | ||
| 6607 | last: &mut [u8], | ||
| 6608 | records: &[u8], | ||
| 6609 | first: u32, | ||
| 6610 | out: &mut Vec<u32>, | ||
| 6611 | ) { | ||
| 6612 | use std::arch::x86_64::{ | ||
| 6613 | __m256i, _mm256_and_si256, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, | ||
| 6614 | _mm256_storeu_si256, | ||
| 6615 | }; | ||
| 6616 | |||
| 6617 | let count = last.len() / 32; | ||
| 6618 | let dst = last.as_mut_ptr(); | ||
| 6619 | let src = records.as_ptr(); | ||
| 6620 | let mut i = 0usize; | ||
| 6621 | |||
| 6622 | // Four 32-byte descriptor records (128 bytes) per iteration: one combined | ||
| 6623 | // equality check on the fast path, and direct stores of the already-loaded | ||
| 6624 | // vectors when any record differs. | ||
| 6625 | while i + 4 <= count { | ||
| 6626 | let base = i * 32; | ||
| 6627 | // SAFETY: `i + 4 <= count`, so `base + 128 <= last.len() == records.len()`. | ||
| 6628 | unsafe { | ||
| 6629 | let o0 = _mm256_loadu_si256(dst.add(base) as *const __m256i); | ||
| 6630 | let n0 = _mm256_loadu_si256(src.add(base) as *const __m256i); | ||
| 6631 | let o1 = _mm256_loadu_si256(dst.add(base + 32) as *const __m256i); | ||
| 6632 | let n1 = _mm256_loadu_si256(src.add(base + 32) as *const __m256i); | ||
| 6633 | let o2 = _mm256_loadu_si256(dst.add(base + 64) as *const __m256i); | ||
| 6634 | let n2 = _mm256_loadu_si256(src.add(base + 64) as *const __m256i); | ||
| 6635 | let o3 = _mm256_loadu_si256(dst.add(base + 96) as *const __m256i); | ||
| 6636 | let n3 = _mm256_loadu_si256(src.add(base + 96) as *const __m256i); | ||
| 6637 | |||
| 6638 | let e0 = _mm256_cmpeq_epi8(o0, n0); | ||
| 6639 | let e1 = _mm256_cmpeq_epi8(o1, n1); | ||
| 6640 | let e2 = _mm256_cmpeq_epi8(o2, n2); | ||
| 6641 | let e3 = _mm256_cmpeq_epi8(o3, n3); | ||
| 6642 | let all = _mm256_and_si256(_mm256_and_si256(e0, e1), _mm256_and_si256(e2, e3)); | ||
| 6643 | if _mm256_movemask_epi8(all) != -1 { | ||
| 6644 | if _mm256_movemask_epi8(e0) != -1 { | ||
| 6645 | _mm256_storeu_si256(dst.add(base) as *mut __m256i, n0); | ||
| 6646 | out.push(first + i as u32); | ||
| 6647 | } | ||
| 6648 | if _mm256_movemask_epi8(e1) != -1 { | ||
| 6649 | _mm256_storeu_si256(dst.add(base + 32) as *mut __m256i, n1); | ||
| 6650 | out.push(first + (i + 1) as u32); | ||
| 6651 | } | ||
| 6652 | if _mm256_movemask_epi8(e2) != -1 { | ||
| 6653 | _mm256_storeu_si256(dst.add(base + 64) as *mut __m256i, n2); | ||
| 6654 | out.push(first + (i + 2) as u32); | ||
| 6655 | } | ||
| 6656 | if _mm256_movemask_epi8(e3) != -1 { | ||
| 6657 | _mm256_storeu_si256(dst.add(base + 96) as *mut __m256i, n3); | ||
| 6658 | out.push(first + (i + 3) as u32); | ||
| 6659 | } | ||
| 6660 | } | ||
| 6661 | } | ||
| 6662 | i += 4; | ||
| 6663 | } | ||
| 6664 | |||
| 6665 | while i < count { | ||
| 6666 | let base = i * 32; | ||
| 6667 | // SAFETY: `i < count`, so `base + 32 <= last.len() == records.len()`. | ||
| 6668 | unsafe { | ||
| 6669 | let o = _mm256_loadu_si256(dst.add(base) as *const __m256i); | ||
| 6670 | let n = _mm256_loadu_si256(src.add(base) as *const __m256i); | ||
| 6671 | if _mm256_movemask_epi8(_mm256_cmpeq_epi8(o, n)) != -1 { | ||
| 6672 | _mm256_storeu_si256(dst.add(base) as *mut __m256i, n); | ||
| 6673 | out.push(first + i as u32); | ||
| 6674 | } | ||
| 6675 | } | ||
| 6676 | i += 1; | ||
| 6677 | } | ||
| 6678 | } | ||
| 6679 | |||
| 6417 | #[cfg(test)] | 6680 | #[cfg(test)] |
| 6418 | mod changed_records_tests { | 6681 | mod changed_records_tests { |
| 6419 | use super::changed_records; | 6682 | use super::{changed_records, changed_records_scalar}; |
| 6420 | 6683 | ||
| 6421 | #[test] | 6684 | #[test] |
| 6422 | fn changed_records_are_those_that_differ_one_by_one() { | 6685 | fn changed_records_are_those_that_differ_one_by_one() { |
| 6423 | for (step, count) in [(32usize, 128usize), (32, 2048), (16, 77), (32, 5), (32, 17)] { | 6686 | for (step, count) in [ |
| 6687 | (32usize, 0usize), | ||
| 6688 | (32, 1), | ||
| 6689 | (32, 3), | ||
| 6690 | (32, 4), | ||
| 6691 | (32, 5), | ||
| 6692 | (32, 17), | ||
| 6693 | (32, 128), | ||
| 6694 | (32, 2048), | ||
| 6695 | (16, 77), | ||
| 6696 | ] { | ||
| 6424 | let mut seed = 7u64; | 6697 | let mut seed = 7u64; |
| 6425 | let mut random = move || { | 6698 | let mut random = move || { |
| 6426 | seed = seed.wrapping_mul(0x5851_F42D_4C95_7F2D).wrapping_add(0x1405_7B7E_F767_814F); | 6699 | seed = seed.wrapping_mul(0x5851_F42D_4C95_7F2D).wrapping_add(0x1405_7B7E_F767_814F); |
| 6427 | (seed >> 33) as usize | 6700 | (seed >> 33) as usize |
| 6428 | }; | 6701 | }; |
| 6429 | let mut last: Vec<u8> = (0..step * count).map(|_| random() as u8).collect(); | 6702 | let mut last: Vec<u8> = (0..step * count).map(|_| random() as u8).collect(); |
| 6703 | let mut last_scalar = last.clone(); | ||
| 6430 | let mut now = last.clone(); | 6704 | let mut now = last.clone(); |
| 6431 | let mut differ = Vec::new(); | 6705 | let mut differ = Vec::new(); |
| 6432 | for slot in 0..count { | 6706 | for slot in 0..count { |
| @@ -6436,14 +6710,60 @@ mod changed_records_tests { | |||
| 6436 | } | 6710 | } |
| 6437 | } | 6711 | } |
| 6438 | let mut out = Vec::new(); | 6712 | let mut out = Vec::new(); |
| 6713 | let mut out_scalar = Vec::new(); | ||
| 6439 | changed_records(&mut last, &now, step, 1000, &mut out); | 6714 | changed_records(&mut last, &now, step, 1000, &mut out); |
| 6715 | changed_records_scalar(&mut last_scalar, &now, step, 1000, &mut out_scalar); | ||
| 6440 | assert_eq!(out, differ); | 6716 | assert_eq!(out, differ); |
| 6717 | assert_eq!(out, out_scalar); | ||
| 6441 | assert_eq!(last, now); | 6718 | assert_eq!(last, now); |
| 6719 | assert_eq!(last, last_scalar); | ||
| 6442 | out.clear(); | 6720 | out.clear(); |
| 6443 | changed_records(&mut last, &now, step, 1000, &mut out); | 6721 | changed_records(&mut last, &now, step, 1000, &mut out); |
| 6444 | assert!(out.is_empty()); | 6722 | assert!(out.is_empty()); |
| 6445 | } | 6723 | } |
| 6446 | } | 6724 | } |
| 6725 | |||
| 6726 | #[test] | ||
| 6727 | #[ignore = "microbenchmark: cargo test --release -p leonida-gpu --lib changed_records_bench -- --ignored --nocapture"] | ||
| 6728 | fn changed_records_bench() { | ||
| 6729 | const SLOTS: usize = 400_000; | ||
| 6730 | const STEP: usize = 32; | ||
| 6731 | const ROUNDS: usize = 50; | ||
| 6732 | let base: Vec<u8> = (0..SLOTS * STEP).map(|i| (i.wrapping_mul(31) >> 3) as u8).collect(); | ||
| 6733 | for (label, dirty_every) in [("0% dirty", 0usize), ("10% dirty (40k/frame)", 10), ("100% dirty", 1)] { | ||
| 6734 | let mut now = base.clone(); | ||
| 6735 | if dirty_every > 0 { | ||
| 6736 | for s in (0..SLOTS).step_by(dirty_every) { | ||
| 6737 | now[s * STEP + (s % STEP)] ^= 0x5A; | ||
| 6738 | } | ||
| 6739 | } | ||
| 6740 | let mut out_s = Vec::with_capacity(SLOTS); | ||
| 6741 | let mut out_v = Vec::with_capacity(SLOTS); | ||
| 6742 | let mut t_scalar = std::time::Duration::ZERO; | ||
| 6743 | let mut t_avx2 = std::time::Duration::ZERO; | ||
| 6744 | for _ in 0..ROUNDS { | ||
| 6745 | let mut last_s = base.clone(); | ||
| 6746 | out_s.clear(); | ||
| 6747 | let t0 = std::time::Instant::now(); | ||
| 6748 | changed_records_scalar(&mut last_s, &now, STEP, 0, &mut out_s); | ||
| 6749 | t_scalar += t0.elapsed(); | ||
| 6750 | |||
| 6751 | let mut last_v = base.clone(); | ||
| 6752 | out_v.clear(); | ||
| 6753 | let t1 = std::time::Instant::now(); | ||
| 6754 | changed_records(&mut last_v, &now, STEP, 0, &mut out_v); | ||
| 6755 | t_avx2 += t1.elapsed(); | ||
| 6756 | |||
| 6757 | assert_eq!(out_s, out_v); | ||
| 6758 | } | ||
| 6759 | let s_us = t_scalar.as_secs_f64() * 1e6 / ROUNDS as f64; | ||
| 6760 | let v_us = t_avx2.as_secs_f64() * 1e6 / ROUNDS as f64; | ||
| 6761 | eprintln!( | ||
| 6762 | "changed_records ({label}, 400k x 32B): scalar={s_us:.1} us/frame, avx2={v_us:.1} us/frame, speedup={:.2}x", | ||
| 6763 | s_us / v_us | ||
| 6764 | ); | ||
| 6765 | } | ||
| 6766 | } | ||
| 6447 | } | 6767 | } |
| 6448 | 6768 | ||
| 6449 | /// Whether both are shader views of one texture the title placed in | 6769 | /// Whether both are shader views of one texture the title placed in |
| @@ -7092,7 +7412,7 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { | |||
| 7092 | compact(&mut ranges, 8); | 7412 | compact(&mut ranges, 8); |
| 7093 | assert!(ranges.len() <= 4); | 7413 | assert!(ranges.len() <= 4); |
| 7094 | for i in 0..10u64 { | 7414 | for i in 0..10u64 { |
| 7095 | assert!(ranges.iter().any(|r| r.0 <= i * 10 && i * 10 + 1 <= r.1), "change {i} lost"); | 7415 | assert!(ranges.iter().any(|r| r.0 <= i * 10 && i * 10 < r.1), "change {i} lost"); |
| 7096 | } | 7416 | } |
| 7097 | let mut touching = vec![(0, 5), (5, 9), (20, 30)]; | 7417 | let mut touching = vec![(0, 5), (5, 9), (20, 30)]; |
| 7098 | compact(&mut touching, 4); | 7418 | compact(&mut touching, 4); |
diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 2d0ec5148..812766e08 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs | |||
| @@ -2286,7 +2286,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho | |||
| 2286 | kept.ranges.change_backend(indexed_sweep_allowed(indexed, sweep_spans_in_ab, sweep_spans)); | 2286 | kept.ranges.change_backend(indexed_sweep_allowed(indexed, sweep_spans_in_ab, sweep_spans)); |
| 2287 | } | 2287 | } |
| 2288 | let changed = host.buffer_changes(); | 2288 | let changed = host.buffer_changes(); |
| 2289 | let all = kept.passes == 0 || (kept.passes % HEAP_ROUND == 0 && !heap_spread()); | 2289 | let all = kept.passes == 0 || (kept.passes.is_multiple_of(HEAP_ROUND) && !heap_spread()); |
| 2290 | let slots = if all { | 2290 | let slots = if all { |
| 2291 | kept.ranges.clear(); | 2291 | kept.ranges.clear(); |
| 2292 | host.buffer_slots() | 2292 | host.buffer_slots() |
| @@ -3202,7 +3202,7 @@ impl State { | |||
| 3202 | } else { | 3202 | } else { |
| 3203 | crate::memory::Use::Reads | 3203 | crate::memory::Use::Reads |
| 3204 | }; | 3204 | }; |
| 3205 | let Some(ready) = self.memory_ready(list, &t, compute, use_) else { | 3205 | let Some(ready) = self.memory_ready(list, t, compute, use_) else { |
| 3206 | once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); | 3206 | once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); |
| 3207 | return false; | 3207 | return false; |
| 3208 | }; | 3208 | }; |
| @@ -5344,7 +5344,7 @@ impl State { | |||
| 5344 | let draws: u32 = census.1.values().sum(); | 5344 | let draws: u32 = census.1.values().sum(); |
| 5345 | if draws > 0 { | 5345 | if draws > 0 { |
| 5346 | let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); | 5346 | let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); |
| 5347 | rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); | 5347 | rects.sort_unstable_by_key(|a| std::cmp::Reverse(a.1)); |
| 5348 | let scissors: Vec<String> = rects | 5348 | let scissors: Vec<String> = rects |
| 5349 | .iter() | 5349 | .iter() |
| 5350 | .take(5) | 5350 | .take(5) |
| @@ -6262,12 +6262,11 @@ impl State { | |||
| 6262 | /// `LEONIDA_BATCH_TEXTURE_DISPATCHES=0`: every dispatch ends the batch, as | 6262 | /// `LEONIDA_BATCH_TEXTURE_DISPATCHES=0`: every dispatch ends the batch, as |
| 6263 | /// before (an A/B switch, `LEONIDA_AB`). | 6263 | /// before (an A/B switch, `LEONIDA_AB`). |
| 6264 | fn dispatched(&mut self, p: &HostPipeline) { | 6264 | fn dispatched(&mut self, p: &HostPipeline) { |
| 6265 | if !crate::toggled!("LEONIDA_BATCH_TEXTURE_DISPATCHES") | 6265 | if (!crate::toggled!("LEONIDA_BATCH_TEXTURE_DISPATCHES") |
| 6266 | || p.stages.iter().any(|stage| stage.translated().stores) | 6266 | || p.stages.iter().any(|stage| stage.translated().stores)) |
| 6267 | && !self.stores_told(p) | ||
| 6267 | { | 6268 | { |
| 6268 | if !self.stores_told(p) { | 6269 | self.buffers_written(); |
| 6269 | self.buffers_written(); | ||
| 6270 | } | ||
| 6271 | } | 6270 | } |
| 6272 | } | 6271 | } |
| 6273 | 6272 | ||
diff --git a/d3d12/crates/leonida-gpu/src/draw/heap_sweep_tests.rs b/d3d12/crates/leonida-gpu/src/draw/heap_sweep_tests.rs index 129cd3210..d521b898d 100644 --- a/d3d12/crates/leonida-gpu/src/draw/heap_sweep_tests.rs +++ b/d3d12/crates/leonida-gpu/src/draw/heap_sweep_tests.rs | |||
| @@ -266,7 +266,7 @@ fn time_fixture(fixture: Fixture) { | |||
| 266 | let owner = if i < fixture.copies { | 266 | let owner = if i < fixture.copies { |
| 267 | i | 267 | i |
| 268 | } else { | 268 | } else { |
| 269 | (i * 31337 ^ (i >> 4)) % fixture.copies | 269 | ((i * 31337) ^ (i >> 4)) % fixture.copies |
| 270 | }; | 270 | }; |
| 271 | let base = (owner as u64) << 20; | 271 | let base = (owner as u64) << 20; |
| 272 | let (low, high) = if i < fixture.copies { | 272 | let (low, high) = if i < fixture.copies { |
diff --git a/d3d12/crates/leonida-gpu/src/fg.rs b/d3d12/crates/leonida-gpu/src/fg.rs index 023b2bec5..e448c6d8b 100644 --- a/d3d12/crates/leonida-gpu/src/fg.rs +++ b/d3d12/crates/leonida-gpu/src/fg.rs | |||
| @@ -479,7 +479,7 @@ pub(crate) fn title_presents(present: u64, token: u64) { | |||
| 479 | }; | 479 | }; |
| 480 | BY_PRESENT[(present % BY_PRESENT.len() as u64) as usize].store((present & 0xffff_ffff) << 32 | u64::from(index), Ordering::Release); | 480 | BY_PRESENT[(present % BY_PRESENT.len() as u64) as usize].store((present & 0xffff_ffff) << 32 | u64::from(index), Ordering::Release); |
| 481 | add(N::Presents, 1); | 481 | add(N::Presents, 1); |
| 482 | if present % 300 == 0 { | 482 | if present.is_multiple_of(300) { |
| 483 | log_counts(present); | 483 | log_counts(present); |
| 484 | } | 484 | } |
| 485 | } | 485 | } |
| @@ -661,7 +661,7 @@ impl WideZ for std::ffi::OsStr { | |||
| 661 | } | 661 | } |
| 662 | 662 | ||
| 663 | /// For `dlss::tests`: starts Streamline as [`start`] does (and leaves it started). | 663 | /// For `dlss::tests`: starts Streamline as [`start`] does (and leaves it started). |
| 664 | #[cfg(test)] | 664 | #[cfg(all(test, feature = "dlss"))] |
| 665 | pub(crate) fn started_for_test(device: &ID3D12Device) -> bool { | 665 | pub(crate) fn started_for_test(device: &ID3D12Device) -> bool { |
| 666 | match init(device) { | 666 | match init(device) { |
| 667 | Ok(state) => { | 667 | Ok(state) => { |
| @@ -843,7 +843,7 @@ pub(crate) fn gbuffer_submitted(depth: u64, motion: u64, size: [u32; 2]) { | |||
| 843 | tracing::info!(n, ?size, ?kept, "frame generation: another G-buffer pass of the frame, no larger than the one kept, passed over"); | 843 | tracing::info!(n, ?size, ?kept, "frame generation: another G-buffer pass of the frame, no larger than the one kept, passed over"); |
| 844 | } | 844 | } |
| 845 | } | 845 | } |
| 846 | Some((_, .., kept)) => { | 846 | Some((.., kept)) => { |
| 847 | let n = GBUFFER_PASSED_OVER.fetch_add(1, Ordering::Relaxed) + 1; | 847 | let n = GBUFFER_PASSED_OVER.fetch_add(1, Ordering::Relaxed) + 1; |
| 848 | if n <= 4 || n.is_power_of_two() { | 848 | if n <= 4 || n.is_power_of_two() { |
| 849 | tracing::info!(n, size = ?kept, larger = ?size, "frame generation: a smaller G-buffer pass of the same frame passed over"); | 849 | tracing::info!(n, size = ?kept, larger = ?size, "frame generation: a smaller G-buffer pass of the same frame passed over"); |
| @@ -974,7 +974,7 @@ pub(crate) fn present_start(frame: u64, presented: Option<&ID3D12Resource>) { | |||
| 974 | let count = FRAME.load(Ordering::Relaxed); | 974 | let count = FRAME.load(Ordering::Relaxed); |
| 975 | // The amount, at the first present and whenever the menu changed it (looked at twice a second | 975 | // The amount, at the first present and whenever the menu changed it (looked at twice a second |
| 976 | // or so): no restart, the proxy swap chain stays. | 976 | // or so): no restart, the proxy swap chain stays. |
| 977 | if s.set.is_none() || count % 8 == 0 { | 977 | if s.set.is_none() || count.is_multiple_of(8) { |
| 978 | let asked = wanted_now(); | 978 | let asked = wanted_now(); |
| 979 | // No more than the card and driver generate (DLSS 4.5 gives up to 5 here: 6x). | 979 | // No more than the card and driver generate (DLSS 4.5 gives up to 5 here: 6x). |
| 980 | // Asked once here (each question restarts Streamline's count of presented frames). | 980 | // Asked once here (each question restarts Streamline's count of presented frames). |
| @@ -1164,10 +1164,10 @@ pub(crate) fn present_end(frame: u64) { | |||
| 1164 | } else if let Ok(token) = fg.sl.new_frame_token(Some(index)) { | 1164 | } else if let Ok(token) = fg.sl.new_frame_token(Some(index)) { |
| 1165 | let _ = fg.sl.pcl_set_marker(sl::PCLMarker::ePresentEnd, token); | 1165 | let _ = fg.sl.pcl_set_marker(sl::PCLMarker::ePresentEnd, token); |
| 1166 | } | 1166 | } |
| 1167 | if index % 300 == 0 && reflex_on() { | 1167 | if index.is_multiple_of(300) && reflex_on() { |
| 1168 | log_reflex_report(fg); | 1168 | log_reflex_report(fg); |
| 1169 | } | 1169 | } |
| 1170 | if index % 300 == 0 { | 1170 | if index.is_multiple_of(300) { |
| 1171 | log_hudless(index); | 1171 | log_hudless(index); |
| 1172 | } | 1172 | } |
| 1173 | let tagged = PRESENT_TAGGED.swap(false, Ordering::Relaxed); | 1173 | let tagged = PRESENT_TAGGED.swap(false, Ordering::Relaxed); |
| @@ -1175,12 +1175,12 @@ pub(crate) fn present_end(frame: u64) { | |||
| 1175 | // present (r_cgbj41: 1 over 30 presents with the window not focused, so not a running count; | 1175 | // present (r_cgbj41: 1 over 30 presents with the window not focused, so not a running count; |
| 1176 | // DLSS-G generates nothing while the window is not focused). | 1176 | // DLSS-G generates nothing while the window is not focused). |
| 1177 | const POLL: u32 = 10; | 1177 | const POLL: u32 = 10; |
| 1178 | if index % POLL == 0 { | 1178 | if index.is_multiple_of(POLL) { |
| 1179 | match fg.sl.dlssg_get_state(&VIEWPORT, None) { | 1179 | match fg.sl.dlssg_get_state(&VIEWPORT, None) { |
| 1180 | Ok(st) => { | 1180 | Ok(st) => { |
| 1181 | let per = if st.status.0 == 0 { st.numFramesActuallyPresented.clamp(1, 6) } else { 1 }; | 1181 | let per = if st.status.0 == 0 { st.numFramesActuallyPresented.clamp(1, 6) } else { 1 }; |
| 1182 | SHOWN.store(per, Ordering::Relaxed); | 1182 | SHOWN.store(per, Ordering::Relaxed); |
| 1183 | if index % 600 == 0 || (index / POLL).is_power_of_two() { | 1183 | if index.is_multiple_of(600) || (index / POLL).is_power_of_two() { |
| 1184 | tracing::info!( | 1184 | tracing::info!( |
| 1185 | index, | 1185 | index, |
| 1186 | tagged, | 1186 | tagged, |
| @@ -1194,7 +1194,7 @@ pub(crate) fn present_end(frame: u64) { | |||
| 1194 | } | 1194 | } |
| 1195 | Err(e) => { | 1195 | Err(e) => { |
| 1196 | SHOWN.store(1, Ordering::Relaxed); | 1196 | SHOWN.store(1, Ordering::Relaxed); |
| 1197 | if index % 600 == 0 { | 1197 | if index.is_multiple_of(600) { |
| 1198 | tracing::warn!(error = %e, "frame generation: no state"); | 1198 | tracing::warn!(error = %e, "frame generation: no state"); |
| 1199 | } | 1199 | } |
| 1200 | } | 1200 | } |
diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index e7aa6b55d..c35e5d060 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs | |||
| @@ -848,21 +848,15 @@ pub(crate) fn removal_context() -> String { | |||
| 848 | use std::fmt::Write; | 848 | use std::fmt::Write; |
| 849 | let now = now_us(); | 849 | let now = now_us(); |
| 850 | let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; | 850 | let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; |
| 851 | let phase = match SUBMITTING[0].load(Ordering::Relaxed) { | 851 | let (started, finished) = (STARTED.load(Ordering::Relaxed), FINISHED.load(Ordering::Relaxed)); |
| 852 | 0 => "between submissions (nothing of ours was running on the card)", | 852 | let phase = submitting_phase(SUBMITTING[0].load(Ordering::Relaxed), started.saturating_sub(finished)); |
| 853 | 1 => "preparing a submission (nothing of ours was running on the card)", | ||
| 854 | 2 => "waiting for the card to run a submission", | ||
| 855 | _ => "copying back what a submission wrote (nothing of ours was running on the card)", | ||
| 856 | }; | ||
| 857 | let mut text = format!( | 853 | let mut text = format!( |
| 858 | "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}", | 854 | "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {started} finished {finished}", |
| 859 | SUBMITTING[1].load(Ordering::Relaxed), | 855 | SUBMITTING[1].load(Ordering::Relaxed), |
| 860 | ms(SUBMITTING[2].load(Ordering::Relaxed)), | 856 | ms(SUBMITTING[2].load(Ordering::Relaxed)), |
| 861 | crate::pipeline::library_removal_note(), | 857 | crate::pipeline::library_removal_note(), |
| 862 | RETIREMENTS[0].load(Ordering::Relaxed), | 858 | RETIREMENTS[0].load(Ordering::Relaxed), |
| 863 | RETIREMENTS[1].load(Ordering::Relaxed), | 859 | RETIREMENTS[1].load(Ordering::Relaxed), |
| 864 | STARTED.load(Ordering::Relaxed), | ||
| 865 | FINISHED.load(Ordering::Relaxed), | ||
| 866 | ); | 860 | ); |
| 867 | let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); | 861 | let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); |
| 868 | let _ = write!(text, "; the last {} things done, newest last:", trail.len()); | 862 | let _ = write!(text, "; the last {} things done, newest last:", trail.len()); |
| @@ -872,6 +866,26 @@ pub(crate) fn removal_context() -> String { | |||
| 872 | text | 866 | text |
| 873 | } | 867 | } |
| 874 | 868 | ||
| 869 | /// What the submitting thread was doing ([`SUBMITTING`]), and how many submissions of ours were started | ||
| 870 | /// and not yet seen finished (`in_air`: [`STARTED`] less [`FINISHED`]). With submissions sent ahead the | ||
| 871 | /// submitting thread can be preparing the next one while earlier ones may still run, so a device lost | ||
| 872 | /// then is told as idle only when that number is 0. (`STARTED` counts a submission from the start of | ||
| 873 | /// its preparation, so the one being prepared is among them; and one not yet seen finished may have | ||
| 874 | /// finished already: the count is of what was not observed complete.) | ||
| 875 | fn submitting_phase(phase: u64, in_air: u64) -> String { | ||
| 876 | let doing = match phase { | ||
| 877 | 0 => "between submissions", | ||
| 878 | 1 => "preparing a submission", | ||
| 879 | 2 => return "waiting for the card to run a submission".to_owned(), | ||
| 880 | _ => "copying back what a submission wrote", | ||
| 881 | }; | ||
| 882 | match in_air { | ||
| 883 | 0 => format!("{doing} (nothing of ours was running on the card)"), | ||
| 884 | 1 => format!("{doing} (1 submission of ours started and not yet seen finished)"), | ||
| 885 | n => format!("{doing} ({n} submissions of ours started and not yet seen finished)"), | ||
| 886 | } | ||
| 887 | } | ||
| 888 | |||
| 875 | /// Says [`removal_context`] in the log, once: called by whoever finds the | 889 | /// Says [`removal_context`] in the log, once: called by whoever finds the |
| 876 | /// host device removed. | 890 | /// host device removed. |
| 877 | pub(crate) fn log_removal_context() { | 891 | pub(crate) fn log_removal_context() { |
| @@ -4006,7 +4020,7 @@ struct Flight { | |||
| 4006 | 4020 | ||
| 4007 | /// One thing in the line of what waits for the card, in order. | 4021 | /// One thing in the line of what waits for the card, in order. |
| 4008 | enum Late { | 4022 | enum Late { |
| 4009 | Run(Flight), | 4023 | Run(Box<Flight>), |
| 4010 | /// A bottom-of-pipe write of the flight before it: address, what, bytes. | 4024 | /// A bottom-of-pipe write of the flight before it: address, what, bytes. |
| 4011 | Write(usize, crate::queue::Written, usize), | 4025 | Write(usize, crate::queue::Written, usize), |
| 4012 | /// A fence (its address) signalled behind the flights before it. | 4026 | /// A fence (its address) signalled behind the flights before it. |
| @@ -5539,6 +5553,7 @@ mod card_steps; | |||
| 5539 | mod cross; | 5553 | mod cross; |
| 5540 | // Leonida: what our own lists take of the card (`LEONIDA_OWN_STAMPS=1`). | 5554 | // Leonida: what our own lists take of the card (`LEONIDA_OWN_STAMPS=1`). |
| 5541 | mod ownstamps; | 5555 | mod ownstamps; |
| 5556 | #[cfg(any(test, feature = "diagnostics"))] | ||
| 5542 | pub(crate) mod indirects; | 5557 | pub(crate) mod indirects; |
| 5543 | // Leonida: the dot letters of the panel and the F1 settings menu. | 5558 | // Leonida: the dot letters of the panel and the F1 settings menu. |
| 5544 | mod font; | 5559 | mod font; |
| @@ -6884,7 +6899,7 @@ impl Host { | |||
| 6884 | let flights: Vec<&Flight> = items | 6899 | let flights: Vec<&Flight> = items |
| 6885 | .iter() | 6900 | .iter() |
| 6886 | .filter_map(|l| match l { | 6901 | .filter_map(|l| match l { |
| 6887 | Late::Run(flight) => Some(flight), | 6902 | Late::Run(flight) => Some(flight.as_ref()), |
| 6888 | _ => None, | 6903 | _ => None, |
| 6889 | }) | 6904 | }) |
| 6890 | .collect(); | 6905 | .collect(); |
| @@ -7248,7 +7263,7 @@ impl Host { | |||
| 7248 | ); | 7263 | ); |
| 7249 | *flying += order.len(); | 7264 | *flying += order.len(); |
| 7250 | *target = *submitted; | 7265 | *target = *submitted; |
| 7251 | items.push(Late::Run(Flight { | 7266 | items.push(Late::Run(Box::new(Flight { |
| 7252 | number: sent.number, | 7267 | number: sent.number, |
| 7253 | fence: *target, | 7268 | fence: *target, |
| 7254 | lists, | 7269 | lists, |
| @@ -7257,7 +7272,7 @@ impl Host { | |||
| 7257 | back: sent.back, | 7272 | back: sent.back, |
| 7258 | own: sent.own, | 7273 | own: sent.own, |
| 7259 | texture_back_ranges: sent.texture_back_ranges, | 7274 | texture_back_ranges: sent.texture_back_ranges, |
| 7260 | })); | 7275 | }))); |
| 7261 | items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); | 7276 | items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); |
| 7262 | *flying >= late_most() | 7277 | *flying >= late_most() |
| 7263 | }; | 7278 | }; |
| @@ -7407,7 +7422,7 @@ impl Host { | |||
| 7407 | ); | 7422 | ); |
| 7408 | *flying += 1; | 7423 | *flying += 1; |
| 7409 | *target = *submitted; | 7424 | *target = *submitted; |
| 7410 | items.push(Late::Run(Flight { | 7425 | items.push(Late::Run(Box::new(Flight { |
| 7411 | number, | 7426 | number, |
| 7412 | fence: *target, | 7427 | fence: *target, |
| 7413 | lists: Vec::new(), | 7428 | lists: Vec::new(), |
| @@ -7416,7 +7431,7 @@ impl Host { | |||
| 7416 | back: sent.back, | 7431 | back: sent.back, |
| 7417 | own: sent.own, | 7432 | own: sent.own, |
| 7418 | texture_back_ranges: sent.texture_back_ranges, | 7433 | texture_back_ranges: sent.texture_back_ranges, |
| 7419 | })); | 7434 | }))); |
| 7420 | items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); | 7435 | items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); |
| 7421 | } | 7436 | } |
| 7422 | LATE_STATS[0].fetch_add(1, Ordering::Relaxed); | 7437 | LATE_STATS[0].fetch_add(1, Ordering::Relaxed); |
| @@ -10947,7 +10962,9 @@ fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> | |||
| 10947 | given[i] = part; | 10962 | given[i] = part; |
| 10948 | } | 10963 | } |
| 10949 | Touch::Part => part += 1, | 10964 | Touch::Part => part += 1, |
| 10950 | Touch::Title | Touch::Nothing => {} | 10965 | #[cfg(test)] |
| 10966 | Touch::Title => {} | ||
| 10967 | Touch::Nothing => {} | ||
| 10951 | } | 10968 | } |
| 10952 | } | 10969 | } |
| 10953 | spans.retain(|s| s.1 < s.2); | 10970 | spans.retain(|s| s.1 < s.2); |
| @@ -11340,6 +11357,7 @@ enum Touch { | |||
| 11340 | /// The copy is given to shaders. | 11357 | /// The copy is given to shaders. |
| 11341 | Write(usize), | 11358 | Write(usize), |
| 11342 | /// Title memory is written. | 11359 | /// Title memory is written. |
| 11360 | #[cfg(test)] | ||
| 11343 | Title, | 11361 | Title, |
| 11344 | Nothing, | 11362 | Nothing, |
| 11345 | /// Another part of the submission begins. | 11363 | /// Another part of the submission begins. |
| @@ -11365,6 +11383,7 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize | |||
| 11365 | span.2 = true; | 11383 | span.2 = true; |
| 11366 | } | 11384 | } |
| 11367 | } | 11385 | } |
| 11386 | #[cfg(test)] | ||
| 11368 | Touch::Title => break, | 11387 | Touch::Title => break, |
| 11369 | Touch::Nothing | Touch::Part => {} | 11388 | Touch::Nothing | Touch::Part => {} |
| 11370 | } | 11389 | } |
| @@ -13382,8 +13401,7 @@ impl Host { | |||
| 13382 | list, | 13401 | list, |
| 13383 | [(texture, base_fmt), (over, over_fmt)], | 13402 | [(texture, base_fmt), (over, over_fmt)], |
| 13384 | &back, | 13403 | &back, |
| 13385 | (placed.left, placed.top), | 13404 | ((placed.left, placed.top), (width, height)), |
| 13386 | (width, height), | ||
| 13387 | ) { | 13405 | ) { |
| 13388 | copy.close(); | 13406 | copy.close(); |
| 13389 | drop(back); | 13407 | drop(back); |
| @@ -14285,6 +14303,19 @@ mod trail { | |||
| 14285 | assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); | 14303 | assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); |
| 14286 | assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); | 14304 | assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); |
| 14287 | } | 14305 | } |
| 14306 | |||
| 14307 | /// A device lost while the submitting thread is between submissions or preparing the next one is | ||
| 14308 | /// told as idle only when none of ours was started and not yet seen finished: with submissions sent | ||
| 14309 | /// ahead some can still be on the card then. | ||
| 14310 | #[test] | ||
| 14311 | fn the_removal_phase_names_submissions_not_yet_seen_finished() { | ||
| 14312 | use super::submitting_phase; | ||
| 14313 | assert_eq!(submitting_phase(1, 0), "preparing a submission (nothing of ours was running on the card)"); | ||
| 14314 | assert_eq!(submitting_phase(1, 1), "preparing a submission (1 submission of ours started and not yet seen finished)"); | ||
| 14315 | assert_eq!(submitting_phase(0, 3), "between submissions (3 submissions of ours started and not yet seen finished)"); | ||
| 14316 | assert_eq!(submitting_phase(2, 5), "waiting for the card to run a submission"); | ||
| 14317 | assert_eq!(submitting_phase(3, 0), "copying back what a submission wrote (nothing of ours was running on the card)"); | ||
| 14318 | } | ||
| 14288 | } | 14319 | } |
| 14289 | 14320 | ||
| 14290 | #[cfg(test)] | 14321 | #[cfg(test)] |
| @@ -14503,8 +14534,7 @@ mod refresh_tests { | |||
| 14503 | let copy = |i: usize| Shadow::unbacked((region + i * PAGE) as u64, unsafe { data.add(i * PAGE) }, PAGE as u64, false); | 14534 | let copy = |i: usize| Shadow::unbacked((region + i * PAGE) as u64, unsafe { data.add(i * PAGE) }, PAGE as u64, false); |
| 14504 | let (a, b, c) = (copy(0), copy(1), copy(2)); | 14535 | let (a, b, c) = (copy(0), copy(1), copy(2)); |
| 14505 | let key = |s: &Arc<Shadow>| Arc::as_ptr(s) as usize; | 14536 | let key = |s: &Arc<Shadow>| Arc::as_ptr(s) as usize; |
| 14506 | let mut batch = Batch::default(); | 14537 | let mut batch = Batch { front: true, ..Default::default() }; |
| 14507 | batch.front = true; | ||
| 14508 | for s in [&a, &b, &c] { | 14538 | for s in [&a, &b, &c] { |
| 14509 | let start = s.span().0 as usize; | 14539 | let start = s.span().0 as usize; |
| 14510 | batch.ahead.insert(key(s), (start, start + PAGE)); | 14540 | batch.ahead.insert(key(s), (start, start + PAGE)); |
diff --git a/d3d12/crates/leonida-gpu/src/host/card_steps.rs b/d3d12/crates/leonida-gpu/src/host/card_steps.rs index 71b61b129..62d2f7a24 100644 --- a/d3d12/crates/leonida-gpu/src/host/card_steps.rs +++ b/d3d12/crates/leonida-gpu/src/host/card_steps.rs | |||
| @@ -1137,7 +1137,6 @@ impl Host { | |||
| 1137 | } | 1137 | } |
| 1138 | record(level == 0, &own.list.list, &own.between, &reads, &writes, gathering.as_mut()); | 1138 | record(level == 0, &own.list.list, &own.between, &reads, &writes, gathering.as_mut()); |
| 1139 | } | 1139 | } |
| 1140 | drop(gathering); | ||
| 1141 | own.list.close(); | 1140 | own.list.close(); |
| 1142 | // SAFETY: a live buffer. | 1141 | // SAFETY: a live buffer. |
| 1143 | let gpu = unsafe { own.between.GetGPUVirtualAddress() }; | 1142 | let gpu = unsafe { own.between.GetGPUVirtualAddress() }; |
diff --git a/d3d12/crates/leonida-gpu/src/host/cross.rs b/d3d12/crates/leonida-gpu/src/host/cross.rs index a61dd1a0c..d75afd095 100644 --- a/d3d12/crates/leonida-gpu/src/host/cross.rs +++ b/d3d12/crates/leonida-gpu/src/host/cross.rs | |||
| @@ -146,7 +146,7 @@ pub(super) fn find(runs: &[&HostList]) -> Vec<Copy> { | |||
| 146 | return Vec::new(); | 146 | return Vec::new(); |
| 147 | } | 147 | } |
| 148 | // The newest first (a stable sort: one flight's writes keep their order). | 148 | // The newest first (a stable sort: one flight's writes keep their order). |
| 149 | writes.sort_by(|a, b| b.3.cmp(&a.3)); | 149 | writes.sort_by_key(|w| std::cmp::Reverse(w.3)); |
| 150 | let mut out = Vec::new(); | 150 | let mut out = Vec::new(); |
| 151 | for (reader, spans) in read { | 151 | for (reader, spans) in read { |
| 152 | last_writers(&reader, &spans, &writes, &mut out); | 152 | last_writers(&reader, &spans, &writes, &mut out); |
| @@ -285,7 +285,7 @@ mod tests { | |||
| 285 | let a = copy(0x10_1000, 0x100); | 285 | let a = copy(0x10_1000, 0x100); |
| 286 | let b = copy(0x10_1080, 0x100); | 286 | let b = copy(0x10_1080, 0x100); |
| 287 | let found = |mut writes: Vec<(Arc<Shadow>, usize, usize, usize)>| { | 287 | let found = |mut writes: Vec<(Arc<Shadow>, usize, usize, usize)>| { |
| 288 | writes.sort_by(|x, y| y.3.cmp(&x.3)); | 288 | writes.sort_by_key(|w| std::cmp::Reverse(w.3)); |
| 289 | let mut out = Vec::new(); | 289 | let mut out = Vec::new(); |
| 290 | last_writers(&big, &[(0x10_1000, 0x11_0000)], &writes, &mut out); | 290 | last_writers(&big, &[(0x10_1000, 0x11_0000)], &writes, &mut out); |
| 291 | let mut out: Vec<(usize, usize, usize)> = out.iter().map(|c| (Arc::as_ptr(&c.writer) as usize, c.from, c.to)).collect(); | 291 | let mut out: Vec<(usize, usize, usize)> = out.iter().map(|c| (Arc::as_ptr(&c.writer) as usize, c.from, c.to)).collect(); |
diff --git a/d3d12/crates/leonida-gpu/src/host/indirects.rs b/d3d12/crates/leonida-gpu/src/host/indirects.rs index 8f09336f7..cfed9bd7f 100644 --- a/d3d12/crates/leonida-gpu/src/host/indirects.rs +++ b/d3d12/crates/leonida-gpu/src/host/indirects.rs | |||
| @@ -12,6 +12,7 @@ | |||
| 12 | //! `LEONIDA_D3D12_DRED=faults` and no data at all: nothing is noted. | 12 | //! `LEONIDA_D3D12_DRED=faults` and no data at all: nothing is noted. |
| 13 | 13 | ||
| 14 | use std::collections::HashMap; | 14 | use std::collections::HashMap; |
| 15 | #[cfg(feature = "diagnostics")] | ||
| 15 | use std::sync::{Arc, Mutex}; | 16 | use std::sync::{Arc, Mutex}; |
| 16 | 17 | ||
| 17 | /// The kind of a direct mesh dispatch. | 18 | /// The kind of a direct mesh dispatch. |
| @@ -39,6 +40,7 @@ pub(crate) struct Indirects { | |||
| 39 | } | 40 | } |
| 40 | 41 | ||
| 41 | /// A list's, shared with the report's table of lists. | 42 | /// A list's, shared with the report's table of lists. |
| 43 | #[cfg(feature = "diagnostics")] | ||
| 42 | pub(crate) type Shared = Arc<Mutex<Indirects>>; | 44 | pub(crate) type Shared = Arc<Mutex<Indirects>>; |
| 43 | 45 | ||
| 44 | impl Indirects { | 46 | impl Indirects { |
diff --git a/d3d12/crates/leonida-gpu/src/host/send.rs b/d3d12/crates/leonida-gpu/src/host/send.rs index d2a2ef0fd..5fdb33cea 100644 --- a/d3d12/crates/leonida-gpu/src/host/send.rs +++ b/d3d12/crates/leonida-gpu/src/host/send.rs | |||
| @@ -32,7 +32,7 @@ const SHORT: usize = 256; | |||
| 32 | 32 | ||
| 33 | /// Whether a run of `len` bytes at offset `at` of a copy goes as pairs. | 33 | /// Whether a run of `len` bytes at offset `at` of a copy goes as pairs. |
| 34 | fn short(at: usize, len: usize) -> bool { | 34 | fn short(at: usize, len: usize) -> bool { |
| 35 | len <= SHORT && at % 4 == 0 && len % 4 == 0 | 35 | len <= SHORT && at.is_multiple_of(4) && len.is_multiple_of(4) |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | /// Whether a run of `len` bytes at offset `at` of a copy in the card's memory | 38 | /// Whether a run of `len` bytes at offset `at` of a copy in the card's memory |
diff --git a/d3d12/crates/leonida-gpu/src/indirect.rs b/d3d12/crates/leonida-gpu/src/indirect.rs index 25a51e859..2ba5eda57 100644 --- a/d3d12/crates/leonida-gpu/src/indirect.rs +++ b/d3d12/crates/leonida-gpu/src/indirect.rs | |||
| @@ -617,6 +617,7 @@ fn validate_layout( | |||
| 617 | /// their own. Replaces the list's compute root signature and pipeline | 617 | /// their own. Replaces the list's compute root signature and pipeline |
| 618 | /// (callers bind theirs after). `None` if the clamp or alignment is not | 618 | /// (callers bind theirs after). `None` if the clamp or alignment is not |
| 619 | /// available. | 619 | /// available. |
| 620 | #[cfg(test)] | ||
| 620 | pub(crate) fn bound( | 621 | pub(crate) fn bound( |
| 621 | list: &HostList, | 622 | list: &HostList, |
| 622 | src: (&ID3D12Resource, u64), | 623 | src: (&ID3D12Resource, u64), |
| @@ -710,6 +711,7 @@ fn clamp_into( | |||
| 710 | /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of | 711 | /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of |
| 711 | /// their draws ([`bound_ahead`]). False, with nothing recorded, if the | 712 | /// their draws ([`bound_ahead`]). False, with nothing recorded, if the |
| 712 | /// layout or the addresses do not fit the clamp. | 713 | /// layout or the addresses do not fit the clamp. |
| 714 | #[cfg(test)] | ||
| 713 | #[allow(clippy::too_many_arguments)] | 715 | #[allow(clippy::too_many_arguments)] |
| 714 | fn record_clamp_as( | 716 | fn record_clamp_as( |
| 715 | c: &Clamp, | 717 | c: &Clamp, |
| @@ -3624,7 +3626,7 @@ void main(uint3 g : SV_GroupID) { | |||
| 3624 | } | 3626 | } |
| 3625 | } | 3627 | } |
| 3626 | // a program that is not packed gets the record as it was | 3628 | // a program that is not packed gets the record as it was |
| 3627 | let (_src, src_ptr, src_gpu) = warp.shared_buffer(256); | 3629 | let (_src, src_ptr, _src_gpu) = warp.shared_buffer(256); |
| 3628 | let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); | 3630 | let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); |
| 3629 | let dst = warp.default_uav(64 << 10); | 3631 | let dst = warp.default_uav(64 << 10); |
| 3630 | let (back, back_ptr, _) = warp.shared_buffer(256); | 3632 | let (back, back_ptr, _) = warp.shared_buffer(256); |
| @@ -4137,7 +4139,6 @@ void work() { | |||
| 4137 | heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2], | 4139 | heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2], |
| 4138 | tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], | 4140 | tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], |
| 4139 | targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], | 4141 | targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], |
| 4140 | depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, | ||
| 4141 | depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, | 4142 | depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, |
| 4142 | stamps: ID3D12QueryHeap, | 4143 | stamps: ID3D12QueryHeap, |
| 4143 | back: ID3D12Resource, | 4144 | back: ID3D12Resource, |
| @@ -4445,7 +4446,6 @@ void work() { | |||
| 4445 | heap_pairs, | 4446 | heap_pairs, |
| 4446 | tables, | 4447 | tables, |
| 4447 | targets, | 4448 | targets, |
| 4448 | depth_written, | ||
| 4449 | depth_tested, | 4449 | depth_tested, |
| 4450 | stamps, | 4450 | stamps, |
| 4451 | back, | 4451 | back, |
diff --git a/d3d12/crates/leonida-gpu/src/indirect/batch.rs b/d3d12/crates/leonida-gpu/src/indirect/batch.rs index 0d5c441e4..54e7240f1 100644 --- a/d3d12/crates/leonida-gpu/src/indirect/batch.rs +++ b/d3d12/crates/leonida-gpu/src/indirect/batch.rs | |||
| @@ -283,6 +283,7 @@ impl Table { | |||
| 283 | /// of the host copy `id`, once the pass has run: a job of it is added if | 283 | /// of the host copy `id`, once the pass has run: a job of it is added if |
| 284 | /// there is none. `None` if the pass cannot read that copy or has no | 284 | /// there is none. `None` if the pass cannot read that copy or has no |
| 285 | /// room for another job. | 285 | /// room for another job. |
| 286 | #[cfg(test)] | ||
| 286 | pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> { | 287 | pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> { |
| 287 | self.place_packed(id, offset, kind, 0) | 288 | self.place_packed(id, offset, kind, 0) |
| 288 | } | 289 | } |
diff --git a/d3d12/crates/leonida-gpu/src/land.rs b/d3d12/crates/leonida-gpu/src/land.rs index d0c8ef117..820b9c5a9 100644 --- a/d3d12/crates/leonida-gpu/src/land.rs +++ b/d3d12/crates/leonida-gpu/src/land.rs | |||
| @@ -676,7 +676,7 @@ pub(crate) unsafe fn piece( | |||
| 676 | copy: *const crate::shadow::Shadow, | 676 | copy: *const crate::shadow::Shadow, |
| 677 | ) -> u64 { | 677 | ) -> u64 { |
| 678 | // SAFETY: the caller's. | 678 | // SAFETY: the caller's. |
| 679 | unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) } | 679 | unsafe { piece_at(title, now, held, parts, (take, beside_on()), notes, copy) } |
| 680 | } | 680 | } |
| 681 | 681 | ||
| 682 | /// [`piece`], and whether a view of ours is looked for. | 682 | /// [`piece`], and whether a view of ours is looked for. |
| @@ -688,9 +688,8 @@ unsafe fn piece_at( | |||
| 688 | now: *const u8, | 688 | now: *const u8, |
| 689 | held: *mut u8, | 689 | held: *mut u8, |
| 690 | parts: &[(usize, usize)], | 690 | parts: &[(usize, usize)], |
| 691 | take: bool, | 691 | (take, beside): (bool, bool), |
| 692 | notes: &mut Notes, | 692 | notes: &mut Notes, |
| 693 | beside: bool, | ||
| 694 | copy: *const crate::shadow::Shadow, | 693 | copy: *const crate::shadow::Shadow, |
| 695 | ) -> u64 { | 694 | ) -> u64 { |
| 696 | let Some(end) = parts.last().map(|p| p.1) else { | 695 | let Some(end) = parts.last().map(|p| p.1) else { |
diff --git a/d3d12/crates/leonida-gpu/src/land/tests.rs b/d3d12/crates/leonida-gpu/src/land/tests.rs index 0dedbade6..43b153f67 100644 --- a/d3d12/crates/leonida-gpu/src/land/tests.rs +++ b/d3d12/crates/leonida-gpu/src/land/tests.rs | |||
| @@ -313,7 +313,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() { | |||
| 313 | while !stop.load(Ordering::Relaxed) { | 313 | while !stop.load(Ordering::Relaxed) { |
| 314 | // Its own dwords, in every other block (in the rest | 314 | // Its own dwords, in every other block (in the rest |
| 315 | // only landings change anything). | 315 | // only landings change anything). |
| 316 | for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { | 316 | for i in (w..LEN / 4).step_by(4 * 97).filter(|i| (i * 4 / BLOCK).is_multiple_of(2)) { |
| 317 | assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); | 317 | assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); |
| 318 | } | 318 | } |
| 319 | value += 1; | 319 | value += 1; |
| @@ -363,7 +363,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() { | |||
| 363 | stop.store(true, Ordering::Relaxed); | 363 | stop.store(true, Ordering::Relaxed); |
| 364 | for (w, writer) in writers.into_iter().enumerate() { | 364 | for (w, writer) in writers.into_iter().enumerate() { |
| 365 | let last = writer.join().expect("nothing undone"); | 365 | let last = writer.join().expect("nothing undone"); |
| 366 | for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { | 366 | for i in (w..LEN / 4).step_by(4 * 97).filter(|i| (i * 4 / BLOCK).is_multiple_of(2)) { |
| 367 | assert_eq!(dword(i).load(Ordering::Relaxed), last); | 367 | assert_eq!(dword(i).load(Ordering::Relaxed), last); |
| 368 | } | 368 | } |
| 369 | } | 369 | } |
| @@ -477,7 +477,7 @@ fn what_landing_costs() { | |||
| 477 | let mut notes = Notes::default(); | 477 | let mut notes = Notes::default(); |
| 478 | for &(at, now, held) in &landing[jobs[j].clone()] { | 478 | for &(at, now, held) in &landing[jobs[j].clone()] { |
| 479 | // SAFETY: each its own bytes. | 479 | // SAFETY: each its own bytes. |
| 480 | unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) }; | 480 | unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], (true, beside), &mut notes, std::ptr::null()) }; |
| 481 | } | 481 | } |
| 482 | notes.flush(); | 482 | notes.flush(); |
| 483 | }); | 483 | }); |
diff --git a/d3d12/crates/leonida-gpu/src/list/thin.rs b/d3d12/crates/leonida-gpu/src/list/thin.rs index ab25e1c2b..1862dfc64 100644 --- a/d3d12/crates/leonida-gpu/src/list/thin.rs +++ b/d3d12/crates/leonida-gpu/src/list/thin.rs | |||
| @@ -1042,6 +1042,7 @@ mod tests { | |||
| 1042 | let mut slot = [0x5256_5476u64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; | 1042 | let mut slot = [0x5256_5476u64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; |
| 1043 | let kept = record(slot.as_ptr() as u64); | 1043 | let kept = record(slot.as_ptr() as u64); |
| 1044 | slot[1] = 99; | 1044 | slot[1] = 99; |
| 1045 | assert_eq!(slot[1], 99); | ||
| 1045 | assert_eq!(kept[1], 2); | 1046 | assert_eq!(kept[1], 2); |
| 1046 | assert_eq!(record(0), [0; RECORD]); | 1047 | assert_eq!(record(0), [0; RECORD]); |
| 1047 | } | 1048 | } |
diff --git a/d3d12/crates/leonida-gpu/src/pipeline/known.rs b/d3d12/crates/leonida-gpu/src/pipeline/known.rs index 4d588896c..c5830e0b7 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/known.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/known.rs | |||
| @@ -61,7 +61,9 @@ fn book() -> Option<&'static Mutex<Book>> { | |||
| 61 | let mut keys = HashSet::new(); | 61 | let mut keys = HashSet::new(); |
| 62 | let mut shaders = HashSet::new(); | 62 | let mut shaders = HashSet::new(); |
| 63 | let ends = [ | 63 | let ends = [ |
| 64 | walk_shaders(&dir, |_, hash, _, _| drop(shaders.insert(hash))), | 64 | walk_shaders(&dir, |_, hash, _, _| { |
| 65 | let _ = shaders.insert(hash); | ||
| 66 | }), | ||
| 65 | walk_pipelines(&dir, |_, bytes| { | 67 | walk_pipelines(&dir, |_, bytes| { |
| 66 | keys.extend(bytes.first_chunk::<16>().copied()); | 68 | keys.extend(bytes.first_chunk::<16>().copied()); |
| 67 | }), | 69 | }), |
| @@ -286,7 +288,9 @@ pub fn store(dir: &Path, which: &[usize], threads: usize, each: impl FnMut(usize | |||
| 286 | /// there is one. | 288 | /// there is one. |
| 287 | pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64, bool)>)) { | 289 | pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64, bool)>)) { |
| 288 | let mut places = HashMap::new(); | 290 | let mut places = HashMap::new(); |
| 289 | walk_shaders(dir, |stage, hash, at, len| drop(places.insert(hash, (stage, at, len)))); | 291 | walk_shaders(dir, |stage, hash, at, len| { |
| 292 | let _ = places.insert(hash, (stage, at, len)); | ||
| 293 | }); | ||
| 290 | let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { return }; | 294 | let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { return }; |
| 291 | let wanted: HashSet<usize> = which.iter().copied().collect(); | 295 | let wanted: HashSet<usize> = which.iter().copied().collect(); |
| 292 | let mut entries = HashMap::new(); | 296 | let mut entries = HashMap::new(); |
diff --git a/d3d12/crates/leonida-gpu/src/port.rs b/d3d12/crates/leonida-gpu/src/port.rs index 3e18d7d3b..5ae39bef3 100644 --- a/d3d12/crates/leonida-gpu/src/port.rs +++ b/d3d12/crates/leonida-gpu/src/port.rs | |||
| @@ -330,7 +330,7 @@ mod tests { | |||
| 330 | let low = |at: u64, len: u64| at.checked_add(len).is_some_and(|end| end <= LOW && len > 0); | 330 | let low = |at: u64, len: u64| at.checked_add(len).is_some_and(|end| end <= LOW && len > 0); |
| 331 | assert!(low(0x34e1_0000, 0xae0_0000)); | 331 | assert!(low(0x34e1_0000, 0xae0_0000)); |
| 332 | assert!(!low(0xffff_0000, 0x2_0000)); | 332 | assert!(!low(0xffff_0000, 0x2_0000)); |
| 333 | assert!(!low(0xe1c80_0000, 0x1000)); | 333 | assert!(!low(0x000e_1c80_0000, 0x1000)); |
| 334 | assert!(!low(u64::MAX, 2)); | 334 | assert!(!low(u64::MAX, 2)); |
| 335 | } | 335 | } |
| 336 | 336 | ||
diff --git a/d3d12/crates/leonida-gpu/src/port_descriptors.rs b/d3d12/crates/leonida-gpu/src/port_descriptors.rs index 3721c040c..0b9d96fbf 100644 --- a/d3d12/crates/leonida-gpu/src/port_descriptors.rs +++ b/d3d12/crates/leonida-gpu/src/port_descriptors.rs | |||
| @@ -599,7 +599,7 @@ mod tests { | |||
| 599 | } | 599 | } |
| 600 | // SAFETY: `memcpy`'s own, into the vector. | 600 | // SAFETY: `memcpy`'s own, into the vector. |
| 601 | unsafe { | 601 | unsafe { |
| 602 | REAL[0].store(libc_memcpy as usize, Relaxed); | 602 | REAL[0].store(libc_memcpy as *const () as usize, Relaxed); |
| 603 | copy(heap.as_mut_ptr().add(40 * 32), records.as_ptr(), records.len()); | 603 | copy(heap.as_mut_ptr().add(40 * 32), records.as_ptr(), records.len()); |
| 604 | // A copy that begins inside a record leaves it to the copy that wrote its first word. | 604 | // A copy that begins inside a record leaves it to the copy that wrote its first word. |
| 605 | copy(heap.as_mut_ptr().add(100 * 32 + 8), records.as_ptr(), 24); | 605 | copy(heap.as_mut_ptr().add(100 * 32 + 8), records.as_ptr(), 24); |
diff --git a/d3d12/crates/leonida-gpu/src/queue.rs b/d3d12/crates/leonida-gpu/src/queue.rs index 6c095d254..801b32e08 100644 --- a/d3d12/crates/leonida-gpu/src/queue.rs +++ b/d3d12/crates/leonida-gpu/src/queue.rs | |||
| @@ -1615,7 +1615,7 @@ mod tests { | |||
| 1615 | 1615 | ||
| 1616 | #[test] | 1616 | #[test] |
| 1617 | fn a_pair_of_timestamps_shows_the_load_it_is_given() { | 1617 | fn a_pair_of_timestamps_shows_the_load_it_is_given() { |
| 1618 | let (start, end) = (0xd0419_6698, 0xd0419_6690); | 1618 | let (start, end) = (0x000d_0419_6698, 0x000d_0419_6690); |
| 1619 | assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000); | 1619 | assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000); |
| 1620 | assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000); | 1620 | assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000); |
| 1621 | assert_eq!(as_loaded(5, start, 100), 1); | 1621 | assert_eq!(as_loaded(5, start, 100), 1); |
diff --git a/d3d12/crates/leonida-gpu/src/queue/behind.rs b/d3d12/crates/leonida-gpu/src/queue/behind.rs index e16ef2983..8e00ccfee 100644 --- a/d3d12/crates/leonida-gpu/src/queue/behind.rs +++ b/d3d12/crates/leonida-gpu/src/queue/behind.rs | |||
| @@ -945,12 +945,6 @@ fn alias_wait(number: u64) { | |||
| 945 | } | 945 | } |
| 946 | } | 946 | } |
| 947 | 947 | ||
| 948 | /// For whoever must see every page mapping the title asked for so far (a read of title memory | ||
| 949 | /// outside the line's order): until they are all done. | ||
| 950 | pub(super) fn alias_drain() { | ||
| 951 | alias_wait(ALIAS_SENT.load(Relaxed)); | ||
| 952 | } | ||
| 953 | |||
| 954 | /// This thread does work the line waits for. | 948 | /// This thread does work the line waits for. |
| 955 | pub(super) fn no_drain_here() { | 949 | pub(super) fn no_drain_here() { |
| 956 | OURS.set(true); | 950 | OURS.set(true); |
diff --git a/d3d12/crates/leonida-gpu/src/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index 8793a88a4..2a781c09e 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs | |||
| @@ -101,7 +101,7 @@ pub(crate) struct ResourceDesc { | |||
| 101 | #[cfg(windows)] | 101 | #[cfg(windows)] |
| 102 | impl ResourceDesc { | 102 | impl ResourceDesc { |
| 103 | /// The texture of this one's levels from `base` on. | 103 | /// The texture of this one's levels from `base` on. |
| 104 | fn from_level(&self, base: u32) -> ResourceDesc { | 104 | fn at_level(&self, base: u32) -> ResourceDesc { |
| 105 | let mut d = *self; | 105 | let mut d = *self; |
| 106 | if base > 0 { | 106 | if base > 0 { |
| 107 | d.width = (d.width >> base).max(1); | 107 | d.width = (d.width >> base).max(1); |
| @@ -1303,9 +1303,12 @@ type Made = (std::sync::Arc<HostTexture>, Option<std::sync::Arc<Twin>>); | |||
| 1303 | /// copy is the card's. | 1303 | /// copy is the card's. |
| 1304 | #[cfg(windows)] | 1304 | #[cfg(windows)] |
| 1305 | struct Hosted { | 1305 | struct Hosted { |
| 1306 | /// The host copy (and twin) once made. Taken out again only by | 1306 | /// The host copy (and twin) once made. Taken out again by |
| 1307 | /// [`let_go_idle`] and when the title releases the resource. | 1307 | /// [`let_go_idle`], by [`want_level`] for one with more levels, and |
| 1308 | made: std::sync::Mutex<Option<Made>>, | 1308 | /// when the title releases the resource. Changed only under its lock |
| 1309 | /// held alone, through [`Hosted::put`] and [`Hosted::take`], which say | ||
| 1310 | /// so in `made_base`. | ||
| 1311 | made: std::sync::RwLock<Option<Made>>, | ||
| 1309 | /// The state and clear value the title created the texture with. | 1312 | /// The state and clear value the title created the texture with. |
| 1310 | state: u32, | 1313 | state: u32, |
| 1311 | clear: Option<[u32; 5]>, | 1314 | clear: Option<[u32; 5]>, |
| @@ -1328,10 +1331,66 @@ struct Hosted { | |||
| 1328 | /// The lowest level a view asked for since it had no host copy | 1331 | /// The lowest level a view asked for since it had no host copy |
| 1329 | /// ([`want_level`]; `u32::MAX`: none said). | 1332 | /// ([`want_level`]; `u32::MAX`: none said). |
| 1330 | wanted: std::sync::atomic::AtomicU32, | 1333 | wanted: std::sync::atomic::AtomicU32, |
| 1334 | /// Leonida: what `made` holds, for the list threads to read without | ||
| 1335 | /// its lock (`LEONIDA_LIST_LOCK_FAST`, | ||
| 1336 | /// `crate::descriptor::list_lock_fast`): the first level of the host | ||
| 1337 | /// copy ([`HostTexture::base`]), [`NO_COPY`] while there is none. | ||
| 1338 | /// Written with `made` whatever the switch says: it may be turned | ||
| 1339 | /// while the title runs. | ||
| 1340 | made_base: std::sync::atomic::AtomicU32, | ||
| 1331 | /// The next host copy takes the place of one with fewer levels. | 1341 | /// The next host copy takes the place of one with fewer levels. |
| 1332 | grown: std::sync::atomic::AtomicBool, | 1342 | grown: std::sync::atomic::AtomicBool, |
| 1333 | } | 1343 | } |
| 1334 | 1344 | ||
| 1345 | /// [`Hosted::made_base`] of a texture without a host copy. | ||
| 1346 | #[cfg(windows)] | ||
| 1347 | const NO_COPY: u32 = u32::MAX; | ||
| 1348 | |||
| 1349 | #[cfg(windows)] | ||
| 1350 | impl Hosted { | ||
| 1351 | /// `made` held alone: to change it, and wherever the list threads took | ||
| 1352 | /// its lock that way before (`crate::descriptor::list_lock_fast` off). | ||
| 1353 | fn alone(&self) -> std::sync::RwLockWriteGuard<'_, Option<Made>> { | ||
| 1354 | self.made.write().unwrap_or_else(|e| e.into_inner()) | ||
| 1355 | } | ||
| 1356 | |||
| 1357 | /// `made` held with the other threads that only look at it. | ||
| 1358 | fn shared(&self) -> std::sync::RwLockReadGuard<'_, Option<Made>> { | ||
| 1359 | self.made.read().unwrap_or_else(|e| e.into_inner()) | ||
| 1360 | } | ||
| 1361 | |||
| 1362 | /// Gives the texture its host copy; `made` is its lock held alone | ||
| 1363 | /// ([`Hosted::alone`]). The word is written after `made`, under that | ||
| 1364 | /// lock. | ||
| 1365 | fn put(&self, made: &mut std::sync::RwLockWriteGuard<'_, Option<Made>>, copy: Made) { | ||
| 1366 | let base = copy.0.base; | ||
| 1367 | **made = Some(copy); | ||
| 1368 | self.made_base.store(base, std::sync::atomic::Ordering::Release); | ||
| 1369 | } | ||
| 1370 | |||
| 1371 | /// Takes the host copy out, if there is one; `made` is its lock held | ||
| 1372 | /// alone ([`Hosted::alone`]). The word is written after `made`, under | ||
| 1373 | /// that lock. | ||
| 1374 | fn take(&self, made: &mut std::sync::RwLockWriteGuard<'_, Option<Made>>) -> Option<Made> { | ||
| 1375 | let copy = made.take(); | ||
| 1376 | self.made_base.store(NO_COPY, std::sync::atomic::Ordering::Release); | ||
| 1377 | copy | ||
| 1378 | } | ||
| 1379 | |||
| 1380 | /// Whether a texture without a host copy gets none now: nobody asks | ||
| 1381 | /// for one to be made (`make`), the host refused it, or the card had | ||
| 1382 | /// no room for it a moment ago (not asked again on every use: | ||
| 1383 | /// [`NO_ROOM_AGAIN_MS`]). | ||
| 1384 | fn none_now(&self, make: bool) -> bool { | ||
| 1385 | use std::sync::atomic::Ordering::Relaxed; | ||
| 1386 | if !make || self.refused.load(Relaxed) { | ||
| 1387 | return true; | ||
| 1388 | } | ||
| 1389 | let no_room = self.no_room.load(Relaxed); | ||
| 1390 | no_room != 0 && !crate::host::long_ago(no_room, NO_ROOM_AGAIN_MS, 0) | ||
| 1391 | } | ||
| 1392 | } | ||
| 1393 | |||
| 1335 | /// Whether a texture the title places in memory is read, kept and uploaded | 1394 | /// Whether a texture the title places in memory is read, kept and uploaded |
| 1336 | /// from the first level its views show on (`LEONIDA_HELD_LEVELS=0`: whole, | 1395 | /// from the first level its views show on (`LEONIDA_HELD_LEVELS=0`: whole, |
| 1337 | /// as before). Such a title describes every level of a texture and views it | 1396 | /// as before). Such a title describes every level of a texture and views it |
| @@ -1444,7 +1503,7 @@ pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync:: | |||
| 1444 | /// one go on showing it until that is done). | 1503 | /// one go on showing it until that is done). |
| 1445 | #[cfg(windows)] | 1504 | #[cfg(windows)] |
| 1446 | pub(crate) fn want_level(this: This, first: u32) { | 1505 | pub(crate) fn want_level(this: This, first: u32) { |
| 1447 | use std::sync::atomic::Ordering::Relaxed; | 1506 | use std::sync::atomic::Ordering::{Acquire, Relaxed}; |
| 1448 | if this.is_null() || !held_only() { | 1507 | if this.is_null() || !held_only() { |
| 1449 | return; | 1508 | return; |
| 1450 | } | 1509 | } |
| @@ -1452,7 +1511,23 @@ pub(crate) fn want_level(this: This, first: u32) { | |||
| 1452 | if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) { | 1511 | if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) { |
| 1453 | return; | 1512 | return; |
| 1454 | } | 1513 | } |
| 1455 | let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 1514 | // Leonida: a host copy that has the level, read without the lock |
| 1515 | // (`crate::descriptor::list_lock_fast`): the answer of nearly every | ||
| 1516 | // call. Every placed view a draw reads asks, on six list threads, and | ||
| 1517 | // each took the texture's lock alone for it (of their samples 1.6 % | ||
| 1518 | // here and 3.5 % in the lookup before it, [`texture_at`]: issue 2707's | ||
| 1519 | // profile). The word is written under that lock, after `made`: what is | ||
| 1520 | // read here is what the lock would have shown a call that came a moment | ||
| 1521 | // sooner. Anything else is looked at again under the lock, as before: | ||
| 1522 | // no copy (the level is noted for whoever makes one, who reads it under | ||
| 1523 | // the same lock) or a copy without the level (replaced). | ||
| 1524 | if crate::descriptor::list_lock_fast() { | ||
| 1525 | let base = r.host.made_base.load(Acquire); | ||
| 1526 | if base != NO_COPY && (base == 0 || base <= base_level(&r.desc, first)) { | ||
| 1527 | return; | ||
| 1528 | } | ||
| 1529 | } | ||
| 1530 | let mut made = r.host.alone(); | ||
| 1456 | let Some((host, _)) = made.as_ref() else { | 1531 | let Some((host, _)) = made.as_ref() else { |
| 1457 | r.host.wanted.fetch_min(first, Relaxed); | 1532 | r.host.wanted.fetch_min(first, Relaxed); |
| 1458 | return; | 1533 | return; |
| @@ -1465,7 +1540,7 @@ pub(crate) fn want_level(this: This, first: u32) { | |||
| 1465 | crate::texture::unstage(this); | 1540 | crate::texture::unstage(this); |
| 1466 | r.host.grown.store(true, Relaxed); | 1541 | r.host.grown.store(true, Relaxed); |
| 1467 | HELD[2].fetch_add(1, Relaxed); | 1542 | HELD[2].fetch_add(1, Relaxed); |
| 1468 | if let Some(old) = made.take() { | 1543 | if let Some(old) = r.host.take(&mut made) { |
| 1469 | REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); | 1544 | REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); |
| 1470 | } | 1545 | } |
| 1471 | } | 1546 | } |
| @@ -1826,9 +1901,15 @@ pub(crate) fn host_waits(this: This) -> bool { | |||
| 1826 | return false; | 1901 | return false; |
| 1827 | } | 1902 | } |
| 1828 | let r = resource(this); | 1903 | let r = resource(this); |
| 1829 | r.desc.dimension != BUFFER | 1904 | if r.desc.dimension == BUFFER || r.host.refused.load(std::sync::atomic::Ordering::Relaxed) { |
| 1830 | && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) | 1905 | return false; |
| 1831 | && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() | 1906 | } |
| 1907 | // Leonida: from the word that says it, with no lock | ||
| 1908 | // (`crate::descriptor::list_lock_fast`); off, under the lock as before. | ||
| 1909 | if crate::descriptor::list_lock_fast() { | ||
| 1910 | return r.host.made_base.load(std::sync::atomic::Ordering::Acquire) == NO_COPY; | ||
| 1911 | } | ||
| 1912 | r.host.alone().is_none() | ||
| 1832 | } | 1913 | } |
| 1833 | 1914 | ||
| 1834 | /// Whether texture `this` has no host copy because the card had no room for | 1915 | /// Whether texture `this` has no host copy because the card had no room for |
| @@ -1850,20 +1931,45 @@ pub(crate) fn waits_for_room(this: This) -> bool { | |||
| 1850 | /// for one the card had no room for a moment ago. | 1931 | /// for one the card had no room for a moment ago. |
| 1851 | #[cfg(windows)] | 1932 | #[cfg(windows)] |
| 1852 | fn hosted(this: This, make: bool) -> Option<Made> { | 1933 | fn hosted(this: This, make: bool) -> Option<Made> { |
| 1853 | use std::sync::atomic::Ordering::Relaxed; | 1934 | use std::sync::atomic::Ordering::{Acquire, Relaxed}; |
| 1854 | let r = resource(this); | 1935 | let r = resource(this); |
| 1855 | if r.desc.dimension == BUFFER { | 1936 | if r.desc.dimension == BUFFER { |
| 1856 | return None; | 1937 | return None; |
| 1857 | } | 1938 | } |
| 1858 | let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 1939 | // Leonida: the two answers nearly every call ends with, without the |
| 1859 | if made.is_none() { | 1940 | // texture's lock held alone (`crate::descriptor::list_lock_fast`): the |
| 1860 | if !make || r.host.refused.load(Relaxed) { | 1941 | // host copy that is there, under the lock held with the other threads |
| 1861 | return None; | 1942 | // that ask for it, and none where none is made now, from the word that |
| 1943 | // says so. Every texture of every draw is asked for here, and what many | ||
| 1944 | // draws share (shadow maps, the sky's textures, atlases) by several of | ||
| 1945 | // the six list threads at once, which then waited for one another: of | ||
| 1946 | // their samples 4.2 % were taking this lock and giving it back (issue | ||
| 1947 | // 2707's profile). Off: alone at every call, as before. | ||
| 1948 | if crate::descriptor::list_lock_fast() { | ||
| 1949 | if r.host.made_base.load(Acquire) == NO_COPY { | ||
| 1950 | if r.host.none_now(make) { | ||
| 1951 | return None; | ||
| 1952 | } | ||
| 1953 | } else { | ||
| 1954 | let made = r.host.shared(); | ||
| 1955 | if let Some(found) = made.as_ref() { | ||
| 1956 | // Noted and handed out under the lock, as below: the sweep | ||
| 1957 | // takes a copy out with the lock held alone | ||
| 1958 | // ([`let_go_of`]), so it sees every asking that came before | ||
| 1959 | // it and the copy each one holds. (Several note their | ||
| 1960 | // moment at once here: never an earlier over a later one.) | ||
| 1961 | let now = crate::host::moment(); | ||
| 1962 | if r.host.used.load(Relaxed) < now { | ||
| 1963 | r.host.used.fetch_max(now, Relaxed); | ||
| 1964 | } | ||
| 1965 | return Some(found.clone()); | ||
| 1966 | } | ||
| 1967 | // (Taken out since the word was read: as before, below.) | ||
| 1862 | } | 1968 | } |
| 1863 | // The card had no room for it a moment ago: not asked again on | 1969 | } |
| 1864 | // every use (`NO_ROOM_AGAIN_MS`). | 1970 | let mut made = r.host.alone(); |
| 1865 | let no_room = r.host.no_room.load(Relaxed); | 1971 | if made.is_none() { |
| 1866 | if no_room != 0 && !crate::host::long_ago(no_room, NO_ROOM_AGAIN_MS, 0) { | 1972 | if r.host.none_now(make) { |
| 1867 | return None; | 1973 | return None; |
| 1868 | } | 1974 | } |
| 1869 | let clear = r | 1975 | let clear = r |
| @@ -1928,7 +2034,7 @@ fn hosted(this: This, make: bool) -> Option<Made> { | |||
| 1928 | } | 2034 | } |
| 1929 | let made_texture = match texture { | 2035 | let made_texture = match texture { |
| 1930 | Some(texture) => Ok((texture, false, None)), | 2036 | Some(texture) => Ok((texture, false, None)), |
| 1931 | None => host_texture(&r.desc.from_level(base), r.host.state, clear), | 2037 | None => host_texture(&r.desc.at_level(base), r.host.state, clear), |
| 1932 | }; | 2038 | }; |
| 1933 | let (texture, castable_r9g9b9e5, initial_state) = match made_texture { | 2039 | let (texture, castable_r9g9b9e5, initial_state) = match made_texture { |
| 1934 | Ok(made) => made, | 2040 | Ok(made) => made, |
| @@ -1987,7 +2093,7 @@ fn hosted(this: This, make: bool) -> Option<Made> { | |||
| 1987 | r.host.remade.fetch_add(1, Relaxed); | 2093 | r.host.remade.fetch_add(1, Relaxed); |
| 1988 | } | 2094 | } |
| 1989 | KINDS[6].fetch_add(1, Relaxed); | 2095 | KINDS[6].fetch_add(1, Relaxed); |
| 1990 | *made = Some((std::sync::Arc::new(host), twin)); | 2096 | r.host.put(&mut made, (std::sync::Arc::new(host), twin)); |
| 1991 | // Slots the title wrote with views of it while it had no host copy | 2097 | // Slots the title wrote with views of it while it had no host copy |
| 1992 | // are made before the next submission runs. | 2098 | // are made before the next submission runs. |
| 1993 | crate::descriptor::texture_made(this as usize); | 2099 | crate::descriptor::texture_made(this as usize); |
| @@ -2295,7 +2401,7 @@ pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { | |||
| 2295 | return None; | 2401 | return None; |
| 2296 | } | 2402 | } |
| 2297 | let memory = r.data() as u64; | 2403 | let memory = r.data() as u64; |
| 2298 | let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 2404 | let made = r.host.shared(); |
| 2299 | Some(match made.as_ref() { | 2405 | Some(match made.as_ref() { |
| 2300 | Some((host, _)) => (2, host.bytes, memory), | 2406 | Some((host, _)) => (2, host.bytes, memory), |
| 2301 | None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), | 2407 | None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), |
| @@ -2350,7 +2456,7 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, | |||
| 2350 | if !fills(&r.desc) { | 2456 | if !fills(&r.desc) { |
| 2351 | continue; | 2457 | continue; |
| 2352 | } | 2458 | } |
| 2353 | let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 2459 | let made = r.host.shared(); |
| 2354 | match made.as_ref() { | 2460 | match made.as_ref() { |
| 2355 | Some((host, _)) => copies.push(match &host.tiled { | 2461 | Some((host, _)) => copies.push(match &host.tiled { |
| 2356 | Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), | 2462 | Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), |
| @@ -2596,40 +2702,11 @@ pub(crate) fn let_go_idle() { | |||
| 2596 | let began = std::time::Instant::now(); | 2702 | let began = std::time::Instant::now(); |
| 2597 | // Lets go of the host copy of the texture at `at` if it has been out of | 2703 | // Lets go of the host copy of the texture at `at` if it has been out of |
| 2598 | // use for `ms` and `frames` and only its title texture holds it: its | 2704 | // use for `ms` and `frames` and only its title texture holds it: its |
| 2599 | // bytes, if it went. | 2705 | // bytes, if it went ([`let_go_of`]). |
| 2600 | let let_go = |at: usize, ms: u64, frames: u64| -> Option<u64> { | 2706 | let let_go = |at: usize, ms: u64, frames: u64| -> Option<u64> { |
| 2601 | // SAFETY: a texture leaves the table before it is freed, under the | 2707 | // SAFETY: a texture leaves the table before it is freed, under the |
| 2602 | // lock held here (`Drop for Resource`). | 2708 | // lock held here (`Drop for Resource`). |
| 2603 | let r = unsafe { &*(at as *const Resource) }; | 2709 | let_go_of(unsafe { &*(at as *const Resource) }, ms, frames) |
| 2604 | // (Without its lock first: most were used lately or have none.) | ||
| 2605 | let used = r.host.used.load(Relaxed); | ||
| 2606 | if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, ms, frames) || crate::texture::host_wrote(at) { | ||
| 2607 | return None; | ||
| 2608 | } | ||
| 2609 | let gone = { | ||
| 2610 | let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 2611 | let idle = made.as_ref().is_some_and(|(host, _)| { | ||
| 2612 | crate::host::long_ago(r.host.used.load(Relaxed), ms, frames) | ||
| 2613 | && std::sync::Arc::strong_count(host) == 1 | ||
| 2614 | && crate::host::references(&host.texture) == 1 | ||
| 2615 | }); | ||
| 2616 | if idle { | ||
| 2617 | // Under the lock: the next use must not find the staging | ||
| 2618 | // state of the texture let go (it says "uploaded"). | ||
| 2619 | crate::texture::unstage(at as This); | ||
| 2620 | r.host.wanted.store(u32::MAX, Relaxed); | ||
| 2621 | made.take() | ||
| 2622 | } else { | ||
| 2623 | None | ||
| 2624 | } | ||
| 2625 | }; | ||
| 2626 | let (host, _) = gone?; | ||
| 2627 | r.host.gone.store(true, Relaxed); | ||
| 2628 | KINDS[2].fetch_add(1, Relaxed); | ||
| 2629 | KINDS[3].fetch_add(host.bytes, Relaxed); | ||
| 2630 | let bytes = host.bytes; | ||
| 2631 | crate::host::retire(host); | ||
| 2632 | Some(bytes) | ||
| 2633 | }; | 2710 | }; |
| 2634 | for at in sweep_batch(&all, from, part, crate::toggled!("LEONIDA_SWEEP_WRAP")).chain(by_age.iter().map(|&(_, at)| at)) { | 2711 | for at in sweep_batch(&all, from, part, crate::toggled!("LEONIDA_SWEEP_WRAP")).chain(by_age.iter().map(|&(_, at)| at)) { |
| 2635 | if bytes >= most { | 2712 | if bytes >= most { |
| @@ -2677,6 +2754,51 @@ pub(crate) fn let_go_idle() { | |||
| 2677 | } | 2754 | } |
| 2678 | } | 2755 | } |
| 2679 | 2756 | ||
| 2757 | /// [`let_go_idle`] for one title texture: lets go of its host copy if it has | ||
| 2758 | /// been out of use for `ms` and `frames` and only the texture holds it; its | ||
| 2759 | /// bytes, if it went. | ||
| 2760 | #[cfg(windows)] | ||
| 2761 | fn let_go_of(r: &Resource, ms: u64, frames: u64) -> Option<u64> { | ||
| 2762 | use std::sync::atomic::Ordering::Relaxed; | ||
| 2763 | let at = std::ptr::from_ref(r) as usize; | ||
| 2764 | // (Without its lock first: most were used lately or have none.) | ||
| 2765 | let used = r.host.used.load(Relaxed); | ||
| 2766 | if used == 0 | ||
| 2767 | || !fills(&r.desc) | ||
| 2768 | || !crate::host::long_ago(used, ms, frames) | ||
| 2769 | || crate::texture::host_wrote(at) | ||
| 2770 | { | ||
| 2771 | return None; | ||
| 2772 | } | ||
| 2773 | let gone = { | ||
| 2774 | // Alone, however the draws take the lock ([`hosted`]): none of them | ||
| 2775 | // notes its asking or is handed the copy between this look and the | ||
| 2776 | // taking. | ||
| 2777 | let mut made = r.host.alone(); | ||
| 2778 | let idle = made.as_ref().is_some_and(|(host, _)| { | ||
| 2779 | crate::host::long_ago(r.host.used.load(Relaxed), ms, frames) | ||
| 2780 | && std::sync::Arc::strong_count(host) == 1 | ||
| 2781 | && crate::host::references(&host.texture) == 1 | ||
| 2782 | }); | ||
| 2783 | if idle { | ||
| 2784 | // Under the lock: the next use must not find the staging | ||
| 2785 | // state of the texture let go (it says "uploaded"). | ||
| 2786 | crate::texture::unstage(at as This); | ||
| 2787 | r.host.wanted.store(u32::MAX, Relaxed); | ||
| 2788 | r.host.take(&mut made) | ||
| 2789 | } else { | ||
| 2790 | None | ||
| 2791 | } | ||
| 2792 | }; | ||
| 2793 | let (host, _) = gone?; | ||
| 2794 | r.host.gone.store(true, Relaxed); | ||
| 2795 | KINDS[2].fetch_add(1, Relaxed); | ||
| 2796 | KINDS[3].fetch_add(host.bytes, Relaxed); | ||
| 2797 | let bytes = host.bytes; | ||
| 2798 | crate::host::retire(host); | ||
| 2799 | Some(bytes) | ||
| 2800 | } | ||
| 2801 | |||
| 2680 | /// Sweeps made with little left to commit ([`commit_floor`]), and the host | 2802 | /// Sweeps made with little left to commit ([`commit_floor`]), and the host |
| 2681 | /// copies they let go beyond what the card's rule lets go, and their bytes, | 2803 | /// copies they let go beyond what the card's rule lets go, and their bytes, |
| 2682 | /// since the start. | 2804 | /// since the start. |
| @@ -2708,13 +2830,15 @@ const FLOOR_IDLE_FRAMES: u64 = 60; | |||
| 2708 | /// and a scene went dark.) | 2830 | /// and a scene went dark.) |
| 2709 | #[cfg(windows)] | 2831 | #[cfg(windows)] |
| 2710 | fn commit_floor() -> bool { | 2832 | fn commit_floor() -> bool { |
| 2833 | fn env_on() -> bool { | ||
| 2834 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
| 2835 | *ON.get_or_init(|| std::env::var_os("LEONIDA_COMMIT_FLOOR").is_some_and(|v| v == "1")) | ||
| 2836 | } | ||
| 2711 | #[cfg(feature = "diagnostics")] | 2837 | #[cfg(feature = "diagnostics")] |
| 2712 | let picked = crate::ab::pick("LEONIDA_COMMIT_FLOOR"); | 2838 | let on = crate::ab::pick("LEONIDA_COMMIT_FLOOR").unwrap_or_else(env_on); |
| 2713 | #[cfg(not(feature = "diagnostics"))] | 2839 | #[cfg(not(feature = "diagnostics"))] |
| 2714 | let picked = None; | 2840 | let on = env_on(); |
| 2715 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
| 2716 | static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); | 2841 | static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); |
| 2717 | let on = picked.unwrap_or_else(|| *ON.get_or_init(|| std::env::var_os("LEONIDA_COMMIT_FLOOR").is_some_and(|v| v == "1"))); | ||
| 2718 | on && crate::residency::available_commit() | 2842 | on && crate::residency::available_commit() |
| 2719 | < *FLOOR.get_or_init(|| { | 2843 | < *FLOOR.get_or_init(|| { |
| 2720 | std::env::var("LEONIDA_COMMIT_FLOOR_MB").ok().and_then(|mb| mb.trim().parse::<u64>().ok()).unwrap_or(4096) << 20 | 2844 | std::env::var("LEONIDA_COMMIT_FLOOR_MB").ok().and_then(|mb| mb.trim().parse::<u64>().ok()).unwrap_or(4096) << 20 |
| @@ -2800,7 +2924,7 @@ pub(crate) fn targets_census() -> [u64; 12] { | |||
| 2800 | for &at in all.iter() { | 2924 | for &at in all.iter() { |
| 2801 | // SAFETY: as in `let_go_idle`. | 2925 | // SAFETY: as in `let_go_idle`. |
| 2802 | let r = unsafe { &*(at as *const Resource) }; | 2926 | let r = unsafe { &*(at as *const Resource) }; |
| 2803 | let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 2927 | let made = r.host.shared(); |
| 2804 | let Some((host, twin)) = made.as_ref() else { | 2928 | let Some((host, twin)) = made.as_ref() else { |
| 2805 | continue; | 2929 | continue; |
| 2806 | }; | 2930 | }; |
| @@ -2861,7 +2985,7 @@ pub(crate) fn census() -> [u64; 10] { | |||
| 2861 | for &at in all.iter() { | 2985 | for &at in all.iter() { |
| 2862 | // SAFETY: as in `let_go_idle`. | 2986 | // SAFETY: as in `let_go_idle`. |
| 2863 | let r = unsafe { &*(at as *const Resource) }; | 2987 | let r = unsafe { &*(at as *const Resource) }; |
| 2864 | let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); | 2988 | let made = r.host.shared(); |
| 2865 | match made.as_ref() { | 2989 | match made.as_ref() { |
| 2866 | Some((host, twin)) => { | 2990 | Some((host, twin)) => { |
| 2867 | let kind = if host.filled { 4 } else { 0 }; | 2991 | let kind = if host.filled { 4 } else { 0 }; |
| @@ -3389,7 +3513,7 @@ fn hand_out_resource( | |||
| 3389 | backing, | 3513 | backing, |
| 3390 | #[cfg(windows)] | 3514 | #[cfg(windows)] |
| 3391 | host: Hosted { | 3515 | host: Hosted { |
| 3392 | made: std::sync::Mutex::new(None), | 3516 | made: std::sync::RwLock::new(None), |
| 3393 | state, | 3517 | state, |
| 3394 | // SAFETY: the title passes a whole clear value (the format, | 3518 | // SAFETY: the title passes a whole clear value (the format, |
| 3395 | // then color or depth and stencil: 5 words) or null. | 3519 | // then color or depth and stencil: 5 words) or null. |
| @@ -3401,6 +3525,7 @@ fn hand_out_resource( | |||
| 3401 | remade: std::sync::atomic::AtomicU32::new(0), | 3525 | remade: std::sync::atomic::AtomicU32::new(0), |
| 3402 | placed: std::sync::atomic::AtomicBool::new(false), | 3526 | placed: std::sync::atomic::AtomicBool::new(false), |
| 3403 | wanted: std::sync::atomic::AtomicU32::new(u32::MAX), | 3527 | wanted: std::sync::atomic::AtomicU32::new(u32::MAX), |
| 3528 | made_base: std::sync::atomic::AtomicU32::new(NO_COPY), | ||
| 3404 | grown: std::sync::atomic::AtomicBool::new(false), | 3529 | grown: std::sync::atomic::AtomicBool::new(false), |
| 3405 | }, | 3530 | }, |
| 3406 | }); | 3531 | }); |
| @@ -3456,6 +3581,7 @@ impl Drop for Resource { | |||
| 3456 | .get_mut() | 3581 | .get_mut() |
| 3457 | .unwrap_or_else(|e| e.into_inner()) | 3582 | .unwrap_or_else(|e| e.into_inner()) |
| 3458 | .take(); | 3583 | .take(); |
| 3584 | *self.host.made_base.get_mut() = NO_COPY; | ||
| 3459 | #[cfg(feature = "diagnostics")] | 3585 | #[cfg(feature = "diagnostics")] |
| 3460 | if made | 3586 | if made |
| 3461 | .as_ref() | 3587 | .as_ref() |
| @@ -3665,9 +3791,19 @@ static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; | |||
| 3665 | /// What a table holds is never taken out: [`PLACED_TEXTURES`] keeps its resources for the run. | 3791 | /// What a table holds is never taken out: [`PLACED_TEXTURES`] keeps its resources for the run. |
| 3666 | #[cfg(windows)] | 3792 | #[cfg(windows)] |
| 3667 | fn placed_shards() -> bool { | 3793 | fn placed_shards() -> bool { |
| 3794 | #[cfg(test)] | ||
| 3795 | if let Some(on) = PLACED_SHARDS_TEST.get() { | ||
| 3796 | return on; | ||
| 3797 | } | ||
| 3668 | crate::toggled!("LEONIDA_PLACED_SHARDS") | 3798 | crate::toggled!("LEONIDA_PLACED_SHARDS") |
| 3669 | } | 3799 | } |
| 3670 | 3800 | ||
| 3801 | #[cfg(all(windows, test))] | ||
| 3802 | thread_local! { | ||
| 3803 | /// A test's own setting of [`placed_shards`] on its thread. | ||
| 3804 | static PLACED_SHARDS_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; | ||
| 3805 | } | ||
| 3806 | |||
| 3671 | /// The tables in front of [`PLACED_TEXTURES`] ([`placed_shards`]). | 3807 | /// The tables in front of [`PLACED_TEXTURES`] ([`placed_shards`]). |
| 3672 | #[cfg(windows)] | 3808 | #[cfg(windows)] |
| 3673 | const PLACED_SHARD_COUNT: usize = 64; | 3809 | const PLACED_SHARD_COUNT: usize = 64; |
| @@ -3687,6 +3823,77 @@ fn placed_shard(address: u64, key: &[u32; 14]) -> &'static std::sync::RwLock<Pla | |||
| 3687 | &PLACED_FOUND[(mixed >> 58) as usize % PLACED_SHARD_COUNT] | 3823 | &PLACED_FOUND[(mixed >> 58) as usize % PLACED_SHARD_COUNT] |
| 3688 | } | 3824 | } |
| 3689 | 3825 | ||
| 3826 | /// Leonida: with `LEONIDA_LIST_LOCK_FAST` (`crate::descriptor::list_lock_fast`) a placed texture a thread found | ||
| 3827 | /// before ([`texture_at`]) is found again in a table of the thread's own, with no lock, in front of the tables | ||
| 3828 | /// of [`placed_shards`]. A lookup there takes and gives back a shared lock: two writes to a word the other list | ||
| 3829 | /// threads write for their own lookups (six threads, 64 tables), for every placed view of every draw; of the | ||
| 3830 | /// list threads' samples 3.5 % were under `placed_texture` (issue 2707's profile). Only in front of those | ||
| 3831 | /// tables: with `LEONIDA_PLACED_SHARDS=0` every lookup takes the one lock, and the diagnostics' count of filler | ||
| 3832 | /// twins sees it, as before. | ||
| 3833 | /// | ||
| 3834 | /// The table has [`PLACED_NEAR_SETS`] places of two textures each (a third of a megabyte, made at the thread's | ||
| 3835 | /// first lookup), by address and format. A texture whose place holds two others is looked up under the lock, | ||
| 3836 | /// as before, and takes the place of one of them once that one was not found again between two such lookups. | ||
| 3837 | /// What a place holds stays true: [`PLACED_TEXTURES`] keeps its resources for the run, and an address and | ||
| 3838 | /// description never come to name another. | ||
| 3839 | #[cfg(windows)] | ||
| 3840 | const PLACED_NEAR_SETS: usize = 1 << PLACED_NEAR_BITS; | ||
| 3841 | |||
| 3842 | /// The bits of a place's number in [`PLACED_NEAR`]. | ||
| 3843 | #[cfg(windows)] | ||
| 3844 | const PLACED_NEAR_BITS: u32 = 11; | ||
| 3845 | |||
| 3846 | /// A place of [`PLACED_NEAR`]: two placed textures, each with its address and description, its resource (0: | ||
| 3847 | /// none yet) and whether it was found here again since a texture last found both places taken. | ||
| 3848 | #[cfg(windows)] | ||
| 3849 | type PlacedNear = [((u64, [u32; 14]), usize, bool); 2]; | ||
| 3850 | |||
| 3851 | #[cfg(windows)] | ||
| 3852 | thread_local! { | ||
| 3853 | /// The placed textures this thread found ([`PLACED_NEAR_SETS`] places; none until it finds one). | ||
| 3854 | static PLACED_NEAR: std::cell::RefCell<Vec<PlacedNear>> = const { std::cell::RefCell::new(Vec::new()) }; | ||
| 3855 | } | ||
| 3856 | |||
| 3857 | /// The place in [`PLACED_NEAR`] of the placed texture at `address` with the description `key`. | ||
| 3858 | #[cfg(windows)] | ||
| 3859 | fn placed_near_set(address: u64, key: &[u32; 14]) -> usize { | ||
| 3860 | // The address and, above its bits, the format, mixed; the top bits pick the place. | ||
| 3861 | let mixed = (address ^ (u64::from(key[8]) << 48)).wrapping_mul(0x9E37_79B9_7F4A_7C15); | ||
| 3862 | (mixed >> (64 - PLACED_NEAR_BITS)) as usize | ||
| 3863 | } | ||
| 3864 | |||
| 3865 | /// The resource of the placed texture at `address` with the description `key`, if this thread found it before | ||
| 3866 | /// and has it still ([`PLACED_NEAR`]). | ||
| 3867 | #[cfg(windows)] | ||
| 3868 | fn placed_near(address: u64, key: &[u32; 14]) -> Option<usize> { | ||
| 3869 | PLACED_NEAR.with_borrow_mut(|sets| { | ||
| 3870 | let set = sets.get_mut(placed_near_set(address, key))?; | ||
| 3871 | let found = set | ||
| 3872 | .iter_mut() | ||
| 3873 | .find(|(known, texture, _)| *texture != 0 && known.0 == address && known.1 == *key)?; | ||
| 3874 | found.2 = true; | ||
| 3875 | Some(found.1) | ||
| 3876 | }) | ||
| 3877 | } | ||
| 3878 | |||
| 3879 | /// This thread found `texture`, under a lock, for the placed texture at `address` with the description `key`: | ||
| 3880 | /// it takes a place in [`PLACED_NEAR`], unless both textures there were found again since the last that did | ||
| 3881 | /// not. | ||
| 3882 | #[cfg(windows)] | ||
| 3883 | fn placed_near_note(address: u64, key: &[u32; 14], texture: usize) { | ||
| 3884 | PLACED_NEAR.with_borrow_mut(|sets| { | ||
| 3885 | if sets.is_empty() { | ||
| 3886 | sets.resize(PLACED_NEAR_SETS, [((0, [0; 14]), 0, false); 2]); | ||
| 3887 | } | ||
| 3888 | let set = &mut sets[placed_near_set(address, key)]; | ||
| 3889 | match set.iter().position(|(_, _, again)| !*again) { | ||
| 3890 | Some(way) => set[way] = ((address, *key), texture, true), | ||
| 3891 | // Both stay this time: the one not found again before the next such lookup goes then. | ||
| 3892 | None => set.iter_mut().for_each(|(_, _, again)| *again = false), | ||
| 3893 | } | ||
| 3894 | }); | ||
| 3895 | } | ||
| 3896 | |||
| 3690 | /// Whether the filler twins are counted with [`placed_shards`] on (`LEONIDA_PLACED_TWINS=1`). | 3897 | /// Whether the filler twins are counted with [`placed_shards`] on (`LEONIDA_PLACED_TWINS=1`). |
| 3691 | #[cfg(all(windows, feature = "diagnostics"))] | 3898 | #[cfg(all(windows, feature = "diagnostics"))] |
| 3692 | fn placed_twins_counted() -> bool { | 3899 | fn placed_twins_counted() -> bool { |
| @@ -3804,13 +4011,27 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { | |||
| 3804 | key[13] = 0; | 4011 | key[13] = 0; |
| 3805 | } | 4012 | } |
| 3806 | let desc = &key; | 4013 | let desc = &key; |
| 3807 | // Leonida: found before, found again under a shared lock (`placed_shards`). | 4014 | // Leonida: found before, found again under a shared lock (`placed_shards`); by this thread, with no |
| 4015 | // lock ([`PLACED_NEAR`]). | ||
| 3808 | let shards = placed_shards(); | 4016 | let shards = placed_shards(); |
| 3809 | if shards | 4017 | let near = shards && crate::descriptor::list_lock_fast(); |
| 3810 | && let Some(&r) = placed_shard(address, desc).read().unwrap_or_else(|e| e.into_inner()).get(&(address, *desc)) | 4018 | if near && let Some(r) = placed_near(address, desc) { |
| 3811 | { | ||
| 3812 | return Some(r as This); | 4019 | return Some(r as This); |
| 3813 | } | 4020 | } |
| 4021 | if shards { | ||
| 4022 | // (The tables' lock is given back before the thread's own table is written.) | ||
| 4023 | let known = placed_shard(address, desc) | ||
| 4024 | .read() | ||
| 4025 | .unwrap_or_else(|e| e.into_inner()) | ||
| 4026 | .get(&(address, *desc)) | ||
| 4027 | .copied(); | ||
| 4028 | if let Some(r) = known { | ||
| 4029 | if near { | ||
| 4030 | placed_near_note(address, desc, r); | ||
| 4031 | } | ||
| 4032 | return Some(r as This); | ||
| 4033 | } | ||
| 4034 | } | ||
| 3814 | let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); | 4035 | let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); |
| 3815 | // How many resources the filler alone would have added (a count for | 4036 | // How many resources the filler alone would have added (a count for |
| 3816 | // the log: `placed_filler_twins`). Diagnostics builds only: without | 4037 | // the log: `placed_filler_twins`). Diagnostics builds only: without |
| @@ -3838,6 +4059,9 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { | |||
| 3838 | if shards { | 4059 | if shards { |
| 3839 | placed_shard(address, desc).write().unwrap_or_else(|e| e.into_inner()).insert((address, *desc), r); | 4060 | placed_shard(address, desc).write().unwrap_or_else(|e| e.into_inner()).insert((address, *desc), r); |
| 3840 | } | 4061 | } |
| 4062 | if near { | ||
| 4063 | placed_near_note(address, desc, r); | ||
| 4064 | } | ||
| 3841 | }; | 4065 | }; |
| 3842 | if let Some(&r) = map.get(&(address, *desc)) { | 4066 | if let Some(&r) = map.get(&(address, *desc)) { |
| 3843 | found(r); | 4067 | found(r); |
| @@ -4441,24 +4665,37 @@ mod tests { | |||
| 4441 | S_OK | 4665 | S_OK |
| 4442 | ); | 4666 | ); |
| 4443 | let r = resource(image); | 4667 | let r = resource(image); |
| 4668 | // Each answer with the texture's lock taken alone, as before, and | ||
| 4669 | // without it where it need not be (`LEONIDA_LIST_LOCK_FAST`). | ||
| 4670 | let either = |answers: &dyn Fn()| { | ||
| 4671 | for fast in [true, false] { | ||
| 4672 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(fast)); | ||
| 4673 | answers(); | ||
| 4674 | } | ||
| 4675 | crate::descriptor::LIST_LOCK_FAST_TEST.set(None); | ||
| 4676 | }; | ||
| 4444 | // As `hosted` leaves a texture the card had no room for just now: | 4677 | // As `hosted` leaves a texture the card had no room for just now: |
| 4445 | // not asked again yet, but still waited for (not refused). | 4678 | // not asked again yet, but still waited for (not refused). |
| 4446 | *r.host.made.lock().unwrap() = None; | 4679 | r.host.take(&mut r.host.alone()); |
| 4447 | r.host.no_room.store(crate::host::moment().max(1), Relaxed); | 4680 | r.host.no_room.store(crate::host::moment().max(1), Relaxed); |
| 4448 | assert!(hosted(image, true).is_none(), "asked again only after NO_ROOM_AGAIN_MS"); | 4681 | either(&|| { |
| 4449 | assert!(host_waits(image), "a texture without room still waits for its host copy"); | 4682 | assert!(hosted(image, true).is_none(), "asked again only after NO_ROOM_AGAIN_MS"); |
| 4450 | assert!(waits_for_room(image), "and whoever looks at it is told to look again"); | 4683 | assert!(host_waits(image), "a texture without room still waits for its host copy"); |
| 4684 | assert!(waits_for_room(image), "and whoever looks at it is told to look again"); | ||
| 4685 | }); | ||
| 4451 | // After the wait, the next use makes it. | 4686 | // After the wait, the next use makes it. |
| 4452 | std::thread::sleep(std::time::Duration::from_millis(NO_ROOM_AGAIN_MS + 200)); | 4687 | std::thread::sleep(std::time::Duration::from_millis(NO_ROOM_AGAIN_MS + 200)); |
| 4453 | assert!(hosted(image, true).is_some(), "made on a later use"); | 4688 | either(&|| assert!(hosted(image, true).is_some(), "made on a later use")); |
| 4454 | assert_eq!(r.host.no_room.load(Relaxed), 0); | 4689 | assert_eq!(r.host.no_room.load(Relaxed), 0); |
| 4455 | assert!(!waits_for_room(image)); | 4690 | assert!(!waits_for_room(image)); |
| 4456 | // Refused: never again. | 4691 | // Refused: never again. |
| 4457 | *r.host.made.lock().unwrap() = None; | 4692 | r.host.take(&mut r.host.alone()); |
| 4458 | r.host.no_room.store(0, Relaxed); | 4693 | r.host.no_room.store(0, Relaxed); |
| 4459 | r.host.refused.store(true, Relaxed); | 4694 | r.host.refused.store(true, Relaxed); |
| 4460 | assert!(hosted(image, true).is_none()); | 4695 | either(&|| { |
| 4461 | assert!(!host_waits(image)); | 4696 | assert!(hosted(image, true).is_none()); |
| 4697 | assert!(!host_waits(image)); | ||
| 4698 | }); | ||
| 4462 | assert!(!waits_for_room(image)); | 4699 | assert!(!waits_for_room(image)); |
| 4463 | crate::object::release_boxed::<Resource>(image); | 4700 | crate::object::release_boxed::<Resource>(image); |
| 4464 | } | 4701 | } |
| @@ -5670,7 +5907,7 @@ float4 lit() : SV_Target { return 1.0; } | |||
| 5670 | // A rule that lets all go sooner than the floor would: the floor adds nothing. | 5907 | // A rule that lets all go sooner than the floor would: the floor adds nothing. |
| 5671 | assert_eq!(commit_floor_times(true, 1_000, u64::MAX, 4), None); | 5908 | assert_eq!(commit_floor_times(true, 1_000, u64::MAX, 4), None); |
| 5672 | assert_eq!(commit_floor_times(true, FLOOR_IDLE_MS, u64::MAX, 4), None); | 5909 | assert_eq!(commit_floor_times(true, FLOOR_IDLE_MS, u64::MAX, 4), None); |
| 5673 | assert!(FLOOR_IDLE_MS >= 2_500 && FLOOR_IDLE_FRAMES >= 60); | 5910 | const { assert!(FLOOR_IDLE_MS >= 2_500 && FLOOR_IDLE_FRAMES >= 60) }; |
| 5674 | } | 5911 | } |
| 5675 | 5912 | ||
| 5676 | #[test] | 5913 | #[test] |
| @@ -5765,4 +6002,426 @@ float4 lit() : SV_Target { return 1.0; } | |||
| 5765 | assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); | 6002 | assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); |
| 5766 | assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); | 6003 | assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); |
| 5767 | } | 6004 | } |
| 6005 | |||
| 6006 | /// How a test's lookups take a texture's lock from one call to the next (`LEONIDA_LIST_LOCK_FAST`): | ||
| 6007 | /// alone every time, as before; without it where they can; and by turns, as `LEONIDA_AB` switches it | ||
| 6008 | /// while the title runs. | ||
| 6009 | #[cfg(windows)] | ||
| 6010 | const TURNS: [[bool; 2]; 3] = [[false, false], [true, true], [false, true]]; | ||
| 6011 | |||
| 6012 | /// Sets that switch for this thread's call number `call` as `turns` has it. | ||
| 6013 | #[cfg(windows)] | ||
| 6014 | fn turn(turns: [bool; 2], call: usize) { | ||
| 6015 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(turns[call % 2])); | ||
| 6016 | } | ||
| 6017 | |||
| 6018 | /// What a thread of its own, with `LEONIDA_LIST_LOCK_FAST` on, answers `ask` of the texture at `at` | ||
| 6019 | /// while this thread holds `held`, that texture's lock: `None` if it had not answered after 20 seconds, | ||
| 6020 | /// for then it waited for the lock. | ||
| 6021 | #[cfg(windows)] | ||
| 6022 | fn asked_while<G, T: Send + 'static>(held: G, at: usize, ask: fn(This) -> T) -> Option<T> { | ||
| 6023 | let (said, heard) = std::sync::mpsc::channel(); | ||
| 6024 | let asking = std::thread::spawn(move || { | ||
| 6025 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(true)); | ||
| 6026 | let _ = said.send(ask(at as This)); | ||
| 6027 | }); | ||
| 6028 | let answer = heard.recv_timeout(std::time::Duration::from_secs(20)).ok(); | ||
| 6029 | drop(held); | ||
| 6030 | asking.join().unwrap(); | ||
| 6031 | answer | ||
| 6032 | } | ||
| 6033 | |||
| 6034 | /// A 4x4 texture the title fills, made as the title makes one. | ||
| 6035 | #[cfg(windows)] | ||
| 6036 | fn filled_texture() -> This { | ||
| 6037 | let null = std::ptr::null(); | ||
| 6038 | let mut image = null; | ||
| 6039 | let rgba = texture(4, 4, 28, 1); | ||
| 6040 | assert_eq!( | ||
| 6041 | create_committed(null, &PROPERTIES, 0, &rgba, 0, null.cast(), &RESOURCE_IIDS[0], &mut image), | ||
| 6042 | S_OK | ||
| 6043 | ); | ||
| 6044 | image | ||
| 6045 | } | ||
| 6046 | |||
| 6047 | /// A view from an earlier level than a placed texture's host copy has gets it another with that level, | ||
| 6048 | /// and one from a level it has leaves it be, with the texture's lock taken alone at every call, without | ||
| 6049 | /// it, and by turns ([`TURNS`]); the word read without the lock says what there is each time. | ||
| 6050 | #[cfg(windows)] | ||
| 6051 | #[test] | ||
| 6052 | fn a_view_from_an_earlier_level_gets_a_copy_with_it_however_the_lock_is_taken() { | ||
| 6053 | use std::sync::atomic::Ordering::Relaxed; | ||
| 6054 | use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; | ||
| 6055 | if crate::host::host().is_none() || !held_only() || !lazy() { | ||
| 6056 | return; | ||
| 6057 | } | ||
| 6058 | // 256x256 BC7, nine levels, 4 KiB blocks. | ||
| 6059 | let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; | ||
| 6060 | let whole = placed_bytes(&desc).unwrap() as usize; | ||
| 6061 | for turns in TURNS { | ||
| 6062 | let mut call = 0; | ||
| 6063 | let mut next = || { | ||
| 6064 | call += 1; | ||
| 6065 | turn(turns, call); | ||
| 6066 | }; | ||
| 6067 | // SAFETY: memory of our own that stays. | ||
| 6068 | let at = unsafe { | ||
| 6069 | VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) | ||
| 6070 | }; | ||
| 6071 | next(); | ||
| 6072 | let texture = texture_at(at as u64, &desc).unwrap(); | ||
| 6073 | let r = resource(texture); | ||
| 6074 | let said = || r.host.made_base.load(Relaxed); | ||
| 6075 | // No host copy yet: the lowest level asked for is noted for the one to be made. | ||
| 6076 | for first in [5, 2, 4] { | ||
| 6077 | next(); | ||
| 6078 | want_level(texture, first); | ||
| 6079 | } | ||
| 6080 | assert_eq!((r.host.wanted.load(Relaxed), said()), (2, NO_COPY)); | ||
| 6081 | next(); | ||
| 6082 | assert!(host_waits(texture) && made_copy(texture).is_none()); | ||
| 6083 | next(); | ||
| 6084 | let copy = host_copy(texture).unwrap(); | ||
| 6085 | assert_eq!((copy.base, said()), (2, 2)); | ||
| 6086 | // Levels it has: the same copy. | ||
| 6087 | for first in [2, 5, 3] { | ||
| 6088 | next(); | ||
| 6089 | want_level(texture, first); | ||
| 6090 | next(); | ||
| 6091 | assert_eq!(host_copy(texture).unwrap().serial, copy.serial); | ||
| 6092 | } | ||
| 6093 | // An earlier one: the copy is taken out, and one with that level made at the next use. | ||
| 6094 | let earlier = base_level(&r.desc, 1); | ||
| 6095 | assert!(earlier < 2); | ||
| 6096 | next(); | ||
| 6097 | want_level(texture, 1); | ||
| 6098 | assert_eq!((r.host.wanted.load(Relaxed), said()), (1, NO_COPY)); | ||
| 6099 | next(); | ||
| 6100 | assert!(host_waits(texture) && made_copy(texture).is_none()); | ||
| 6101 | next(); | ||
| 6102 | let more = host_copy(texture).unwrap(); | ||
| 6103 | assert_eq!((more.base, said()), (earlier, earlier)); | ||
| 6104 | assert!(more.serial != copy.serial && more.grown.load(Relaxed)); | ||
| 6105 | // The whole of it, after which nothing asks for more. | ||
| 6106 | for _ in 0..2 { | ||
| 6107 | next(); | ||
| 6108 | want_level(texture, 0); | ||
| 6109 | } | ||
| 6110 | next(); | ||
| 6111 | let all = host_copy(texture).unwrap(); | ||
| 6112 | assert_eq!((all.base, said()), (0, 0)); | ||
| 6113 | next(); | ||
| 6114 | want_level(texture, 0); | ||
| 6115 | assert_eq!(made_copy(texture).map(|copy| copy.serial), Some(all.serial)); | ||
| 6116 | } | ||
| 6117 | crate::descriptor::LIST_LOCK_FAST_TEST.set(None); | ||
| 6118 | } | ||
| 6119 | |||
| 6120 | /// The sweep lets a host copy go only while its title texture alone holds it, however the draws before | ||
| 6121 | /// asked for it ([`TURNS`]): what they were handed is all that is held besides, and their asking is | ||
| 6122 | /// noted. A copy let go is seen gone at once, and made again at the next use. | ||
| 6123 | #[cfg(windows)] | ||
| 6124 | #[test] | ||
| 6125 | fn a_copy_goes_when_its_texture_alone_holds_it_and_not_before() { | ||
| 6126 | use std::sync::atomic::Ordering::Relaxed; | ||
| 6127 | if crate::host::host().is_none() || !lazy() { | ||
| 6128 | return; // no host GPU here | ||
| 6129 | } | ||
| 6130 | // (A use is told from none by its moment, which is 0 in a run's first tenth of a second.) | ||
| 6131 | while crate::host::moment() == 0 { | ||
| 6132 | std::thread::sleep(std::time::Duration::from_millis(10)); | ||
| 6133 | } | ||
| 6134 | for turns in TURNS { | ||
| 6135 | let mut call = 0; | ||
| 6136 | let mut next = || { | ||
| 6137 | call += 1; | ||
| 6138 | turn(turns, call); | ||
| 6139 | }; | ||
| 6140 | let image = filled_texture(); | ||
| 6141 | let r = resource(image); | ||
| 6142 | next(); | ||
| 6143 | assert!(host_waits(image) && made_copy(image).is_none()); | ||
| 6144 | assert_eq!(let_go_of(r, 0, 0), None, "never used"); | ||
| 6145 | next(); | ||
| 6146 | let held = host_copy(image).unwrap(); | ||
| 6147 | let used = r.host.used.load(Relaxed); | ||
| 6148 | assert!(used != 0 && r.host.made_base.load(Relaxed) == 0); | ||
| 6149 | // Asked every way, many times: nothing keeps a copy but who was handed one. | ||
| 6150 | for _ in 0..64 { | ||
| 6151 | next(); | ||
| 6152 | assert!(!host_waits(image) && host_resource(image).is_some()); | ||
| 6153 | assert_eq!(made_copy(image).map(|copy| copy.serial), Some(held.serial)); | ||
| 6154 | } | ||
| 6155 | assert_eq!(std::sync::Arc::strong_count(&held), 2, "the texture's and the one handed out"); | ||
| 6156 | assert!(r.host.used.load(Relaxed) >= used); | ||
| 6157 | assert_eq!(let_go_of(r, 0, 0), None, "held by who asked for it"); | ||
| 6158 | next(); | ||
| 6159 | assert_eq!(made_copy(image).map(|copy| copy.serial), Some(held.serial)); | ||
| 6160 | let (serial, bytes) = (held.serial, held.bytes); | ||
| 6161 | drop(held); | ||
| 6162 | assert_eq!(let_go_of(r, 0, 0), Some(bytes), "only its texture held it"); | ||
| 6163 | assert_eq!(r.host.made_base.load(Relaxed), NO_COPY); | ||
| 6164 | next(); | ||
| 6165 | assert!(host_waits(image) && made_copy(image).is_none()); | ||
| 6166 | next(); | ||
| 6167 | let again = host_copy(image).unwrap(); | ||
| 6168 | assert!(again.serial != serial && r.host.made_base.load(Relaxed) == 0); | ||
| 6169 | drop(again); | ||
| 6170 | crate::object::release_boxed::<Resource>(image); | ||
| 6171 | } | ||
| 6172 | crate::descriptor::LIST_LOCK_FAST_TEST.set(None); | ||
| 6173 | } | ||
| 6174 | |||
| 6175 | /// A thread's own table of placed textures (`LEONIDA_LIST_LOCK_FAST`): two that share a place are both | ||
| 6176 | /// kept; a third is looked up under the lock as before while those two are found again, and takes the | ||
| 6177 | /// place of the one that no longer is. | ||
| 6178 | #[cfg(windows)] | ||
| 6179 | #[test] | ||
| 6180 | fn a_place_keeps_the_two_textures_found_again() { | ||
| 6181 | let key = [3u32, 0, 0, 0, 16, 0, 16, 0x1_0001, 28, 1, 0, 0, 0, 0]; | ||
| 6182 | // Three addresses of one place (numbers only: nothing is made or read at them). | ||
| 6183 | let a = 0x5eed_0000_0000u64; | ||
| 6184 | let place = placed_near_set(a, &key); | ||
| 6185 | let mut others = | ||
| 6186 | (1..).map(|i: u64| a + (i << 16)).filter(|&at| placed_near_set(at, &key) == place); | ||
| 6187 | let (b, c) = (others.next().unwrap(), others.next().unwrap()); | ||
| 6188 | assert_eq!(placed_near(a, &key), None, "nothing before the thread found one"); | ||
| 6189 | placed_near_note(a, &key, 0xa0); | ||
| 6190 | placed_near_note(b, &key, 0xb0); | ||
| 6191 | assert_eq!((placed_near(a, &key), placed_near(b, &key)), (Some(0xa0), Some(0xb0))); | ||
| 6192 | // Another description at an address is another texture. | ||
| 6193 | let mut wider = key; | ||
| 6194 | wider[4] = 32; | ||
| 6195 | assert_eq!(placed_near_set(a, &wider), place); | ||
| 6196 | assert_eq!(placed_near(a, &wider), None); | ||
| 6197 | // A third: the two found again since stay, and it is looked up under the lock each time. | ||
| 6198 | placed_near_note(c, &key, 0xc0); | ||
| 6199 | assert_eq!(placed_near(c, &key), None); | ||
| 6200 | assert_eq!((placed_near(a, &key), placed_near(b, &key)), (Some(0xa0), Some(0xb0))); | ||
| 6201 | placed_near_note(c, &key, 0xc0); | ||
| 6202 | assert_eq!(placed_near(c, &key), None); | ||
| 6203 | // One of the two is no longer asked for: the third takes its place. | ||
| 6204 | assert_eq!(placed_near(b, &key), Some(0xb0)); | ||
| 6205 | placed_near_note(c, &key, 0xc0); | ||
| 6206 | assert_eq!(placed_near(a, &key), None); | ||
| 6207 | assert_eq!((placed_near(b, &key), placed_near(c, &key)), (Some(0xb0), Some(0xc0))); | ||
| 6208 | } | ||
| 6209 | |||
| 6210 | /// [`texture_at`] finds a placed texture again as its switches say: under the tables' lock every time | ||
| 6211 | /// with `LEONIDA_LIST_LOCK_FAST=0`, as before; in the thread's own table with it on, whatever filler its | ||
| 6212 | /// description comes with; and never there with `LEONIDA_PLACED_SHARDS=0`, where every lookup takes the | ||
| 6213 | /// one lock and the count of filler twins sees it. | ||
| 6214 | #[cfg(windows)] | ||
| 6215 | #[test] | ||
| 6216 | fn placed_lookups_keep_to_their_switches() { | ||
| 6217 | use windows_sys::Win32::System::Memory::{MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc}; | ||
| 6218 | // Addresses no other texture has: reserved, and never read (no host copy is asked for). | ||
| 6219 | // SAFETY: a reservation of our own that stays. | ||
| 6220 | let base = unsafe { VirtualAlloc(std::ptr::null(), 4 << 16, MEM_RESERVE, PAGE_NOACCESS) } as u64; | ||
| 6221 | assert!(base != 0); | ||
| 6222 | let at = |i: u64| base + (i << 16); | ||
| 6223 | let key = [3u32, 0, 0, 0, 16, 0, 16, 0x1_0001, 28, 1, 0, 0, 0, 0]; | ||
| 6224 | let filled = |filler: u32| { | ||
| 6225 | let mut desc = key; | ||
| 6226 | (desc[1], desc[13]) = (filler, !filler); | ||
| 6227 | desc | ||
| 6228 | }; | ||
| 6229 | // (`LEONIDA_PLACED_FILLER=1` keeps the filler in what a texture is.) | ||
| 6230 | let twins = std::env::var_os("LEONIDA_PLACED_FILLER").is_none_or(|v| v != "1"); | ||
| 6231 | let near = |i: u64| placed_near(at(i), &key).map(|r| r as This); | ||
| 6232 | PLACED_SHARDS_TEST.set(Some(true)); | ||
| 6233 | // Off: the thread keeps nothing. | ||
| 6234 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(false)); | ||
| 6235 | let one = texture_at(at(0), &key).unwrap(); | ||
| 6236 | assert_eq!(texture_at(at(0), &key), Some(one)); | ||
| 6237 | assert_eq!(near(0), None); | ||
| 6238 | // On: kept once it was found under the lock, and found there after. | ||
| 6239 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(true)); | ||
| 6240 | assert_eq!(texture_at(at(0), &key), Some(one)); | ||
| 6241 | assert_eq!(near(0), Some(one)); | ||
| 6242 | assert_eq!(texture_at(at(0), &key), Some(one)); | ||
| 6243 | if twins { | ||
| 6244 | assert_eq!(texture_at(at(0), &filled(7)), Some(one), "the filler is no part of a texture"); | ||
| 6245 | } | ||
| 6246 | // One made with it on is kept at once; another description there is another texture. | ||
| 6247 | let two = texture_at(at(1), &key).unwrap(); | ||
| 6248 | assert!(two != one); | ||
| 6249 | assert_eq!((near(1), texture_at(at(1), &key)), (Some(two), Some(two))); | ||
| 6250 | let mut wider = key; | ||
| 6251 | wider[4] = 32; | ||
| 6252 | let three = texture_at(at(1), &wider).unwrap(); | ||
| 6253 | assert!(three != two); | ||
| 6254 | assert_eq!((texture_at(at(1), &key), texture_at(at(1), &wider)), (Some(two), Some(three))); | ||
| 6255 | // Another thread has a table of its own, and finds the same textures. | ||
| 6256 | let (address, known) = (at(1), two as usize); | ||
| 6257 | std::thread::spawn(move || { | ||
| 6258 | PLACED_SHARDS_TEST.set(Some(true)); | ||
| 6259 | crate::descriptor::LIST_LOCK_FAST_TEST.set(Some(true)); | ||
| 6260 | assert_eq!(placed_near(address, &key), None); | ||
| 6261 | assert_eq!(texture_at(address, &key).map(|r| r as usize), Some(known)); | ||
| 6262 | assert_eq!(placed_near(address, &key), Some(known)); | ||
| 6263 | }) | ||
| 6264 | .join() | ||
| 6265 | .unwrap(); | ||
| 6266 | // Without the tables in front, the one lock every time: the thread's table is neither asked nor | ||
| 6267 | // written, and a second filler at one texture is counted. | ||
| 6268 | PLACED_SHARDS_TEST.set(Some(false)); | ||
| 6269 | #[cfg(feature = "diagnostics")] | ||
| 6270 | let counted = placed_filler_twins(); | ||
| 6271 | let four = texture_at(at(2), &key).unwrap(); | ||
| 6272 | assert_eq!(texture_at(at(2), &key), Some(four)); | ||
| 6273 | if twins { | ||
| 6274 | assert_eq!(texture_at(at(2), &filled(7)), Some(four)); | ||
| 6275 | assert_eq!(texture_at(at(2), &filled(8)), Some(four)); | ||
| 6276 | #[cfg(feature = "diagnostics")] | ||
| 6277 | assert!(placed_filler_twins() > counted, "a second filler is counted"); | ||
| 6278 | } | ||
| 6279 | assert_eq!(near(2), None); | ||
| 6280 | PLACED_SHARDS_TEST.set(None); | ||
| 6281 | crate::descriptor::LIST_LOCK_FAST_TEST.set(None); | ||
| 6282 | } | ||
| 6283 | |||
| 6284 | /// That a texture has no host copy, and that none is made for one the host refused, is read without the | ||
| 6285 | /// texture's lock (`LEONIDA_LIST_LOCK_FAST`): answered while another thread holds that lock alone. | ||
| 6286 | #[cfg(windows)] | ||
| 6287 | #[test] | ||
| 6288 | fn a_texture_without_a_copy_is_answered_for_without_its_lock() { | ||
| 6289 | use std::sync::atomic::Ordering::Relaxed; | ||
| 6290 | let image = filled_texture(); | ||
| 6291 | let (r, at) = (resource(image), image as usize); | ||
| 6292 | // (It has one already with `LEONIDA_LAZY_TEXTURES=0`.) | ||
| 6293 | r.host.take(&mut r.host.alone()); | ||
| 6294 | let told = asked_while(r.host.alone(), at, |image| (host_waits(image), made_copy(image).is_some())); | ||
| 6295 | assert_eq!(told, Some((lazy(), false))); | ||
| 6296 | r.host.refused.store(true, Relaxed); | ||
| 6297 | let told = asked_while(r.host.alone(), at, |image| (host_waits(image), host_copy(image).is_some())); | ||
| 6298 | assert_eq!(told, Some((false, false))); | ||
| 6299 | crate::object::release_boxed::<Resource>(image); | ||
| 6300 | } | ||
| 6301 | |||
| 6302 | /// A host copy that is there is handed out while another thread holds the texture's lock with it | ||
| 6303 | /// (`LEONIDA_LIST_LOCK_FAST`: shared among those that ask, where each took it alone), and that it has | ||
| 6304 | /// the level a view starts at is known while another holds the lock alone. | ||
| 6305 | #[cfg(windows)] | ||
| 6306 | #[test] | ||
| 6307 | fn a_copy_that_is_there_is_handed_out_under_a_shared_lock() { | ||
| 6308 | use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; | ||
| 6309 | if crate::host::host().is_none() || !held_only() || !lazy() { | ||
| 6310 | return; | ||
| 6311 | } | ||
| 6312 | // 256x256 BC7, nine levels, 4 KiB blocks. | ||
| 6313 | let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; | ||
| 6314 | let whole = placed_bytes(&desc).unwrap() as usize; | ||
| 6315 | // SAFETY: memory of our own that stays. | ||
| 6316 | let memory = unsafe { | ||
| 6317 | VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) | ||
| 6318 | }; | ||
| 6319 | let texture = texture_at(memory as u64, &desc).unwrap(); | ||
| 6320 | want_level(texture, 2); | ||
| 6321 | let copy = host_copy(texture).unwrap(); | ||
| 6322 | assert_eq!(copy.base, 2); | ||
| 6323 | let (r, at) = (resource(texture), texture as usize); | ||
| 6324 | let handed = asked_while(r.host.shared(), at, |texture| host_copy(texture).map(|copy| copy.serial)); | ||
| 6325 | assert_eq!(handed, Some(Some(copy.serial))); | ||
| 6326 | let told = asked_while(r.host.alone(), at, |texture| { | ||
| 6327 | want_level(texture, 5); | ||
| 6328 | host_waits(texture) | ||
| 6329 | }); | ||
| 6330 | assert_eq!(told, Some(false)); | ||
| 6331 | assert_eq!(host_copy(texture).unwrap().serial, copy.serial); | ||
| 6332 | } | ||
| 6333 | |||
| 6334 | /// Six threads view placed textures from levels of their own choosing, at once ([`TURNS`]): each is | ||
| 6335 | /// handed a host copy with the level it asked for, whatever the others did between its asking and its | ||
| 6336 | /// use. | ||
| 6337 | #[cfg(windows)] | ||
| 6338 | #[test] | ||
| 6339 | fn no_thread_is_handed_a_copy_without_the_level_it_asked_for() { | ||
| 6340 | use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; | ||
| 6341 | const TEXTURES: usize = 12; | ||
| 6342 | if crate::host::host().is_none() || !held_only() || !lazy() { | ||
| 6343 | return; | ||
| 6344 | } | ||
| 6345 | // 256x256 BC7, nine levels, 4 KiB blocks. | ||
| 6346 | let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; | ||
| 6347 | let whole = placed_bytes(&desc).unwrap() as usize; | ||
| 6348 | for turns in TURNS { | ||
| 6349 | // SAFETY: memory of our own that stays. | ||
| 6350 | let memory = unsafe { | ||
| 6351 | VirtualAlloc(std::ptr::null(), whole * TEXTURES, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) | ||
| 6352 | } as usize; | ||
| 6353 | assert!(memory != 0); | ||
| 6354 | // (Made before the threads start: a resource can be found a moment before it is marked as | ||
| 6355 | // placed, and a level asked for in that moment is not noted.) | ||
| 6356 | let textures: Vec<usize> = (0..TEXTURES) | ||
| 6357 | .map(|i| texture_at((memory + i * whole) as u64, &desc).unwrap() as usize) | ||
| 6358 | .collect(); | ||
| 6359 | std::thread::scope(|scope| { | ||
| 6360 | for thread in 0..6u32 { | ||
| 6361 | let textures = &textures; | ||
| 6362 | scope.spawn(move || { | ||
| 6363 | let mut random = 0x9E37_79B9u32.wrapping_mul(thread + 1); | ||
| 6364 | for call in 0..600 { | ||
| 6365 | turn(turns, call); | ||
| 6366 | random = random.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 6367 | let (which, first) = ((random >> 8) as usize % TEXTURES, (random >> 24) % 9); | ||
| 6368 | let texture = texture_at((memory + which * whole) as u64, &desc).unwrap(); | ||
| 6369 | assert_eq!(texture as usize, textures[which]); | ||
| 6370 | want_level(texture, first); | ||
| 6371 | let copy = host_copy(texture).expect("a host copy"); | ||
| 6372 | let from = base_level(&resource(texture).desc, first); | ||
| 6373 | assert!( | ||
| 6374 | copy.base <= from, | ||
| 6375 | "asked from level {first} (a copy from {from} has it), handed one from {}", | ||
| 6376 | copy.base | ||
| 6377 | ); | ||
| 6378 | } | ||
| 6379 | }); | ||
| 6380 | } | ||
| 6381 | }); | ||
| 6382 | } | ||
| 6383 | } | ||
| 6384 | |||
| 6385 | /// Threads ask for a texture's host copy and hold it a moment while another lets it go whenever its | ||
| 6386 | /// texture alone holds it ([`TURNS`]): a copy someone holds is never the one let go, and every asking | ||
| 6387 | /// is handed one. | ||
| 6388 | #[cfg(windows)] | ||
| 6389 | #[test] | ||
| 6390 | fn a_copy_someone_holds_is_not_let_go_under_them() { | ||
| 6391 | use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; | ||
| 6392 | if crate::host::host().is_none() { | ||
| 6393 | return; // no host GPU here | ||
| 6394 | } | ||
| 6395 | for turns in TURNS { | ||
| 6396 | let image = filled_texture(); | ||
| 6397 | let (at, done) = (image as usize, AtomicBool::new(false)); | ||
| 6398 | let asked = std::thread::scope(|scope| { | ||
| 6399 | let asking: Vec<_> = (0..3) | ||
| 6400 | .map(|_| { | ||
| 6401 | scope.spawn(|| { | ||
| 6402 | for call in 0..300 { | ||
| 6403 | turn(turns, call); | ||
| 6404 | let held = host_copy(at as This).expect("made at each use"); | ||
| 6405 | let found = made_copy(at as This).expect("a held copy stays"); | ||
| 6406 | assert_eq!(found.serial, held.serial); | ||
| 6407 | assert!(!host_waits(at as This)); | ||
| 6408 | } | ||
| 6409 | }) | ||
| 6410 | }) | ||
| 6411 | .collect(); | ||
| 6412 | scope.spawn(|| { | ||
| 6413 | while !done.load(Relaxed) { | ||
| 6414 | let_go_of(resource(at as This), 0, 0); | ||
| 6415 | std::thread::yield_now(); | ||
| 6416 | } | ||
| 6417 | }); | ||
| 6418 | // (The sweep is stopped whether they all came through or not.) | ||
| 6419 | let asked: Vec<_> = asking.into_iter().map(|thread| thread.join()).collect(); | ||
| 6420 | done.store(true, Relaxed); | ||
| 6421 | asked | ||
| 6422 | }); | ||
| 6423 | assert!(asked.iter().all(Result::is_ok)); | ||
| 6424 | crate::object::release_boxed::<Resource>(image); | ||
| 6425 | } | ||
| 6426 | } | ||
| 5768 | } | 6427 | } |
diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 95a9350af..bf1727297 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs | |||
| @@ -83,7 +83,7 @@ impl CopiedState { | |||
| 83 | fn new(pages: usize) -> Self { | 83 | fn new(pages: usize) -> Self { |
| 84 | let words = pages.div_ceil(64); | 84 | let words = pages.div_ceil(64); |
| 85 | let mut uncopied_bits = vec![u64::MAX; words]; | 85 | let mut uncopied_bits = vec![u64::MAX; words]; |
| 86 | if pages % 64 != 0 { | 86 | if !pages.is_multiple_of(64) { |
| 87 | uncopied_bits[words - 1] = (1u64 << (pages % 64)) - 1; | 87 | uncopied_bits[words - 1] = (1u64 << (pages % 64)) - 1; |
| 88 | } | 88 | } |
| 89 | Self { pages: vec![0; pages], uncopied_bits, uncopied: pages, ranged: Default::default() } | 89 | Self { pages: vec![0; pages], uncopied_bits, uncopied: pages, ranged: Default::default() } |
| @@ -112,6 +112,7 @@ impl CopiedState { | |||
| 112 | } | 112 | } |
| 113 | 113 | ||
| 114 | /// How many pages were copied at least once. | 114 | /// How many pages were copied at least once. |
| 115 | #[cfg(any(test, feature = "diagnostics"))] | ||
| 115 | fn copied_count(&self) -> usize { | 116 | fn copied_count(&self) -> usize { |
| 116 | self.pages.len() - self.uncopied | 117 | self.pages.len() - self.uncopied |
| 117 | } | 118 | } |
| @@ -1624,15 +1625,63 @@ impl Flights { | |||
| 1624 | /// read, could undo that write. (The merge of a waited-for submission | 1625 | /// read, could undo that write. (The merge of a waited-for submission |
| 1625 | /// stores every byte of a differing stretch back into the copy.) | 1626 | /// stores every byte of a differing stretch back into the copy.) |
| 1626 | fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { | 1627 | fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { |
| 1627 | let mut differs = 0u8; | 1628 | let n = now.len().min(held.len()).min(title.len()); |
| 1629 | #[cfg(target_arch = "x86_64")] | ||
| 1630 | if n >= 32 && std::arch::is_x86_feature_detected!("avx2") { | ||
| 1631 | // SAFETY: the processor has AVX2 and all three slices cover `n` bytes. | ||
| 1632 | return unsafe { merge_piece_avx2(now, held, title, n) }; | ||
| 1633 | } | ||
| 1634 | merge_piece_scalar(&now[..n], &mut held[..n], &mut title[..n]) | ||
| 1635 | } | ||
| 1636 | |||
| 1637 | fn merge_piece_scalar(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { | ||
| 1638 | let mut differs = false; | ||
| 1628 | for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { | 1639 | for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { |
| 1629 | let wrote = if *n != *h { 0xffu8 } else { 0 }; | 1640 | if *n != *h { |
| 1630 | let merged = (*t & !wrote) | (*n & wrote); | 1641 | *h = *n; |
| 1631 | differs |= merged ^ *t; | 1642 | if *t != *n { |
| 1632 | *t = merged; | 1643 | *t = *n; |
| 1633 | *h = (*h & !wrote) | (*n & wrote); | 1644 | differs = true; |
| 1645 | } | ||
| 1646 | } | ||
| 1634 | } | 1647 | } |
| 1635 | differs != 0 | 1648 | differs |
| 1649 | } | ||
| 1650 | |||
| 1651 | /// [`merge_piece`] with 32-byte AVX2 comparisons: skips 32-byte blocks where | ||
| 1652 | /// `now == held` without writing either `held` or `title`. | ||
| 1653 | /// | ||
| 1654 | /// # Safety | ||
| 1655 | /// AVX2, and `now`, `held`, `title` each hold at least `len` non-overlapping bytes. | ||
| 1656 | #[cfg(target_arch = "x86_64")] | ||
| 1657 | #[target_feature(enable = "avx2")] | ||
| 1658 | unsafe fn merge_piece_avx2(now: &[u8], held: &mut [u8], title: &mut [u8], len: usize) -> bool { | ||
| 1659 | use std::arch::x86_64::*; | ||
| 1660 | let mut differs = false; | ||
| 1661 | let mut i = 0; | ||
| 1662 | let np = now.as_ptr(); | ||
| 1663 | let hp = held.as_mut_ptr(); | ||
| 1664 | let tp = title.as_mut_ptr(); | ||
| 1665 | while i + 32 <= len { | ||
| 1666 | // SAFETY: `i + 32 <= len`, all pointers valid for `len` bytes. | ||
| 1667 | unsafe { | ||
| 1668 | let vn = _mm256_loadu_si256(np.add(i).cast()); | ||
| 1669 | let vh = _mm256_loadu_si256(hp.add(i).cast()); | ||
| 1670 | let eq = _mm256_cmpeq_epi8(vn, vh); | ||
| 1671 | if _mm256_movemask_epi8(eq) != -1i32 { | ||
| 1672 | _mm256_storeu_si256(hp.add(i).cast(), vn); | ||
| 1673 | let vt = _mm256_loadu_si256(tp.add(i).cast()); | ||
| 1674 | let merged = _mm256_blendv_epi8(vn, vt, eq); | ||
| 1675 | let xor = _mm256_xor_si256(merged, vt); | ||
| 1676 | if _mm256_testz_si256(xor, xor) == 0 { | ||
| 1677 | _mm256_storeu_si256(tp.add(i).cast(), merged); | ||
| 1678 | differs = true; | ||
| 1679 | } | ||
| 1680 | } | ||
| 1681 | } | ||
| 1682 | i += 32; | ||
| 1683 | } | ||
| 1684 | differs | merge_piece_scalar(&now[i..len], &mut held[i..len], &mut title[i..len]) | ||
| 1636 | } | 1685 | } |
| 1637 | 1686 | ||
| 1638 | /// `[from, to)` without the ranges of `skip`, in order. | 1687 | /// `[from, to)` without the ranges of `skip`, in order. |
| @@ -2643,11 +2692,90 @@ mod wide_tests { | |||
| 2643 | /// those are to be written, so a title write that lands between the read | 2692 | /// those are to be written, so a title write that lands between the read |
| 2644 | /// and the write elsewhere in the stretch stays (upstream VIctory #2009). | 2693 | /// and the write elsewhere in the stretch stays (upstream VIctory #2009). |
| 2645 | /// `mask` is scratch. | 2694 | /// `mask` is scratch. |
| 2695 | /// Appends contiguous differing byte runs encoded by bitmask `diff` starting | ||
| 2696 | /// at `base`, coalescing with an immediately preceding run in `runs`. | ||
| 2697 | #[inline] | ||
| 2698 | fn push_diff_mask(runs: &mut Vec<(usize, usize)>, base: usize, mut diff: u64) { | ||
| 2699 | while diff != 0 { | ||
| 2700 | let first = diff.trailing_zeros() as usize; | ||
| 2701 | let count = (diff >> first).trailing_ones() as usize; | ||
| 2702 | let at = base + first; | ||
| 2703 | match runs.last_mut() { | ||
| 2704 | Some((a, len)) if *a + *len == at => *len += count, | ||
| 2705 | _ => runs.push((at, count)), | ||
| 2706 | } | ||
| 2707 | if first + count >= 64 { | ||
| 2708 | break; | ||
| 2709 | } | ||
| 2710 | diff &= u64::MAX << (first + count); | ||
| 2711 | } | ||
| 2712 | } | ||
| 2713 | |||
| 2714 | #[cfg(target_arch = "x86_64")] | ||
| 2715 | #[target_feature(enable = "avx2")] | ||
| 2716 | unsafe fn back_piece_avx2(host: &mut [u8], old: &[u8], title: &mut [u8], runs: &mut Vec<(usize, usize)>) { | ||
| 2717 | use std::arch::x86_64::*; | ||
| 2718 | let n = title.len(); | ||
| 2719 | let hp = host.as_mut_ptr(); | ||
| 2720 | let op = old.as_ptr(); | ||
| 2721 | let tp = title.as_mut_ptr(); | ||
| 2722 | let mut i = 0; | ||
| 2723 | while i + 32 <= n { | ||
| 2724 | // SAFETY: `i + 32 <= n`, all three buffers cover `n` bytes. | ||
| 2725 | unsafe { | ||
| 2726 | let vh = _mm256_loadu_si256(hp.add(i).cast()); | ||
| 2727 | let vo = _mm256_loadu_si256(op.add(i).cast()); | ||
| 2728 | let vt = _mm256_loadu_si256(tp.add(i).cast()); | ||
| 2729 | let gpu = _mm256_andnot_si256(_mm256_cmpeq_epi8(vh, vo), _mm256_cmpeq_epi8(vt, vo)); | ||
| 2730 | let merged = _mm256_blendv_epi8(vt, vh, gpu); | ||
| 2731 | let xor_h = _mm256_xor_si256(merged, vh); | ||
| 2732 | if _mm256_testz_si256(xor_h, xor_h) == 0 { | ||
| 2733 | _mm256_storeu_si256(hp.add(i).cast(), merged); | ||
| 2734 | } | ||
| 2735 | let diff_t = (!_mm256_movemask_epi8(_mm256_cmpeq_epi8(merged, vt))) as u32; | ||
| 2736 | if diff_t != 0 { | ||
| 2737 | _mm256_storeu_si256(tp.add(i).cast(), merged); | ||
| 2738 | push_diff_mask(runs, i, u64::from(diff_t)); | ||
| 2739 | } | ||
| 2740 | } | ||
| 2741 | i += 32; | ||
| 2742 | } | ||
| 2743 | if i < n { | ||
| 2744 | back_piece_scalar(&mut host[i..n], &old[i..n], &mut title[i..n], runs, i); | ||
| 2745 | } | ||
| 2746 | } | ||
| 2747 | |||
| 2748 | fn back_piece_scalar(host: &mut [u8], old: &[u8], title: &mut [u8], runs: &mut Vec<(usize, usize)>, base: usize) { | ||
| 2749 | let mut push = |start: usize, len: usize| match runs.last_mut() { | ||
| 2750 | Some((a, n)) if *a + *n == start => *n += len, | ||
| 2751 | _ => runs.push((start, len)), | ||
| 2752 | }; | ||
| 2753 | let mut run_start = None; | ||
| 2754 | for (i, ((t, h), o)) in title.iter_mut().zip(host.iter_mut()).zip(old).enumerate() { | ||
| 2755 | let gpu = (*h != *o) && (*t == *o); | ||
| 2756 | let merged = if gpu { *h } else { *t }; | ||
| 2757 | let changed = merged != *t; | ||
| 2758 | *t = merged; | ||
| 2759 | *h = merged; | ||
| 2760 | match (changed, run_start) { | ||
| 2761 | (true, None) => run_start = Some(base + i), | ||
| 2762 | (false, Some(start)) => { | ||
| 2763 | push(start, base + i - start); | ||
| 2764 | run_start = None; | ||
| 2765 | } | ||
| 2766 | _ => {} | ||
| 2767 | } | ||
| 2768 | } | ||
| 2769 | if let Some(start) = run_start { | ||
| 2770 | push(start, base + title.len() - start); | ||
| 2771 | } | ||
| 2772 | } | ||
| 2773 | |||
| 2646 | fn back_piece( | 2774 | fn back_piece( |
| 2647 | host: &mut [u8], | 2775 | host: &mut [u8], |
| 2648 | old: &[u8], | 2776 | old: &[u8], |
| 2649 | title: &mut Vec<u8>, | 2777 | title: &mut Vec<u8>, |
| 2650 | mask: &mut Vec<u8>, | 2778 | _mask: &mut Vec<u8>, |
| 2651 | runs: &mut Vec<(usize, usize)>, | 2779 | runs: &mut Vec<(usize, usize)>, |
| 2652 | read: impl FnOnce(usize, &mut [u8]) -> bool, | 2780 | read: impl FnOnce(usize, &mut [u8]) -> bool, |
| 2653 | ) -> Option<(usize, usize)> { | 2781 | ) -> Option<(usize, usize)> { |
| @@ -2664,45 +2792,19 @@ fn back_piece( | |||
| 2664 | if !read(first, title) { | 2792 | if !read(first, title) { |
| 2665 | return None; | 2793 | return None; |
| 2666 | } | 2794 | } |
| 2667 | // Title memory with the GPU's bytes put in; the copy takes the title's | ||
| 2668 | // bytes in turn. | ||
| 2669 | // Without a branch, so the loop runs many bytes at a time: the GPU's | ||
| 2670 | // byte where the copy's byte is not what it was before the submission | ||
| 2671 | // and the title left its byte as it was, else the title's. (With the | ||
| 2672 | // two searches above this was 44 ms a frame for 970 pieces.) | ||
| 2673 | // Where the shader and the title both changed a byte while the GPU ran, | 2795 | // Where the shader and the title both changed a byte while the GPU ran, |
| 2674 | // the title's stays: the shader computed its byte from the copy's older | 2796 | // the title's stays: the shader computed its byte from the copy's older |
| 2675 | // data (one cleared a bit of a record the title had already replaced, | 2797 | // data (one cleared a bit of a record the title had already replaced, |
| 2676 | // and copying it back broke the title's object: an access violation | 2798 | // and copying it back broke the title's object: an access violation |
| 2677 | // through 0xffffffff00000000; PalmVIDev e0b70476, Leonida f39c6c2). | 2799 | // through 0xffffffff00000000; PalmVIDev e0b70476, Leonida f39c6c2). |
| 2678 | mask.clear(); | 2800 | #[cfg(target_arch = "x86_64")] |
| 2679 | mask.resize(n, 0); | 2801 | if n >= 32 && std::arch::is_x86_feature_detected!("avx2") { |
| 2680 | let mut differs = 0u8; | 2802 | // SAFETY: the processor has AVX2 and slices are valid for `n` bytes. |
| 2681 | for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { | 2803 | unsafe { back_piece_avx2(host, old, title, runs) }; |
| 2682 | let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; | 2804 | return (!runs.is_empty()).then_some((first, n)); |
| 2683 | let merged = (*t & !gpu) | (*h & gpu); | ||
| 2684 | *m = merged ^ *t; | ||
| 2685 | differs |= *m; | ||
| 2686 | *t = merged; | ||
| 2687 | *h = merged; | ||
| 2688 | } | ||
| 2689 | if differs == 0 { | ||
| 2690 | return None; | ||
| 2691 | } | ||
| 2692 | let mut i = 0; | ||
| 2693 | while i < n { | ||
| 2694 | while i < n && mask[i] == 0 { | ||
| 2695 | i += 1; | ||
| 2696 | } | ||
| 2697 | let start = i; | ||
| 2698 | while i < n && mask[i] != 0 { | ||
| 2699 | i += 1; | ||
| 2700 | } | ||
| 2701 | if i > start { | ||
| 2702 | runs.push((start, i - start)); | ||
| 2703 | } | ||
| 2704 | } | 2805 | } |
| 2705 | Some((first, n)) | 2806 | back_piece_scalar(host, old, title, runs, 0); |
| 2807 | (!runs.is_empty()).then_some((first, n)) | ||
| 2706 | } | 2808 | } |
| 2707 | 2809 | ||
| 2708 | /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages | 2810 | /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages |
| @@ -2739,6 +2841,15 @@ pub(crate) fn merged_stats() -> [u64; 3] { | |||
| 2739 | /// byte is. | 2841 | /// byte is. |
| 2740 | fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { | 2842 | fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { |
| 2741 | let n = now.len().min(was.len()); | 2843 | let n = now.len().min(was.len()); |
| 2844 | #[cfg(target_arch = "x86_64")] | ||
| 2845 | if n >= 64 && std::arch::is_x86_feature_detected!("avx2") { | ||
| 2846 | // SAFETY: the processor has AVX2 and both slices cover `n` bytes. | ||
| 2847 | return unsafe { changed_runs_avx2(now, was, n) }; | ||
| 2848 | } | ||
| 2849 | changed_runs_scalar(now, was, n) | ||
| 2850 | } | ||
| 2851 | |||
| 2852 | fn changed_runs_scalar(now: &[u8], was: &[u8], n: usize) -> Vec<(usize, usize)> { | ||
| 2742 | let mut runs = Vec::new(); | 2853 | let mut runs = Vec::new(); |
| 2743 | let mut i = 0; | 2854 | let mut i = 0; |
| 2744 | while i < n { | 2855 | while i < n { |
| @@ -2765,6 +2876,54 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { | |||
| 2765 | runs | 2876 | runs |
| 2766 | } | 2877 | } |
| 2767 | 2878 | ||
| 2879 | /// [`changed_runs`] using 64-byte AVX2 comparisons and bitmask run extraction. | ||
| 2880 | /// | ||
| 2881 | /// # Safety | ||
| 2882 | /// AVX2, and `now` and `was` each cover at least `n` bytes. | ||
| 2883 | #[cfg(target_arch = "x86_64")] | ||
| 2884 | #[target_feature(enable = "avx2")] | ||
| 2885 | unsafe fn changed_runs_avx2(now: &[u8], was: &[u8], n: usize) -> Vec<(usize, usize)> { | ||
| 2886 | use std::arch::x86_64::*; | ||
| 2887 | let mut runs: Vec<(usize, usize)> = Vec::new(); | ||
| 2888 | let mut i = 0; | ||
| 2889 | let np = now.as_ptr(); | ||
| 2890 | let wp = was.as_ptr(); | ||
| 2891 | while i + 64 <= n { | ||
| 2892 | // SAFETY: `i + 64 <= n`. | ||
| 2893 | let (eq0, eq1) = unsafe { | ||
| 2894 | let a0 = _mm256_loadu_si256(np.add(i).cast()); | ||
| 2895 | let b0 = _mm256_loadu_si256(wp.add(i).cast()); | ||
| 2896 | let a1 = _mm256_loadu_si256(np.add(i + 32).cast()); | ||
| 2897 | let b1 = _mm256_loadu_si256(wp.add(i + 32).cast()); | ||
| 2898 | let c0 = _mm256_cmpeq_epi8(a0, b0); | ||
| 2899 | let c1 = _mm256_cmpeq_epi8(a1, b1); | ||
| 2900 | (_mm256_movemask_epi8(c0), _mm256_movemask_epi8(c1)) | ||
| 2901 | }; | ||
| 2902 | if (eq0 & eq1) != -1i32 { | ||
| 2903 | let differ = u64::from((!eq0) as u32) | (u64::from((!eq1) as u32) << 32); | ||
| 2904 | push_diff_mask(&mut runs, i, differ); | ||
| 2905 | } | ||
| 2906 | i += 64; | ||
| 2907 | } | ||
| 2908 | while i < n { | ||
| 2909 | while i < n && now[i] == was[i] { | ||
| 2910 | i += 1; | ||
| 2911 | } | ||
| 2912 | if i >= n { | ||
| 2913 | break; | ||
| 2914 | } | ||
| 2915 | let first = i; | ||
| 2916 | while i < n && now[i] != was[i] { | ||
| 2917 | i += 1; | ||
| 2918 | } | ||
| 2919 | match runs.last_mut() { | ||
| 2920 | Some((a, len)) if *a + *len == first => *len += i - first, | ||
| 2921 | _ => runs.push((first, i - first)), | ||
| 2922 | } | ||
| 2923 | } | ||
| 2924 | runs | ||
| 2925 | } | ||
| 2926 | |||
| 2768 | /// The kernel's page. | 2927 | /// The kernel's page. |
| 2769 | const KERNEL_PAGE: usize = 4096; | 2928 | const KERNEL_PAGE: usize = 4096; |
| 2770 | 2929 | ||
| @@ -3663,6 +3822,173 @@ mod merge_tests { | |||
| 3663 | assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); | 3822 | assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); |
| 3664 | } | 3823 | } |
| 3665 | 3824 | ||
| 3825 | #[test] | ||
| 3826 | fn avx2_merge_back_and_runs_match_scalar_across_lengths_and_patterns() { | ||
| 3827 | let mut seed = 0x1234_5678u32; | ||
| 3828 | let mut next = || { | ||
| 3829 | seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); | ||
| 3830 | seed | ||
| 3831 | }; | ||
| 3832 | for len in [0, 1, 7, 31, 32, 33, 63, 64, 65, 95, 128, 255, 513, 4097] { | ||
| 3833 | let old: Vec<u8> = (0..len).map(|i| (i * 11 + 3) as u8).collect(); | ||
| 3834 | let mut now = old.clone(); | ||
| 3835 | let mut title0 = old.clone(); | ||
| 3836 | for _ in 0..(len / 6).max(1) { | ||
| 3837 | if len == 0 { | ||
| 3838 | break; | ||
| 3839 | } | ||
| 3840 | let idx = next() as usize % len; | ||
| 3841 | now[idx] ^= (next() & 0xff) as u8; | ||
| 3842 | if next() & 3 == 0 { | ||
| 3843 | title0[idx] ^= 0x3c; | ||
| 3844 | } | ||
| 3845 | } | ||
| 3846 | let (mut held_s, mut title_s) = (old.clone(), title0.clone()); | ||
| 3847 | let (mut held_v, mut title_v) = (old.clone(), title0.clone()); | ||
| 3848 | assert_eq!( | ||
| 3849 | super::merge_piece_scalar(&now, &mut held_s, &mut title_s), | ||
| 3850 | super::merge_piece(&now, &mut held_v, &mut title_v), | ||
| 3851 | "merge bool mismatch at len={len}" | ||
| 3852 | ); | ||
| 3853 | assert_eq!(held_s, held_v, "merge held mismatch at len={len}"); | ||
| 3854 | assert_eq!(title_s, title_v, "merge title mismatch at len={len}"); | ||
| 3855 | assert_eq!( | ||
| 3856 | super::changed_runs_scalar(&now, &old, len), | ||
| 3857 | changed_runs(&now, &old), | ||
| 3858 | "changed_runs mismatch at len={len}" | ||
| 3859 | ); | ||
| 3860 | |||
| 3861 | // Also test back_piece across boundary-crossing contiguous & single-byte runs. | ||
| 3862 | let (mut host_s, mut title_bs) = (now.clone(), title0.clone()); | ||
| 3863 | let mut runs_s = Vec::new(); | ||
| 3864 | super::back_piece_scalar(&mut host_s, &old, &mut title_bs, &mut runs_s, 0); | ||
| 3865 | |||
| 3866 | let (mut host_v, mut title_bv) = (now.clone(), title0.clone()); | ||
| 3867 | let (mut mask, mut runs_v) = (Vec::new(), Vec::new()); | ||
| 3868 | if let Some(first) = super::first_difference(&host_v, &old) { | ||
| 3869 | let last = super::last_difference(&host_v, &old).unwrap_or(first); | ||
| 3870 | let slice_n = last + 1 - first; | ||
| 3871 | title_bv.truncate(first + slice_n); | ||
| 3872 | let mut scratch = Vec::new(); | ||
| 3873 | let res = back_piece(&mut host_v, &old, &mut scratch, &mut mask, &mut runs_v, |off, into| { | ||
| 3874 | into.copy_from_slice(&title0[off..off + into.len()]); | ||
| 3875 | true | ||
| 3876 | }); | ||
| 3877 | let expected_changed = !runs_s.is_empty(); | ||
| 3878 | assert_eq!(res.is_some(), expected_changed, "back_piece res mismatch len={len}"); | ||
| 3879 | if expected_changed { | ||
| 3880 | let abs_v: Vec<(usize, usize)> = runs_v.iter().map(|&(a, l)| (first + a, l)).collect(); | ||
| 3881 | assert_eq!(abs_v, runs_s, "back_piece runs mismatch len={len}"); | ||
| 3882 | assert_eq!(&scratch[..], &title_bs[first..=last], "back_piece scratch mismatch len={len}"); | ||
| 3883 | } | ||
| 3884 | } | ||
| 3885 | } | ||
| 3886 | } | ||
| 3887 | |||
| 3888 | /// `--release` A/B benchmark for `merge_piece`, `changed_runs`, and `back_piece` | ||
| 3889 | /// on 64 KiB pieces (sparse 10% scattered GPU writes + empty pieces). | ||
| 3890 | #[test] | ||
| 3891 | #[ignore] | ||
| 3892 | fn shadow_avx2_bench() { | ||
| 3893 | const N: usize = PIECE; | ||
| 3894 | let old: Vec<u8> = (0..N).map(|i| (i * 7 + 13) as u8).collect(); | ||
| 3895 | let mut gpu = old.clone(); | ||
| 3896 | // ~240 sparse 4-byte writes across the 64 KiB stretch (like real shader outputs). | ||
| 3897 | for off in (12..N - 8).step_by(272) { | ||
| 3898 | gpu[off..off + 4].copy_from_slice(&[0xaa, 0xbb, 0xcc, 0xdd]); | ||
| 3899 | } | ||
| 3900 | let mut title0 = old.clone(); | ||
| 3901 | for off in (40..N - 8).step_by(512) { | ||
| 3902 | title0[off] ^= 0x11; | ||
| 3903 | } | ||
| 3904 | fn bench(iters: usize, mut f: impl FnMut()) -> f64 { | ||
| 3905 | let mut best = f64::MAX; | ||
| 3906 | for _ in 0..8 { | ||
| 3907 | let t = std::time::Instant::now(); | ||
| 3908 | for _ in 0..iters { | ||
| 3909 | f(); | ||
| 3910 | } | ||
| 3911 | best = best.min(t.elapsed().as_secs_f64() * 1e6 / iters as f64); | ||
| 3912 | } | ||
| 3913 | best | ||
| 3914 | } | ||
| 3915 | let (mut held_s, mut title_s) = (old.clone(), title0.clone()); | ||
| 3916 | let (mut held_v, mut title_v) = (old.clone(), title0.clone()); | ||
| 3917 | let merge_s = bench(500, || { | ||
| 3918 | held_s.copy_from_slice(&old); | ||
| 3919 | title_s.copy_from_slice(&title0); | ||
| 3920 | std::hint::black_box(super::merge_piece_scalar(std::hint::black_box(&gpu), &mut held_s, &mut title_s)); | ||
| 3921 | }); | ||
| 3922 | let merge_v = bench(500, || { | ||
| 3923 | held_v.copy_from_slice(&old); | ||
| 3924 | title_v.copy_from_slice(&title0); | ||
| 3925 | std::hint::black_box(super::merge_piece(std::hint::black_box(&gpu), &mut held_v, &mut title_v)); | ||
| 3926 | }); | ||
| 3927 | let runs_s = bench(1000, || { | ||
| 3928 | std::hint::black_box(super::changed_runs_scalar(std::hint::black_box(&gpu), std::hint::black_box(&old), N)); | ||
| 3929 | }); | ||
| 3930 | let runs_v = bench(1000, || { | ||
| 3931 | std::hint::black_box(changed_runs(std::hint::black_box(&gpu), std::hint::black_box(&old))); | ||
| 3932 | }); | ||
| 3933 | let (mut host_s, mut ts_vec, mut mask_s, mut r_s) = (gpu.clone(), Vec::new(), Vec::new(), Vec::new()); | ||
| 3934 | let back_s = bench(500, || { | ||
| 3935 | host_s.copy_from_slice(&gpu); | ||
| 3936 | r_s.clear(); | ||
| 3937 | if let Some(first) = super::first_difference(&host_s, &old) { | ||
| 3938 | let last = super::last_difference(&host_s, &old).unwrap_or(first); | ||
| 3939 | let len = last + 1 - first; | ||
| 3940 | let (h_slice, o_slice) = (&mut host_s[first..=last], &old[first..=last]); | ||
| 3941 | ts_vec.clear(); | ||
| 3942 | ts_vec.resize(len, 0); | ||
| 3943 | ts_vec.copy_from_slice(&title0[first..first + len]); | ||
| 3944 | mask_s.clear(); | ||
| 3945 | mask_s.resize(len, 0); | ||
| 3946 | let mut differs = 0u8; | ||
| 3947 | for (((t, h), o), m) in ts_vec.iter_mut().zip(h_slice.iter_mut()).zip(o_slice).zip(mask_s.iter_mut()) { | ||
| 3948 | let g = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; | ||
| 3949 | let merged = (*t & !g) | (*h & g); | ||
| 3950 | *m = merged ^ *t; | ||
| 3951 | differs |= *m; | ||
| 3952 | *t = merged; | ||
| 3953 | *h = merged; | ||
| 3954 | } | ||
| 3955 | if differs != 0 { | ||
| 3956 | let mut i = 0; | ||
| 3957 | while i < len { | ||
| 3958 | while i < len && mask_s[i] == 0 { | ||
| 3959 | i += 1; | ||
| 3960 | } | ||
| 3961 | let start = i; | ||
| 3962 | while i < len && mask_s[i] != 0 { | ||
| 3963 | i += 1; | ||
| 3964 | } | ||
| 3965 | if i > start { | ||
| 3966 | r_s.push((start, i - start)); | ||
| 3967 | } | ||
| 3968 | } | ||
| 3969 | } | ||
| 3970 | } | ||
| 3971 | std::hint::black_box(&r_s); | ||
| 3972 | }); | ||
| 3973 | let (mut host_v, mut tv_vec, mut mask_v, mut r_v) = (gpu.clone(), Vec::new(), Vec::new(), Vec::new()); | ||
| 3974 | let back_v = bench(500, || { | ||
| 3975 | host_v.copy_from_slice(&gpu); | ||
| 3976 | let _ = back_piece(&mut host_v, &old, &mut tv_vec, &mut mask_v, &mut r_v, |off, into| { | ||
| 3977 | into.copy_from_slice(&title0[off..off + into.len()]); | ||
| 3978 | true | ||
| 3979 | }); | ||
| 3980 | std::hint::black_box(&r_v); | ||
| 3981 | }); | ||
| 3982 | println!( | ||
| 3983 | "64 KiB sparse: merge scalar={merge_s:.2}us vs avx2={merge_v:.2}us ({:.2}x); \ | ||
| 3984 | changed_runs scalar={runs_s:.2}us vs avx2={runs_v:.2}us ({:.2}x); \ | ||
| 3985 | back_piece scalar={back_s:.2}us vs avx2={back_v:.2}us ({:.2}x)", | ||
| 3986 | merge_s / merge_v, | ||
| 3987 | runs_s / runs_v, | ||
| 3988 | back_s / back_v | ||
| 3989 | ); | ||
| 3990 | } | ||
| 3991 | |||
| 3666 | 3992 | ||
| 3667 | /// What shaders wrote reaches a page that is away only while the runtime | 3993 | /// What shaders wrote reaches a page that is away only while the runtime |
| 3668 | /// changes a mapping; a page that stays away loses it, and nothing else. | 3994 | /// changes a mapping; a page that stays away loses it, and nothing else. |
| @@ -6206,18 +6532,26 @@ impl Shadow { | |||
| 6206 | title.clear(); | 6532 | title.clear(); |
| 6207 | title.resize(n, 0); | 6533 | title.resize(n, 0); |
| 6208 | let mapped = crate::host::read_into((start + at) as *const u8, title); | 6534 | let mapped = crate::host::read_into((start + at) as *const u8, title); |
| 6209 | let was = title.clone(); | 6535 | thread_local! { |
| 6210 | let mut changed = false; | 6536 | static MERGE_WAS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; |
| 6211 | for (a, b) in outside(at, at + n, skip) { | ||
| 6212 | let (a, b) = (a - at, b - at); | ||
| 6213 | // Title memory that is not mapped: the CPU's side keeps what | ||
| 6214 | // the card wrote, as before; `title` is scratch then. | ||
| 6215 | changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); | ||
| 6216 | } | ||
| 6217 | if !mapped || !changed { | ||
| 6218 | return 0; | ||
| 6219 | } | 6537 | } |
| 6220 | put_changed(start + at, &was, title) | 6538 | MERGE_WAS.with_borrow_mut(|was| { |
| 6539 | if mapped { | ||
| 6540 | was.clear(); | ||
| 6541 | was.extend_from_slice(title); | ||
| 6542 | } | ||
| 6543 | let mut changed = false; | ||
| 6544 | for (a, b) in outside(at, at + n, skip) { | ||
| 6545 | let (a, b) = (a - at, b - at); | ||
| 6546 | // Title memory that is not mapped: the CPU's side keeps what | ||
| 6547 | // the card wrote, as before; `title` is scratch then. | ||
| 6548 | changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); | ||
| 6549 | } | ||
| 6550 | if !mapped || !changed { | ||
| 6551 | return 0; | ||
| 6552 | } | ||
| 6553 | put_changed(start + at, was, title) | ||
| 6554 | }) | ||
| 6221 | } | 6555 | } |
| 6222 | } | 6556 | } |
| 6223 | 6557 | ||
| @@ -6548,7 +6882,7 @@ mod land_tests { | |||
| 6548 | }); | 6882 | }); |
| 6549 | let mut now = vec![0u8; LEN]; | 6883 | let mut now = vec![0u8; LEN]; |
| 6550 | for round in 1..200u32 { | 6884 | for round in 1..200u32 { |
| 6551 | for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) { | 6885 | for block in (0..BLOCKS).filter(|b| !(*b as u32 * 5 + round).is_multiple_of(3)) { |
| 6552 | for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) { | 6886 | for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) { |
| 6553 | now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes()); | 6887 | now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes()); |
| 6554 | } | 6888 | } |
diff --git a/d3d12/crates/leonida-gpu/src/texback.rs b/d3d12/crates/leonida-gpu/src/texback.rs index 92ee5afc4..c578e23c8 100644 --- a/d3d12/crates/leonida-gpu/src/texback.rs +++ b/d3d12/crates/leonida-gpu/src/texback.rs | |||
| @@ -429,8 +429,10 @@ fn write(landing: &Landing) { | |||
| 429 | use crate::land::{count, spent, stat}; | 429 | use crate::land::{count, spent, stat}; |
| 430 | static COPIED: AtomicU64 = AtomicU64::new(0); | 430 | static COPIED: AtomicU64 = AtomicU64::new(0); |
| 431 | thread_local! { | 431 | thread_local! { |
| 432 | /// The texture as it is tiled, kept from one to the next ([`light`]). | 432 | /// The texture as it is tiled and its pre-tile snapshot (for `copy` |
| 433 | static TILED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; | 433 | /// page diffing), kept from one landing to the next ([`light`]). |
| 434 | static SCRATCH: std::cell::RefCell<(Vec<u8>, Vec<u8>)> = | ||
| 435 | const { std::cell::RefCell::new((Vec::new(), Vec::new())) }; | ||
| 434 | } | 436 | } |
| 435 | /// Memory kept for the next up to this size. | 437 | /// Memory kept for the next up to this size. |
| 436 | const KEPT: usize = 32 << 20; | 438 | const KEPT: usize = 32 << 20; |
| @@ -446,9 +448,6 @@ fn write(landing: &Landing) { | |||
| 446 | let (at, end) = (landing.ticket.at, landing.ticket.end); | 448 | let (at, end) = (landing.ticket.at, landing.ticket.end); |
| 447 | let size = end - at; | 449 | let size = end - at; |
| 448 | let copy = landing.ticket.copy; | 450 | let copy = landing.ticket.copy; |
| 449 | // What title memory held, for a copy's write: only the pages that change | ||
| 450 | // go back ([`changed_pages`]). | ||
| 451 | let mut before = Vec::new(); | ||
| 452 | // The texture as it will be, in `tiled` (`size` bytes); whether it is. | 451 | // The texture as it will be, in `tiled` (`size` bytes); whether it is. |
| 453 | let tile = |tiled: &mut [u8], before: &mut Vec<u8>| { | 452 | let tile = |tiled: &mut [u8], before: &mut Vec<u8>| { |
| 454 | // Keep title bytes the subresources do not cover. | 453 | // Keep title bytes the subresources do not cover. |
| @@ -491,17 +490,17 @@ fn write(landing: &Landing) { | |||
| 491 | put | 490 | put |
| 492 | }; | 491 | }; |
| 493 | let bytes = if light { | 492 | let bytes = if light { |
| 494 | let written = TILED.with_borrow_mut(|kept| { | 493 | let written = SCRATCH.with_borrow_mut(|(kept, before)| { |
| 495 | if kept.len() < size { | 494 | if kept.len() < size { |
| 496 | kept.resize(size, 0); | 495 | kept.resize(size, 0); |
| 497 | } | 496 | } |
| 498 | let written = if tile(&mut kept[..size], &mut before) { | 497 | let written = if tile(&mut kept[..size], before) { |
| 499 | // The lock for the write alone: who lets the allocation go | 498 | // The lock for the write alone: who lets the allocation go |
| 500 | // or maps other memory there waits for a copy, not for the | 499 | // or maps other memory there waits for a copy, not for the |
| 501 | // tiling, and what it made invalid meanwhile is not written. | 500 | // tiling, and what it made invalid meanwhile is not written. |
| 502 | let _tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); | 501 | let _tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); |
| 503 | if landing.ticket.valid.load(Ordering::Acquire) { | 502 | if landing.ticket.valid.load(Ordering::Acquire) { |
| 504 | Some(put(&kept[..size], &before)) | 503 | Some(put(&kept[..size], before)) |
| 505 | } else { | 504 | } else { |
| 506 | stale(); | 505 | stale(); |
| 507 | None | 506 | None |
| @@ -512,6 +511,9 @@ fn write(landing: &Landing) { | |||
| 512 | if kept.capacity() > KEPT { | 511 | if kept.capacity() > KEPT { |
| 513 | *kept = Vec::new(); | 512 | *kept = Vec::new(); |
| 514 | } | 513 | } |
| 514 | if before.capacity() > KEPT { | ||
| 515 | *before = Vec::new(); | ||
| 516 | } | ||
| 515 | written | 517 | written |
| 516 | }); | 518 | }); |
| 517 | let Some(bytes) = written else { | 519 | let Some(bytes) = written else { |
| @@ -520,6 +522,7 @@ fn write(landing: &Landing) { | |||
| 520 | bytes | 522 | bytes |
| 521 | } else { | 523 | } else { |
| 522 | let mut tiled = vec![0u8; size]; | 524 | let mut tiled = vec![0u8; size]; |
| 525 | let mut before = Vec::new(); | ||
| 523 | if !tile(&mut tiled, &mut before) { | 526 | if !tile(&mut tiled, &mut before) { |
| 524 | return; | 527 | return; |
| 525 | } | 528 | } |
| @@ -770,4 +773,52 @@ mod tests { | |||
| 770 | assert_eq!(now(), second, "a read-back was written into an allocation that went"); | 773 | assert_eq!(now(), second, "a read-back was written into an allocation that went"); |
| 771 | drop(title); | 774 | drop(title); |
| 772 | } | 775 | } |
| 776 | |||
| 777 | #[test] | ||
| 778 | fn copy_readbacks_write_changed_pages_across_reused_scratch() { | ||
| 779 | use leonida_formats::texture::{Desc, Dimension, Layout, Swizzle}; | ||
| 780 | const OWNER: usize = 0x7e57_bac1; | ||
| 781 | let layout = Layout::new(&Desc { | ||
| 782 | dimension: Dimension::Tex2d, | ||
| 783 | width: 64, | ||
| 784 | height: 32, | ||
| 785 | depth: 1, | ||
| 786 | mips: 1, | ||
| 787 | element_bytes: 4, | ||
| 788 | block: 1, | ||
| 789 | samples: 1, | ||
| 790 | swizzle: Swizzle::LINEAR, | ||
| 791 | }) | ||
| 792 | .unwrap(); | ||
| 793 | let size = layout.size as usize; // 8192 bytes (2 pages) | ||
| 794 | let mut title = vec![0x11u8; size]; | ||
| 795 | let at = title.as_mut_ptr() as usize; | ||
| 796 | let (pitch, rows) = (256usize, 32u32); | ||
| 797 | let make_landing = |data: Vec<u8>| Landing { | ||
| 798 | footprints: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { | ||
| 799 | Offset: 0, | ||
| 800 | Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Width: 64, Height: 32, Depth: 1, RowPitch: pitch as u32, ..Default::default() }, | ||
| 801 | }], | ||
| 802 | rows: vec![rows], | ||
| 803 | mips: 1, | ||
| 804 | layout: layout.clone(), | ||
| 805 | ticket: track(OWNER, at, at + size, true), | ||
| 806 | data, | ||
| 807 | subs: u64::MAX, | ||
| 808 | }; | ||
| 809 | // First copy modifies only page 1; page 0 stays 0x11. | ||
| 810 | let mut d1 = vec![0x11u8; size]; | ||
| 811 | d1[4096..4128].fill(0x22); | ||
| 812 | write(&make_landing(d1.clone())); | ||
| 813 | // SAFETY: `title` stays live for the duration of the test. | ||
| 814 | let snap1 = unsafe { std::slice::from_raw_parts(at as *const u8, size) }.to_vec(); | ||
| 815 | assert_eq!(snap1, d1); | ||
| 816 | // Second copy (reusing thread-local `before`) modifies only page 0; page 1 stays as snap1. | ||
| 817 | let mut d2 = d1; | ||
| 818 | d2[0..32].fill(0x33); | ||
| 819 | write(&make_landing(d2.clone())); | ||
| 820 | let snap2 = unsafe { std::slice::from_raw_parts(at as *const u8, size) }.to_vec(); | ||
| 821 | assert_eq!(snap2, d2); | ||
| 822 | drop(title); | ||
| 823 | } | ||
| 773 | } | 824 | } |
diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index 32ce3a491..cb9f50a06 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs | |||
| @@ -3671,7 +3671,7 @@ mod allocation_costs { | |||
| 3671 | seen.push(digest(&bytes)); | 3671 | seen.push(digest(&bytes)); |
| 3672 | } | 3672 | } |
| 3673 | } | 3673 | } |
| 3674 | let text: Vec<u8> = (0..400u32).map(|i| (i * 37 >> 2) as u8).collect(); | 3674 | let text: Vec<u8> = (0..400u32).map(|i| ((i * 37) >> 2) as u8).collect(); |
| 3675 | for at in 0..399 { | 3675 | for at in 0..399 { |
| 3676 | let mut bytes = text.clone(); | 3676 | let mut bytes = text.clone(); |
| 3677 | bytes.swap(at, at + 1); | 3677 | bytes.swap(at, at + 1); |
diff --git a/d3d12/crates/leonida-gpu/src/titlewrite/decode.rs b/d3d12/crates/leonida-gpu/src/titlewrite/decode.rs index a33f5e79b..b4a01b3a2 100644 --- a/d3d12/crates/leonida-gpu/src/titlewrite/decode.rs +++ b/d3d12/crates/leonida-gpu/src/titlewrite/decode.rs | |||
| @@ -604,7 +604,7 @@ mod tests { | |||
| 604 | f.extend([0x9c, 0x41, 0x5a, 0x48, 0x8b, 0x4c, 0x24, 0x28]); | 604 | f.extend([0x9c, 0x41, 0x5a, 0x48, 0x8b, 0x4c, 0x24, 0x28]); |
| 605 | f.extend([0x4c, 0x89, 0x11, 0x48, 0x89, 0x51, 0x08, 0x48, 0x89, 0x41, 0x10, 0xc3]); | 605 | f.extend([0x4c, 0x89, 0x11, 0x48, 0x89, 0x51, 0x08, 0x48, 0x89, 0x41, 0x10, 0xc3]); |
| 606 | type F = unsafe extern "system" fn(*mut u64, u64, u64, u64, *mut [u64; 3]); | 606 | type F = unsafe extern "system" fn(*mut u64, u64, u64, u64, *mut [u64; 3]); |
| 607 | let (there, operand, compared) = (spread(1), spread(2), if seed % 3 == 0 { spread(1) } else { spread(3) }); | 607 | let (there, operand, compared) = (spread(1), spread(2), if seed.is_multiple_of(3) { spread(1) } else { spread(3) }); |
| 608 | let flags = 0x202 | (spread(4) & 0x8d5) as u32; | 608 | let flags = 0x202 | (spread(4) & 0x8d5) as u32; |
| 609 | let (mut memory, mut out) = (there, [0; 3]); | 609 | let (mut memory, mut out) = (there, [0; 3]); |
| 610 | // SAFETY: the code above, which keeps to the calling convention. | 610 | // SAFETY: the code above, which keeps to the calling convention. |
diff --git a/d3d12/crates/leonida-gpu/src/watch.rs b/d3d12/crates/leonida-gpu/src/watch.rs index 747198367..a43ff741c 100644 --- a/d3d12/crates/leonida-gpu/src/watch.rs +++ b/d3d12/crates/leonida-gpu/src/watch.rs | |||
| @@ -1061,7 +1061,7 @@ fn ask_early(every: std::time::Duration) { | |||
| 1061 | idle = 0; | 1061 | idle = 0; |
| 1062 | } | 1062 | } |
| 1063 | round += 1; | 1063 | round += 1; |
| 1064 | if round % 64 == 0 { | 1064 | if round.is_multiple_of(64) { |
| 1065 | hot.retain(|_, n| { | 1065 | hot.retain(|_, n| { |
| 1066 | *n /= 2; | 1066 | *n /= 2; |
| 1067 | *n > 0 | 1067 | *n > 0 |
| @@ -4254,7 +4254,7 @@ pub fn title_memory_reading_now() -> Option<Reading> { | |||
| 4254 | /// write access is given back. | 4254 | /// write access is given back. |
| 4255 | pub fn title_memory_remapped(at: usize, len: usize) { | 4255 | pub fn title_memory_remapped(at: usize, len: usize) { |
| 4256 | crate::texback::remapped(at, len); | 4256 | crate::texback::remapped(at, len); |
| 4257 | open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); | 4257 | open(&title_memory_changed(at, len), at, at.saturating_add(len)); |
| 4258 | } | 4258 | } |
| 4259 | 4259 | ||
| 4260 | /// The runtime is about to unmap title memory `[at, at + len)`: it is | 4260 | /// The runtime is about to unmap title memory `[at, at + len)`: it is |
| @@ -4536,7 +4536,7 @@ fn page_protection(at: usize) -> Option<(u32, bool)> { | |||
| 4536 | let flags = unsafe { info.VirtualAttributes.Flags }; | 4536 | let flags = unsafe { info.VirtualAttributes.Flags }; |
| 4537 | // Bit 0: the page is in memory; then bits 4 to 14 are its protection and | 4537 | // Bit 0: the page is in memory; then bits 4 to 14 are its protection and |
| 4538 | // bit 15 says that it can be shared. | 4538 | // bit 15 says that it can be shared. |
| 4539 | let said = (ok && flags & 1 != 0).then(|| (((flags >> 4) & 0x7ff) as u32, flags >> 15 & 1 != 0)); | 4539 | let said = (ok && flags & 1 != 0).then_some((((flags >> 4) & 0x7ff) as u32, flags >> 15 & 1 != 0)); |
| 4540 | #[cfg(feature = "diagnostics")] | 4540 | #[cfg(feature = "diagnostics")] |
| 4541 | { | 4541 | { |
| 4542 | fault_count(if said.is_some() { FA_PAGES } else { FA_PAGES_UNSAID }, 1); | 4542 | fault_count(if said.is_some() { FA_PAGES } else { FA_PAGES_UNSAID }, 1); |
| @@ -5958,7 +5958,7 @@ mod tests { | |||
| 5958 | seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); | 5958 | seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); |
| 5959 | (seed >> 33) as usize % n | 5959 | (seed >> 33) as usize % n |
| 5960 | }; | 5960 | }; |
| 5961 | for round in 0..40_000 { | 5961 | for round in 0..40_000u32 { |
| 5962 | // About the ends of pieces and words. | 5962 | // About the ends of pieces and words. |
| 5963 | let block = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); | 5963 | let block = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); |
| 5964 | if next(3) == 0 { | 5964 | if next(3) == 0 { |
| @@ -5967,7 +5967,7 @@ mod tests { | |||
| 5967 | assert_eq!(set.insert(block), other.insert(block)); | 5967 | assert_eq!(set.insert(block), other.insert(block)); |
| 5968 | } | 5968 | } |
| 5969 | assert_eq!(set.contains(block), other.contains(&block)); | 5969 | assert_eq!(set.contains(block), other.contains(&block)); |
| 5970 | if round % 64 == 0 { | 5970 | if round.is_multiple_of(64) { |
| 5971 | let a = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); | 5971 | let a = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); |
| 5972 | let b = a + [next(10), next(300), 2 * Blocks::IN_PIECE + next(100)][next(3)]; | 5972 | let b = a + [next(10), next(300), 2 * Blocks::IN_PIECE + next(100)][next(3)]; |
| 5973 | assert!(set.range(a..b).eq(other.range(a..b).copied()), "{a}..{b}"); | 5973 | assert!(set.range(a..b).eq(other.range(a..b).copied()), "{a}..{b}"); |
diff --git a/d3d12/crates/leonida-hle/src/modules/clock.rs b/d3d12/crates/leonida-hle/src/modules/clock.rs index d39bf4b91..a4f167616 100644 --- a/d3d12/crates/leonida-hle/src/modules/clock.rs +++ b/d3d12/crates/leonida-hle/src/modules/clock.rs | |||
| @@ -14,7 +14,10 @@ use leonida_menu::knobs::clock; | |||
| 14 | use crate::{HleModule, hle_export}; | 14 | use crate::{HleModule, hle_export}; |
| 15 | 15 | ||
| 16 | /// `QueryPerformanceCounter`: the title's count. | 16 | /// `QueryPerformanceCounter`: the title's count. |
| 17 | pub extern "system" fn QueryPerformanceCounter(out: *mut i64) -> i32 { | 17 | /// |
| 18 | /// # Safety | ||
| 19 | /// If `out` is non-null, it must be valid for a write of an `i64`. | ||
| 20 | pub unsafe extern "system" fn QueryPerformanceCounter(out: *mut i64) -> i32 { | ||
| 18 | if out.is_null() { | 21 | if out.is_null() { |
| 19 | return 0; | 22 | return 0; |
| 20 | } | 23 | } |
| @@ -46,9 +49,9 @@ mod tests { | |||
| 46 | #[test] | 49 | #[test] |
| 47 | fn the_title_count_follows_the_host_until_the_rate_changes() { | 50 | fn the_title_count_follows_the_host_until_the_rate_changes() { |
| 48 | let mut a = 0i64; | 51 | let mut a = 0i64; |
| 49 | assert_eq!(QueryPerformanceCounter(&mut a), 1); | 52 | assert_eq!(unsafe { QueryPerformanceCounter(&mut a) }, 1); |
| 50 | let host = clock::host_now(); | 53 | let host = clock::host_now(); |
| 51 | assert!(host >= a && a > 0); | 54 | assert!(host >= a && a > 0); |
| 52 | assert_eq!(QueryPerformanceCounter(std::ptr::null_mut()), 0); | 55 | assert_eq!(unsafe { QueryPerformanceCounter(std::ptr::null_mut()) }, 0); |
| 53 | } | 56 | } |
| 54 | } | 57 | } |
diff --git a/d3d12/crates/leonida-hle/src/modules/dstorage.rs b/d3d12/crates/leonida-hle/src/modules/dstorage.rs index 427b75e40..124212af0 100644 --- a/d3d12/crates/leonida-hle/src/modules/dstorage.rs +++ b/d3d12/crates/leonida-hle/src/modules/dstorage.rs | |||
| @@ -441,7 +441,10 @@ fn read_direct(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Re | |||
| 441 | /// Read at a time. | 441 | /// Read at a time. |
| 442 | const MOST: usize = 1 << 20; | 442 | const MOST: usize = 1 << 20; |
| 443 | let sector = SECTOR as u64; | 443 | let sector = SECTOR as u64; |
| 444 | if offset % sector == 0 && out.len() % SECTOR == 0 && out.as_ptr() as usize % SECTOR == 0 { | 444 | if offset.is_multiple_of(sector) |
| 445 | && out.len().is_multiple_of(SECTOR) | ||
| 446 | && (out.as_ptr() as usize).is_multiple_of(SECTOR) | ||
| 447 | { | ||
| 445 | return read_overlapped(file, out, offset); | 448 | return read_overlapped(file, out, offset); |
| 446 | } | 449 | } |
| 447 | thread_local! { | 450 | thread_local! { |
| @@ -1421,9 +1424,10 @@ fn execute(request: &Request) -> Result<(), HRESULT> { | |||
| 1421 | } | 1424 | } |
| 1422 | let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; | 1425 | let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; |
| 1423 | // (The parts of a request a timeline tells apart: `LEONIDA_TIMELINE`.) | 1426 | // (The parts of a request a timeline tells apart: `LEONIDA_TIMELINE`.) |
| 1424 | let reading = leonida_gpu::timeline::span("streaming: reading the source"); | 1427 | let source = { |
| 1425 | let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; | 1428 | let _reading = leonida_gpu::timeline::span("streaming: reading the source"); |
| 1426 | drop(reading); | 1429 | read_source(request).map_err(|hr| fail(hr, "reading the source"))? |
| 1430 | }; | ||
| 1427 | // The console's order: zlib first, then BCPack. | 1431 | // The console's order: zlib first, then BCPack. |
| 1428 | let source = if bc != 0 && options & ZLIB != 0 { | 1432 | let source = if bc != 0 && options & ZLIB != 0 { |
| 1429 | let _inflating = leonida_gpu::timeline::span("streaming: inflating"); | 1433 | let _inflating = leonida_gpu::timeline::span("streaming: inflating"); |
| @@ -2199,7 +2203,7 @@ mod tests { | |||
| 2199 | for round in 0..2 { | 2203 | for round in 0..2 { |
| 2200 | for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { | 2204 | for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { |
| 2201 | let file = Files::open_for_test(&path, mode); | 2205 | let file = Files::open_for_test(&path, mode); |
| 2202 | let at: Vec<u64> = (0..READS).map(|_| random() % (len - SIZE as u64) & !15).collect(); | 2206 | let at: Vec<u64> = (0..READS).map(|_| (random() % (len - SIZE as u64)) & !15).collect(); |
| 2203 | for pass in ["cold", "again"] { | 2207 | for pass in ["cold", "again"] { |
| 2204 | let next = std::sync::atomic::AtomicUsize::new(0); | 2208 | let next = std::sync::atomic::AtomicUsize::new(0); |
| 2205 | let busy = AtomicU64::new(0); | 2209 | let busy = AtomicU64::new(0); |
diff --git a/d3d12/crates/leonida-hle/src/modules/gameinput.rs b/d3d12/crates/leonida-hle/src/modules/gameinput.rs index 9d8940210..81535812e 100644 --- a/d3d12/crates/leonida-hle/src/modules/gameinput.rs +++ b/d3d12/crates/leonida-hle/src/modules/gameinput.rs | |||
| @@ -2372,9 +2372,8 @@ mod tests { | |||
| 2372 | Value::Pad(p) => assert_eq!((p.right_trigger, p.left_x), (1.0, 1.0)), | 2372 | Value::Pad(p) => assert_eq!((p.right_trigger, p.left_x), (1.0, 1.0)), |
| 2373 | _ => unreachable!(), | 2373 | _ => unreachable!(), |
| 2374 | } | 2374 | } |
| 2375 | match &state.slots[KEYBOARD].history.back().map(|r| &r.value) { | 2375 | if let Some(Value::Keys(k)) = &state.slots[KEYBOARD].history.back().map(|r| &r.value) { |
| 2376 | Some(Value::Keys(k)) => assert!(k.iter().all(|k| k.virtual_key == b'D')), | 2376 | assert!(k.iter().all(|k| k.virtual_key == b'D')); |
| 2377 | _ => {} | ||
| 2378 | } | 2377 | } |
| 2379 | } | 2378 | } |
| 2380 | 2379 | ||
diff --git a/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs b/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs index 00a2978c4..2c0ecd2d3 100644 --- a/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs +++ b/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs | |||
| @@ -650,7 +650,7 @@ mod tests { | |||
| 650 | assert_eq!(pad, PadState { left_x: -1.0, ..Default::default() }, "{ms} ms"); | 650 | assert_eq!(pad, PadState { left_x: -1.0, ..Default::default() }, "{ms} ms"); |
| 651 | } | 651 | } |
| 652 | // The mouse button let go and pressed again: it shoots from the vehicle, and is still no accelerator. | 652 | // The mouse button let go and pressed again: it shoots from the vehicle, and is still no accelerator. |
| 653 | k.pad(&keys(&[b'W', b'A']), CAR, 60_008 * MS); | 653 | k.pad(&keys(b"WA"), CAR, 60_008 * MS); |
| 654 | let pad = k.pad(&held, CAR, 60_016 * MS); | 654 | let pad = k.pad(&held, CAR, 60_016 * MS); |
| 655 | assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, left_x: -1.0, ..Default::default() }); | 655 | assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, left_x: -1.0, ..Default::default() }); |
| 656 | // W let go and pressed again: it accelerates. | 656 | // W let go and pressed again: it accelerates. |
diff --git a/d3d12/crates/leonida-hle/src/modules/xmem.rs b/d3d12/crates/leonida-hle/src/modules/xmem.rs index 99393503d..1ef349638 100644 --- a/d3d12/crates/leonida-hle/src/modules/xmem.rs +++ b/d3d12/crates/leonida-hle/src/modules/xmem.rs | |||
| @@ -1287,6 +1287,9 @@ fn arrange(base: usize, pages: &[usize]) { | |||
| 1287 | { | 1287 | { |
| 1288 | slice.index = have; | 1288 | slice.index = have; |
| 1289 | owner.insert(have, other); | 1289 | owner.insert(have, other); |
| 1290 | } else { | ||
| 1291 | // No page had `want`: none has `have` once this one leaves it. | ||
| 1292 | owner.remove(&have); | ||
| 1290 | } | 1293 | } |
| 1291 | if let Some(slice) = table.pages.get_mut(number) { | 1294 | if let Some(slice) = table.pages.get_mut(number) { |
| 1292 | slice.index = want; | 1295 | slice.index = want; |
| @@ -1547,7 +1550,10 @@ fn alias_chunk() -> usize { | |||
| 1547 | /// are to show are looked up now, while their sources show them (the title maps other pages into | 1550 | /// are to show are looked up now, while their sources show them (the title maps other pages into |
| 1548 | /// its pool next); what comes back maps them, once, on whichever thread calls it. | 1551 | /// its pool next); what comes back maps them, once, on whichever thread calls it. |
| 1549 | pub fn map_aliases_later(ranges: &[(u64, u64, u64)]) -> Box<dyn FnOnce() -> bool + Send> { | 1552 | pub fn map_aliases_later(ranges: &[(u64, u64, u64)]) -> Box<dyn FnOnce() -> bool + Send> { |
| 1550 | if ranges.iter().any(|&(to, from, _)| to as usize % PAGE != 0 || (from != 0 && from as usize % PAGE != 0)) { | 1553 | if ranges |
| 1554 | .iter() | ||
| 1555 | .any(|&(to, from, _)| !(to as usize).is_multiple_of(PAGE) || (from != 0 && !(from as usize).is_multiple_of(PAGE))) | ||
| 1556 | { | ||
| 1551 | // Not on pages: as before, in the call. | 1557 | // Not on pages: as before, in the call. |
| 1552 | let done = map_aliases(ranges); | 1558 | let done = map_aliases(ranges); |
| 1553 | return Box::new(move || done); | 1559 | return Box::new(move || done); |
| @@ -2558,6 +2564,26 @@ mod tests { | |||
| 2558 | assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); | 2564 | assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); |
| 2559 | } | 2565 | } |
| 2560 | 2566 | ||
| 2567 | #[test] | ||
| 2568 | fn arrange_forgets_the_slice_a_page_left_for_an_unowned_one() { | ||
| 2569 | // A page that moves to a slice no page has leaves its own slice | ||
| 2570 | // with no page either: a later page moved there in the same call | ||
| 2571 | // must not move the first one back. | ||
| 2572 | let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, GRAPHICS | ADDRESS_32BIT, PAGE_NOACCESS); | ||
| 2573 | assert!(!base.is_null() && (base as usize) < 1 << 32); | ||
| 2574 | let pages = allocate(4); | ||
| 2575 | let index = |number: usize| page_table().pages.get(&number).map(|s| s.index); | ||
| 2576 | let at = |page: usize| base.wrapping_byte_add(page * PAGE); | ||
| 2577 | // Slice 1 has no page any more. | ||
| 2578 | assert_eq!(XMemFreePhysicalPages(1, &pages[1]), 1); | ||
| 2579 | // pages[2] goes from slice 2 to the free slice 1, then pages[3] | ||
| 2580 | // from slice 3 to slice 2, which pages[2] just left. | ||
| 2581 | arrange(at(1) as usize, &pages[2..]); | ||
| 2582 | assert_eq!([index(pages[2]), index(pages[3])], [Some(1), Some(2)]); | ||
| 2583 | assert_eq!(XMemFreePhysicalPages(1, &pages[0]), 1); | ||
| 2584 | assert_eq!(XMemFreePhysicalPages(2, pages[2..].as_ptr()), 1); | ||
| 2585 | } | ||
| 2586 | |||
| 2561 | /// The two steps of a page-mapping copy: what the ranges are to show is looked up at the | 2587 | /// The two steps of a page-mapping copy: what the ranges are to show is looked up at the |
| 2562 | /// call; the pool mapped to other pages before the mapping is done changes nothing of it. A | 2588 | /// call; the pool mapped to other pages before the mapping is done changes nothing of it. A |
| 2563 | /// page that shows the same page already stays mapped, and a source of 0 unmaps. | 2589 | /// page that shows the same page already stays mapped, and a source of 0 unmaps. |
diff --git a/d3d12/crates/leonida-loader/src/descriptor_sites.rs b/d3d12/crates/leonida-loader/src/descriptor_sites.rs index 4386bb34c..78272358c 100644 --- a/d3d12/crates/leonida-loader/src/descriptor_sites.rs +++ b/d3d12/crates/leonida-loader/src/descriptor_sites.rs | |||
| @@ -278,7 +278,7 @@ mod tests { | |||
| 278 | let mine = [Site { window: 0x1100, ..*site }]; | 278 | let mine = [Site { window: 0x1100, ..*site }]; |
| 279 | assert_eq!(apply(place, 0x10000, &raw const *marks as usize, &mine), [Hooked::Done]); | 279 | assert_eq!(apply(place, 0x10000, &raw const *marks as usize, &mine), [Hooked::Done]); |
| 280 | assert_eq!(*((place + 0x1100 + site.store) as *const u8), 0xe9); | 280 | assert_eq!(*((place + 0x1100 + site.store) as *const u8), 0xe9); |
| 281 | let (plain, hooked): (F, F) = (std::mem::transmute(plain), std::mem::transmute(hooked)); | 281 | let (plain, hooked) = (std::mem::transmute::<usize, F>(plain), std::mem::transmute::<usize, F>(hooked)); |
| 282 | let record: [u8; 32] = std::array::from_fn(|k| k as u8 ^ 0x5a); | 282 | let record: [u8; 32] = std::array::from_fn(|k| k as u8 ^ 0x5a); |
| 283 | // In the heap: slot 0x40 + 3 of its start. | 283 | // In the heap: slot 0x40 + 3 of its start. |
| 284 | let table = heap.add(0x2000 + 0x40 * 32); | 284 | let table = heap.add(0x2000 + 0x40 * 32); |
diff --git a/d3d12/crates/leonida-loader/src/write_sites.rs b/d3d12/crates/leonida-loader/src/write_sites.rs index 9600e4679..6e17ab372 100644 --- a/d3d12/crates/leonida-loader/src/write_sites.rs +++ b/d3d12/crates/leonida-loader/src/write_sites.rs | |||
| @@ -346,7 +346,7 @@ mod tests { | |||
| 346 | let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at); | 346 | let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at); |
| 347 | assert_eq!(apply("t.dll", second, 0x1000, &list), 1); | 347 | assert_eq!(apply("t.dll", second, 0x1000, &list), 1); |
| 348 | assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9); | 348 | assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9); |
| 349 | let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); | 349 | let (plain, changed) = (std::mem::transmute::<usize, F>(place), std::mem::transmute::<usize, F>(second)); |
| 350 | for was in 0..=255u8 { | 350 | for was in 0..=255u8 { |
| 351 | let mut bytes = [[0u8; 0x40]; 2]; | 351 | let mut bytes = [[0u8; 0x40]; 2]; |
| 352 | bytes[0][0x31] = was; | 352 | bytes[0][0x31] = was; |
| @@ -422,7 +422,7 @@ mod tests { | |||
| 422 | if size == 0 { | 422 | if size == 0 { |
| 423 | continue; | 423 | continue; |
| 424 | } | 424 | } |
| 425 | let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); | 425 | let (plain, changed) = (std::mem::transmute::<usize, F>(place), std::mem::transmute::<usize, F>(second)); |
| 426 | let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; | 426 | let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; |
| 427 | for seed in 0..200u64 { | 427 | for seed in 0..200u64 { |
| 428 | let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); | 428 | let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); |
diff --git a/d3d12/crates/leonida-lua/src/input.rs b/d3d12/crates/leonida-lua/src/input.rs index e8f055c0d..a20a51521 100644 --- a/d3d12/crates/leonida-lua/src/input.rs +++ b/d3d12/crates/leonida-lua/src/input.rs | |||
| @@ -61,6 +61,12 @@ mod host { | |||
| 61 | focus: bool, | 61 | focus: bool, |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | impl Default for Keys { | ||
| 65 | fn default() -> Keys { | ||
| 66 | Keys::new() | ||
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 64 | impl Keys { | 70 | impl Keys { |
| 65 | pub fn new() -> Keys { | 71 | pub fn new() -> Keys { |
| 66 | Keys { focus: focused() } | 72 | Keys { focus: focused() } |
| @@ -78,6 +84,12 @@ mod host { | |||
| 78 | empty_until: [Option<Instant>; 4], | 84 | empty_until: [Option<Instant>; 4], |
| 79 | } | 85 | } |
| 80 | 86 | ||
| 87 | impl Default for Pads { | ||
| 88 | fn default() -> Pads { | ||
| 89 | Pads::new() | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 81 | impl Pads { | 93 | impl Pads { |
| 82 | pub fn new() -> Pads { | 94 | pub fn new() -> Pads { |
| 83 | Pads { | 95 | Pads { |
diff --git a/d3d12/crates/leonida-lua/src/memory.rs b/d3d12/crates/leonida-lua/src/memory.rs index 80eb68ab1..1ade9ca08 100644 --- a/d3d12/crates/leonida-lua/src/memory.rs +++ b/d3d12/crates/leonida-lua/src/memory.rs | |||
| @@ -91,7 +91,7 @@ impl Pattern { | |||
| 91 | } | 91 | } |
| 92 | } | 92 | } |
| 93 | } else { | 93 | } else { |
| 94 | if flat.len() % 2 != 0 { | 94 | if !flat.len().is_multiple_of(2) { |
| 95 | return Err("an odd number of digits".into()); | 95 | return Err("an odd number of digits".into()); |
| 96 | } | 96 | } |
| 97 | for pair in flat.chunks(2) { | 97 | for pair in flat.chunks(2) { |
diff --git a/d3d12/crates/leonida-lua/src/tests.rs b/d3d12/crates/leonida-lua/src/tests.rs index 62884f5e5..748c557ec 100644 --- a/d3d12/crates/leonida-lua/src/tests.rs +++ b/d3d12/crates/leonida-lua/src/tests.rs | |||
| @@ -353,7 +353,7 @@ fn a_mod_that_fails_is_switched_off_and_the_others_go_on() { | |||
| 353 | assert_eq!(status(&rt, "a_bad"), Status::Running); | 353 | assert_eq!(status(&rt, "a_bad"), Status::Running); |
| 354 | // Both loaded: two pages, both keys held. | 354 | // Both loaded: two pages, both keys held. |
| 355 | assert_eq!(fake.pages.borrow().last().unwrap().len(), 2); | 355 | assert_eq!(fake.pages.borrow().last().unwrap().len(), 2); |
| 356 | assert_eq!(fake.injected.borrow().last().unwrap(), &[b'A', b'W']); | 356 | assert_eq!(fake.injected.borrow().last().unwrap(), b"AW"); |
| 357 | for frame in 1..=3 { | 357 | for frame in 1..=3 { |
| 358 | pass(&mut rt, frame); | 358 | pass(&mut rt, frame); |
| 359 | } | 359 | } |
| @@ -367,7 +367,7 @@ fn a_mod_that_fails_is_switched_off_and_the_others_go_on() { | |||
| 367 | let pages = fake.pages.borrow().last().unwrap().clone(); | 367 | let pages = fake.pages.borrow().last().unwrap().clone(); |
| 368 | assert_eq!(pages.len(), 1); | 368 | assert_eq!(pages.len(), 1); |
| 369 | assert_eq!(pages[0].title, "Good page"); | 369 | assert_eq!(pages[0].title, "Good page"); |
| 370 | assert_eq!(fake.injected.borrow().last().unwrap(), &[b'A']); | 370 | assert_eq!(fake.injected.borrow().last().unwrap(), b"A"); |
| 371 | assert!( | 371 | assert!( |
| 372 | fake.of("a_bad") | 372 | fake.of("a_bad") |
| 373 | .iter() | 373 | .iter() |
diff --git a/d3d12/crates/leonida-menu/src/knobs.rs b/d3d12/crates/leonida-menu/src/knobs.rs index 0de62e406..3a003b2c1 100644 --- a/d3d12/crates/leonida-menu/src/knobs.rs +++ b/d3d12/crates/leonida-menu/src/knobs.rs | |||
| @@ -425,7 +425,7 @@ mod tests { | |||
| 425 | assert!(injected_keys().is_empty()); | 425 | assert!(injected_keys().is_empty()); |
| 426 | set_injected_keys(&[b'W', 0x20, 0xA0, b'W']); | 426 | set_injected_keys(&[b'W', 0x20, 0xA0, b'W']); |
| 427 | assert_eq!(injected_keys(), [0x20, b'W', 0xA0]); | 427 | assert_eq!(injected_keys(), [0x20, b'W', 0xA0]); |
| 428 | set_injected_keys(&[b'D']); | 428 | set_injected_keys(b"D"); |
| 429 | assert_eq!(injected_keys(), [b'D']); | 429 | assert_eq!(injected_keys(), [b'D']); |
| 430 | set_injected_keys(&[]); | 430 | set_injected_keys(&[]); |
| 431 | assert!(injected_keys().is_empty()); | 431 | assert!(injected_keys().is_empty()); |
diff --git a/d3d12/crates/leonida-menu/src/overlay.rs b/d3d12/crates/leonida-menu/src/overlay.rs index 6bf727819..f731233c3 100644 --- a/d3d12/crates/leonida-menu/src/overlay.rs +++ b/d3d12/crates/leonida-menu/src/overlay.rs | |||
| @@ -289,7 +289,7 @@ mod tests { | |||
| 289 | size: 20.0, | 289 | size: 20.0, |
| 290 | colour: [255, 255, 255, 255], | 290 | colour: [255, 255, 255, 255], |
| 291 | }; | 291 | }; |
| 292 | let p = painter.paint(&[text.clone()], 1.0).unwrap(); | 292 | let p = painter.paint(std::slice::from_ref(&text), 1.0).unwrap(); |
| 293 | assert_eq!(p.origin, (100, 50)); | 293 | assert_eq!(p.origin, (100, 50)); |
| 294 | // Two 20-pixel dot letters, 12 wide each. | 294 | // Two 20-pixel dot letters, 12 wide each. |
| 295 | assert_eq!((p.layers.width, p.layers.height), (24, 20)); | 295 | assert_eq!((p.layers.width, p.layers.height), (24, 20)); |
diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode.rs b/d3d12/crates/leonida-shader/src/emit/bitcode.rs index d47cc7d9e..429af0157 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode.rs | |||
| @@ -7,6 +7,8 @@ | |||
| 7 | 7 | ||
| 8 | use std::collections::HashMap; | 8 | use std::collections::HashMap; |
| 9 | 9 | ||
| 10 | use crate::fxhash::FxHashMap; | ||
| 11 | |||
| 10 | pub mod census; | 12 | pub mod census; |
| 11 | pub mod opt; | 13 | pub mod opt; |
| 12 | 14 | ||
| @@ -217,12 +219,12 @@ enum MdDef { | |||
| 217 | #[derive(Default)] | 219 | #[derive(Default)] |
| 218 | pub(crate) struct Module { | 220 | pub(crate) struct Module { |
| 219 | types: Vec<TypeDef>, | 221 | types: Vec<TypeDef>, |
| 220 | type_ids: HashMap<TypeDef, u32>, | 222 | type_ids: FxHashMap<TypeDef, u32>, |
| 221 | consts: Vec<(Ty, Const)>, | 223 | consts: Vec<(Ty, Const)>, |
| 222 | const_ids: HashMap<(Ty, Const), u32>, | 224 | const_ids: FxHashMap<(Ty, Const), u32>, |
| 223 | globals: Vec<Global>, | 225 | globals: Vec<Global>, |
| 224 | funcs: Vec<Func>, | 226 | funcs: Vec<Func>, |
| 225 | func_ids: HashMap<String, u32>, | 227 | func_ids: FxHashMap<String, u32>, |
| 226 | insts: Vec<Inst>, | 228 | insts: Vec<Inst>, |
| 227 | blocks: Vec<Block>, | 229 | blocks: Vec<Block>, |
| 228 | mds: Vec<MdDef>, | 230 | mds: Vec<MdDef>, |
diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index 17ba66416..cd7195d74 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs | |||
| @@ -42,6 +42,8 @@ | |||
| 42 | 42 | ||
| 43 | use std::collections::HashMap; | 43 | use std::collections::HashMap; |
| 44 | 44 | ||
| 45 | use crate::fxhash::FxHashMap; | ||
| 46 | |||
| 45 | use super::{ | 47 | use super::{ |
| 46 | Attr, Bin, Cast, Const, Func, Inst, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, | 48 | Attr, Bin, Cast, Const, Func, Inst, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, |
| 47 | successors, | 49 | successors, |
| @@ -147,8 +149,8 @@ fn opposite(p: u8) -> u8 { | |||
| 147 | /// and comparisons (by their operands) with a known outcome. | 149 | /// and comparisons (by their operands) with a known outcome. |
| 148 | #[derive(Default)] | 150 | #[derive(Default)] |
| 149 | struct Facts { | 151 | struct Facts { |
| 150 | bits: HashMap<V, bool>, | 152 | bits: FxHashMap<V, bool>, |
| 151 | compares: HashMap<(u8, V, V), bool>, | 153 | compares: FxHashMap<(u8, V, V), bool>, |
| 152 | } | 154 | } |
| 153 | 155 | ||
| 154 | /// The facts a block added, to forget when its part of the tree is done. | 156 | /// The facts a block added, to forget when its part of the tree is done. |
| @@ -248,7 +250,11 @@ impl Module { | |||
| 248 | // the next (a loop's registers that only go round), and a | 250 | // the next (a loop's registers that only go round), and a |
| 249 | // branch that goes one way leaves blocks with one way in. | 251 | // branch that goes one way leaves blocks with one way in. |
| 250 | for _ in 0..4 { | 252 | for _ in 0..4 { |
| 251 | let mut changed = self.merge(passes); | 253 | let mut changed = false; |
| 254 | if passes & REUSE != 0 { | ||
| 255 | changed |= self.hoist_handles(); | ||
| 256 | } | ||
| 257 | changed |= self.merge(passes); | ||
| 252 | if passes & FOLD != 0 { | 258 | if passes & FOLD != 0 { |
| 253 | changed |= self.prune(); | 259 | changed |= self.prune(); |
| 254 | } | 260 | } |
| @@ -770,6 +776,121 @@ impl Module { | |||
| 770 | }) | 776 | }) |
| 771 | } | 777 | } |
| 772 | 778 | ||
| 779 | /// Hoists uniform `dx.op.createHandleFromHeap` calls (and their `annotateHandle` | ||
| 780 | /// plus pure, non-trapping index/clamp operands such as `cbufferLoadLegacy` + add) | ||
| 781 | /// to the earliest dominating block where all operands are defined, so `REUSE` | ||
| 782 | /// collapses identical descriptors created in sibling branches or loops to one. | ||
| 783 | fn hoist_handles(&mut self) -> bool { | ||
| 784 | if self.blocks.len() <= 1 { | ||
| 785 | return false; | ||
| 786 | } | ||
| 787 | let tree = self.dominator_tree(); | ||
| 788 | let mut depth = vec![0usize; self.blocks.len()]; | ||
| 789 | let mut dfs = vec![0usize]; | ||
| 790 | while let Some(b) = dfs.pop() { | ||
| 791 | for &c in &tree.children[b] { | ||
| 792 | depth[c] = depth[b] + 1; | ||
| 793 | dfs.push(c); | ||
| 794 | } | ||
| 795 | } | ||
| 796 | let mut def_block: Vec<Option<usize>> = vec![None; self.insts.len()]; | ||
| 797 | for &b in &tree.order { | ||
| 798 | for &i in self.blocks[b].phis.iter().chain(&self.blocks[b].body) { | ||
| 799 | def_block[i as usize] = Some(b); | ||
| 800 | } | ||
| 801 | } | ||
| 802 | let is_false = |v: V| matches!(v, V::Const(c) if matches!(self.consts[c as usize].1, Const::Int(0))); | ||
| 803 | let mut eligible = vec![false; self.insts.len()]; | ||
| 804 | let mut work = Vec::new(); | ||
| 805 | for &b in &tree.order { | ||
| 806 | for &i in &self.blocks[b].body { | ||
| 807 | if let Op::Call(f, args) = &self.insts[i as usize].op | ||
| 808 | && self.funcs[*f as usize].name == "dx.op.createHandleFromHeap" | ||
| 809 | && args.len() >= 4 | ||
| 810 | && is_false(args[3]) | ||
| 811 | { | ||
| 812 | eligible[i as usize] = true; | ||
| 813 | work.push(i); | ||
| 814 | } | ||
| 815 | } | ||
| 816 | } | ||
| 817 | if work.is_empty() { | ||
| 818 | return false; | ||
| 819 | } | ||
| 820 | // Mark `annotateHandle` wrapping an eligible uniform heap handle. | ||
| 821 | for &b in &tree.order { | ||
| 822 | for &i in &self.blocks[b].body { | ||
| 823 | if let Op::Call(f, args) = &self.insts[i as usize].op | ||
| 824 | && self.funcs[*f as usize].name == "dx.op.annotateHandle" | ||
| 825 | && let Some(&V::Inst(h)) = args.get(1) | ||
| 826 | && eligible[h as usize] | ||
| 827 | { | ||
| 828 | eligible[i as usize] = true; | ||
| 829 | } | ||
| 830 | } | ||
| 831 | } | ||
| 832 | // Walk backward from eligible handles to include pure, non-trapping index/clamp operands. | ||
| 833 | while let Some(i) = work.pop() { | ||
| 834 | for_each_operand(&self.insts[i as usize].op, |v| { | ||
| 835 | let V::Inst(op) = v else { return }; | ||
| 836 | if eligible[op as usize] || def_block[op as usize].is_none() { | ||
| 837 | return; | ||
| 838 | } | ||
| 839 | let hoistable = match &self.insts[op as usize].op { | ||
| 840 | Op::Bin(bin, _, _) => !matches!(bin, Bin::UDiv | Bin::SDiv | Bin::URem), | ||
| 841 | Op::Cast(..) | Op::Extract(..) => true, | ||
| 842 | Op::Call(f, _) => { | ||
| 843 | let name = &self.funcs[*f as usize].name; | ||
| 844 | name.starts_with("dx.op.cbufferLoadLegacy") | ||
| 845 | || name == "dx.op.binary.i32" | ||
| 846 | || name == "dx.op.createHandleFromBinding" | ||
| 847 | || name.starts_with("dx.op.createHandleForLib") | ||
| 848 | } | ||
| 849 | _ => false, | ||
| 850 | }; | ||
| 851 | if hoistable { | ||
| 852 | eligible[op as usize] = true; | ||
| 853 | work.push(op); | ||
| 854 | } | ||
| 855 | }); | ||
| 856 | } | ||
| 857 | // Move eligible instructions in RPO order to the deepest dominating operand block. | ||
| 858 | let mut moved = false; | ||
| 859 | for &b in &tree.order { | ||
| 860 | if b == 0 { | ||
| 861 | continue; | ||
| 862 | } | ||
| 863 | let body = std::mem::take(&mut self.blocks[b].body); | ||
| 864 | let mut kept = Vec::with_capacity(body.len()); | ||
| 865 | for i in body { | ||
| 866 | if !eligible[i as usize] { | ||
| 867 | kept.push(i); | ||
| 868 | continue; | ||
| 869 | } | ||
| 870 | let mut target = 0usize; | ||
| 871 | let mut ok = true; | ||
| 872 | for_each_operand(&self.insts[i as usize].op, |v| { | ||
| 873 | if let V::Inst(op) = v { | ||
| 874 | match def_block[op as usize] { | ||
| 875 | Some(ob) if depth[ob] > depth[target] => target = ob, | ||
| 876 | Some(_) => {} | ||
| 877 | None => ok = false, | ||
| 878 | } | ||
| 879 | } | ||
| 880 | }); | ||
| 881 | if ok && target != b && depth[target] < depth[b] { | ||
| 882 | self.blocks[target].body.push(i); | ||
| 883 | def_block[i as usize] = Some(target); | ||
| 884 | moved = true; | ||
| 885 | } else { | ||
| 886 | kept.push(i); | ||
| 887 | } | ||
| 888 | } | ||
| 889 | self.blocks[b].body = kept; | ||
| 890 | } | ||
| 891 | moved | ||
| 892 | } | ||
| 893 | |||
| 773 | /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the | 894 | /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the |
| 774 | /// dominator tree. Returns whether anything changed. | 895 | /// dominator tree. Returns whether anything changed. |
| 775 | fn merge(&mut self, passes: u32) -> bool { | 896 | fn merge(&mut self, passes: u32) -> bool { |
| @@ -866,16 +987,16 @@ impl Module { | |||
| 866 | }; | 987 | }; |
| 867 | // The values every path to the block being walked has computed | 988 | // The values every path to the block being walked has computed |
| 868 | // (those of the blocks above it in the tree, and its own so far). | 989 | // (those of the blocks above it in the tree, and its own so far). |
| 869 | let mut known: HashMap<Key, V> = HashMap::new(); | 990 | let mut known: FxHashMap<Key, V> = FxHashMap::default(); |
| 870 | // Dominating memory reads still valid (no `Effect::Writes` since). | 991 | // Dominating memory reads still valid (no `Effect::Writes` since). |
| 871 | let mut dom_reads: HashMap<Key, V> = HashMap::new(); | 992 | let mut dom_reads: FxHashMap<Key, V> = FxHashMap::default(); |
| 872 | // Wave/quad operations in the current block (active lanes stay fixed within a block). | 993 | // Wave/quad operations in the current block (active lanes stay fixed within a block). |
| 873 | let mut lane_reads: HashMap<Key, V> = HashMap::new(); | 994 | let mut lane_reads: FxHashMap<Key, V> = FxHashMap::default(); |
| 874 | let mut facts = Facts::default(); | 995 | let mut facts = Facts::default(); |
| 875 | let (yes, no) = (self.bool(true), self.bool(false)); | 996 | let (yes, no) = (self.bool(true), self.bool(false)); |
| 876 | enum Step { | 997 | enum Step { |
| 877 | Enter(usize), | 998 | Enter(usize), |
| 878 | Leave(Vec<Key>, Learned, Vec<Key>, Option<HashMap<Key, V>>), | 999 | Leave(Vec<Key>, Learned, Vec<Key>, Option<FxHashMap<Key, V>>), |
| 879 | } | 1000 | } |
| 880 | let mut steps = vec![Step::Enter(0)]; | 1001 | let mut steps = vec![Step::Enter(0)]; |
| 881 | while let Some(step) = steps.pop() { | 1002 | while let Some(step) = steps.pop() { |
| @@ -928,7 +1049,7 @@ impl Module { | |||
| 928 | } | 1049 | } |
| 929 | // Two joins of the same values from the same blocks are one. | 1050 | // Two joins of the same values from the same blocks are one. |
| 930 | if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { | 1051 | if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { |
| 931 | let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new(); | 1052 | let mut joins: FxHashMap<Vec<(usize, V)>, V> = FxHashMap::default(); |
| 932 | for &p in &self.blocks[b].phis { | 1053 | for &p in &self.blocks[b].phis { |
| 933 | if repl[p as usize].is_some() { | 1054 | if repl[p as usize].is_some() { |
| 934 | continue; | 1055 | continue; |
| @@ -1311,7 +1432,7 @@ impl Module { | |||
| 1311 | body.push(i); | 1432 | body.push(i); |
| 1312 | continue; | 1433 | continue; |
| 1313 | }; | 1434 | }; |
| 1314 | let mut value = |m: &mut Module, body: &mut Vec<u32>, t: &Cond| -> V { | 1435 | let value = |m: &mut Module, body: &mut Vec<u32>, t: &Cond| -> V { |
| 1315 | t.existing.unwrap_or_else(|| { | 1436 | t.existing.unwrap_or_else(|| { |
| 1316 | let x = m.insts.len() as u32; | 1437 | let x = m.insts.len() as u32; |
| 1317 | m.insts.push(Inst { ty: i1, op: Op::Bin(Bin::Xor, t.base, yes) }); | 1438 | m.insts.push(Inst { ty: i1, op: Op::Bin(Bin::Xor, t.base, yes) }); |
| @@ -1771,7 +1892,7 @@ mod tests { | |||
| 1771 | .. | 1892 | .. |
| 1772 | } = kit(); | 1893 | } = kit(); |
| 1773 | let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); | 1894 | let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); |
| 1774 | let mut cond = |m: &mut Module, k: V| { | 1895 | let cond = |m: &mut Module, k: V| { |
| 1775 | let v = m.call(b, reads, vec![k, k]); | 1896 | let v = m.call(b, reads, vec![k, k]); |
| 1776 | m.cmp(b, pred::NE, v, zero) | 1897 | m.cmp(b, pred::NE, v, zero) |
| 1777 | }; | 1898 | }; |
| @@ -2713,6 +2834,65 @@ mod tests { | |||
| 2713 | } | 2834 | } |
| 2714 | 2835 | ||
| 2715 | #[test] | 2836 | #[test] |
| 2837 | fn uniform_heap_handles_hoist_out_of_branches_and_deduplicate() { | ||
| 2838 | let Diamond { | ||
| 2839 | k: Kit { mut m, b: entry, writes, .. }, | ||
| 2840 | then, | ||
| 2841 | other, | ||
| 2842 | join, | ||
| 2843 | .. | ||
| 2844 | } = diamond(); | ||
| 2845 | let i32t = m.int(32); | ||
| 2846 | let i1t = m.int(1); | ||
| 2847 | let cfty = m.func_ty(i32t, vec![i32t, i32t]); | ||
| 2848 | let cb = m.function("dx.op.cbufferLoadLegacy.i32", cfty, Some(Attr::ReadOnly), false); | ||
| 2849 | let hfty = m.func_ty(i32t, vec![i32t, i32t, i1t, i1t]); | ||
| 2850 | let heap = m.function("dx.op.createHandleFromHeap", hfty, Some(Attr::ReadNone), false); | ||
| 2851 | let afty = m.func_ty(i32t, vec![i32t, i32t, i32t]); | ||
| 2852 | let ann = m.function("dx.op.annotateHandle", afty, Some(Attr::ReadNone), false); | ||
| 2853 | let (op_heap, op_ann, op_cb) = (m.i32(218), m.i32(216), m.i32(59)); | ||
| 2854 | let (slot, off, props) = (m.i32(0), m.i32(4), m.i32(1)); | ||
| 2855 | let (no, yes) = (m.bool(false), m.bool(true)); | ||
| 2856 | |||
| 2857 | // Both branches independently compute `cb(0) + 4` -> uniform `createHandleFromHeap` -> `annotateHandle`. | ||
| 2858 | let r1 = m.call(then, cb, vec![op_cb, slot]); | ||
| 2859 | let idx1 = m.bin(then, Bin::Add, r1, off); | ||
| 2860 | let h1 = m.call(then, heap, vec![op_heap, idx1, no, no]); | ||
| 2861 | let a1 = m.call(then, ann, vec![op_ann, h1, props]); | ||
| 2862 | m.call(then, writes, vec![a1, off]); | ||
| 2863 | |||
| 2864 | let r2 = m.call(other, cb, vec![op_cb, slot]); | ||
| 2865 | let idx2 = m.bin(other, Bin::Add, r2, off); | ||
| 2866 | let h2 = m.call(other, heap, vec![op_heap, idx2, no, no]); | ||
| 2867 | let a2 = m.call(other, ann, vec![op_ann, h2, props]); | ||
| 2868 | m.call(other, writes, vec![a2, off]); | ||
| 2869 | |||
| 2870 | // A nonuniform handle in `then` must NOT be hoisted to `entry`. | ||
| 2871 | let h_nu = m.call(then, heap, vec![op_heap, idx1, no, yes]); | ||
| 2872 | m.call(then, writes, vec![h_nu, off]); | ||
| 2873 | let _ = join; | ||
| 2874 | |||
| 2875 | m.optimise(REUSE | DEAD); | ||
| 2876 | let then_stores = super::tests::stores(&m, then); | ||
| 2877 | let other_stores = super::tests::stores(&m, other); | ||
| 2878 | assert_eq!( | ||
| 2879 | then_stores[0][0], other_stores[0][0], | ||
| 2880 | "uniform heap handles in sibling branches should hoist to entry and collapse to one" | ||
| 2881 | ); | ||
| 2882 | let V::Inst(a_id) = then_stores[0][0] else { panic!() }; | ||
| 2883 | assert!( | ||
| 2884 | m.blocks[entry].body.contains(&a_id), | ||
| 2885 | "hoisted annotateHandle should live in entry" | ||
| 2886 | ); | ||
| 2887 | let V::Inst(nu_id) = then_stores[1][0] else { panic!() }; | ||
| 2888 | assert!( | ||
| 2889 | m.blocks[then].body.contains(&nu_id), | ||
| 2890 | "nonuniform createHandleFromHeap must remain in its branch" | ||
| 2891 | ); | ||
| 2892 | m.write(); | ||
| 2893 | } | ||
| 2894 | |||
| 2895 | #[test] | ||
| 2716 | fn cross_block_reads_reuse_dominating_load_without_writes() { | 2896 | fn cross_block_reads_reuse_dominating_load_without_writes() { |
| 2717 | let Diamond { | 2897 | let Diamond { |
| 2718 | k: Kit { mut m, b: entry, reads, writes, .. }, | 2898 | k: Kit { mut m, b: entry, reads, writes, .. }, |
diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index 33a85fb23..0e7523e0f 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs | |||
| @@ -14,6 +14,7 @@ use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, Ty, V, pred}; | |||
| 14 | use super::container::SigElement; | 14 | use super::container::SigElement; |
| 15 | use super::shader::{Shader, flags}; | 15 | use super::shader::{Shader, flags}; |
| 16 | use crate::ShaderError; | 16 | use crate::ShaderError; |
| 17 | use crate::fxhash::{FxHashMap, FxHashSet}; | ||
| 17 | use crate::gfx10::{Dpp, Fields, NULL, Operand}; | 18 | use crate::gfx10::{Dpp, Fields, NULL, Operand}; |
| 18 | use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; | 19 | use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; |
| 19 | use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; | 20 | use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; |
| @@ -412,25 +413,25 @@ fn half_shift(width: u32) -> u32 { | |||
| 412 | 413 | ||
| 413 | /// [`Lower::load_uses`]'s index: per scalar load, (the descriptor's place in | 414 | /// [`Lower::load_uses`]'s index: per scalar load, (the descriptor's place in |
| 414 | /// [`Resources::descriptors`], the instruction using it, the dword the source starts at). | 415 | /// [`Resources::descriptors`], the instruction using it, the dword the source starts at). |
| 415 | type LoadUses = HashMap<Site, Vec<(usize, Site, u8)>>; | 416 | type LoadUses = FxHashMap<Site, Vec<(usize, Site, u8)>>; |
| 416 | 417 | ||
| 417 | struct Lower<'a> { | 418 | struct Lower<'a> { |
| 418 | s: Shader, | 419 | s: Shader, |
| 419 | x: &'a Parts<'a>, | 420 | x: &'a Parts<'a>, |
| 420 | bad: &'a HashMap<Value, Why>, | 421 | bad: &'a HashMap<Value, Why>, |
| 421 | lane_fail: HashMap<Value, Why>, | 422 | lane_fail: FxHashMap<Value, Why>, |
| 422 | vals: HashMap<Value, Val>, | 423 | vals: FxHashMap<Value, Val>, |
| 423 | floats: HashMap<Value, V>, | 424 | floats: FxHashMap<Value, V>, |
| 424 | /// DXIL block per IR block (unreachable: none). | 425 | /// DXIL block per IR block (unreachable: none). |
| 425 | block: Vec<Option<usize>>, | 426 | block: Vec<Option<usize>>, |
| 426 | cur: usize, | 427 | cur: usize, |
| 427 | bools: HashMap<(usize, Bool), V>, | 428 | bools: FxHashMap<(usize, Bool), V>, |
| 428 | lane_bits: HashMap<Value, V>, | 429 | lane_bits: FxHashMap<Value, V>, |
| 429 | /// IR phi location by value. | 430 | /// IR phi location by value. |
| 430 | phi_at: HashMap<Value, (usize, usize)>, | 431 | phi_at: FxHashMap<Value, (usize, usize)>, |
| 431 | /// Descriptor dwords with no host value (addresses, formats, all of a constant | 432 | /// Descriptor dwords with no host value (addresses, formats, all of a constant |
| 432 | /// buffer's): no program reads them as numbers ([`Self::dead`]). | 433 | /// buffer's): no program reads them as numbers ([`Self::dead`]). |
| 433 | stale: HashSet<Value>, | 434 | stale: FxHashSet<Value>, |
| 434 | /// See [`ordered_section`] (pixel programs). | 435 | /// See [`ordered_section`] (pixel programs). |
| 435 | ordered: HashSet<Site>, | 436 | ordered: HashSet<Site>, |
| 436 | /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its | 437 | /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its |
| @@ -443,11 +444,11 @@ struct Lower<'a> { | |||
| 443 | root_copy: Option<V>, | 444 | root_copy: Option<V>, |
| 444 | /// Whether the page [`Lower::memory`] last looked for has a copy. | 445 | /// Whether the page [`Lower::memory`] last looked for has a copy. |
| 445 | page_there: Option<V>, | 446 | page_there: Option<V>, |
| 446 | mask_phis: HashMap<Value, V>, | 447 | mask_phis: FxHashMap<Value, V>, |
| 447 | pending_masks: Vec<(V, usize, usize)>, | 448 | pending_masks: Vec<(V, usize, usize)>, |
| 448 | data_phis: Vec<(V, usize, usize)>, | 449 | data_phis: Vec<(V, usize, usize)>, |
| 449 | read_phis: HashSet<Value>, | 450 | read_phis: FxHashSet<Value>, |
| 450 | params: HashMap<Value, (usize, u32)>, | 451 | params: FxHashMap<Value, (usize, u32)>, |
| 451 | user_data: Option<V>, | 452 | user_data: Option<V>, |
| 452 | user_reads: BTreeMap<u32, UserData>, | 453 | user_reads: BTreeMap<u32, UserData>, |
| 453 | /// Table descriptors read or written sixteen bits a channel | 454 | /// Table descriptors read or written sixteen bits a channel |
| @@ -456,33 +457,33 @@ struct Lower<'a> { | |||
| 456 | /// [`Self::places_read_as_halves`], found before the code is lowered. | 457 | /// [`Self::places_read_as_halves`], found before the code is lowered. |
| 457 | halves_only: std::collections::BTreeSet<(u8, u32)>, | 458 | halves_only: std::collections::BTreeSet<(u8, u32)>, |
| 458 | samplers: Vec<[u32; 4]>, | 459 | samplers: Vec<[u32; 4]>, |
| 459 | descriptors: HashMap<(Site, bool), &'a Source>, | 460 | descriptors: FxHashMap<(Site, bool), &'a Source>, |
| 460 | scalar: HashMap<Site, Address>, | 461 | scalar: FxHashMap<Site, Address>, |
| 461 | /// The values a scalar or vector instruction or a phi reads, gathered on the first call | 462 | /// The values a scalar or vector instruction or a phi reads, gathered on the first call |
| 462 | /// of [`Self::read_as_number`] (which scanned the whole program on every call before). | 463 | /// of [`Self::read_as_number`] (which scanned the whole program on every call before). |
| 463 | numbers: OnceCell<HashSet<Value>>, | 464 | numbers: OnceCell<FxHashSet<Value>>, |
| 464 | /// The instructions reading each value, in program order and each once, gathered on the | 465 | /// The instructions reading each value, in program order and each once, gathered on the |
| 465 | /// first call of [`Self::computed_with`] (which scanned the whole program on every call, | 466 | /// first call of [`Self::computed_with`] (which scanned the whole program on every call, |
| 466 | /// and again for each move it followed, before). | 467 | /// and again for each move it followed, before). |
| 467 | readers: OnceCell<HashMap<Value, Vec<&'a Inst>>>, | 468 | readers: OnceCell<FxHashMap<Value, Vec<&'a Inst>>>, |
| 468 | /// Which resource descriptors take each scalar load as (a leaf of) their source, gathered | 469 | /// Which resource descriptors take each scalar load as (a leaf of) their source, gathered |
| 469 | /// on the first call of [`Self::load_uses`] (see there). | 470 | /// on the first call of [`Self::load_uses`] (see there). |
| 470 | load_uses: OnceCell<LoadUses>, | 471 | load_uses: OnceCell<LoadUses>, |
| 471 | /// The scalar loads a sampler's source is, gathered on the first call of | 472 | /// The scalar loads a sampler's source is, gathered on the first call of |
| 472 | /// [`Self::is_sampler_load`]. | 473 | /// [`Self::is_sampler_load`]. |
| 473 | sampler_loads: OnceCell<HashSet<Site>>, | 474 | sampler_loads: OnceCell<FxHashSet<Site>>, |
| 474 | exports: HashMap<Site, &'a Export>, | 475 | exports: FxHashMap<Site, &'a Export>, |
| 475 | interps: HashMap<Site, &'a Interp>, | 476 | interps: FxHashMap<Site, &'a Interp>, |
| 476 | handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, | 477 | handles: FxHashMap<(usize, Site, u8, bool, (u32, u32)), V>, |
| 477 | /// Element strides read from the host's table by heap slot | 478 | /// Element strides read from the host's table by heap slot |
| 478 | /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. | 479 | /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. |
| 479 | strides: HashMap<(usize, Site, u8), V>, | 480 | strides: FxHashMap<(usize, Site, u8), V>, |
| 480 | /// Handles of raw twins ([`Lower::raw_twin`]) and the bytes each twin | 481 | /// Handles of raw twins ([`Lower::raw_twin`]) and the bytes each twin |
| 481 | /// begins before its view ([`super::shader::VIEW_BIAS_MASK`]), added to | 482 | /// begins before its view ([`super::shader::VIEW_BIAS_MASK`]), added to |
| 482 | /// every offset through it ([`Lower::buffer_op`]). | 483 | /// every offset through it ([`Lower::buffer_op`]). |
| 483 | twin_bias: HashMap<V, V>, | 484 | twin_bias: FxHashMap<V, V>, |
| 484 | /// Blocks splitting the edge from one IR block to another. | 485 | /// Blocks splitting the edge from one IR block to another. |
| 485 | edges: HashMap<(usize, usize), usize>, | 486 | edges: FxHashMap<(usize, usize), usize>, |
| 486 | /// Per IR block: a `done` export is behind every lane entering it. | 487 | /// Per IR block: a `done` export is behind every lane entering it. |
| 487 | exported: Vec<bool>, | 488 | exported: Vec<bool>, |
| 488 | /// Reverse-postorder index per IR block. | 489 | /// Reverse-postorder index per IR block. |
| @@ -613,16 +614,16 @@ struct Lower<'a> { | |||
| 613 | /// The paired form: what the lowering keeps per console lane ([`Lower::swap_lanes`]). | 614 | /// The paired form: what the lowering keeps per console lane ([`Lower::swap_lanes`]). |
| 614 | #[derive(Default)] | 615 | #[derive(Default)] |
| 615 | struct LaneState { | 616 | struct LaneState { |
| 616 | vals: HashMap<Value, Val>, | 617 | vals: FxHashMap<Value, Val>, |
| 617 | floats: HashMap<Value, V>, | 618 | floats: FxHashMap<Value, V>, |
| 618 | bools: HashMap<(usize, Bool), V>, | 619 | bools: FxHashMap<(usize, Bool), V>, |
| 619 | lane_bits: HashMap<Value, V>, | 620 | lane_bits: FxHashMap<Value, V>, |
| 620 | lane_fail: HashMap<Value, Why>, | 621 | lane_fail: FxHashMap<Value, Why>, |
| 621 | mask_phis: HashMap<Value, V>, | 622 | mask_phis: FxHashMap<Value, V>, |
| 622 | pending_masks: Vec<(V, usize, usize)>, | 623 | pending_masks: Vec<(V, usize, usize)>, |
| 623 | data_phis: Vec<(V, usize, usize)>, | 624 | data_phis: Vec<(V, usize, usize)>, |
| 624 | handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, | 625 | handles: FxHashMap<(usize, Site, u8, bool, (u32, u32)), V>, |
| 625 | strides: HashMap<(usize, Site, u8), V>, | 626 | strides: FxHashMap<(usize, Site, u8), V>, |
| 626 | clane: Option<V>, | 627 | clane: Option<V>, |
| 627 | partial_active: Option<V>, | 628 | partial_active: Option<V>, |
| 628 | } | 629 | } |
| @@ -1713,13 +1714,13 @@ pub(super) fn with_paired_lanes<R>(f: impl FnOnce() -> R) -> R { | |||
| 1713 | f() | 1714 | f() |
| 1714 | } | 1715 | } |
| 1715 | 1716 | ||
| 1716 | /// As [`with_local_waves`], with every other use of a lane mask as a number | 1717 | // As `with_local_waves`, with every other use of a lane mask as a number |
| 1717 | /// and every lane read and write taken per host wave too: the program runs | 1718 | // and every lane read and write taken per host wave too: the program runs |
| 1718 | /// as it would on a console of 32-lane waves, lanes numbered 0..31 or | 1719 | // as it would on a console of 32-lane waves, lanes numbered 0..31 or |
| 1719 | /// 32..63 by half. Right for code that only relies on what HLSL's wave | 1720 | // 32..63 by half. Right for code that only relies on what HLSL's wave |
| 1720 | /// operations promise; a program that takes one wave to be its whole | 1721 | // operations promise; a program that takes one wave to be its whole |
| 1721 | /// thread group gets per-half results. The last resort for programs that | 1722 | // thread group gets per-half results. The last resort for programs that |
| 1722 | /// do not translate otherwise. | 1723 | // do not translate otherwise. |
| 1723 | thread_local! { | 1724 | thread_local! { |
| 1724 | /// [`with_lds_loose`] is running. | 1725 | /// [`with_lds_loose`] is running. |
| 1725 | static LDS_LOOSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; | 1726 | static LDS_LOOSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| @@ -2434,7 +2435,7 @@ fn div_fixup_zero_first() -> bool { | |||
| 2434 | impl<'a> Lower<'a> { | 2435 | impl<'a> Lower<'a> { |
| 2435 | fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>, counted: bool) -> Self { | 2436 | fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>, counted: bool) -> Self { |
| 2436 | let p = x.p; | 2437 | let p = x.p; |
| 2437 | let mut phi_at = HashMap::new(); | 2438 | let mut phi_at = FxHashMap::default(); |
| 2438 | for (b, block) in p.blocks.iter().enumerate() { | 2439 | for (b, block) in p.blocks.iter().enumerate() { |
| 2439 | for (i, phi) in block.phis.iter().enumerate() { | 2440 | for (i, phi) in block.phis.iter().enumerate() { |
| 2440 | phi_at.insert(phi.value, (b, i)); | 2441 | phi_at.insert(phi.value, (b, i)); |
| @@ -2572,7 +2573,7 @@ impl<'a> Lower<'a> { | |||
| 2572 | // (each host wave on its own, `with_local_waves`, gives and | 2573 | // (each host wave on its own, `with_local_waves`, gives and |
| 2573 | // takes nothing through LDS: no dwords where a program with all | 2574 | // takes nothing through LDS: no dwords where a program with all |
| 2574 | // of D3D12's 32 KiB of its own has not got them) | 2575 | // of D3D12's 32 KiB of its own has not got them) |
| 2575 | if !LOCAL_WAVES.get() || s.lds_dwords + 2 * waves + 1 <= 8192 { | 2576 | if !LOCAL_WAVES.get() || s.lds_dwords + 2 * waves < 8192 { |
| 2576 | s.lds_dwords += 2 * waves; | 2577 | s.lds_dwords += 2 * waves; |
| 2577 | } | 2578 | } |
| 2578 | if group > 32 { | 2579 | if group > 32 { |
| @@ -2829,19 +2830,19 @@ impl<'a> Lower<'a> { | |||
| 2829 | s, | 2830 | s, |
| 2830 | x, | 2831 | x, |
| 2831 | bad, | 2832 | bad, |
| 2832 | lane_fail: HashMap::new(), | 2833 | lane_fail: FxHashMap::default(), |
| 2833 | vals: HashMap::new(), | 2834 | vals: FxHashMap::default(), |
| 2834 | floats: HashMap::new(), | 2835 | floats: FxHashMap::default(), |
| 2835 | block: vec![None; p.blocks.len()], | 2836 | block: vec![None; p.blocks.len()], |
| 2836 | cur: 0, | 2837 | cur: 0, |
| 2837 | bools: HashMap::new(), | 2838 | bools: FxHashMap::default(), |
| 2838 | lane_bits: HashMap::new(), | 2839 | lane_bits: FxHashMap::default(), |
| 2839 | phi_at, | 2840 | phi_at, |
| 2840 | mask_phis: HashMap::new(), | 2841 | mask_phis: FxHashMap::default(), |
| 2841 | pending_masks: Vec::new(), | 2842 | pending_masks: Vec::new(), |
| 2842 | data_phis: Vec::new(), | 2843 | data_phis: Vec::new(), |
| 2843 | read_phis: HashSet::new(), | 2844 | read_phis: FxHashSet::default(), |
| 2844 | stale: HashSet::new(), | 2845 | stale: FxHashSet::default(), |
| 2845 | coherent: HashSet::new(), | 2846 | coherent: HashSet::new(), |
| 2846 | root_copy: None, | 2847 | root_copy: None, |
| 2847 | page_there: None, | 2848 | page_there: None, |
| @@ -2869,7 +2870,7 @@ impl<'a> Lower<'a> { | |||
| 2869 | sampler_loads: OnceCell::new(), | 2870 | sampler_loads: OnceCell::new(), |
| 2870 | exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), | 2871 | exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), |
| 2871 | interps: { | 2872 | interps: { |
| 2872 | let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); | 2873 | let mut m: FxHashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); |
| 2873 | // A first half whose result is also read as data (an f16 second half keeps | 2874 | // A first half whose result is also read as data (an f16 second half keeps |
| 2874 | // the other half of its dst, PS_DeferredTextured): evaluated as the pair it | 2875 | // the other half of its dst, PS_DeferredTextured): evaluated as the pair it |
| 2875 | // starts. Approximate for those other bits (P0 + i P10 on the console); a | 2876 | // starts. Approximate for those other bits (P0 + i P10 on the console); a |
| @@ -2887,10 +2888,10 @@ impl<'a> Lower<'a> { | |||
| 2887 | } | 2888 | } |
| 2888 | m | 2889 | m |
| 2889 | }, | 2890 | }, |
| 2890 | handles: HashMap::new(), | 2891 | handles: FxHashMap::default(), |
| 2891 | strides: HashMap::new(), | 2892 | strides: FxHashMap::default(), |
| 2892 | twin_bias: HashMap::new(), | 2893 | twin_bias: FxHashMap::default(), |
| 2893 | edges: HashMap::new(), | 2894 | edges: FxHashMap::default(), |
| 2894 | exported: vec![false; p.blocks.len()], | 2895 | exported: vec![false; p.blocks.len()], |
| 2895 | rpo: vec![usize::MAX; p.blocks.len()], | 2896 | rpo: vec![usize::MAX; p.blocks.len()], |
| 2896 | tail: vec![None; p.blocks.len()], | 2897 | tail: vec![None; p.blocks.len()], |
| @@ -4499,7 +4500,7 @@ impl<'a> Lower<'a> { | |||
| 4499 | /// first call ([`Self::numbers`]; see [`Self::computed_with`]). | 4500 | /// first call ([`Self::numbers`]; see [`Self::computed_with`]). |
| 4500 | fn read_as_number(&self, v: Value) -> bool { | 4501 | fn read_as_number(&self, v: Value) -> bool { |
| 4501 | let numbers = self.numbers.get_or_init(|| { | 4502 | let numbers = self.numbers.get_or_init(|| { |
| 4502 | let mut read = HashSet::new(); | 4503 | let mut read = FxHashSet::default(); |
| 4503 | for b in &self.x.p.blocks { | 4504 | for b in &self.x.p.blocks { |
| 4504 | read.extend(b.phis.iter().flat_map(|p| p.args.iter().copied())); | 4505 | read.extend(b.phis.iter().flat_map(|p| p.args.iter().copied())); |
| 4505 | for i in &b.insts { | 4506 | for i in &b.insts { |
| @@ -4530,7 +4531,7 @@ impl<'a> Lower<'a> { | |||
| 4530 | /// "39f0 translate 25 s to 2.6 s". Not timed in this tree yet. | 4531 | /// "39f0 translate 25 s to 2.6 s". Not timed in this tree yet. |
| 4531 | fn computed_with(&self, v: Value, depth: u32) -> bool { | 4532 | fn computed_with(&self, v: Value, depth: u32) -> bool { |
| 4532 | let readers = self.readers.get_or_init(|| { | 4533 | let readers = self.readers.get_or_init(|| { |
| 4533 | let mut readers: HashMap<Value, Vec<&'a Inst>> = HashMap::new(); | 4534 | let mut readers: FxHashMap<Value, Vec<&'a Inst>> = FxHashMap::default(); |
| 4534 | for i in self.x.p.blocks.iter().flat_map(|b| &b.insts) { | 4535 | for i in self.x.p.blocks.iter().flat_map(|b| &b.insts) { |
| 4535 | for r in &i.reads { | 4536 | for r in &i.reads { |
| 4536 | // (an instruction that reads the value twice is listed once) | 4537 | // (an instruction that reads the value twice is listed once) |
| @@ -4577,7 +4578,7 @@ impl<'a> Lower<'a> { | |||
| 4577 | /// `the_index_of_load_uses_answers_as_the_scan_did`). | 4578 | /// `the_index_of_load_uses_answers_as_the_scan_did`). |
| 4578 | fn load_uses(&self, of: Site) -> impl Iterator<Item = (Site, u8)> + '_ { | 4579 | fn load_uses(&self, of: Site) -> impl Iterator<Item = (Site, u8)> + '_ { |
| 4579 | let all = self.load_uses.get_or_init(|| { | 4580 | let all = self.load_uses.get_or_init(|| { |
| 4580 | let mut all = LoadUses::new(); | 4581 | let mut all = LoadUses::default(); |
| 4581 | for (n, d) in self.x.res.descriptors.iter().enumerate() { | 4582 | for (n, d) in self.x.res.descriptors.iter().enumerate() { |
| 4582 | if d.role != Role::Resource { | 4583 | if d.role != Role::Resource { |
| 4583 | continue; | 4584 | continue; |
| @@ -4601,7 +4602,7 @@ impl<'a> Lower<'a> { | |||
| 4601 | fn is_sampler_load(&self, load: Site) -> bool { | 4602 | fn is_sampler_load(&self, load: Site) -> bool { |
| 4602 | self.sampler_loads | 4603 | self.sampler_loads |
| 4603 | .get_or_init(|| { | 4604 | .get_or_init(|| { |
| 4604 | let mut loads = HashSet::new(); | 4605 | let mut loads = FxHashSet::default(); |
| 4605 | for d in self.x.res.descriptors.iter().filter(|d| d.role == Role::Sampler) { | 4606 | for d in self.x.res.descriptors.iter().filter(|d| d.role == Role::Sampler) { |
| 4606 | d.source.for_each_leaf(&mut |leaf| { | 4607 | d.source.for_each_leaf(&mut |leaf| { |
| 4607 | if let Source::Loaded { load, .. } = *leaf { | 4608 | if let Source::Loaded { load, .. } = *leaf { |
diff --git a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs index 9756ca4f9..3da8f6ffd 100644 --- a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs | |||
| @@ -106,7 +106,7 @@ fn accesses_through_twins_begin_where_the_view_does() { | |||
| 106 | root_indexed_views: Vec::new(), | 106 | root_indexed_views: Vec::new(), |
| 107 | half_views: Vec::new(), | 107 | half_views: Vec::new(), |
| 108 | }; | 108 | }; |
| 109 | let data: Vec<u32> = (0..32u32).map(|i| 0x5100_0000 | i * 0x0101).collect(); | 109 | let data: Vec<u32> = (0..32u32).map(|i| 0x5100_0000 | (i * 0x0101)).collect(); |
| 110 | let title: Vec<u32> = vec![0xdead_beef; 32]; | 110 | let title: Vec<u32> = vec![0xdead_beef; 32]; |
| 111 | let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); | 111 | let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); |
| 112 | let mut ran = 0; | 112 | let mut ran = 0; |
diff --git a/d3d12/crates/leonida-shader/src/emit/water_tests.rs b/d3d12/crates/leonida-shader/src/emit/water_tests.rs index 895c1a9d3..d3b4bbbe1 100644 --- a/d3d12/crates/leonida-shader/src/emit/water_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/water_tests.rs | |||
| @@ -212,7 +212,7 @@ const fn sop2(op: u32, sdst: u32, ssrc0: u32, ssrc1: u32) -> u32 { | |||
| 212 | 212 | ||
| 213 | /// VOP3 `v_mbcnt_lo_u32_b32` (`hi: false`) or `_hi_` of the two sources (operand codes). | 213 | /// VOP3 `v_mbcnt_lo_u32_b32` (`hi: false`) or `_hi_` of the two sources (operand codes). |
| 214 | const fn mbcnt(hi: bool, vdst: u32, src0: u32, src1: u32) -> [u32; 2] { | 214 | const fn mbcnt(hi: bool, vdst: u32, src0: u32, src1: u32) -> [u32; 2] { |
| 215 | [0xD765_0000 + ((hi as u32) << 16) | vdst, src0 | src1 << 9] | 215 | [(0xD765_0000 + ((hi as u32) << 16)) | vdst, src0 | src1 << 9] |
| 216 | } | 216 | } |
| 217 | 217 | ||
| 218 | const VCC: u32 = 106; | 218 | const VCC: u32 = 106; |
| @@ -466,7 +466,7 @@ fn allocation_loop_program() -> NativeProgram { | |||
| 466 | let top_at = 5; // the dwords of `init` | 466 | let top_at = 5; // the dwords of `init` |
| 467 | region.push(0); | 467 | region.push(0); |
| 468 | let branch_at = region.len() - 1; | 468 | let branch_at = region.len() - 1; |
| 469 | let offset = (top_at as i32 - (branch_at as i32 + 1)) as i16 as u16 as u32; | 469 | let offset = (top_at - (branch_at as i32 + 1)) as i16 as u16 as u32; |
| 470 | region[branch_at] = 0xBF85_0000 | offset; // s_cbranch_scc1 to the top | 470 | region[branch_at] = 0xBF85_0000 | offset; // s_cbranch_scc1 to the top |
| 471 | two_waves(&head, cmp, ®ion, &[]) | 471 | two_waves(&head, cmp, ®ion, &[]) |
| 472 | } | 472 | } |
diff --git a/d3d12/crates/leonida-shader/src/fxhash.rs b/d3d12/crates/leonida-shader/src/fxhash.rs new file mode 100644 index 000000000..907fd93e2 --- /dev/null +++ b/d3d12/crates/leonida-shader/src/fxhash.rs | |||
| @@ -0,0 +1,182 @@ | |||
| 1 | //! A fast hasher for the translator's tables. | ||
| 2 | //! | ||
| 3 | //! The standard library's maps hash with SipHash, which is made to resist keys chosen by an | ||
| 4 | //! attacker and costs a few dozen cycles a key. The keys here are numbers the translator made | ||
| 5 | //! (values, blocks, types) of a program it is reading from the user's own files, so nothing | ||
| 6 | //! gains by that; in a sampling profile of the whole archive's translation SipHash was under a | ||
| 7 | //! frame of the translator in a fifth of the samples. [`crate::structure`] has long had its own | ||
| 8 | //! multiply-rotate hasher for the same reason; this is the one the other tables share. | ||
| 9 | //! | ||
| 10 | //! The hash is a multiplication per word, then a rotation that brings the best mixed bits (the | ||
| 11 | //! high ones, since a product only carries upward) to where the table takes its bucket from. | ||
| 12 | //! A table's iteration order depends on the hasher: use these for tables that are looked up, or | ||
| 13 | //! walked for a result that is the same in any order (`Lower::read_phis` is, a closure); a table | ||
| 14 | //! whose order reaches the output is sorted or kept in a `Vec` or a `BTreeMap`. | ||
| 15 | |||
| 16 | use std::collections::{HashMap, HashSet}; | ||
| 17 | use std::hash::{BuildHasherDefault, Hasher}; | ||
| 18 | |||
| 19 | /// [`HashMap`] with [`FxHasher`]; made with `FxHashMap::default()`, not `new()`. | ||
| 20 | pub(crate) type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>; | ||
| 21 | /// [`HashSet`] with [`FxHasher`]; made with `FxHashSet::default()`, not `new()`. | ||
| 22 | pub(crate) type FxHashSet<K> = HashSet<K, BuildHasherDefault<FxHasher>>; | ||
| 23 | |||
| 24 | /// An odd constant with about as many ones as zeros, scattered (the golden ratio's bits would do | ||
| 25 | /// as well). | ||
| 26 | const K: u64 = 0xf135_7aea_2e62_a9c5; | ||
| 27 | |||
| 28 | #[derive(Default, Clone, Copy)] | ||
| 29 | pub(crate) struct FxHasher(u64); | ||
| 30 | |||
| 31 | impl FxHasher { | ||
| 32 | #[inline] | ||
| 33 | fn add(&mut self, word: u64) { | ||
| 34 | self.0 = self.0.wrapping_add(word).wrapping_mul(K); | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | impl Hasher for FxHasher { | ||
| 39 | #[inline] | ||
| 40 | fn finish(&self) -> u64 { | ||
| 41 | self.0.rotate_left(26) | ||
| 42 | } | ||
| 43 | |||
| 44 | #[inline] | ||
| 45 | fn write(&mut self, bytes: &[u8]) { | ||
| 46 | let mut chunks = bytes.chunks_exact(8); | ||
| 47 | for c in &mut chunks { | ||
| 48 | self.add(u64::from_le_bytes(c.try_into().unwrap())); | ||
| 49 | } | ||
| 50 | let rest = chunks.remainder(); | ||
| 51 | if !rest.is_empty() { | ||
| 52 | // The tail's length goes in with it, so that "a" and "a\0" differ. | ||
| 53 | let mut word = [0u8; 8]; | ||
| 54 | word[..rest.len()].copy_from_slice(rest); | ||
| 55 | self.add(u64::from_le_bytes(word) ^ (rest.len() as u64) << 56); | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | #[inline] | ||
| 60 | fn write_u8(&mut self, n: u8) { | ||
| 61 | self.add(u64::from(n)); | ||
| 62 | } | ||
| 63 | |||
| 64 | #[inline] | ||
| 65 | fn write_u16(&mut self, n: u16) { | ||
| 66 | self.add(u64::from(n)); | ||
| 67 | } | ||
| 68 | |||
| 69 | #[inline] | ||
| 70 | fn write_u32(&mut self, n: u32) { | ||
| 71 | self.add(u64::from(n)); | ||
| 72 | } | ||
| 73 | |||
| 74 | #[inline] | ||
| 75 | fn write_u64(&mut self, n: u64) { | ||
| 76 | self.add(n); | ||
| 77 | } | ||
| 78 | |||
| 79 | #[inline] | ||
| 80 | fn write_usize(&mut self, n: usize) { | ||
| 81 | self.add(n as u64); | ||
| 82 | } | ||
| 83 | } | ||
| 84 | |||
| 85 | #[cfg(test)] | ||
| 86 | mod tests { | ||
| 87 | use super::*; | ||
| 88 | use std::hash::{BuildHasher, Hash}; | ||
| 89 | |||
| 90 | fn hash_of<T: Hash + ?Sized>(x: &T) -> u64 { | ||
| 91 | BuildHasherDefault::<FxHasher>::default().hash_one(x) | ||
| 92 | } | ||
| 93 | |||
| 94 | #[test] | ||
| 95 | fn the_same_key_hashes_the_same_and_near_keys_differ() { | ||
| 96 | assert_eq!(hash_of(&(1u32, 2u32)), hash_of(&(1u32, 2u32))); | ||
| 97 | assert_ne!(hash_of(&(1u32, 2u32)), hash_of(&(2u32, 1u32))); | ||
| 98 | assert_ne!(hash_of(&0u32), hash_of(&1u32)); | ||
| 99 | // A string is its bytes and a terminator: neither a prefix of another nor one with | ||
| 100 | // zeros after it hashes alike. | ||
| 101 | let names = ["", "a", "a\0", "a\0\0", "ab", "abcdefgh", "abcdefgh\0", "abcdefghi", "abcdefgh12345678"]; | ||
| 102 | for (i, a) in names.iter().enumerate() { | ||
| 103 | for b in &names[i + 1..] { | ||
| 104 | assert_ne!(hash_of(*a), hash_of(*b), "{a:?} and {b:?}"); | ||
| 105 | } | ||
| 106 | } | ||
| 107 | // Slices of numbers of unequal length (their length is hashed first). | ||
| 108 | assert_ne!(hash_of(&[1u32, 2][..]), hash_of(&[1u32, 2, 0][..])); | ||
| 109 | assert_ne!(hash_of(&Vec::<u32>::new()), hash_of(&vec![0u32])); | ||
| 110 | } | ||
| 111 | |||
| 112 | /// The tables take a bucket from the low bits and a tag from the top seven: keys that are | ||
| 113 | /// small numbers, a number and a multiple of a power of two (the cases a product's weak low | ||
| 114 | /// bits would clump), pairs and triples, spread over both as a hash of random words does: | ||
| 115 | /// no bucket of 4,096 holds more than 3 times the mean, and every tag is used about as | ||
| 116 | /// often as the others. | ||
| 117 | #[test] | ||
| 118 | fn small_number_keys_spread_over_buckets_and_tags() { | ||
| 119 | fn check(name: &str, hashes: &[u64]) { | ||
| 120 | let n = hashes.len(); | ||
| 121 | let mut buckets = vec![0u32; 4096]; | ||
| 122 | let mut tags = vec![0u32; 128]; | ||
| 123 | for &h in hashes { | ||
| 124 | buckets[(h & 4095) as usize] += 1; | ||
| 125 | tags[(h >> 57) as usize] += 1; | ||
| 126 | } | ||
| 127 | let mean = n as f64 / 4096.0; | ||
| 128 | let most = f64::from(*buckets.iter().max().unwrap()); | ||
| 129 | assert!(most <= 3.0 * mean, "{name}: a bucket of {most} against a mean of {mean}"); | ||
| 130 | let (low, high) = (*tags.iter().min().unwrap(), *tags.iter().max().unwrap()); | ||
| 131 | let tag_mean = n as f64 / 128.0; | ||
| 132 | assert!( | ||
| 133 | f64::from(low) >= tag_mean / 2.0 && f64::from(high) <= tag_mean * 2.0, | ||
| 134 | "{name}: tags from {low} to {high} against a mean of {tag_mean}" | ||
| 135 | ); | ||
| 136 | } | ||
| 137 | let n = 1u32 << 17; | ||
| 138 | check("0..n", &(0..n).map(|i| hash_of(&i)).collect::<Vec<_>>()); | ||
| 139 | check("i * 4096", &(0..n).map(|i| hash_of(&(i << 12))).collect::<Vec<_>>()); | ||
| 140 | check("i * 65536 as u64", &(0..n).map(|i| hash_of(&(u64::from(i) << 16))).collect::<Vec<_>>()); | ||
| 141 | check( | ||
| 142 | "(i % 512, i / 512)", | ||
| 143 | &(0..n).map(|i| hash_of(&(i % 512, i / 512))).collect::<Vec<_>>(), | ||
| 144 | ); | ||
| 145 | check( | ||
| 146 | "(tag, i)", | ||
| 147 | &(0..n).map(|i| hash_of(&(u8::try_from(i % 5).unwrap(), i / 5))).collect::<Vec<_>>(), | ||
| 148 | ); | ||
| 149 | check( | ||
| 150 | "(u8, i, i + 1)", | ||
| 151 | &(0..n).map(|i| hash_of(&(1u8, i, i + 1))).collect::<Vec<_>>(), | ||
| 152 | ); | ||
| 153 | } | ||
| 154 | |||
| 155 | /// The maps behave as std's do (the hasher only chooses where an entry goes): a few | ||
| 156 | /// thousand random inserts, lookups and removals against a `BTreeMap`. | ||
| 157 | #[test] | ||
| 158 | fn a_map_with_the_hasher_agrees_with_an_ordered_one() { | ||
| 159 | use std::collections::BTreeMap; | ||
| 160 | let mut fx = FxHashMap::<(u32, u8), u32>::default(); | ||
| 161 | let mut reference = BTreeMap::new(); | ||
| 162 | let mut seed = 0x2545_f491_4f6c_dd1du64; | ||
| 163 | let mut next = move || { | ||
| 164 | seed ^= seed << 13; | ||
| 165 | seed ^= seed >> 7; | ||
| 166 | seed ^= seed << 17; | ||
| 167 | seed | ||
| 168 | }; | ||
| 169 | for step in 0..20_000u32 { | ||
| 170 | let r = next(); | ||
| 171 | let key = ((r % 1500) as u32, ((r >> 20) % 3) as u8); | ||
| 172 | match (r >> 40) % 3 { | ||
| 173 | 0 => assert_eq!(fx.insert(key, step), reference.insert(key, step)), | ||
| 174 | 1 => assert_eq!(fx.remove(&key), reference.remove(&key)), | ||
| 175 | _ => assert_eq!(fx.get(&key), reference.get(&key)), | ||
| 176 | } | ||
| 177 | } | ||
| 178 | assert_eq!(fx.len(), reference.len()); | ||
| 179 | let mut set = FxHashSet::<String>::default(); | ||
| 180 | assert!(set.insert("x".to_owned()) && !set.insert("x".to_owned()) && set.contains("x")); | ||
| 181 | } | ||
| 182 | } | ||
diff --git a/d3d12/crates/leonida-shader/src/io.rs b/d3d12/crates/leonida-shader/src/io.rs index ba53eb059..5e710f7bc 100644 --- a/d3d12/crates/leonida-shader/src/io.rs +++ b/d3d12/crates/leonida-shader/src/io.rs | |||
| @@ -32,6 +32,7 @@ | |||
| 32 | //! (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). | 32 | //! (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | primitives << 12). |
| 33 | 33 | ||
| 34 | use crate::ShaderError; | 34 | use crate::ShaderError; |
| 35 | use crate::fxhash::{FxHashMap, FxHashSet}; | ||
| 35 | use crate::gfx10::{Fields, Operand}; | 36 | use crate::gfx10::{Fields, Operand}; |
| 36 | use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; | 37 | use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; |
| 37 | use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; | 38 | use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; |
| @@ -340,7 +341,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { | |||
| 340 | }, | 341 | }, |
| 341 | ..Io::default() | 342 | ..Io::default() |
| 342 | }; | 343 | }; |
| 343 | let defs: std::collections::HashMap<Value, Site> = p | 344 | let defs: FxHashMap<Value, Site> = p |
| 344 | .blocks | 345 | .blocks |
| 345 | .iter() | 346 | .iter() |
| 346 | .enumerate() | 347 | .enumerate() |
| @@ -352,7 +353,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { | |||
| 352 | .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) | 353 | .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) |
| 353 | }) | 354 | }) |
| 354 | .collect(); | 355 | .collect(); |
| 355 | let phis: std::collections::HashMap<Value, (usize, usize)> = p | 356 | let phis: FxHashMap<Value, (usize, usize)> = p |
| 356 | .blocks | 357 | .blocks |
| 357 | .iter() | 358 | .iter() |
| 358 | .enumerate() | 359 | .enumerate() |
| @@ -470,12 +471,12 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { | |||
| 470 | // half need not be evaluated. A first half also read as data (or used | 471 | // half need not be evaluated. A first half also read as data (or used |
| 471 | // without a second half) must keep P0 + i * P10. Follow phi uses too, | 472 | // without a second half) must keep P0 + i * P10. Follow phi uses too, |
| 472 | // without forcing ordinary pairs to read per-vertex attributes. | 473 | // without forcing ordinary pairs to read per-vertex attributes. |
| 473 | let folded: std::collections::HashSet<_> = io | 474 | let folded: FxHashSet<_> = io |
| 474 | .interps | 475 | .interps |
| 475 | .iter() | 476 | .iter() |
| 476 | .filter_map(|(s, i)| matches!(i, Interp::Interpolated { .. }).then_some(*s)) | 477 | .filter_map(|(s, i)| matches!(i, Interp::Interpolated { .. }).then_some(*s)) |
| 477 | .collect(); | 478 | .collect(); |
| 478 | let mut used: std::collections::HashSet<_> = p | 479 | let mut used: FxHashSet<_> = p |
| 479 | .blocks | 480 | .blocks |
| 480 | .iter() | 481 | .iter() |
| 481 | .enumerate() | 482 | .enumerate() |
| @@ -568,8 +569,8 @@ fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) { | |||
| 568 | /// Finds the first halves of interpolations. | 569 | /// Finds the first halves of interpolations. |
| 569 | struct Halves<'a> { | 570 | struct Halves<'a> { |
| 570 | p: &'a Program, | 571 | p: &'a Program, |
| 571 | defs: &'a std::collections::HashMap<Value, Site>, | 572 | defs: &'a FxHashMap<Value, Site>, |
| 572 | phis: &'a std::collections::HashMap<Value, (usize, usize)>, | 573 | phis: &'a FxHashMap<Value, (usize, usize)>, |
| 573 | } | 574 | } |
| 574 | 575 | ||
| 575 | impl Halves<'_> { | 576 | impl Halves<'_> { |
diff --git a/d3d12/crates/leonida-shader/src/ir.rs b/d3d12/crates/leonida-shader/src/ir.rs index 75c855505..f32680b71 100644 --- a/d3d12/crates/leonida-shader/src/ir.rs +++ b/d3d12/crates/leonida-shader/src/ir.rs | |||
| @@ -152,7 +152,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr | |||
| 152 | } | 152 | } |
| 153 | leaders.sort_unstable(); | 153 | leaders.sort_unstable(); |
| 154 | leaders.dedup(); | 154 | leaders.dedup(); |
| 155 | let parked = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs); | 155 | let (parked, mut cache) = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs); |
| 156 | let block_at = |offset: usize| { | 156 | let block_at = |offset: usize| { |
| 157 | leaders | 157 | leaders |
| 158 | .binary_search(&offset) | 158 | .binary_search(&offset) |
| @@ -174,11 +174,18 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr | |||
| 174 | .collect(); | 174 | .collect(); |
| 175 | for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { | 175 | for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { |
| 176 | let b = leaders.partition_point(|&l| l <= machine.offset) - 1; | 176 | let b = leaders.partition_point(|&l| l <= machine.offset) - 1; |
| 177 | let name = machine.name().ok_or(ShaderError::Unsupported { | 177 | let cached = cache.as_mut().and_then(|c| c.get_mut(n)).and_then(|slot| slot.take()); |
| 178 | offset: machine.offset, | 178 | let (name, mut fields, mut cached_effects) = match cached { |
| 179 | what: "unknown opcode", | 179 | Some(d) => (d.name, d.fields, d.effects), |
| 180 | })?; | 180 | None => ( |
| 181 | let mut fields = machine.fields(wave64); | 181 | machine.name().ok_or(ShaderError::Unsupported { |
| 182 | offset: machine.offset, | ||
| 183 | what: "unknown opcode", | ||
| 184 | })?, | ||
| 185 | machine.fields(wave64), | ||
| 186 | None, | ||
| 187 | ), | ||
| 188 | }; | ||
| 182 | // A move to or from a scalar parked in a VGPR lane (`unspill`): its register | 189 | // A move to or from a scalar parked in a VGPR lane (`unspill`): its register |
| 183 | // codes may be ones the machine word cannot hold. | 190 | // codes may be ones the machine word cannot hold. |
| 184 | if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) | 191 | if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) |
| @@ -186,6 +193,8 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr | |||
| 186 | && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() | 193 | && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() |
| 187 | { | 194 | { |
| 188 | (*to, *from) = (parked[k].1, parked[k].2); | 195 | (*to, *from) = (parked[k].1, parked[k].2); |
| 196 | // The register effects were worked out before this substitution. | ||
| 197 | cached_effects = None; | ||
| 189 | } | 198 | } |
| 190 | let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); | 199 | let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); |
| 191 | // A conditional SOPP branch to fallthrough has no register effects | 200 | // A conditional SOPP branch to fallthrough has no register effects |
| @@ -210,7 +219,11 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr | |||
| 210 | Flow::Stop => Exit::End, | 219 | Flow::Stop => Exit::End, |
| 211 | }; | 220 | }; |
| 212 | } | 221 | } |
| 213 | if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { | 222 | let effects = match cached_effects { |
| 223 | Some(e) => Some(e), | ||
| 224 | None => effects(&machine, &fields, name, lanes, vgprs)?, | ||
| 225 | }; | ||
| 226 | if let Some((mut reads, writes)) = effects { | ||
| 214 | // Lanes disabled in EXEC keep the old value. | 227 | // Lanes disabled in EXEC keep the old value. |
| 215 | for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { | 228 | for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { |
| 216 | if !reads.contains(w) { | 229 | if !reads.contains(w) { |
| @@ -266,6 +279,15 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr | |||
| 266 | /// a scalar later, say. Where that keeps a pair from being one, each life of a | 279 | /// a scalar later, say. Where that keeps a pair from being one, each life of a |
| 267 | /// lane (the saves that reach a restore in common, and those restores) is a | 280 | /// lane (the saves that reach a restore in common, and those restores) is a |
| 268 | /// store of its own. | 281 | /// store of its own. |
| 282 | /// Fields and register effects decoded once for an instruction. `unspill` | ||
| 283 | /// has to walk every instruction to find parked scalars, and `build` walks | ||
| 284 | /// them again; without this, a program with a lane save decodes each twice. | ||
| 285 | struct Decoded { | ||
| 286 | name: &'static str, | ||
| 287 | fields: Fields, | ||
| 288 | effects: Option<(Vec<Reg>, Vec<Reg>)>, | ||
| 289 | } | ||
| 290 | |||
| 269 | fn unspill( | 291 | fn unspill( |
| 270 | list: &mut [gfx10::Instruction], | 292 | list: &mut [gfx10::Instruction], |
| 271 | flows: &[Flow], | 293 | flows: &[Flow], |
| @@ -273,7 +295,7 @@ fn unspill( | |||
| 273 | wave64: bool, | 295 | wave64: bool, |
| 274 | lanes: u8, | 296 | lanes: u8, |
| 275 | vgprs: u16, | 297 | vgprs: u16, |
| 276 | ) -> Vec<(usize, u8, u8)> { | 298 | ) -> (Vec<(usize, u8, u8)>, Option<Vec<Option<Decoded>>>) { |
| 277 | // Nothing is parked in a lane unless the code has a save or a restore of one, and the scan | 299 | // Nothing is parked in a lane unless the code has a save or a restore of one, and the scan |
| 278 | // takes the fields and the effects of every instruction to find that out: most programs | 300 | // takes the fields and the effects of every instruction to find that out: most programs |
| 279 | // have none. | 301 | // have none. |
| @@ -281,7 +303,7 @@ fn unspill( | |||
| 281 | .iter() | 303 | .iter() |
| 282 | .any(|i| matches!(i.name(), Some("v_writelane_b32" | "v_readlane_b32"))) | 304 | .any(|i| matches!(i.name(), Some("v_writelane_b32" | "v_readlane_b32"))) |
| 283 | { | 305 | { |
| 284 | return Vec::new(); | 306 | return (Vec::new(), None); |
| 285 | } | 307 | } |
| 286 | unspill_scan(list, flows, leaders, wave64, lanes, vgprs) | 308 | unspill_scan(list, flows, leaders, wave64, lanes, vgprs) |
| 287 | } | 309 | } |
| @@ -295,7 +317,7 @@ fn unspill_scan( | |||
| 295 | wave64: bool, | 317 | wave64: bool, |
| 296 | lanes: u8, | 318 | lanes: u8, |
| 297 | vgprs: u16, | 319 | vgprs: u16, |
| 298 | ) -> Vec<(usize, u8, u8)> { | 320 | ) -> (Vec<(usize, u8, u8)>, Option<Vec<Option<Decoded>>>) { |
| 299 | /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). | 321 | /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). |
| 300 | fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> { | 322 | fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> { |
| 301 | let Fields::Valu(v) = fields else { return None }; | 323 | let Fields::Valu(v) = fields else { return None }; |
| @@ -324,22 +346,23 @@ fn unspill_scan( | |||
| 324 | let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len()); | 346 | let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len()); |
| 325 | let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len()); | 347 | let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len()); |
| 326 | let mut read: Vec<Vec<u8>> = Vec::with_capacity(list.len()); | 348 | let mut read: Vec<Vec<u8>> = Vec::with_capacity(list.len()); |
| 349 | let mut cache: Vec<Option<Decoded>> = Vec::with_capacity(list.len()); | ||
| 327 | for inst in list.iter() { | 350 | for inst in list.iter() { |
| 328 | let Some(name) = inst.name() else { return Vec::new() }; | 351 | let Some(name) = inst.name() else { return (Vec::new(), None) }; |
| 329 | let fields = inst.fields(wave64); | 352 | let fields = inst.fields(wave64); |
| 330 | let park = parked(inst, &fields); | 353 | let park = parked(inst, &fields); |
| 331 | let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { | 354 | let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { |
| 332 | return Vec::new(); | 355 | return (Vec::new(), None); |
| 333 | }; | 356 | }; |
| 334 | let mut codes = Vec::new(); | 357 | let mut codes = Vec::new(); |
| 335 | let mut from = Vec::new(); | 358 | let mut from = Vec::new(); |
| 336 | if let Some((reads, writes)) = effects { | 359 | if let Some((reads, writes)) = &effects { |
| 337 | for ® in &writes { | 360 | for ® in writes { |
| 338 | if let Reg::S(c) = reg { | 361 | if let Reg::S(c) = reg { |
| 339 | codes.push(c); | 362 | codes.push(c); |
| 340 | } | 363 | } |
| 341 | } | 364 | } |
| 342 | for ® in &reads { | 365 | for ® in reads { |
| 343 | if let Reg::S(c) = reg { | 366 | if let Reg::S(c) = reg { |
| 344 | from.push(c); | 367 | from.push(c); |
| 345 | } | 368 | } |
| @@ -350,7 +373,7 @@ fn unspill_scan( | |||
| 350 | // ordinary ones. (Relative writes still do.) | 373 | // ordinary ones. (Relative writes still do.) |
| 351 | let relative = name == "v_movrels_b32"; | 374 | let relative = name == "v_movrels_b32"; |
| 352 | let n_reads = reads.len(); | 375 | let n_reads = reads.len(); |
| 353 | for (k, reg) in reads.into_iter().chain(writes).enumerate() { | 376 | for (k, ®) in reads.iter().chain(writes.iter()).enumerate() { |
| 354 | if relative && k < n_reads && matches!(reg, Reg::V(_)) { | 377 | if relative && k < n_reads && matches!(reg, Reg::V(_)) { |
| 355 | continue; | 378 | continue; |
| 356 | } | 379 | } |
| @@ -365,6 +388,7 @@ fn unspill_scan( | |||
| 365 | parks.push(park); | 388 | parks.push(park); |
| 366 | written.push(codes); | 389 | written.push(codes); |
| 367 | read.push(from); | 390 | read.push(from); |
| 391 | cache.push(Some(Decoded { name, fields, effects })); | ||
| 368 | } | 392 | } |
| 369 | let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); | 393 | let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); |
| 370 | for reg in 0..256 { | 394 | for reg in 0..256 { |
| @@ -391,7 +415,7 @@ fn unspill_scan( | |||
| 391 | } | 415 | } |
| 392 | } | 416 | } |
| 393 | if parks.iter().all(Option::is_none) { | 417 | if parks.iter().all(Option::is_none) { |
| 394 | return Vec::new(); | 418 | return (Vec::new(), None); |
| 395 | } | 419 | } |
| 396 | // Lane pairs (register, lower lane) that always move together: each | 420 | // Lane pairs (register, lower lane) that always move together: each |
| 397 | // save of the lower lane is followed, in the same block and before its | 421 | // save of the lower lane is followed, in the same block and before its |
| @@ -583,7 +607,7 @@ fn unspill_scan( | |||
| 583 | } | 607 | } |
| 584 | Some((of, pairs, codes.into_iter().flatten().collect())) | 608 | Some((of, pairs, codes.into_iter().flatten().collect())) |
| 585 | }; | 609 | }; |
| 586 | let Some(mut chosen) = plan(false) else { return Vec::new() }; | 610 | let Some(mut chosen) = plan(false) else { return (Vec::new(), None) }; |
| 587 | let lonely = |(of, pairs, _): &(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)| { | 611 | let lonely = |(of, pairs, _): &(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)| { |
| 588 | (0..list.len()).any(|i| { | 612 | (0..list.len()).any(|i| { |
| 589 | parks[i].is_some_and(|p| p.0) | 613 | parks[i].is_some_and(|p| p.0) |
| @@ -599,8 +623,9 @@ fn unspill_scan( | |||
| 599 | chosen = split; | 623 | chosen = split; |
| 600 | } | 624 | } |
| 601 | let (store, pairs, codes) = chosen; | 625 | let (store, pairs, codes) = chosen; |
| 602 | let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { | 626 | let put = |list: &mut [gfx10::Instruction], cache: &mut [Option<Decoded>], i: usize, encoding, opcode: u16, word: u32| { |
| 603 | list[i] = gfx10::Instruction::new(list[i].offset, encoding, opcode, vec![word]); | 627 | list[i] = gfx10::Instruction::new(list[i].offset, encoding, opcode, vec![word]); |
| 628 | cache[i] = None; | ||
| 604 | }; | 629 | }; |
| 605 | // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code | 630 | // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code |
| 606 | // from `PARKED` up does not fit the word: s0 stands in for it there. | 631 | // from `PARKED` up does not fit the word: s0 stands in for it there. |
| @@ -614,7 +639,7 @@ fn unspill_scan( | |||
| 614 | }; | 639 | }; |
| 615 | let slot = codes[store[i]]; | 640 | let slot = codes[store[i]]; |
| 616 | if pairs.iter().any(|p| p.0 == store[i]) { | 641 | if pairs.iter().any(|p| p.0 == store[i]) { |
| 617 | let Some(j) = partner(i) else { return Vec::new() }; | 642 | let Some(j) = partner(i) else { return (Vec::new(), None) }; |
| 618 | // A save moves the pair where its second half is saved; a | 643 | // A save moves the pair where its second half is saved; a |
| 619 | // restore where its first half is restored. | 644 | // restore where its first half is restored. |
| 620 | let (at, gone) = if save { (j, i) } else { (i, j) }; | 645 | let (at, gone) = if save { (j, i) } else { (i, j) }; |
| @@ -632,14 +657,14 @@ fn unspill_scan( | |||
| 632 | for (i, edit) in edits { | 657 | for (i, edit) in edits { |
| 633 | match edit { | 658 | match edit { |
| 634 | Some((wide, dst, src)) => { | 659 | Some((wide, dst, src)) => { |
| 635 | put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); | 660 | put(list, &mut cache, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); |
| 636 | moves.push((i, dst, src)); | 661 | moves.push((i, dst, src)); |
| 637 | } | 662 | } |
| 638 | None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), | 663 | None => put(list, &mut cache, i, gfx10::Encoding::Sopp, 0, NOP), |
| 639 | } | 664 | } |
| 640 | } | 665 | } |
| 641 | moves.sort_unstable(); | 666 | moves.sort_unstable(); |
| 642 | moves | 667 | (moves, Some(cache)) |
| 643 | } | 668 | } |
| 644 | 669 | ||
| 645 | /// Rename register reads and writes after changing edges in a reducible graph. | 670 | /// Rename register reads and writes after changing edges in a reducible graph. |
| @@ -1904,11 +1929,11 @@ mod tests { | |||
| 1904 | let mut scanned = quick.clone(); | 1929 | let mut scanned = quick.clone(); |
| 1905 | let by_unspill = unspill(&mut quick, &flows, &leaders, wave64, lanes, 256); | 1930 | let by_unspill = unspill(&mut quick, &flows, &leaders, wave64, lanes, 256); |
| 1906 | let by_scan = unspill_scan(&mut scanned, &flows, &leaders, wave64, lanes, 256); | 1931 | let by_scan = unspill_scan(&mut scanned, &flows, &leaders, wave64, lanes, 256); |
| 1907 | assert_eq!(by_unspill, by_scan, "{name}, wave64 {wave64}"); | 1932 | assert_eq!(by_unspill.0, by_scan.0, "{name}, wave64 {wave64}"); |
| 1908 | assert_eq!(quick, scanned, "{name}, wave64 {wave64}"); | 1933 | assert_eq!(quick, scanned, "{name}, wave64 {wave64}"); |
| 1909 | // The cases that park something do have the scan make moves. | 1934 | // The cases that park something do have the scan make moves. |
| 1910 | assert_eq!(!by_scan.is_empty(), parks, "{name}, wave64 {wave64}"); | 1935 | assert_eq!(!by_scan.0.is_empty(), parks, "{name}, wave64 {wave64}"); |
| 1911 | found += by_scan.len(); | 1936 | found += by_scan.0.len(); |
| 1912 | } | 1937 | } |
| 1913 | } | 1938 | } |
| 1914 | assert!(found >= 8, "{found}"); | 1939 | assert!(found >= 8, "{found}"); |
diff --git a/d3d12/crates/leonida-shader/src/lib.rs b/d3d12/crates/leonida-shader/src/lib.rs index 6ec69c586..e1adf5074 100644 --- a/d3d12/crates/leonida-shader/src/lib.rs +++ b/d3d12/crates/leonida-shader/src/lib.rs | |||
| @@ -11,6 +11,7 @@ pub mod bvh; | |||
| 11 | pub mod dxbc; | 11 | pub mod dxbc; |
| 12 | pub mod dxil; | 12 | pub mod dxil; |
| 13 | pub mod emit; | 13 | pub mod emit; |
| 14 | mod fxhash; | ||
| 14 | pub mod gfx10; | 15 | pub mod gfx10; |
| 15 | pub mod io; | 16 | pub mod io; |
| 16 | pub mod ir; | 17 | pub mod ir; |
diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index 86e9699df..25dd7882b 100644 --- a/d3d12/docs/switches.md +++ b/d3d12/docs/switches.md | |||
| @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is ** | |||
| 6 | settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, | 6 | settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, |
| 7 | and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | 7 | and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. |
| 8 | 8 | ||
| 9 | 663 names; 623 have a sentence of a comment below, the others no comment or only a bare list. | 9 | 664 names; 624 have a sentence of a comment below, the others no comment or only a bare list. |
| 10 | 10 | ||
| 11 | - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a | 11 | - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a |
| 12 | switch read some other way; its default is not given here. | 12 | switch read some other way; its default is not given here. |
| @@ -356,6 +356,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | |||
| 356 | | `LEONIDA_LIGHT_REFRESH` | see the code | | | | `leonida-gpu/host.rs` +1 | Whether the refreshes of host copies go the light way (`LEONIDA_LIGHT_REFRESH=0`: as before): view memory nothing wrote since it was last asked about is known by its bits ([`PUBLISHED`]), a copy nothing of whose range ch... | | 356 | | `LEONIDA_LIGHT_REFRESH` | see the code | | | | `leonida-gpu/host.rs` +1 | Whether the refreshes of host copies go the light way (`LEONIDA_LIGHT_REFRESH=0`: as before): view memory nothing wrote since it was last asked about is known by its bits ([`PUBLISHED`]), a copy nothing of whose range ch... | |
| 357 | | `LEONIDA_LIST_ALIAS_EXACT` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` +1 | On by default; `LEONIDA_LIST_ALIAS_EXACT=0`: as before. | | 357 | | `LEONIDA_LIST_ALIAS_EXACT` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` +1 | On by default; `LEONIDA_LIST_ALIAS_EXACT=0`: as before. | |
| 358 | | `LEONIDA_LIST_FRONTS` | see the code | yes | | yes | `leonida-gpu/host.rs` | Whether a list's steps are gone through for what they refresh once, when the list is closed, by the thread that closes it (`LEONIDA_LIST_FRONTS=0`: by the thread that prepares the submission, for every submission, as bef... | | 358 | | `LEONIDA_LIST_FRONTS` | see the code | yes | | yes | `leonida-gpu/host.rs` | Whether a list's steps are gone through for what they refresh once, when the list is closed, by the thread that closes it (`LEONIDA_LIST_FRONTS=0`: by the thread that prepares the submission, for every submission, as bef... | |
| 359 | | `LEONIDA_LIST_LOCK_FAST` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor.rs` +1 | `LEONIDA_LIST_LOCK_FAST=0` takes the locks as before; by turns under A/B (the table is published either way, so a reader finds all of it whenever this comes on). | | ||
| 359 | | `LEONIDA_LIST_POOL` | see the code | | | | `leonida-gpu/list.rs` | Whether host lists that have run are used again (on by default; `LEONIDA_LIST_POOL=0`: each is made new and thrown away, as before). | | 360 | | `LEONIDA_LIST_POOL` | see the code | | | | `leonida-gpu/list.rs` | Whether host lists that have run are used again (on by default; `LEONIDA_LIST_POOL=0`: each is made new and thrown away, as before). | |
| 360 | | `LEONIDA_LIST_SLOTS` | see the code | | | | `leonida-gpu/draw.rs` | For the frame listing, after a draw whose shader `LEONIDA_LIST_SLOTS` names: the heap slots it will pick textures from by index, and what the title and the host hold there (one `~slot` line each), with the words they wer... | | 361 | | `LEONIDA_LIST_SLOTS` | see the code | | | | `leonida-gpu/draw.rs` | For the frame listing, after a draw whose shader `LEONIDA_LIST_SLOTS` names: the heap slots it will pick textures from by index, and what the title and the host hold there (one `~slot` line each), with the words they wer... | |
| 361 | | `LEONIDA_LIST_VIEWS` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | Whether a list makes a view its tables hold once (`LEONIDA_LIST_VIEWS=0`: for every table). | | 362 | | `LEONIDA_LIST_VIEWS` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | Whether a list makes a view its tables hold once (`LEONIDA_LIST_VIEWS=0`: for every table). | |
| @@ -579,7 +580,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | |||
| 579 | | `LEONIDA_VIEW_COPY` | see the code | | | | `leonida-gpu/descriptor/host.rs` | `LEONIDA_VIEW_COPY=0`: made in place, as before. | | 580 | | `LEONIDA_VIEW_COPY` | see the code | | | | `leonida-gpu/descriptor/host.rs` | `LEONIDA_VIEW_COPY=0`: made in place, as before. | |
| 580 | | `LEONIDA_VIEW_EXTENT` | see the code | | | | `leonida-gpu/descriptor/host.rs` +1 | `LEONIDA_VIEW_EXTENT=0` looks the copy up by the view's range alone, as before. | | 581 | | `LEONIDA_VIEW_EXTENT` | see the code | | | | `leonida-gpu/descriptor/host.rs` +1 | `LEONIDA_VIEW_EXTENT=0` looks the copy up by the view's range alone, as before. | |
| 581 | | `LEONIDA_VIEW_GUARD` | see the code | | | | `leonida-gpu/watch.rs` | `LEONIDA_VIEW_GUARD=0`: each address for itself, as before. | | 582 | | `LEONIDA_VIEW_GUARD` | see the code | | | | `leonida-gpu/watch.rs` | `LEONIDA_VIEW_GUARD=0`: each address for itself, as before. | |
| 582 | | `LEONIDA_VIEW_INLINE` | see the code | | | | `leonida-gpu/descriptor.rs` | `LEONIDA_VIEW_INLINE=0`: every view is an entry, as before. | | 583 | | `LEONIDA_VIEW_INLINE` | see the code | | | | `leonida-gpu/descriptor.rs` +1 | `LEONIDA_VIEW_INLINE=0`: every view is an entry, as before. | |
| 583 | | `LEONIDA_VIEW_THREADS` | see the code | | | | `leonida-gpu/land.rs` | Calls `f` with every number below `count`, on this thread and on threads kept for making descriptors (`LEONIDA_VIEW_THREADS`, 4 with this one, 6 for records; 1: on this one alone). | | 584 | | `LEONIDA_VIEW_THREADS` | see the code | | | | `leonida-gpu/land.rs` | Calls `f` with every number below `count`, on this thread and on threads kept for making descriptors (`LEONIDA_VIEW_THREADS`, 4 with this one, 6 for records; 1: on this one alone). | |
| 584 | | `LEONIDA_VIEW_THREADS_WIDE` | see the code | yes | | yes | `leonida-gpu/land.rs` | Threads of the pool for the views picked by index ([`each_view`]): as before, and with `LEONIDA_VIEW_THREADS_WIDE=1`. | | 585 | | `LEONIDA_VIEW_THREADS_WIDE` | see the code | yes | | yes | `leonida-gpu/land.rs` | Threads of the pool for the views picked by index ([`each_view`]): as before, and with `LEONIDA_VIEW_THREADS_WIDE=1`. | |
| 585 | | `LEONIDA_VIPATCH_NO_VIGNETTE` | see the code | | | | `leonida-gpu/host/menu.rs` +1 | | | 586 | | `LEONIDA_VIPATCH_NO_VIGNETTE` | see the code | | | | `leonida-gpu/host/menu.rs` +1 | | |
diff --git a/docs/README.md b/docs/README.md index 1bc9ffcbb..860f7ef8a 100644 --- a/docs/README.md +++ b/docs/README.md | |||
| @@ -19,7 +19,7 @@ method, scope and caveats. No game data is included. | |||
| 19 | | [modding.md](modding.md) | The mod format: `mods/<folder>/mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | | 19 | | [modding.md](modding.md) | The mod format: `mods/<folder>/mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | |
| 20 | | [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). | | 20 | | [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). | |
| 21 | | [dev-tools.md](dev-tools.md) | The development CLI `scripts/dev.py`: `discover` (text or `--json`, schema version 1) lists the boot-trace analyzer and the guest-scene runner with their help commands and prerequisites, without running them; live attach, pause, step and screenshots are not available through it. | | 21 | | [dev-tools.md](dev-tools.md) | The development CLI `scripts/dev.py`: `discover` (text or `--json`, schema version 1) lists the boot-trace analyzer and the guest-scene runner with their help commands and prerequisites, without running them; live attach, pause, step and screenshots are not available through it. | |
| 22 | | [agent_collaboration.md](agent_collaboration.md) | How contributors' coding agents work together through GitHub: which machine profile takes which work, the `AGENT-MSG`, `RUN` and `TEST-WANTED` blocks, and the evidence tags. A convention, not a measurement. | | 22 | | [agent_collaboration.md](agent_collaboration.md) | How contributors' coding agents work together through GitHub: which machine profile takes which work, the `AGENT-MSG`, `RUN`, `PICTURE` and `TEST-WANTED` blocks (`PICTURE` from `tools/picture_metrics.py`: a frame's luma, dark regions, lattice and block detectors, an 8x8 diff and a defect class, numbers only), and the evidence tags. A convention, not a measurement. | |
| 23 | | [history/README.md](history/README.md) | The original repository's surviving history as portable, hashed text: the 251 `old-pr/*` branch tips and the 135 indexed old issues, with the script that regenerates them ([#563](https://github.com/ubiquitarianism/leonida/issues/563)). | | 23 | | [history/README.md](history/README.md) | The original repository's surviving history as portable, hashed text: the 251 `old-pr/*` branch tips and the 135 indexed old issues, with the script that regenerates them ([#563](https://github.com/ubiquitarianism/leonida/issues/563)). | |
| 24 | | [port_status.md](port_status.md) | Where the port stands: Leonida's runtime and shader pipeline as the base, what was patched in from VIctory, and what is still open. | | 24 | | [port_status.md](port_status.md) | Where the port stands: Leonida's runtime and shader pipeline as the base, what was patched in from VIctory, and what is still open. | |
| 25 | | [port_plan.md](port_plan.md) | What the title needs that Leonida's runtime does not do yet, taken from VIctory, in the order the title hits it and where each fix lands. | | 25 | | [port_plan.md](port_plan.md) | What the title needs that Leonida's runtime does not do yet, taken from VIctory, in the order the title hits it and where each fix lands. | |
diff --git a/docs/agent_collaboration.md b/docs/agent_collaboration.md index 23f43323f..67f7325e5 100644 --- a/docs/agent_collaboration.md +++ b/docs/agent_collaboration.md | |||
| @@ -1,7 +1,7 @@ | |||
| 1 | # Agents working together | 1 | # Agents working together |
| 2 | 2 | ||
| 3 | Many contributors work through a coding agent, each on its own machine. This page is how those agents share work | 3 | Many contributors work through a coding agent, each on its own machine. This page is how those agents share work |
| 4 | without their humans briefing them: where they read and write, which machine takes which kind of work, three blocks | 4 | without their humans briefing them: where they read and write, which machine takes which kind of work, four blocks |
| 5 | with fixed fields, and how sure a claim is. It adds to [CONTRIBUTING.md](../CONTRIBUTING.md) and | 5 | with fixed fields, and how sure a claim is. It adds to [CONTRIBUTING.md](../CONTRIBUTING.md) and |
| 6 | [AGENTS.md](../AGENTS.md) and replaces nothing in them. No game data is included. | 6 | [AGENTS.md](../AGENTS.md) and replaces nothing in them. No game data is included. |
| 7 | 7 | ||
| @@ -35,10 +35,10 @@ with fixed fields, and how sure a claim is. It adds to [CONTRIBUTING.md](../CONT | |||
| 35 | - M is wide: say the video memory and whether it is a laptop, since an 8 GB laptop and a 16 GB desktop card behave | 35 | - M is wide: say the video memory and whether it is a laptop, since an 8 GB laptop and a 16 GB desktop card behave |
| 36 | differently. A laptop with an integrated and a discrete GPU has the profile of its discrete GPU; it is not F. | 36 | differently. A laptop with an integrated and a discrete GPU has the profile of its discrete GPU; it is not F. |
| 37 | 37 | ||
| 38 | ## Three blocks | 38 | ## Four blocks |
| 39 | 39 | ||
| 40 | Each block starts with its prefix (`AGENT-MSG`, `RUN`, `TEST-WANTED`) so a search finds it, and says it is | 40 | Each block starts with its prefix (`AGENT-MSG`, `RUN`, `PICTURE`, `TEST-WANTED`) so a search finds it, and says it |
| 41 | AI-assisted. Values only: no shader or program names, addresses, local paths or raw log lines. | 41 | is AI-assisted. Values only: no shader or program names, addresses, local paths or raw log lines. |
| 42 | 42 | ||
| 43 | A message from one agent to another: | 43 | A message from one agent to another: |
| 44 | 44 | ||
| @@ -77,6 +77,31 @@ VERDICT: prediction <held | missed by ...> | |||
| 77 | Two runs compare only when `BASE`, `RECIPE`, `CACHES` and `INSTRUMENTS` match, apart from the variable under study: | 77 | Two runs compare only when `BASE`, `RECIPE`, `CACHES` and `INSTRUMENTS` match, apart from the variable under study: |
| 78 | a diagnostic run and a progress run do not compare even when the recipe reads the same. | 78 | a diagnostic run and a progress run do not compare even when the recipe reads the same. |
| 79 | 79 | ||
| 80 | What a frame shows, in numbers: `python -I tools/picture_metrics.py <frame> [<reference>]` prints the block from a | ||
| 81 | PNG or PPM on your disk, `--json` the same numbers as JSON. The frame stays local: the block has no pixels, no image | ||
| 82 | and no path. Fill in the first line; the values below are from a synthetic frame: | ||
| 83 | |||
| 84 | ``` | ||
| 85 | PICTURE | 2026-11-27 14:05 UTC | <GitHub handle> | AI-assisted: <tool> | ||
| 86 | FRAME: 1280x720 | reference 1280x720 | ||
| 87 | LUMA: mean 126.75 | min 0 | max 128 | sd 12.59 | dark 0.0098 | ||
| 88 | DARK 4x4: 0.01 0.01 0.01 0.01 / 0.01 0.01 0.01 0.01 / 0.01 0.01 0.01 0.01 / 0.01 0.01 0.01 0.01 | ||
| 89 | LATTICE: tile 8 | period 16 | phase 9 | diagonal + | corner TL | tiles 900 | cover 1.0 | ||
| 90 | BLOCKS: none | ||
| 91 | DIFF: changed 0 of 14400 8x8 tiles | share 0.0 | reference luma mean 126.75 | ||
| 92 | CLASS: LATTICE (measured) | given: none | ||
| 93 | EVIDENCE: MEASURED (tools/picture_metrics.py, 2 frames) | ||
| 94 | ``` | ||
| 95 | |||
| 96 | `CLASS` is one of `LATTICE`, `BLACK-NEAR`, `BLOCKS`, `FLASH`, `CHAR-BLACK`, `CHAR-MISSING`, `2D-MISSING`, | ||
| 97 | `STRAY-GEO`, `SMEAR` or `OK`. The tool measures the first four and `OK`; the other five need to know what the scene | ||
| 98 | should show, so only a human gives them (`--class`, with `--region X,Y,W,H` for the numbers of the part concerned), | ||
| 99 | and they print as `given`, never as `measured`. A measured class is a hint: a human confirms it before it is | ||
| 100 | called a defect. Several sharp rectangles (HUD panels, window frames) can read as `BLOCKS`, and blocks off the | ||
| 101 | frame's origin are given at the divisor of their edges (16-pixel blocks shifted by 4 read as 4x4). A lattice that | ||
| 102 | repeats fewer than three times in the frame is not reported. A 1280x720 frame takes a few seconds. Put the block | ||
| 103 | next to the `RUN` block of the run that made the frame. | ||
| 104 | |||
| 80 | A request for a test on a machine you do not have, as a comment on the pull request to test. With no pull request, it | 105 | A request for a test on a machine you do not have, as a comment on the pull request to test. With no pull request, it |
| 81 | is its own issue titled `TEST-WANTED [<profile>] <one line>`, closed by its author when done, so that | 106 | is its own issue titled `TEST-WANTED [<profile>] <one line>`, closed by its author when done, so that |
| 82 | `gh issue list --search "TEST-WANTED in:title"` lists what is waiting; labels would do better if maintainers add them: | 107 | `gh issue list --search "TEST-WANTED in:title"` lists what is waiting; labels would do better if maintainers add them: |
diff --git a/docs/boot.md b/docs/boot.md index e6fbea587..7dc1691c2 100644 --- a/docs/boot.md +++ b/docs/boot.md | |||
| @@ -262,6 +262,29 @@ If startup stops before the first D3D12 call, the combined command still prints | |||
| 262 | or invalid requested trace is reported on stderr and sets exit code 2. In a partial JSON report that section | 262 | or invalid requested trace is reported on stderr and sets exit code 2. In a partial JSON report that section |
| 263 | is `null`; if neither input yields a report, stdout is empty. | 263 | is `null`; if neither input yields a report, stdout is empty. |
| 264 | 264 | ||
| 265 | ### Past the first frame: which of these three stops is it | ||
| 266 | |||
| 267 | A run that stops without a frame looks the same in the present count; the `[rt]` lines say which of these three | ||
| 268 | stops it was. The rule behind the held value is in [`d3d12_xs_console_abi.md`](d3d12_xs_console_abi.md) §5.5. A | ||
| 269 | device loss and the title's watchdog have their own lines (`[rt] aftermath: device lost` and `[rt] hang watchdog:`), | ||
| 270 | and a `list values so far` line with a nonzero `at device loss` reason is a device loss even when `released unmet` | ||
| 271 | is 0. | ||
| 272 | |||
| 273 | | Stop | Lines to read | The measured shape | | ||
| 274 | |---|---|---| | ||
| 275 | | **Pipelines still compiling** | `[rt] mem-probe t=` `pipelines live ... (made N / M, X s / Y s in vkCreate*Pipelines)`; `[rt] submit frame` | the `made` pair and the `vkCreate*Pipelines` seconds keep rising: one run made 763 graphics and 619 compute pipelines (2,296 modules, 732 MiB of SPIR-V) with 45 minutes of `vkCreate*Pipeline` CPU time, and its scene's first frame came as the builds ended. | | ||
| 276 | | **A held console value** | `[rt] d3d12_xs: list values so far`: `released unmet` by reason, then `oldest held gate ...`; `[rt] submit frame` | `0 released unmet` in every reason while the oldest gate's age grows, and the `submit frame` lines stop: one console value wait stayed unmet for 101 minutes; of 209 gates, 192 were met and 0 released unmet. | | ||
| 277 | | **Host memory** | `[rt] mem-probe breakdown t=` (what the runtime holds) and the cgroup's peak | the runtime's `allocated` is large and the cgroup peak is at its cap: 22.3 GB of 24 GB killed one run 21 minutes in, before a world frame, and 22.2 GB killed another after it had drawn one; a later run of the same scene peaked at 23.6 GB. | | ||
| 278 | |||
| 279 | The `mem-probe` rows need `LEONIDA_MEM_PROBE=30` at the start; without it there is no `mem-probe` line. `submit frame` | ||
| 280 | is every `LEONIDA_SUBMIT_FRAME_SECONDS` (default 10; `0` turns it off), and `LEONIDA_LIST_VALUES=0` drops the gate | ||
| 281 | counters. The `[rt]` lines are the Vulkan layer's stderr, not a launcher log. | ||
| 282 | |||
| 283 | Check the cgroup first when the process is gone without an `exit` event: a peak at `MemoryMax` plus the kernel's OOM | ||
| 284 | line is host memory. Otherwise the `made` count decides: while it rises the run is compiling; once it is flat, a | ||
| 285 | growing `oldest held gate` names the held value. The cgroup's peak is its `memory.peak`, or | ||
| 286 | `systemctl show -p MemoryPeak <scope>` and the scope's journal. | ||
| 287 | |||
| 265 | ## 4. The open questions, and the trace signal for each | 288 | ## 4. The open questions, and the trace signal for each |
| 266 | 289 | ||
| 267 | The questions are in [`d3d12_vulkan.md`](d3d12_vulkan.md) §8.2; this table takes the same 1–22 in | 290 | The questions are in [`d3d12_vulkan.md`](d3d12_vulkan.md) §8.2; this table takes the same 1–22 in |
diff --git a/docs/cpu_features.md b/docs/cpu_features.md index 47ffd81dc..9c4e97ea3 100644 --- a/docs/cpu_features.md +++ b/docs/cpu_features.md | |||
| @@ -43,10 +43,27 @@ Each flagged site was read by hand in a private copy (not quoted here): | |||
| 43 | - The 8 privileged and 1 `int n` hits are data: tables of 32-bit offsets placed in `.text` (some inside a `.pdata` | 43 | - The 8 privileged and 1 `int n` hits are data: tables of 32-bit offsets placed in `.text` (some inside a `.pdata` |
| 44 | range) that the linear sweep decodes as instructions. They are listed for completeness, not as code to replace. | 44 | range) that the linear sweep decodes as instructions. They are listed for completeness, not as code to replace. |
| 45 | 45 | ||
| 46 | No AVX-512, VAES, VPCLMULQDQ, SHA, RDPID, RDPRU, XOP, FMA4, TBM, SYSCALL or SYSENTER instruction was found. The | 46 | No AVX-512, VAES, VPCLMULQDQ, SHA, RDPID, RDPRU, XOP, FMA4, TBM, SYSCALL or SYSENTER instruction was found. No RDTSC, |
| 47 | 256-bit integer, FMA3, F16C, BMI1/2, ADX, MOVBE, AES-NI and PCLMULQDQ instructions it uses are on every Intel CPU | 47 | RDTSCP, RDRAND, RDSEED, FSGSBASE or CLFLUSHOPT instruction is in the image either. The remaining features counted by |
| 48 | since Haswell/Broadwell and every AMD CPU since Zen, so they are counted but not flagged. No RDTSC or RDTSCP is | 48 | `tools/cpu_feature_scan.py` (at `0b11d86b`) are in its `baseline` class — present on every Intel CPU since |
| 49 | in the image. | 49 | Haswell/Broadwell and every AMD CPU since Zen: |
| 50 | |||
| 51 | | Feature | Sites | Inside `.pdata` | Outside `.pdata` | Notes | | ||
| 52 | |---|---:|---:|---:|---| | ||
| 53 | | `AVX` | 2,981,637 | 2,871,070 | 110,567 | Includes 31,970 `vbroadcastss` and 131 `vbroadcastsd` sites in `.pdata` with an `xmm` register source (`mod == 3`), which are AVX2 rather than AVX1 | | ||
| 54 | | `FMA` (FMA3) | 204,279 | 200,924 | 3,355 | 45 mnemonics (`132`/`213`/`231`, `ps`/`pd`/`ss`/`sd`, including 3 `vfmaddsub*`/`vfmsubadd*` sites) | | ||
| 55 | | `AVX2` | 86,018 | 81,500 | 4,518 | Zero `vgather*` or `vpgather*` sites; 284 of the `.pdata` hits are AVX1 mnemonics that share the `vp` prefix (`234` `vptest`, `42` `vperm2f128`, `8` `vpermilps`) | | ||
| 56 | | `BMI1` | 60,850 | 58,398 | 2,452 | `bextr` (21,546), `andn` (17,585), `tzcnt` (11,827), `blsr` (7,301), `blsi` (139); zero `blsmsk` | | ||
| 57 | | `BMI2` | 14,959 | 12,403 | 2,556 | `shlx` (7,581), `mulx` (1,612), `shrx` (1,309), `rorx` (1,064), `bzhi` (808), `sarx` (29); zero `pdep` or `pext` in `.pdata` | | ||
| 58 | | `AES` | 3,390 | 13 | 3,377 | `vaesimc` in `.pdata`; the hits outside `.pdata` are data | | ||
| 59 | | `F16C` | 3,303 | 2,966 | 337 | `vcvtph2ps` (1,526) and `vcvtps2ph` (1,440) | | ||
| 60 | | `ADX` | 2,678 | 0 | 2,678 | Data outside `.pdata`; zero sites inside `.pdata` | | ||
| 61 | | `PCLMULQDQ` | 1,128 | 0 | 1,128 | Data outside `.pdata`; zero sites inside `.pdata` | | ||
| 62 | | `POPCNT` | 458 | 442 | 16 | — | | ||
| 63 | | `MOVBE` | 422 | 195 | 227 | — | | ||
| 64 | | `LZCNT` | 321 | 294 | 27 | 149 4-byte and 145 5-to-9-byte encodings in `.pdata` | | ||
| 65 | | `CX16` | 56 | 56 | 0 | `cmpxchg16b` | | ||
| 66 | | `PREFETCHW` | 5 | 5 | 0 | `0F 0D /1`: architectural NOP on Intel 64 CPUs without `PREFETCHW` | | ||
| 50 | 67 | ||
| 51 | ## What it means for the runtime | 68 | ## What it means for the runtime |
| 52 | 69 | ||
| @@ -70,6 +87,31 @@ in the image. | |||
| 70 | 87 | ||
| 71 | Not measured: which of these sites a boot reaches, and in which order. | 88 | Not measured: which of these sites a boot reaches, and in which order. |
| 72 | 89 | ||
| 90 | ### Hosts with AVX1 and SSE4.2 (Sandy Bridge and Ivy Bridge) | ||
| 91 | |||
| 92 | An Intel Sandy Bridge or Ivy Bridge host (for example an Intel Core i7-2600, `CPUID.1:ECX = 0x1FBAE3FF`, `XCR0 = 0x7`) | ||
| 93 | has 256-bit `YMM0`–`YMM15`, `XSAVE`/`OSXSAVE`, `AVX`, `SSE4.2`, `POPCNT`, `CX16`, `AES-NI` and `PCLMULQDQ`, so it | ||
| 94 | passes the `host_cpu` AVX preflight, executes the 2,839,253 genuine AVX1 `.pdata` sites (`2,871,070` minus the 32,101 | ||
| 95 | register-source `vbroadcastss`/`vbroadcastsd` sites, plus the 284 `vp`-prefixed AVX1 sites) natively, and treats the 5 | ||
| 96 | `PREFETCHW` sites (`0F 0D /1`) as hint NOPs (Intel SDM Vol. 2B). What it lacks inside `.pdata` is the Haswell/ABM | ||
| 97 | delta: `FMA` (200,924), `AVX2` (81,216 plus 32,101 register-source `vbroadcastss`/`vbroadcastsd`), `BMI1` (58,398), | ||
| 98 | `BMI2` (12,403), `F16C` (2,966 on Sandy Bridge; native on Ivy Bridge), `LZCNT` (294) and `MOVBE` (195). | ||
| 99 | |||
| 100 | Those instructions split into two execution classes on a pre-Haswell CPU: | ||
| 101 | |||
| 102 | - **Fault with `#UD` (`STATUS_ILLEGAL_INSTRUCTION`):** every VEX `0F38`/`0F3A` instruction in that set (`FMA3`, `F16C`, | ||
| 103 | `bextr`/`andn`/`blsr`/`blsi`, `BMI2`, `AVX2` broadcasts/permutes/blends/variable shifts, and register-source | ||
| 104 | `vbroadcastss`/`vbroadcastsd`), 256-bit `0F`-map integer `vp* ymm` operations, and `MOVBE`. | ||
| 105 | - **Do not fault (`LZCNT` and `TZCNT`):** legacy `LZCNT` (`F3 0F BD`) and `TZCNT` (`F3 0F BC`) have no VEX form in | ||
| 106 | x86-64, and a CPU without `LZCNT`/`BMI1` ignores the `F3` prefix and executes `BSR` or `BSF` instead (Intel SDM | ||
| 107 | Vol. 2A/2B). `BSR` returns the bit index (`width - 1 - lzcnt`) rather than the leading-zero count and leaves the | ||
| 108 | destination undefined when the source is zero. `BSF` writes the same bit index as `TZCNT` for non-zero inputs, but | ||
| 109 | leaves `CF` undefined and leaves the destination unmodified when the source is zero, whereas 988 of the 11,827 | ||
| 110 | `.pdata` `tzcnt` sites are immediately followed by a `CF`-reading instruction (`793` `cmovb`, `174` `cmovae`, `20` | ||
| 111 | `jae`, `1` `jb`). Supporting an `AVX1` host therefore requires rewriting `LZCNT` and `TZCNT` sites before code runs | ||
| 112 | (149 of the 294 `.pdata` `lzcnt` sites are 4-byte `F3 0F BD /r` encodings without REX, shorter than a 5-byte | ||
| 113 | `jmp rel32`) rather than relying on `#UD`. | ||
| 114 | |||
| 73 | ### Hosts without AVX | 115 | ### Hosts without AVX |
| 74 | 116 | ||
| 75 | Measured on one host: Intel Xeon X5675 (Westmere, SSE4.2; no AVX, AVX2, FMA, BMI2 or XSAVE), Fedora 44, | 117 | Measured on one host: Intel Xeon X5675 (Westmere, SSE4.2; no AVX, AVX2, FMA, BMI2 or XSAVE), Fedora 44, |
diff --git a/docs/design.md b/docs/design.md index 2a3126b20..79385b39d 100644 --- a/docs/design.md +++ b/docs/design.md | |||
| @@ -383,7 +383,7 @@ How the generated SPIR-V expects the runtime to work: | |||
| 383 | | Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py` (on `cs_store` and `ps_m15`: the block, its interface entry, `spirv-val`, the metadata, no block without a tail read, and the `--mesh-compute` address). The whole hand-written GPU test set in `runtime/test/shaders` is translated with the flag by `build.py` or `scripts/run_gpu_tests.py` under `LEONIDA_PC_TAIL_UBO=1`, and the index's `pc_tail` entries say which modules read the tail; how many do changes as shaders are added, so no count is kept here. The GPU test programs bind the block (`runtime/test/vk_pc_tail.h`; the list is in docs/testing.md), except with `--mesh-compute`, whose tests skip. The D3D12 layer does not yet: it refuses pipelines on a device with fewer than 144 push-constant bytes (`push_constants_fit` in `d3d12_vulkan_device.cpp`). | | 383 | | Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py` (on `cs_store` and `ps_m15`: the block, its interface entry, `spirv-val`, the metadata, no block without a tail read, and the `--mesh-compute` address). The whole hand-written GPU test set in `runtime/test/shaders` is translated with the flag by `build.py` or `scripts/run_gpu_tests.py` under `LEONIDA_PC_TAIL_UBO=1`, and the index's `pc_tail` entries say which modules read the tail; how many do changes as shaders are added, so no count is kept here. The GPU test programs bind the block (`runtime/test/vk_pc_tail.h`; the list is in docs/testing.md), except with `--mesh-compute`, whose tests skip. The D3D12 layer does not yet: it refuses pipelines on a device with fewer than 144 push-constant bytes (`push_constants_fit` in `d3d12_vulkan_device.cpp`). | |
| 384 | | Address guard (`--address-guard`) | **Prototype, off by default.** Every `Gen.host_addr` access (buffer, `global_`, scalar and BVH loads, stores and atomics) calls `%guard_fn` with the access's sign-extended 48-bit heap offset, its kind and its span. An access whose first and last byte are below the arena's size passes after one compare. Any other access looks up the 4 KiB pages of its first and last byte in the runtime's two-level page table (level 1 by offset bits 47..32, level 2 one bit per page). A refused load reads the zero area at `heap_base + 0x71000`. A refused store or atomic goes to the dump area at `+ 0x78000`, and an atomic returns 0. Each refusal is counted in the header at `+ 0x70000`. The entry block reads that header once. Without its magic (runtime `LEONIDA_ADDRESS_GUARD` unset) every access passes, and without the flag the module is unchanged byte for byte. The index records `"address_guard": true`. Format: `runtime/src/address_guard.h`, `tools/address_guard.py`; design and costs: `docs/d3d12_vulkan.md` 3.3, "Address guard". **Checked:** `tests/semantic/test_address_guard.py` (fixture `cs_address_guard` through `spirv_mini_interp` with the guard on, off at run time and without the flag; kinds and spans per instruction family; the table model), `runtime/test/address_guard_test.cpp`, and `scripts/run_address_guard_gpu_test.py` (lavapipe, Mesa 26.3.1: the refused loads read 0 over real memory, and the store and the atomic land in the dump area). | | 384 | | Address guard (`--address-guard`) | **Prototype, off by default.** Every `Gen.host_addr` access (buffer, `global_`, scalar and BVH loads, stores and atomics) calls `%guard_fn` with the access's sign-extended 48-bit heap offset, its kind and its span. An access whose first and last byte are below the arena's size passes after one compare. Any other access looks up the 4 KiB pages of its first and last byte in the runtime's two-level page table (level 1 by offset bits 47..32, level 2 one bit per page). A refused load reads the zero area at `heap_base + 0x71000`. A refused store or atomic goes to the dump area at `+ 0x78000`, and an atomic returns 0. Each refusal is counted in the header at `+ 0x70000`. The entry block reads that header once. Without its magic (runtime `LEONIDA_ADDRESS_GUARD` unset) every access passes, and without the flag the module is unchanged byte for byte. The index records `"address_guard": true`. Format: `runtime/src/address_guard.h`, `tools/address_guard.py`; design and costs: `docs/d3d12_vulkan.md` 3.3, "Address guard". **Checked:** `tests/semantic/test_address_guard.py` (fixture `cs_address_guard` through `spirv_mini_interp` with the guard on, off at run time and without the flag; kinds and spans per instruction family; the table model), `runtime/test/address_guard_test.cpp`, and `scripts/run_address_guard_gpu_test.py` (lavapipe, Mesa 26.3.1: the refused loads read 0 over real memory, and the store and the atomic land in the dump area). | |
| 385 | | `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. | | 385 | | `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. | |
| 386 | | `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. | | 386 | | `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. **NVIDIA driver workaround (2026-11-25):** the low-16 mask on every int-derived value that merges into a preserved 16-bit half is emitted as `OpBitFieldUExtract` (base 0, count 16), not `OpBitwiseAnd & 0xFFFF`. The sites: the VOP3 16-bit integer results (`v_add/sub_{nc_,}{i16,u16}`, the shifts, `v_mad_{u16,i16}` and `v_{min,max,med}3_{u16,i16}`), the signed `v_cvt_i16_f16`/`v_cvt_norm_i16_f16` conversions (a Bitcast of an `%int` convert), and the signed `saturate_int16` feeding d16 image/buffer stores. NVIDIA's shader compiler (RTX 4070 SUPER, wave32) miscompiles the `And` when its operand passed through `%int` ops and the result merges with the preserved high half — `v_add_nc_i16 v14, v3, v12 op_sel:[1,1,0] clamp` wrote `0x1113AAA8` for `0x0002AAA8` (low half fine, kept half corrupted); the same `And`-free extract gives the right word, `SClamp` on `%int` or select-based clamps do not dodge it, and the `op_sel` destination-high merge (`(old & 0xFFFF) \| (lo << 16)`) is unaffected. GPU-checked on the RTX 4070 SUPER (the repro and 160 randomized `op_sel`/`clamp` cases, 0 mismatches against a Python reference) and on the Radeon iGPU (gfx1036, `--pc-tail-ubo`); semantics unchanged (`spirv-val` clean, the CPU interpreter agrees). | |
| 387 | | Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). It computes `floor(LOD) + (LOD - floor(LOD) >= 0.5)`, which is exact in binary32, not `Floor(LOD + 0.5)`: that sum rounds `0x3effffff` up to 1.0, and on an RTX 5070 (621.24) the gather then read mip 1 where native `image_sample_l` at the same LOD reads mip 0. | | 387 | | Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). It computes `floor(LOD) + (LOD - floor(LOD) >= 0.5)`, which is exact in binary32, not `Floor(LOD + 0.5)`: that sum rounds `0x3effffff` up to 1.0, and on an RTX 5070 (621.24) the gather then read mip 1 where native `image_sample_l` at the same LOD reads mip 0. | |
| 388 | | `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. | | 388 | | `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. | |
| 389 | | SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | | 389 | | SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | |
| @@ -412,7 +412,7 @@ How the generated SPIR-V expects the runtime to work: | |||
| 412 | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | 412 | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | |
| 413 | | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | 413 | | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | |
| 414 | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | 414 | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | |
| 415 | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | | 415 | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | |
| 416 | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | | 416 | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | |
| 417 | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | | 417 | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | |
| 418 | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | | 418 | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | |
| @@ -536,6 +536,7 @@ How the generated SPIR-V expects the runtime to work: | |||
| 536 | | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 536 | | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | |
| 537 | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as the hardware does: the delta P1 − P0 (and P2 − P0) is rounded to f16 first — the SPI's P10/P20 words for a 16-bit channel are per-half f16 differences, measured below — and P0 + i·P10 + j·P20 is summed in f32 with i, j = `BaryCoordKHR`.y/.z (f32, not f16) before p2 clamps and narrows toward zero. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator sums P0 + i·P10 + j·P20 in f32 and narrows toward zero — SHADER-468: the driver's ISA runs the pair inside `s_round_mode 0x000c`, so the narrow is toward zero whatever the shader's own MODE writes are) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Measured on AMD hardware (SHADER-468, `tools/f16_interp_probe.py`; native 64×64 draws of a hand-written `f16vec2` varying through `vk_harness` on the Ryzen 5 7600 iGPU, gfx1036, AMD Windows driver 24.10.24, Vulkan 1.3.280; 12 draws, six value sets × orthographic and perspective, 98,304 samples):** the SPI writes P10/P20 as f16 differences of the two halves (round to nearest even) — a pair whose difference is 66,504, past the largest f16, interpolates to inf where the f32 difference stays finite — the sum is f32 (an f16 sum misses 11,385 of the 98,304 samples) and `v_interp_p2_f16` narrows **toward zero** (nearest even misses 36,078). The f16-delta model explains 98,274 of 98,304 samples, against 89,993 for the same model without the f16 delta, 86,919 for an f16 sum and 62,226 for nearest-even narrowing; until 2026-11-22 the translation used the f32 difference and nearest even, which is what the last number measures. The narrow follows MODE.FP16_ROUND, which every AMD compiler sets toward zero around this pair (LLVM `SIModeRegister`: "f16 interpolation instructions need double precision round to zero"; the Windows driver's ISA runs both ops inside `s_round_mode 0x000c`), so the translated p2 rounds toward zero whatever the shader's own MODE writes are. The weights are the SPI's f32 values, not f16: a perspective triangle (w = 1, 2, 4) quantized to f16 misses most samples, f32 matches. Confirmed by `tests/semantic/test_interp_f16_round.py` (both cases fail on the old translation). **Still unverified:** the 30 misses (26 where the exact value is a few 2^-24 — the hardware gives the smallest f16 subnormal where a plain toward-zero narrow gives zero — and 4 at an exact f16 grid boundary, where the vertex-0 weight is the SPI's own f32 value rather than 1 − i − j), f16 inf/NaN halves and `p1lv_f16`, and what a 32-bit `p1/p2_f32` read of a 16-bit-mode channel returns: with the LDS words holding f16 lanes that read cannot be the f16-rounded smooth value the "Pixel-shader interpolants" row assumes, but no Vulkan or D3D12 shader can ask for 16-bit mode and a 32-bit read of the same attribute, so it stays unmeasured. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | | 537 | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as the hardware does: the delta P1 − P0 (and P2 − P0) is rounded to f16 first — the SPI's P10/P20 words for a 16-bit channel are per-half f16 differences, measured below — and P0 + i·P10 + j·P20 is summed in f32 with i, j = `BaryCoordKHR`.y/.z (f32, not f16) before p2 clamps and narrows toward zero. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator sums P0 + i·P10 + j·P20 in f32 and narrows toward zero — SHADER-468: the driver's ISA runs the pair inside `s_round_mode 0x000c`, so the narrow is toward zero whatever the shader's own MODE writes are) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Measured on AMD hardware (SHADER-468, `tools/f16_interp_probe.py`; native 64×64 draws of a hand-written `f16vec2` varying through `vk_harness` on the Ryzen 5 7600 iGPU, gfx1036, AMD Windows driver 24.10.24, Vulkan 1.3.280; 12 draws, six value sets × orthographic and perspective, 98,304 samples):** the SPI writes P10/P20 as f16 differences of the two halves (round to nearest even) — a pair whose difference is 66,504, past the largest f16, interpolates to inf where the f32 difference stays finite — the sum is f32 (an f16 sum misses 11,385 of the 98,304 samples) and `v_interp_p2_f16` narrows **toward zero** (nearest even misses 36,078). The f16-delta model explains 98,274 of 98,304 samples, against 89,993 for the same model without the f16 delta, 86,919 for an f16 sum and 62,226 for nearest-even narrowing; until 2026-11-22 the translation used the f32 difference and nearest even, which is what the last number measures. The narrow follows MODE.FP16_ROUND, which every AMD compiler sets toward zero around this pair (LLVM `SIModeRegister`: "f16 interpolation instructions need double precision round to zero"; the Windows driver's ISA runs both ops inside `s_round_mode 0x000c`), so the translated p2 rounds toward zero whatever the shader's own MODE writes are. The weights are the SPI's f32 values, not f16: a perspective triangle (w = 1, 2, 4) quantized to f16 misses most samples, f32 matches. Confirmed by `tests/semantic/test_interp_f16_round.py` (both cases fail on the old translation). **Still unverified:** the 30 misses (26 where the exact value is a few 2^-24 — the hardware gives the smallest f16 subnormal where a plain toward-zero narrow gives zero — and 4 at an exact f16 grid boundary, where the vertex-0 weight is the SPI's own f32 value rather than 1 − i − j), f16 inf/NaN halves and `p1lv_f16`, and what a 32-bit `p1/p2_f32` read of a 16-bit-mode channel returns: with the LDS words holding f16 lanes that read cannot be the f16-rounded smooth value the "Pixel-shader interpolants" row assumes, but no Vulkan or D3D12 shader can ask for 16-bit mode and a 32-bit read of the same attribute, so it stays unmeasured. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | |
| 538 | | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | | 538 | | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | |
| 539 | | S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.26, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.26 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on two Apple M3s, macOS 26.5.1 and 27.0 (MoltenVK 1.4.2), where it answers true, and on KosmicKrisp and llvmpipe (Mesa 26.3.1) on both, where it answers false; on the 27.0 M3 `ps_ssharp` and its five variants pass in auto mode on all three drivers, and on an Apple M5 (macOS 26.6.2, MoltenVK) the probe answers false ("the sampler applies mipLodBias") and they pass without the flag (#1774). GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | | ||
| 539 | | Computed I/J barycentrics without `PerVertexKHR` (`--f16-interp-fallback`) | Under `--f16-interp-fallback` (without `--bary-fallback`), pixel shaders have no `PerVertexKHR` `[3 x vec4]` attribute arrays (neither Metal/MoltenVK nor devices without `VK_KHR_fragment_shader_barycentric` support them; `tools/vk_subgroup_info.py` sets `per_vertex_inputs: false` there, causing `make_game.py` to pass `--f16-interp-fallback`). Previously, `interp_ij_analysis` in `tools/rdna2spirv.py` raised `Unsupported` on any computed `v_interp_p1/p2` `(I, J)` pair under `--f16-interp-fallback`, refusing all 207 computed-barycentric pixel shaders in the corpus (`26,296 / 26,503`). Neither `InterpolateAtOffset` (`OpCapability InterpolationFunction` requires `sampleRateShading`, which the runtime does not enable, and SPIRV-Cross MSL rejects `interpolate_at_offset` on `BuiltIn BaryCoordKHR`) nor a geometry shader is required: in real arithmetic, because `%bary` (`BuiltIn BaryCoordKHR`) carries perspective-correct barycentrics `(1 − I_c − J_c, I_c, J_c)`, every smooth attribute or decoded f16 half (`%in_attrN` / `%in_f16hN_{lo,hi}`) is affine in `(I, J)` across a 2x2 fragment quad (`P^(q) = P_0 + I^(q) P_10 + J^(q) P_20`) even under perspective foreshortening. `tools/rdna2spirv.py` (`Gen.ij_quad_eval` and `assemble`) declares `OpCapability FragmentBarycentricKHR` + `SPV_KHR_fragment_shader_barycentric` for `%bary` (recording `features: ["fragmentShaderBarycentric"]` in `index.json`, so the device must support `VK_KHR_fragment_shader_barycentric` for `BaryCoordKHR`, though not `PerVertexKHR` compilation: MoltenVK runs it natively, while drivers without `VK_KHR_fragment_shader_barycentric` such as KosmicKrisp skip it) alongside core Vulkan 1.0 `OpCapability DerivativeControl` (which adds no extra `VkPhysicalDeviceFeatures` bit and consumes zero extra `Location` slots), and hoists all `OpDPdxFine` / `OpDPdyFine` evaluations into the uniform `%entry` block (satisfying SPIR-V uniform control flow when `v_interp_p1/p2` sits inside divergent `EXEC` branches): `%entry` computes `(dI_x, dI_y)` and `(dJ_x, dJ_y)` of `%bc.y` / `%bc.z`, the 2x2 screen-quad Jacobian determinant `det = dI_x · dJ_y − dI_y · dJ_x`, and `(P_c, dP_x, dP_y)` for each computed `(input, component)`, while each computed site solves pixel steps `alpha = ((I − I_c) · dJ_y − (J − J_c) · dI_y) / det`, `beta = (dI_x · (J − J_c) − dJ_x · (I − I_c)) / det` and evaluates `P_c + alpha · dP_x + beta · dP_y`. **Shortcut (finite-difference amplification and `det == 0` fallback):** smooth fragment inputs and `BaryCoordKHR` arrive from the rasterizer quantized to binary32 (per-lane residual `\|e_q\| <= 0.5·ulp(P_q) + \|P_10\|·0.5·ulp(I_q) + \|P_20\|·0.5·ulp(J_q)`), and 1-pixel quad differences amplify that rounding by `1 + 2\|alpha\| + 2\|beta\|` (`alpha ~ (I − I_c) / (dI/dx)`, proportional to pixel step up to the primitive's pixel span): sub-pixel barycentric offsets (`\|alpha\|, \|beta\| <= 1` px) stay near input precision (`~2e-6` on `1920x1080` `W = (1, 2.5, 4)`), ~1,000-pixel constant jumps on `[-2.75, 10]` reach `1.09e-3` in IEEE binary32 (`2.04e-3` / `1` f16 ulp at `1.5 → 1.4990234375` on an RTX 4090, `@ecox982745`, NVIDIA `616.64`, #2239), and >1,100-pixel jumps to `(0, 0)` across a `2048`-pixel perspective triangle with `P in [1.5, 4096]` reach `0.358` (`>300` f16 ulps at `1.5`, bounded by `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp`). To guard degenerate zero-area, subnormal, infinite, or NaN determinants without `OpFDiv`-by-zero, `1 / det` overflow, or MoltenVK's `OpFOrdNotEqual` NaN bug (`!=` in SPIRV-Cross MSL), `%entry` checks `0x00800000 <= (OpBitcast_u32(det) & 0x7FFFFFFF) < 0x7F800000` in integer ops (`OpUGreaterThanEqual` / `OpULessThan`), clamping the divisor to `1.0` and returning `P_c` when outside the IEEE-754 normal f32 range (including 1D/line primitives where `J` is constant across the quad, `det == 0`, so computed `I` is ignored in favour of `P_c`). Like the non-computed path, `v_interp_p1lv_f16` takes `P_0` from the interpolated attribute (`vsrc2` is unread; the corpus has `0` computed `*_f16` ops), while `--bary-fallback`, `mixed_f32` (flat + smooth f32 on one location), `v_interp_mov_f32` `p10`/`p20`, and computed 32-bit reads of 16-bit-flagged interpolants remain `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VINTRP) and Khronos SPIR-V 1.3 (`OpDPdxFine`, `OpDPdyFine`, `DerivativeControl`). Confirmed across the full shader corpus: all `207 / 207` previously refused pixel shaders (`1,139` `v_interp_p1_f32` / `v_interp_p2_f32` computed pairs; `0` computed `*_f16` ops, `2` shaders also reading non-computed `*_f16` inputs) translate and pass `spirv-val --target-env vulkan1.2 --allow-offset-texture-operand` under `--f16-interp-fallback`, bringing `--f16-interp-fallback` corpus translation from `26,296 / 26,503` (`99.22%`) to `26,503 / 26,503` (`100%`), while default-flag outputs stay byte-identical across all 207 shaders. Checked on the CPU (`spirv_mini_interp` 2x2 quad evaluation across dyadic weights, `64x64`, `1920x1080`, and `2048`-pixel perspective `w` foreshortening with tight binary64 Jacobian and `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp` error bounds, non-uniform `EXEC`-masked branches, non-`v0`/`v1` operand registers, between-ops `J` writes, `v_interp_p1lv_f16` `vsrc2` invariance, line-primitive `det == 0` / subnormal / `±inf` / `NaN` determinants, and `f16_halves` metadata) and with `spirv-val` by `tests/semantic/test_interp_computed_ij_fallback.py` (`tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm`) and `tests/semantic/test_interp_computed_ij.py`. **GPU-verified through Vulkan** on `Apple M3` (`@EvgHaze`, MoltenVK `1.4.2`, #2239), `Apple M3 Pro` (`@wavehs`, MoltenVK `1.4.0`, #2239), `NVIDIA GeForce RTX 3090` (Windows driver `610.88`, Vulkan `1.4.341`, `VK_LAYER_KHRONOS_validation` `1.4.363`, `LEONIDA_F16_INTERP_FALLBACK=1`, `LEONIDA_BARY_FALLBACK=0`), and `NVIDIA GeForce RTX 5070` (`@lixonik`, Windows driver `610.88`, #2239): `runtime/test/shaders/ps_ij_computed.asm` drawn with `vs_ids` passes `vk_pipeline_check`, `runtime/test/shaders/check.py`, and `scripts/run_gpu_tests.py` (`4,096 / 4,096` pixels exact on RTX 3090/5070 and within `1e-6` natively on MoltenVK, `0` validation errors). | | 540 | | Computed I/J barycentrics without `PerVertexKHR` (`--f16-interp-fallback`) | Under `--f16-interp-fallback` (without `--bary-fallback`), pixel shaders have no `PerVertexKHR` `[3 x vec4]` attribute arrays (neither Metal/MoltenVK nor devices without `VK_KHR_fragment_shader_barycentric` support them; `tools/vk_subgroup_info.py` sets `per_vertex_inputs: false` there, causing `make_game.py` to pass `--f16-interp-fallback`). Previously, `interp_ij_analysis` in `tools/rdna2spirv.py` raised `Unsupported` on any computed `v_interp_p1/p2` `(I, J)` pair under `--f16-interp-fallback`, refusing all 207 computed-barycentric pixel shaders in the corpus (`26,296 / 26,503`). Neither `InterpolateAtOffset` (`OpCapability InterpolationFunction` requires `sampleRateShading`, which the runtime does not enable, and SPIRV-Cross MSL rejects `interpolate_at_offset` on `BuiltIn BaryCoordKHR`) nor a geometry shader is required: in real arithmetic, because `%bary` (`BuiltIn BaryCoordKHR`) carries perspective-correct barycentrics `(1 − I_c − J_c, I_c, J_c)`, every smooth attribute or decoded f16 half (`%in_attrN` / `%in_f16hN_{lo,hi}`) is affine in `(I, J)` across a 2x2 fragment quad (`P^(q) = P_0 + I^(q) P_10 + J^(q) P_20`) even under perspective foreshortening. `tools/rdna2spirv.py` (`Gen.ij_quad_eval` and `assemble`) declares `OpCapability FragmentBarycentricKHR` + `SPV_KHR_fragment_shader_barycentric` for `%bary` (recording `features: ["fragmentShaderBarycentric"]` in `index.json`, so the device must support `VK_KHR_fragment_shader_barycentric` for `BaryCoordKHR`, though not `PerVertexKHR` compilation: MoltenVK runs it natively, while drivers without `VK_KHR_fragment_shader_barycentric` such as KosmicKrisp skip it) alongside core Vulkan 1.0 `OpCapability DerivativeControl` (which adds no extra `VkPhysicalDeviceFeatures` bit and consumes zero extra `Location` slots), and hoists all `OpDPdxFine` / `OpDPdyFine` evaluations into the uniform `%entry` block (satisfying SPIR-V uniform control flow when `v_interp_p1/p2` sits inside divergent `EXEC` branches): `%entry` computes `(dI_x, dI_y)` and `(dJ_x, dJ_y)` of `%bc.y` / `%bc.z`, the 2x2 screen-quad Jacobian determinant `det = dI_x · dJ_y − dI_y · dJ_x`, and `(P_c, dP_x, dP_y)` for each computed `(input, component)`, while each computed site solves pixel steps `alpha = ((I − I_c) · dJ_y − (J − J_c) · dI_y) / det`, `beta = (dI_x · (J − J_c) − dJ_x · (I − I_c)) / det` and evaluates `P_c + alpha · dP_x + beta · dP_y`. **Shortcut (finite-difference amplification and `det == 0` fallback):** smooth fragment inputs and `BaryCoordKHR` arrive from the rasterizer quantized to binary32 (per-lane residual `\|e_q\| <= 0.5·ulp(P_q) + \|P_10\|·0.5·ulp(I_q) + \|P_20\|·0.5·ulp(J_q)`), and 1-pixel quad differences amplify that rounding by `1 + 2\|alpha\| + 2\|beta\|` (`alpha ~ (I − I_c) / (dI/dx)`, proportional to pixel step up to the primitive's pixel span): sub-pixel barycentric offsets (`\|alpha\|, \|beta\| <= 1` px) stay near input precision (`~2e-6` on `1920x1080` `W = (1, 2.5, 4)`), ~1,000-pixel constant jumps on `[-2.75, 10]` reach `1.09e-3` in IEEE binary32 (`2.04e-3` / `1` f16 ulp at `1.5 → 1.4990234375` on an RTX 4090, `@ecox982745`, NVIDIA `616.64`, #2239), and >1,100-pixel jumps to `(0, 0)` across a `2048`-pixel perspective triangle with `P in [1.5, 4096]` reach `0.358` (`>300` f16 ulps at `1.5`, bounded by `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp`). To guard degenerate zero-area, subnormal, infinite, or NaN determinants without `OpFDiv`-by-zero, `1 / det` overflow, or MoltenVK's `OpFOrdNotEqual` NaN bug (`!=` in SPIRV-Cross MSL), `%entry` checks `0x00800000 <= (OpBitcast_u32(det) & 0x7FFFFFFF) < 0x7F800000` in integer ops (`OpUGreaterThanEqual` / `OpULessThan`), clamping the divisor to `1.0` and returning `P_c` when outside the IEEE-754 normal f32 range (including 1D/line primitives where `J` is constant across the quad, `det == 0`, so computed `I` is ignored in favour of `P_c`). Like the non-computed path, `v_interp_p1lv_f16` takes `P_0` from the interpolated attribute (`vsrc2` is unread; the corpus has `0` computed `*_f16` ops), while `--bary-fallback`, `mixed_f32` (flat + smooth f32 on one location), `v_interp_mov_f32` `p10`/`p20`, and computed 32-bit reads of 16-bit-flagged interpolants remain `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VINTRP) and Khronos SPIR-V 1.3 (`OpDPdxFine`, `OpDPdyFine`, `DerivativeControl`). Confirmed across the full shader corpus: all `207 / 207` previously refused pixel shaders (`1,139` `v_interp_p1_f32` / `v_interp_p2_f32` computed pairs; `0` computed `*_f16` ops, `2` shaders also reading non-computed `*_f16` inputs) translate and pass `spirv-val --target-env vulkan1.2 --allow-offset-texture-operand` under `--f16-interp-fallback`, bringing `--f16-interp-fallback` corpus translation from `26,296 / 26,503` (`99.22%`) to `26,503 / 26,503` (`100%`), while default-flag outputs stay byte-identical across all 207 shaders. Checked on the CPU (`spirv_mini_interp` 2x2 quad evaluation across dyadic weights, `64x64`, `1920x1080`, and `2048`-pixel perspective `w` foreshortening with tight binary64 Jacobian and `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp` error bounds, non-uniform `EXEC`-masked branches, non-`v0`/`v1` operand registers, between-ops `J` writes, `v_interp_p1lv_f16` `vsrc2` invariance, line-primitive `det == 0` / subnormal / `±inf` / `NaN` determinants, and `f16_halves` metadata) and with `spirv-val` by `tests/semantic/test_interp_computed_ij_fallback.py` (`tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm`) and `tests/semantic/test_interp_computed_ij.py`. **GPU-verified through Vulkan** on `Apple M3` (`@EvgHaze`, MoltenVK `1.4.2`, #2239), `Apple M3 Pro` (`@wavehs`, MoltenVK `1.4.0`, #2239), `NVIDIA GeForce RTX 3090` (Windows driver `610.88`, Vulkan `1.4.341`, `VK_LAYER_KHRONOS_validation` `1.4.363`, `LEONIDA_F16_INTERP_FALLBACK=1`, `LEONIDA_BARY_FALLBACK=0`), and `NVIDIA GeForce RTX 5070` (`@lixonik`, Windows driver `610.88`, #2239): `runtime/test/shaders/ps_ij_computed.asm` drawn with `vs_ids` passes `vk_pipeline_check`, `runtime/test/shaders/check.py`, and `scripts/run_gpu_tests.py` (`4,096 / 4,096` pixels exact on RTX 3090/5070 and within `1e-6` natively on MoltenVK, `0` validation errors). | |
| 540 | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | 541 | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | |
| 541 | | `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | | 542 | | `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | |
| @@ -621,10 +622,21 @@ cross-half code on 32-wide subgroups. | |||
| 621 | 622 | ||
| 622 | ## Disassembling shaders | 623 | ## Disassembling shaders |
| 623 | 624 | ||
| 624 | The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package | 625 | The AMDGPU disassembler needs LLVM 23+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-23` package |
| 625 | installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no | 626 | installs it at `/usr/lib/llvm-23/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no |
| 626 | `llvm-mc.exe`. On Windows, either build a native one or run it from WSL. | 627 | `llvm-mc.exe`. On Windows, either build a native one or run it from WSL. |
| 627 | 628 | ||
| 629 | 23+ is the requirement because of the pipeline library: LLVM 21.1.8 decodes all 26,503 shaders of `shaders.rpf`, but | ||
| 630 | 840 of the 2,684 compute programs there come out of its listings with 79,490 undecodable words and 8,310 | ||
| 631 | `exp invalid_target_N` words, so the translator refuses them as `fall-through into undecodable words` and the stage | ||
| 632 | ends at 1,844 of 2,684. | ||
| 633 | Under LLVM 23.1.5 those 840 have no undecodable word, and the stage translates 2,683 of the 2,684 and passes | ||
| 634 | `spirv-val`; the 2,684th is refused for `s_sethalt`, which the translator does not implement, under either version. | ||
| 635 | 1,674 of the 1,844 that already translated print differently under 23.1.5, because LLVM prints some operands | ||
| 636 | differently; re-translated from those listings all 1,674 pass, and the other 170 listings are byte-identical | ||
| 637 | (`-mcpu=gfx1013`, `--stages cs`, 1.0.2.1). `scripts/build_llvm_mc.ps1` builds 23.1.5 by default for this reason; keep | ||
| 638 | `LLVM_MC` on 23+ for the `shaders` stage. | ||
| 639 | |||
| 628 | Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone | 640 | Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone |
| 629 | with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools | 641 | with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools |
| 630 | don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in | 642 | don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in |
| @@ -640,10 +652,10 @@ powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 | |||
| 640 | python -I make_game.py --game "D:\path\to\your\package" --stages shaders | 652 | python -I make_game.py --game "D:\path\to\your\package" --stages shaders |
| 641 | ``` | 653 | ``` |
| 642 | 654 | ||
| 643 | WSL: install `llvm-21` and give `LLVM_MC` the whole command: | 655 | WSL: install `llvm-23` and give `LLVM_MC` the whole command: |
| 644 | 656 | ||
| 645 | ``` | 657 | ``` |
| 646 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc | 658 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc |
| 647 | python -I make_game.py --game "D:\path\to\your\package" --stages shaders | 659 | python -I make_game.py --game "D:\path\to\your\package" --stages shaders |
| 648 | ``` | 660 | ``` |
| 649 | 661 | ||
| @@ -655,7 +667,7 @@ on stdin, so a WSL command never receives a Windows file path. | |||
| 655 | with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: | 667 | with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: |
| 656 | 668 | ||
| 657 | ``` | 669 | ``` |
| 658 | LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I <repo>/tools/shader_disasm.py <work>/shaders/fssm | 670 | LLVM_MC=/usr/lib/llvm-23/bin/llvm-mc python3 -I <repo>/tools/shader_disasm.py <work>/shaders/fssm |
| 659 | ``` | 671 | ``` |
| 660 | 672 | ||
| 661 | Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the | 673 | Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the |
diff --git a/docs/dev-tools.md b/docs/dev-tools.md index d36091ec3..ed7fa4355 100644 --- a/docs/dev-tools.md +++ b/docs/dev-tools.md | |||
| @@ -59,6 +59,39 @@ recorded events, and the exit status reports the analysis result. | |||
| 59 | 59 | ||
| 60 | You can also run `python -I tools/boot_trace.py` with the same arguments. | 60 | You can also run `python -I tools/boot_trace.py` with the same arguments. |
| 61 | 61 | ||
| 62 | ## Check the shader chain of a work folder | ||
| 63 | |||
| 64 | `tools/chain_check.py` prints one page of counts for each link between the game files and the GPU. It reads the | ||
| 65 | work folder that `make_game.py` built and, if you pass one, the log of one run: | ||
| 66 | |||
| 67 | ```powershell | ||
| 68 | python -I tools/chain_check.py <work> | ||
| 69 | python -I tools/chain_check.py <work> --log <OutDir>\<Name>.log --json | ||
| 70 | ``` | ||
| 71 | |||
| 72 | The page has one block per link, and each block gets a verdict (OK, WARN or FAIL) and its most likely cause: | ||
| 73 | |||
| 74 | - tools: the llvm-mc each family was disassembled with and its AMDGPU target, spirv-val, and whether the | ||
| 75 | translator sources recorded in the folder still match this checkout's; | ||
| 76 | - one block per family (game programs, pipeline library, FSPX, BVH, executable): programs unpacked, listings, | ||
| 77 | listings with rejected words, programs translated, and up to 5 refusal reasons from `logs/shaders.log`; | ||
| 78 | - contract: tagged and plain modules, and the runtime folders that are present or absent (`fspx_compute` and the | ||
| 79 | others); | ||
| 80 | - runtime, from `--log` (`scripts/windows-boot/boot.ps1`'s `<Name>.log`): modules loaded, failed device slot calls, | ||
| 81 | failed D3D12 calls, compute pipeline builds, waits at the compile gate, device faults and the exit code. | ||
| 82 | |||
| 83 | The last line names the weakest link: the first block, in chain order, with the worst verdict. | ||
| 84 | |||
| 85 | A family is FAIL when more than 1% of its programs have no module. An llvm-mc older than 23 is a WARN (#1923). The | ||
| 86 | `--help` text lists every threshold. The report prints counts and fixed words only: no program names, no log lines | ||
| 87 | and no paths. A refusal reason is printed only when it matches a message from `tools/rdna2spirv.py`; any other | ||
| 88 | reason is counted as `other`. A D3D12 method name is printed only when the runtime's sources contain it, and the | ||
| 89 | end of a boot digest only in the forms boot.ps1 writes. Add `--show-paths` to name the folder and the log, but not | ||
| 90 | in a report you publish. | ||
| 91 | |||
| 92 | The exit code is `0` whatever the verdicts. With `--strict` it is `1` when a block is FAIL, and bad arguments exit | ||
| 93 | `2`. Probing asks llvm-mc, spirv-val and git for their versions; `--no-probe` runs nothing. | ||
| 94 | |||
| 62 | ## Run a synthetic guest scene | 95 | ## Run a synthetic guest scene |
| 63 | 96 | ||
| 64 | Use the existing headless runner with a loader and guest built on Windows | 97 | Use the existing headless runner with a loader and guest built on Windows |
diff --git a/docs/linux.md b/docs/linux.md index b6be52568..d1cdb8d92 100644 --- a/docs/linux.md +++ b/docs/linux.md | |||
| @@ -53,9 +53,12 @@ default stages leave `runtime` out (`check,shaders,assets,pipelines`). | |||
| 53 | 53 | ||
| 54 | Notes: | 54 | Notes: |
| 55 | 55 | ||
| 56 | - **llvm-mc**: Debian and Ubuntu's `llvm-21` installs it only as `llvm-mc-21` and `/usr/lib/llvm-21/bin/llvm-mc`. | 56 | - **llvm-mc**: the `shaders` stage needs LLVM 23 or newer, so install `llvm-23` where the distribution has it. Debian and Ubuntu's `llvm-21` installs `llvm-mc` only as `llvm-mc-21` and `/usr/lib/llvm-21/bin/llvm-mc`. |
| 57 | With `LLVM_MC` unset the tools use the plain `llvm-mc` when it is on `PATH` and otherwise the newest of those | 57 | With `LLVM_MC` unset the tools use the plain `llvm-mc` when it is on `PATH` and otherwise the newest of those |
| 58 | versioned names (`tools/mc_command.py`). Set `LLVM_MC` to choose another one. | 58 | versioned names (`tools/mc_command.py`). Set `LLVM_MC` to choose another one. The `shaders` stage needs LLVM 23+ |
| 59 | for its pipeline library: 21.1.8's listings of 840 of its 2,684 compute programs carry 79,490 undecodable words and | ||
| 60 | the translator refuses them, while 23.1.5 leaves none in those 840 and the stage translates 2,683 of 2,684 | ||
| 61 | ([design.md](design.md#disassembling-shaders)). | ||
| 59 | - **File names are case-sensitive.** The build opens the package's files by their exact names | 62 | - **File names are case-sensitive.** The build opens the package's files by their exact names |
| 60 | (`MicrosoftGame.Config`, `Catalog000.bin`, ...). A copy whose names changed case on the way is reported with the | 63 | (`MicrosoftGame.Config`, `Catalog000.bin`, ...). A copy whose names changed case on the way is reported with the |
| 61 | name it found and the one it needs; nothing is renamed for you. | 64 | name it found and the one it needs; nothing is renamed for you. |
diff --git a/docs/linux_proton.md b/docs/linux_proton.md index 61627b69a..8117a01f5 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md | |||
| @@ -97,6 +97,13 @@ What it does: | |||
| 97 | - **Limits:** a hard time limit (`--seconds`, then SIGTERM and SIGKILL 10 s later), a lock so one run happens at a | 97 | - **Limits:** a hard time limit (`--seconds`, then SIGTERM and SIGKILL 10 s later), a lock so one run happens at a |
| 98 | time (`--lock`, by default in `XDG_RUNTIME_DIR`), and teardown of Wine and the whole session on exit, time-out or | 98 | time (`--lock`, by default in `XDG_RUNTIME_DIR`), and teardown of Wine and the whole session on exit, time-out or |
| 99 | signal. | 99 | signal. |
| 100 | - **Shader cache:** the session's `XDG_CACHE_HOME`, where NVIDIA's `GLCache` and Mesa's shader cache go, is the | ||
| 101 | caller's when it is set, or the folder `--cache DIR` names; both are kept from run to run, so a later launch does | ||
| 102 | not compile every pipeline in the driver again. Without either, or with `--cache fresh`, it is a new folder in the | ||
| 103 | run folder, for a cold-cache run. The summary's first line says which (`shader cache: kept in DIR` or `fresh`). | ||
| 104 | The flag picks the XDG cache root; a driver's own variable (`MESA_SHADER_CACHE_DIR`, the older | ||
| 105 | `MESA_GLSL_CACHE_DIR`, NVIDIA's `__GL_SHADER_DISK_CACHE_PATH`) wins over it. A fresh run unsets them and empties | ||
| 106 | the run folder's `session/cache`, so it is cold; with a kept cache the caller's variables stay. | ||
| 100 | - **Traces:** `gta6rt --run` with `--trace` and `--trace-d3d12`, a fresh `--overlay` and save folder in the run | 107 | - **Traces:** `gta6rt --run` with `--trace` and `--trace-d3d12`, a fresh `--overlay` and save folder in the run |
| 101 | folder. Every other `LEONIDA_*` variable reaches the runtime unchanged, so `LEONIDA_INPUT_SCRIPT=a@210,a@240` | 108 | folder. Every other `LEONIDA_*` variable reaches the runtime unchanged, so `LEONIDA_INPUT_SCRIPT=a@210,a@240` |
| 102 | presses A as above. Arguments after `--` go to `gta6rt`. | 109 | presses A as above. Arguments after `--` go to `gta6rt`. |
diff --git a/docs/shader_validation.md b/docs/shader_validation.md index 4215afb6a..294648249 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md | |||
| @@ -1343,8 +1343,14 @@ mask or VCC) and `v_cmp_class_f32` e64, each read back with `v_cndmask_b32_e64`. | |||
| 1343 | `mul:2`/`mul:4`/`div:2` and `clamp`, with VGPR, SGPR, inline-constant and literal sources within the constant-bus | 1343 | `mul:2`/`mul:4`/`div:2` and `clamp`, with VGPR, SGPR, inline-constant and literal sources within the constant-bus |
| 1344 | limits. It runs one lane through `tests/semantic/spirv_mini_interp.py` against its own exact-rational ISA model, with | 1344 | limits. It runs one lane through `tests/semantic/spirv_mini_interp.py` against its own exact-rational ISA model, with |
| 1345 | the shrinking, skips and exit codes of `salu_diff.py`. Any NaN matches any NaN. It does not judge denormal operands | 1345 | the shrinking, skips and exit codes of `salu_diff.py`. Any NaN matches any NaN. It does not judge denormal operands |
| 1346 | or results, a computed NaN read as an integer, the clamp of a NaN or an output modifier that gives a zero: those | 1346 | or results, a computed NaN read as an integer, the clamp of a NaN, an output modifier that gives a zero, and the |
| 1347 | programs are counted as skips with the reason. | 1347 | class bits of a NaN whose quiet bit the model does not know (a `v_fmamk_f32` NaN, or a pass-through of one): those |
| 1348 | programs are counted as skips with the reason. The model knows a computed NaN's payload only for a quiet NaN; | ||
| 1349 | for `v_fmamk_f32` it assumes the quiet bit the arithmetic gives, while on gfx1036 under the game's MODE the | ||
| 1350 | hardware mostly returns the NaN source's word but sometimes quiets a signalling one (`f32_hw_s5.log`: signalling | ||
| 1351 | NaN passes unchanged 3 of 4, quieted 1 of 4), and a driver that quiets where the model does not changes the class | ||
| 1352 | bit a `v_cmp_class_f32` reads. That is why the fuzzed `sNaN -> v_fmamk_f32 -> v_cmp_class_f32` divergence was a | ||
| 1353 | model gap, not a translator bug: on both GPUs the translated bit matched what the hardware itself produces. | ||
| 1348 | 1354 | ||
| 1349 | `--oracle hw` runs the kernels under the MODE inferred for the game's shaders (IEEE off, f32 denormals flushed). With | 1355 | `--oracle hw` runs the kernels under the MODE inferred for the game's shaders (IEEE off, f32 denormals flushed). With |
| 1350 | the assembler's compute default (IEEE on) the hardware ignores `omod`: `v_fract_f32_e64 v4, -v16 mul:2` with v16 = 0.5 | 1356 | the assembler's compute default (IEEE on) the hardware ignores `omod`: `v_fract_f32_e64 v4, -v16 mul:2` with v16 = 0.5 |
diff --git a/docs/testing.md b/docs/testing.md index 635c700a6..ba91fb2af 100644 --- a/docs/testing.md +++ b/docs/testing.md | |||
| @@ -163,7 +163,7 @@ C++ `runtime/` tests are not run by it; use the fork's CI as above. | |||
| 163 | 163 | ||
| 164 | - **Python 3.12+**, which `make_game.py` requires (it stops with "Python 3.12 or newer is needed" on an older one, so | 164 | - **Python 3.12+**, which `make_game.py` requires (it stops with "Python 3.12 or newer is needed" on an older one, so |
| 165 | its tests fail there too). `scripts/run_gpu_tests.py` on its own runs on 3.10 or newer. | 165 | its tests fail there too). `scripts/run_gpu_tests.py` on its own runs on 3.10 or newer. |
| 166 | - **`llvm-mc` with the AMDGPU target** (LLVM 21+). The official LLVM Windows release has no AMDGPU target. On | 166 | - **`llvm-mc` with the AMDGPU target** (LLVM 21+ to assemble the test fixtures, 23+ for the `shaders` stage; see below). The official LLVM Windows release has no AMDGPU target. On |
| 167 | Windows, use one of: | 167 | Windows, use one of: |
| 168 | - `scripts\build_llvm_mc.ps1`, which builds a native `llvm-mc.exe` (needs git and the Visual Studio C++ tools); | 168 | - `scripts\build_llvm_mc.ps1`, which builds a native `llvm-mc.exe` (needs git and the Visual Studio C++ tools); |
| 169 | - conda-forge's `llvm-tools` package, whose Windows build includes the AMDGPU target; | 169 | - conda-forge's `llvm-tools` package, whose Windows build includes the AMDGPU target; |
| @@ -193,6 +193,13 @@ C++ `runtime/` tests are not run by it; use the fork's CI as above. | |||
| 193 | 193 | ||
| 194 | If it reports `not a valid operand`, point `LLVM_MC` at a build that accepts this instruction. The Windows | 194 | If it reports `not a valid operand`, point `LLVM_MC` at a build that accepts this instruction. The Windows |
| 195 | conda-forge `llvm-tools` 23.1.6 package assembled the same f16 programs. | 195 | conda-forge `llvm-tools` 23.1.6 package assembled the same f16 programs. |
| 196 | |||
| 197 | The `shaders` stage needs LLVM 23+ as well, for reasons that have nothing to do with the tests above: 840 of the | ||
| 198 | 2,684 compute programs in the pipeline library come out of LLVM 21.1.8's listings with 79,490 undecodable words, so | ||
| 199 | the translator refuses them (`fall-through into undecodable words`) and 1,844 of 2,684 reach the output. 23.1.5 | ||
| 200 | decodes those 840 with no rejected word and the stage translates 2,683 of 2,684 (the last is refused for | ||
| 201 | `s_sethalt`, which the translator does not implement); `scripts\build_llvm_mc.ps1` builds 23.1.5 by default | ||
| 202 | ([design.md](design.md), "Disassembling shaders"). | ||
| 196 | - **SPIRV-Tools** (`spirv-as`, `spirv-val`): part of the Vulkan SDK, or a distribution package. | 203 | - **SPIRV-Tools** (`spirv-as`, `spirv-val`): part of the Vulkan SDK, or a distribution package. |
| 197 | - **A C++20 compiler, CMake and the Vulkan headers** to build the test programs: | 204 | - **A C++20 compiler, CMake and the Vulkan headers** to build the test programs: |
| 198 | - Windows: the full runtime needs Visual Studio 2022 with "Desktop development with C++" and Windows SDK | 205 | - Windows: the full runtime needs Visual Studio 2022 with "Desktop development with C++" and Windows SDK |
| @@ -400,6 +407,18 @@ WINEPREFIX="$HOME/.local/share/leonida-wine" ctest --test-dir runtime/build/wind | |||
| 400 | Use a recent xwin: 0.10.0 lays out SDK 10.0.26100 with the command above, while 0.6.5 stops with "unable to find | 407 | Use a recent xwin: 0.10.0 lays out SDK 10.0.26100 with the command above, while 0.6.5 stops with "unable to find |
| 401 | x86_64 headers for Win11SDK_10.0.26100". | 408 | x86_64 headers for Win11SDK_10.0.26100". |
| 402 | 409 | ||
| 410 | On a Mac (Apple Silicon) the same steps work with Homebrew's LLVM and lld (`brew install llvm lld xwin`; the cross | ||
| 411 | tools are `clang-cl`, `lld-link`, `llvm-lib`, `llvm-rc` and `llvm-mt` under `$(brew --prefix)/opt/llvm/bin` and | ||
| 412 | `$(brew --prefix)/opt/lld/bin`) and the WineHQ macOS build, an x86-64 Wine that runs under Rosetta. Homebrew's | ||
| 413 | `wine-stable` cask is disabled (it does not pass Gatekeeper), so take the archive the cask names from its | ||
| 414 | `url` and check it against the cask's `sha256`. Configure with `-DCMAKE_CROSSCOMPILING_EMULATOR=<path to its wine>` | ||
| 415 | when `wine` is not on `PATH`; a path with spaces (`Wine Stable.app`) is easiest behind a small wrapper script. Run | ||
| 416 | `ctest` with `ROSETTA_ADVERTISE_AVX=1`: without it Rosetta hides AVX from Wine, and the `run_tiny_*` loader tests stop | ||
| 417 | with "the game's code needs AVX, and this CPU or OS lacks AVX, OSXSAVE". Measured on an Apple M3 (macOS 26.5.1, | ||
| 418 | Wine 11.0, its bundled MoltenVK 1.4.1) at `main` `fbf100b1b`: 1084 targets build, and `ctest -j 6 --timeout 120` | ||
| 419 | gives 461 of 482 passed (440 without `ROSETTA_ADVERTISE_AVX`). The display is the Mac's own, so no virtual X server | ||
| 420 | is needed. | ||
| 421 | |||
| 403 | On a machine without a display (a server, a container, WSL without WSLg), Wine has no graphics driver to create a | 422 | On a machine without a display (a server, a container, WSL without WSLg), Wine has no graphics driver to create a |
| 404 | Vulkan instance with, so every Vulkan test fails with `vkCreateInstance failed (VkResult -3)` and, with | 423 | Vulkan instance with, so every Vulkan test fails with `vkCreateInstance failed (VkResult -3)` and, with |
| 405 | `WINEDEBUG=+vulkan`, "Failed to load Wine graphics driver supporting Vulkan". Run the tests under a virtual X server, | 424 | `WINEDEBUG=+vulkan`, "Failed to load Wine graphics driver supporting Vulkan". Run the tests under a virtual X server, |
| @@ -985,6 +1004,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | |||
| 985 | | `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | | 1004 | | `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | |
| 986 | | `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | | 1005 | | `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | |
| 987 | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | | 1006 | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | |
| 1007 | | `ps_ssharp` fails on some Macs with MoltenVK 1.4.2 (an Apple M3, not an M5 Pro): `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` where `tools/vk_subgroup_info.py --lod-bias` measures that the sampler drops the bias (see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.26 cases | | ||
| 988 | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | | 1008 | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | |
| 989 | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | 1009 | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | |
| 990 | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | | 1010 | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | |
| @@ -998,6 +1018,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | |||
| 998 | | `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | | 1018 | | `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | |
| 999 | | `ps_cndmask_sign_mods` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x7fc00000, 0x7fc00000, 0x80000001, 0x7fc00000`, want `0xff800001, 0x7f800001, 0x80000001, 0x7f800001` | The same `nir_to_msl` NaN-constant path as `cs_bvh` above: the shader selects between `float` NaNs with sign and payload (`-NaN`, `+NaN`), and KosmicKrisp prints each such constant as `(NAN)` (`0x7fc00000`). Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; the same test passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | | 1019 | | `ps_cndmask_sign_mods` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x7fc00000, 0x7fc00000, 0x80000001, 0x7fc00000`, want `0xff800001, 0x7f800001, 0x80000001, 0x7f800001` | The same `nir_to_msl` NaN-constant path as `cs_bvh` above: the shader selects between `float` NaNs with sign and payload (`-NaN`, `+NaN`), and KosmicKrisp prints each such constant as `(NAN)` (`0x7fc00000`). Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; the same test passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | |
| 1000 | | `ps_valu16_mad_sel` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x8003, 0xdb880000, 0x7fc00000, 0x80000000`, want `0x8003, 0xdb880000, 0xffffffff, 0x80000000` | Same cause: a value the shader writes as `0xffffffff` (`-1`) reaches the render target as `0x7fc00000` because `nir_to_msl` types the shared register as `float` and prints the NaN-range constant as `(NAN)`. Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | | 1020 | | `ps_valu16_mad_sel` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x8003, 0xdb880000, 0x7fc00000, 0x80000000`, want `0x8003, 0xdb880000, 0xffffffff, 0x80000000` | Same cause: a value the shader writes as `0xffffffff` (`-1`) reaches the render target as `0x7fc00000` because `nir_to_msl` types the shared register as `float` and prints the NaN-range constant as `(NAN)`. Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | |
| 1021 | | `cs_fmt_all` fails on a Mac with KosmicKrisp: word 293 reads `0x80007e00`, want `0x80007c01` | The same `(NAN)` printing as the rows above, still in Mesa `main`: `emit_src_component` in `src/kosmickrisp/compiler/msl_type_inference.c` prints every `float`-typed NaN constant as `(NAN)`, dropping its payload and sign. Here the input `0x7f800001` of a 16-bit float store becomes `0x7fc00000`, which narrows to `0x7e00` instead of `0x7c01`. Measured on an Apple M3 (macOS 26.5.1) with Mesa 26.3.1 at `main` `a73a57e13` | Expected with KosmicKrisp; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) pass on the same machine. Do not weaken the expected words | | ||
| 1001 | | `cs_fma_fused` fails on a Mac with KosmicKrisp: word 7 reads `0x7352`, want `0x7351` | The f16 multiply-add (round to odd), computed at run time, comes out as if the product were rounded first: the exact product, 14988, is halfway between the f16 values 14984 (`0x7351`) and 14992 (`0x7352`), the addend is -2^-22, and one rounding gives `0x7351`. Measured on an Apple M3 with Mesa 26.3.1, 20 of 20 runs (the review of #1724). While the fixture's f16 operands were literals the constant was folded exactly, so the test passed there | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) give `0x7351` on the same machine. The f32 words KosmicKrisp splits are accepted under `--fma glsl`; the f16 word is not, since it does not use `Fma` | | 1022 | | `cs_fma_fused` fails on a Mac with KosmicKrisp: word 7 reads `0x7352`, want `0x7351` | The f16 multiply-add (round to odd), computed at run time, comes out as if the product were rounded first: the exact product, 14988, is halfway between the f16 values 14984 (`0x7351`) and 14992 (`0x7352`), the addend is -2^-22, and one rounding gives `0x7351`. Measured on an Apple M3 with Mesa 26.3.1, 20 of 20 runs (the review of #1724). While the fixture's f16 operands were literals the constant was folded exactly, so the test passed there | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) give `0x7351` on the same machine. The f32 words KosmicKrisp splits are accepted under `--fma glsl`; the f16 word is not, since it does not use `Fma` | |
| 1002 | | CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | | 1023 | | CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | |
| 1003 | | `scripts/build_runtime.ps1` stops at once: "The checkout path ... contains '%'" (`build_llvm_mc.ps1`: "-Temp ... contains '%'") | A `%` in the checkout's path (or in `-Temp`). cmd.exe expands `%...%` in the generated `_build.cmd` (twice on a `CALL` line), and even with that escaped, `cl` rejects a `%` in the path-valued `/D` definitions of the test targets (`D8038: invalid argument`) however it is quoted. Older scripts failed in configure or a few hundred steps into Ninja instead | Move or clone the checkout (or choose a `-Temp`) in a folder without `%` in its path | | 1024 | | `scripts/build_runtime.ps1` stops at once: "The checkout path ... contains '%'" (`build_llvm_mc.ps1`: "-Temp ... contains '%'") | A `%` in the checkout's path (or in `-Temp`). cmd.exe expands `%...%` in the generated `_build.cmd` (twice on a `CALL` line), and even with that escaped, `cl` rejects a `%` in the path-valued `/D` definitions of the test targets (`D8038: invalid argument`) however it is quoted. Older scripts failed in configure or a few hundred steps into Ninja instead | Move or clone the checkout (or choose a `-Temp`) in a folder without `%` in its path | |
diff --git a/make_game.py b/make_game.py index 1a97a5022..4d857315e 100644 --- a/make_game.py +++ b/make_game.py | |||
| @@ -1072,7 +1072,7 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N | |||
| 1072 | if "shaders" in stages: | 1072 | if "shaders" in stages: |
| 1073 | mc = mc_command()[0] | 1073 | mc = mc_command()[0] |
| 1074 | if not (os.path.isfile(mc) or shutil.which(mc)): | 1074 | if not (os.path.isfile(mc) or shutil.which(mc)): |
| 1075 | missing.append("llvm-mc (LLVM 21+ with the AMDGPU target). " + mc_install_hint().replace("\n", " ") | 1075 | missing.append("llvm-mc (LLVM 23+ with the AMDGPU target). " + mc_install_hint().replace("\n", " ") |
| 1076 | + " (docs/design.md)." + appdata_hint(mc)) | 1076 | + " (docs/design.md)." + appdata_hint(mc)) |
| 1077 | for t in ("spirv-as", "spirv-val"): | 1077 | for t in ("spirv-as", "spirv-val"): |
| 1078 | if not shutil.which(t): | 1078 | if not shutil.which(t): |
| @@ -2018,7 +2018,7 @@ FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--no-ftz32", " | |||
| 2018 | ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), | 2018 | ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), |
| 2019 | ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), | 2019 | ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), |
| 2020 | ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback"), | 2020 | ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback"), |
| 2021 | ("--mesh-serial-waves", "mesh_serial_waves")) | 2021 | ("--mesh-serial-waves", "mesh_serial_waves"), ("--explicit-lod-bias", "explicit_lod_bias")) |
| 2022 | 2022 | ||
| 2023 | 2023 | ||
| 2024 | def fallback_flags(a) -> tuple[str, ...]: | 2024 | def fallback_flags(a) -> tuple[str, ...]: |
| @@ -2169,6 +2169,19 @@ def runtime_gpu_info() -> dict: | |||
| 2169 | return {} | 2169 | return {} |
| 2170 | 2170 | ||
| 2171 | 2171 | ||
| 2172 | def runtime_gpu_explicit_lod_bias(): | ||
| 2173 | """explicit_lod_bias as tools/vk_subgroup_info.py --lod-bias measures it on the GPU the runtime would use (one | ||
| 2174 | compute dispatch): True where the sampler drops mipLodBias (MoltenVK on an Apple M3, not on an M5 Pro), False | ||
| 2175 | where it applies it, None when it can't tell.""" | ||
| 2176 | try: | ||
| 2177 | r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py"), "--lod-bias"], | ||
| 2178 | capture_output=True, text=True, timeout=60) | ||
| 2179 | v = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") | ||
| 2180 | return None if v is None else bool(v) | ||
| 2181 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | ||
| 2182 | return None | ||
| 2183 | |||
| 2184 | |||
| 2172 | def runtime_gpu_per_vertex(): | 2185 | def runtime_gpu_per_vertex(): |
| 2173 | """per_vertex_inputs as tools/vk_subgroup_info.py answers for the GPU the runtime would use: False where the | 2186 | """per_vertex_inputs as tools/vk_subgroup_info.py answers for the GPU the runtime would use: False where the |
| 2174 | driver can't compile PerVertexKHR (MoltenVK) or lacks fragmentShaderBarycentric, None when it can't tell.""" | 2187 | driver can't compile PerVertexKHR (MoltenVK) or lacks fragmentShaderBarycentric, None when it can't tell.""" |
| @@ -2780,7 +2793,9 @@ def assets(game: str, work: str, wav: bool, jobs: int, dump_jobs: int | None = N | |||
| 2780 | if need_ogg: | 2793 | if need_ogg: |
| 2781 | # Lossless: the banks' Opus packets repackaged as standard Ogg Opus files (PCM streams as .wav) | 2794 | # Lossless: the banks' Opus packets repackaged as standard Ogg Opus files (PCM streams as .wav) |
| 2782 | log("assets: audio streams -> Ogg Opus") | 2795 | log("assets: audio streams -> Ogg Opus") |
| 2783 | py("awc_opus.py", os.path.join(out, "audio", "awc"), ogg, "--jobs", str(jobs)) | 2796 | # A stopped run leaves most of the Ogg files written but no marker, so a restarted stage would repack every |
| 2797 | # bank from the beginning; --skip-existing makes that restart pick up where it stopped. | ||
| 2798 | py("awc_opus.py", os.path.join(out, "audio", "awc"), ogg, "--jobs", str(jobs), "--skip-existing") | ||
| 2784 | mark(ogg_done, "awc_opus.py") | 2799 | mark(ogg_done, "awc_opus.py") |
| 2785 | progress.tick(force=True) | 2800 | progress.tick(force=True) |
| 2786 | if need_wav: | 2801 | if need_wav: |
| @@ -3657,6 +3672,9 @@ def main() -> int: | |||
| 3657 | ap.add_argument("--texel-offset-fallback", action="store_true", | 3672 | ap.add_argument("--texel-offset-fallback", action="store_true", |
| 3658 | help="fold the run-time texel offset of image_sample*_o into the coordinate, for devices " | 3673 | help="fold the run-time texel offset of image_sample*_o into the coordinate, for devices " |
| 3659 | "without VK_KHR_maintenance8") | 3674 | "without VK_KHR_maintenance8") |
| 3675 | ap.add_argument("--explicit-lod-bias", action="store_true", | ||
| 3676 | help="apply the S# LOD bias in the shaders, for a driver whose sampler drops it; on by itself " | ||
| 3677 | "where tools/vk_subgroup_info.py --lod-bias measures that (MoltenVK on an Apple M3, not an M5 Pro)") | ||
| 3660 | ap.add_argument("--f16-interp-fallback", action="store_true", | 3678 | ap.add_argument("--f16-interp-fallback", action="store_true", |
| 3661 | help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " | 3679 | help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " |
| 3662 | "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") | 3680 | "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") |
| @@ -3768,6 +3786,14 @@ def main() -> int: | |||
| 3768 | a.f16_interp_fallback = True | 3786 | a.f16_interp_fallback = True |
| 3769 | elif per_vertex is None: | 3787 | elif per_vertex is None: |
| 3770 | a.f16_interp_fallback = keep_recorded_fallback("--f16-interp-fallback", work) | 3788 | a.f16_interp_fallback = keep_recorded_fallback("--f16-interp-fallback", work) |
| 3789 | if "shaders" in stages and not a.explicit_lod_bias: | ||
| 3790 | drops_bias = runtime_gpu_explicit_lod_bias() | ||
| 3791 | if drops_bias is True: | ||
| 3792 | log("shaders: tools/vk_subgroup_info.py --lod-bias measures that the GPU the runtime would use drops the " | ||
| 3793 | "sampler's LOD bias: translating with --explicit-lod-bias") | ||
| 3794 | a.explicit_lod_bias = True | ||
| 3795 | elif drops_bias is None: | ||
| 3796 | a.explicit_lod_bias = keep_recorded_fallback("--explicit-lod-bias", work) | ||
| 3771 | if "shaders" in stages: | 3797 | if "shaders" in stages: |
| 3772 | if a.bary_fallback: | 3798 | if a.bary_fallback: |
| 3773 | # Command-line precedence: --bary-fallback wins over LEONIDA_BARY_FALLBACK=0. | 3799 | # Command-line precedence: --bary-fallback wins over LEONIDA_BARY_FALLBACK=0. |
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 765b2611a..86ac03626 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -12,6 +12,20 @@ if(MSVC) | |||
| 12 | add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/utf-8>) | 12 | add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/utf-8>) |
| 13 | endif() | 13 | endif() |
| 14 | 14 | ||
| 15 | # A function that reaches its closing brace without returning is undefined behaviour: the caller reads | ||
| 16 | # whatever the register held. MSVC has two codes for it: C4716 when the function has no return at all, | ||
| 17 | # which is an error by default, and C4715 when some paths return and others do not, which is only a | ||
| 18 | # warning - at the default warning level, not just at /W4 (measured: cl /EHsc alone reports it). A change | ||
| 19 | # in this tree dropped a return out; from a function with early returns, so it was C4715, and a green | ||
| 20 | # build carried it. A full Release build of this commit reports none, so /we4715 costs nothing today and | ||
| 21 | # stops the next one. Not /we4716: that code is already an error. Not guarded to /W4 targets either, | ||
| 22 | # because C4715 is reported without /W4, which is exactly the third-party target that sets only /utf-8. | ||
| 23 | if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") | ||
| 24 | # Only C and C++, for the same reason /utf-8 above carries the filter: ml64 (abi_probe.asm) warns A4018 for a | ||
| 25 | # switch it does not know, and the C++ half still gets the error. | ||
| 26 | add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/we4715>) | ||
| 27 | endif() | ||
| 28 | |||
| 15 | if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) | 29 | if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) |
| 16 | message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") | 30 | message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") |
| 17 | endif() | 31 | endif() |
| @@ -413,6 +427,12 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 413 | target_compile_options(d3d12_xs_alloc_size_test PRIVATE /W4 /permissive- /utf-8) | 427 | target_compile_options(d3d12_xs_alloc_size_test PRIVATE /W4 /permissive- /utf-8) |
| 414 | target_link_options(d3d12_xs_alloc_size_test PRIVATE /OPT:NOREF) | 428 | target_link_options(d3d12_xs_alloc_size_test PRIVATE /OPT:NOREF) |
| 415 | 429 | ||
| 430 | # copy_elements of xg_xs_layout.h: fixed-width element copies against the runtime-sized loop, byte for byte. | ||
| 431 | add_executable(texel_copy_test test/texel_copy_test.cpp) | ||
| 432 | target_include_directories(texel_copy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 433 | target_compile_definitions(texel_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 434 | target_compile_options(texel_copy_test PRIVATE /W4 /permissive- /utf-8) | ||
| 435 | |||
| 416 | # acphal shim ABI test: resolves the registered acphal.dll exports through the registry. | 436 | # acphal shim ABI test: resolves the registered acphal.dll exports through the registry. |
| 417 | add_executable(acphal_test | 437 | add_executable(acphal_test |
| 418 | test/acphal_test.cpp | 438 | test/acphal_test.cpp |
| @@ -1878,6 +1898,7 @@ if(BUILD_TESTING) | |||
| 1878 | endif() | 1898 | endif() |
| 1879 | if(WIN32 AND TARGET xg_xs_test) | 1899 | if(WIN32 AND TARGET xg_xs_test) |
| 1880 | add_test(NAME xg_xs COMMAND xg_xs_test) | 1900 | add_test(NAME xg_xs COMMAND xg_xs_test) |
| 1901 | add_test(NAME texel_copy COMMAND texel_copy_test) | ||
| 1881 | endif() | 1902 | endif() |
| 1882 | if(WIN32 AND TARGET d3d12_xs_alloc_size_test) | 1903 | if(WIN32 AND TARGET d3d12_xs_alloc_size_test) |
| 1883 | add_test(NAME d3d12_xs_alloc_size COMMAND d3d12_xs_alloc_size_test) | 1904 | add_test(NAME d3d12_xs_alloc_size COMMAND d3d12_xs_alloc_size_test) |
| @@ -3010,8 +3031,10 @@ if(TARGET Vulkan::Headers) | |||
| 3010 | add_test(NAME d3d12_noop_copy COMMAND d3d12_noop_copy_test) | 3031 | add_test(NAME d3d12_noop_copy COMMAND d3d12_noop_copy_test) |
| 3011 | set_tests_properties(d3d12_noop_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45) | 3032 | set_tests_properties(d3d12_noop_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45) |
| 3012 | set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) | 3033 | set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) |
| 3034 | # The control pays the same device bring-up as the test above before it waits its 20 ms, so it gets the same | ||
| 3035 | # budget: a parallel ctest killed it at 10 s, and WILL_FAIL inverts an exit code but not a ***Timeout. | ||
| 3013 | add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control) | 3036 | add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control) |
| 3014 | set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10) | 3037 | set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 60) |
| 3015 | # Textures share blocks of device memory, and a reused range neither leaks old texels nor touches its neighbours. | 3038 | # Textures share blocks of device memory, and a reused range neither leaks old texels nor touches its neighbours. |
| 3016 | add_executable(d3d12_texture_memory_test test/d3d12_texture_memory_test.cpp) | 3039 | add_executable(d3d12_texture_memory_test test/d3d12_texture_memory_test.cpp) |
| 3017 | target_link_libraries(d3d12_texture_memory_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) | 3040 | target_link_libraries(d3d12_texture_memory_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) |
diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 2f0d42ec9..a5779419e 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | # The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py | 1 | # The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py, |
| 2 | # and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in | 2 | # tools/vk_subgroup_info.py, whose answer picks --bary-fallback, and tools/vk_lod_bias.py, which its --lod-bias |
| 3 | # make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer. | 3 | # measurement imports for --explicit-lod-bias). Track the shader-stage dependencies in make_game.py's |
| 4 | # TRANSLATION_SOURCES here too, including the native PSO catalog writer. | ||
| 4 | # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py | 5 | # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py |
| 5 | # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). | 6 | # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). |
| 6 | # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. | 7 | # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. |
| @@ -34,6 +35,7 @@ set(LEONIDA_TRANSLATOR_DEPS | |||
| 34 | ${_leonida_repo}/tools/spirv_loop_guard.py | 35 | ${_leonida_repo}/tools/spirv_loop_guard.py |
| 35 | ${_leonida_repo}/tools/spirv_opt.py | 36 | ${_leonida_repo}/tools/spirv_opt.py |
| 36 | ${_leonida_repo}/tools/spirv_stubs.py | 37 | ${_leonida_repo}/tools/spirv_stubs.py |
| 38 | ${_leonida_repo}/tools/vk_lod_bias.py | ||
| 37 | ${_leonida_repo}/tools/vk_subgroup_info.py | 39 | ${_leonida_repo}/tools/vk_subgroup_info.py |
| 38 | ${_leonida_repo}/tools/wave64_emulate_opt.py | 40 | ${_leonida_repo}/tools/wave64_emulate_opt.py |
| 39 | ${_leonida_repo}/tools/wave64_halves.py) | 41 | ${_leonida_repo}/tools/wave64_halves.py) |
diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h index b2b58576c..e3467c8d9 100644 --- a/runtime/shims/xg_xs_layout.h +++ b/runtime/shims/xg_xs_layout.h | |||
| @@ -408,6 +408,22 @@ private: | |||
| 408 | uint32_t axis_offset[3][256]{}; | 408 | uint32_t axis_offset[3][256]{}; |
| 409 | }; | 409 | }; |
| 410 | 410 | ||
| 411 | // One row of a tiled mip: element x lives `columns[x]` bytes after `tiled` in the console layout and `x * bytes` after | ||
| 412 | // `linear` in the row. `Width` is the element size as a compile-time constant (1/2/4/8/16), so each std::memcpy has a | ||
| 413 | // fixed size and the compiler emits one load and one store instead of a call. Width 0 keeps the runtime size, which is | ||
| 414 | // what every other element size (and the reference the tests compare against) uses. Both give the same bytes: only the | ||
| 415 | // way the size reaches memcpy differs, never the addresses. | ||
| 416 | template<bool Into, uint32_t Width, class Byte> | ||
| 417 | inline void copy_tiled_row(const Byte* source, Byte* destination, uint64_t tiled, uint64_t linear, | ||
| 418 | const uint64_t* columns, uint32_t count, uint32_t runtime_bytes) { | ||
| 419 | const uint32_t bytes = Width ? Width : runtime_bytes; | ||
| 420 | for (uint32_t x = 0; x < count; ++x) { | ||
| 421 | const uint64_t at = tiled + columns[x]; | ||
| 422 | const uint64_t to = linear + uint64_t(x) * bytes; | ||
| 423 | std::memcpy(destination + (Into ? at : to), source + (Into ? to : at), bytes); | ||
| 424 | } | ||
| 425 | } | ||
| 426 | |||
| 411 | // The element copy behind XG's CopyIntoSubresource / CopyFromSubresource (xg_xs.cpp) and the D3D12 layer's fill of | 427 | // The element copy behind XG's CopyIntoSubresource / CopyFromSubresource (xg_xs.cpp) and the D3D12 layer's fill of |
| 412 | // textures the title keeps in its own memory (d3d12_vulkan_device.cpp, TitleTextures): one mip of one array slice | 428 | // textures the title keeps in its own memory (d3d12_vulkan_device.cpp, TitleTextures): one mip of one array slice |
| 413 | // between the console layout (`tiled`, from the texture's base) and linear rows of elements `row_pitch` bytes apart, | 429 | // between the console layout (`tiled`, from the texture's base) and linear rows of elements `row_pitch` bytes apart, |
| @@ -432,10 +448,16 @@ inline void copy_elements(const Texture& t, uint32_t level, uint32_t slice, cons | |||
| 432 | std::memcpy(destination + (Into ? tiled : linear), source + (Into ? linear : tiled), row_bytes); | 448 | std::memcpy(destination + (Into ? tiled : linear), source + (Into ? linear : tiled), row_bytes); |
| 433 | continue; | 449 | continue; |
| 434 | } | 450 | } |
| 435 | for (uint32_t x = 0; x < mip.width_elements; ++x) { | 451 | // Dispatch on the element size once per row; sizes other than 1/2/4/8/16 take the runtime-size loop. |
| 436 | const uint64_t at = tiled + columns[x]; | 452 | const uint64_t* const column = columns.data(); |
| 437 | const uint64_t to = linear + uint64_t(x) * bytes; | 453 | const uint32_t count = mip.width_elements; |
| 438 | std::memcpy(destination + (Into ? at : to), source + (Into ? to : at), bytes); | 454 | switch (bytes) { |
| 455 | case 1: copy_tiled_row<Into, 1>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 456 | case 2: copy_tiled_row<Into, 2>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 457 | case 4: copy_tiled_row<Into, 4>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 458 | case 8: copy_tiled_row<Into, 8>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 459 | case 16: copy_tiled_row<Into, 16>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 460 | default: copy_tiled_row<Into, 0>(source, destination, tiled, linear, column, count, bytes); break; | ||
| 439 | } | 461 | } |
| 440 | } | 462 | } |
| 441 | } | 463 | } |
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 002baa4d1..2891fc6a1 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py | |||
| @@ -133,6 +133,23 @@ def asm_mattr(path): | |||
| 133 | CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} | 133 | CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} |
| 134 | 134 | ||
| 135 | 135 | ||
| 136 | def explicit_lod_bias(): | ||
| 137 | """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0). Unset, it is on where tools/vk_subgroup_info.py --lod-bias measures that | ||
| 138 | the sampler drops mipLodBias (one compute dispatch from Python, no test programs needed), the rule of | ||
| 139 | scripts/run_gpu_tests.py. No answer leaves it off.""" | ||
| 140 | v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() | ||
| 141 | if v in ("1", "true", "yes", "on"): | ||
| 142 | return True | ||
| 143 | if v in ("0", "false", "no", "off"): | ||
| 144 | return False | ||
| 145 | try: | ||
| 146 | r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py"), "--lod-bias"], | ||
| 147 | capture_output=True, text=True, timeout=60) | ||
| 148 | return json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") is True | ||
| 149 | except (OSError, ValueError, IndexError, AttributeError, subprocess.SubprocessError): | ||
| 150 | return False | ||
| 151 | |||
| 152 | |||
| 136 | def asm_fssm_fields(path): | 153 | def asm_fssm_fields(path): |
| 137 | """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" | 154 | """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" |
| 138 | at, words = None, [] | 155 | at, words = None, [] |
| @@ -237,6 +254,8 @@ def translate_tests(work, names, gpu_flags=None): | |||
| 237 | cmd += ["--fma", os.environ["LEONIDA_FMA"]] | 254 | cmd += ["--fma", os.environ["LEONIDA_FMA"]] |
| 238 | if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8 | 255 | if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8 |
| 239 | cmd.append("--texel-offset-fallback") | 256 | cmd.append("--texel-offset-fallback") |
| 257 | if explicit_lod_bias(): # the S# LOD bias in the shader, where the sampler drops it (LEONIDA_EXPLICIT_LOD_BIAS) | ||
| 258 | cmd.append("--explicit-lod-bias") | ||
| 240 | # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). | 259 | # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). |
| 241 | if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): | 260 | if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): |
| 242 | cmd.append("--pc-tail-ubo") | 261 | cmd.append("--pc-tail-ubo") |
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 713f8f182..544f79a45 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py | |||
| @@ -137,7 +137,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm | |||
| 137 | "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", | 137 | "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", |
| 138 | "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", | 138 | "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", |
| 139 | "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", | 139 | "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", |
| 140 | "cs_w32_exec_computed") | 140 | "cs_w32_exec_computed", "cs_exec_copy") |
| 141 | # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is | 141 | # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is |
| 142 | # narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with | 142 | # narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with |
| 143 | # 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may | 143 | # 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may |
| @@ -146,7 +146,7 @@ WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} | |||
| 146 | WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", | 146 | WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", |
| 147 | "cs_w32_cvt_f16_mods", | 147 | "cs_w32_cvt_f16_mods", |
| 148 | "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", | 148 | "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", |
| 149 | "cs_w32_exec_computed") | 149 | "cs_w32_exec_computed", "cs_exec_copy") |
| 150 | CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), | 150 | CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), |
| 151 | ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), | 151 | ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), |
| 152 | ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), | 152 | ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), |
| @@ -241,7 +241,11 @@ CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), | |||
| 241 | ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]), | 241 | ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]), |
| 242 | # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR) | 242 | # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR) |
| 243 | ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, | 243 | ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, |
| 244 | 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF])] | 244 | 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF]), |
| 245 | # EXEC restored through an SGPR copy keeps the narrowing's identity: the mask word still | ||
| 246 | # gathers (cs_exec_copy.asm header); out[1] is exec_lo's own word, 0xFFFFFFFF | ||
| 247 | ("cs_exec_copy", [0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 0, | ||
| 248 | 0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 1])] | ||
| 245 | # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. | 249 | # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. |
| 246 | # The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. | 250 | # The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. |
| 247 | # Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. | 251 | # Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. |
| @@ -1642,6 +1646,10 @@ SAMPLER_CASES = [("point", ssharp_words(1), (0, 1)), # 0 / | |||
| 1642 | ("point min_lod 1", ssharp_words(1, min_lod=1), (0, 1)), # 1 / 1: MIN_LOD clamps an explicit LOD too | 1646 | ("point min_lod 1", ssharp_words(1, min_lod=1), (0, 1)), # 1 / 1: MIN_LOD clamps an explicit LOD too |
| 1643 | ("point bias +1", ssharp_words(1, bias=1), (0, 1)), # 1 / 1: the S# bias applies to an explicit LOD | 1647 | ("point bias +1", ssharp_words(1, bias=1), (0, 1)), # 1 / 1: the S# bias applies to an explicit LOD |
| 1644 | ("point bias -1", ssharp_words(1, bias=-1), (0, 1)), # 0 / 0 | 1648 | ("point bias -1", ssharp_words(1, bias=-1), (0, 1)), # 0 / 0 |
| 1649 | # +-0.26 keeps LOD 0 / 1 on levels 0 / 1; the bias counted twice (+-0.52) moves one of them. | ||
| 1650 | # Not +-0.3: NVIDIA moves NEAREST to level 1 at about +0.289 (Vulkan allows 0.25..0.5) | ||
| 1651 | ("point bias +0.26", ssharp_words(1, bias=0.26), (0, 1)), # 0 / 1 | ||
| 1652 | ("point bias -0.26", ssharp_words(1, bias=-0.26), (0, 1)), # 0 / 1 | ||
| 1645 | ("none", ssharp_words(0), (0, 1)), # 0 / 0: MIP_FILTER_NONE reads the base level | 1653 | ("none", ssharp_words(0), (0, 1)), # 0 / 0: MIP_FILTER_NONE reads the base level |
| 1646 | ("none min_lod 1", ssharp_words(0, min_lod=1), (0, 1)), # 0 / 0: and ignores the LOD clamp | 1654 | ("none min_lod 1", ssharp_words(0, min_lod=1), (0, 1)), # 0 / 0: and ignores the LOD clamp |
| 1647 | ("point base 1", ssharp_words(1), (1, 1))] # 1 / 1: the T#'s BASE_LEVEL starts the view | 1655 | ("point base 1", ssharp_words(1), (1, 1))] # 1 / 1: the T#'s BASE_LEVEL starts the view |
| @@ -1684,10 +1692,40 @@ def sampler_mismatch(data, words, view): | |||
| 1684 | return "" | 1692 | return "" |
| 1685 | 1693 | ||
| 1686 | 1694 | ||
| 1687 | def sampler_test(tools, spirv): | 1695 | def sampler_compare_mismatch(data, words, view): |
| 1688 | """ps_ssharp: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by sampler_level. | 1696 | """ps_ssharp_c: the first pixel whose (c_lz, c_lz, c, c) is not the compare result of the level the S# and T# |
| 1689 | A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at each pixel.""" | 1697 | select (vk_sampler_test --dref: depth 0.25 in level 0 and 0.75 in level 1, reference 0.5, LESS_EQUAL), or "".""" |
| 1690 | shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_ssharp")] | 1698 | if len(data) != SAMPLER_SIZE ** 2 * 16: |
| 1699 | return f"expected {SAMPLER_SIZE ** 2} RGBA32F pixels, got {len(data)} bytes" | ||
| 1700 | explicit, implicit = (float(sampler_level(words, view, lod) == 1) for lod in (0, 1)) | ||
| 1701 | want = (explicit, explicit, implicit, implicit) | ||
| 1702 | for i, got in enumerate(struct.iter_unpack("<4f", data)): | ||
| 1703 | if any(not math.isclose(g, w, rel_tol=0, abs_tol=1e-6) for g, w in zip(got, want)): | ||
| 1704 | y, x = divmod(i, SAMPLER_SIZE) | ||
| 1705 | return f"({x},{y}): {tuple(round(g, 4) for g in got)} != {want}" | ||
| 1706 | return "" | ||
| 1707 | |||
| 1708 | |||
| 1709 | # The pixel shaders judged by sampler_test and the vk_sampler_test mode each needs. Each writes an explicit-LOD-0 sample | ||
| 1710 | # and an LOD-1 sample, so the same SAMPLER_CASES expectations hold for all: ps_ssharp (image_sample_lz and | ||
| 1711 | # image_sample), ps_ssharp_ld (image_sample_l and image_sample_d), ps_ssharp_b (image_sample_lz and image_sample_b), | ||
| 1712 | # ps_ssharp_cube and ps_ssharp_3d (image_sample_lz and image_sample on a cube and a volume) and ps_ssharp_c | ||
| 1713 | # (image_sample_c_lz and image_sample_c on a depth texture, judged as compare results); ps_ssharp_o (image_sample_lz_o | ||
| 1714 | # and image_sample_o) runs only under LEONIDA_TEXOFF_FALLBACK=1, its Grad derivatives being what it checks. | ||
| 1715 | SAMPLER_FIXTURES = {"ps_ssharp": (), "ps_ssharp_ld": (), "ps_ssharp_b": (), "ps_ssharp_cube": ("--cube",), | ||
| 1716 | "ps_ssharp_3d": ("--3d",), "ps_ssharp_c": ("--dref",), "ps_ssharp_o": ()} | ||
| 1717 | SSHARP_LESS_EQUAL = 3 << 12 # S# word 0 DEPTH_COMPARE_FUNC [14:12] = LESS_EQUAL (Vulkan's VK_COMPARE_OP_LESS_OR_EQUAL) | ||
| 1718 | |||
| 1719 | |||
| 1720 | def sampler_test(tools, spirv, ps="ps_ssharp"): | ||
| 1721 | """A SAMPLER_FIXTURES shader: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by | ||
| 1722 | sampler_level. A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at | ||
| 1723 | each pixel; ps_ssharp_c's compare reads 0 on level 0 and 1 on level 1.""" | ||
| 1724 | mode = SAMPLER_FIXTURES[ps] | ||
| 1725 | dref = "--dref" in mode | ||
| 1726 | if ps == "ps_ssharp_o" and os.environ.get("LEONIDA_TEXOFF_FALLBACK") != "1": | ||
| 1727 | return Skip("SKIP (needs LEONIDA_TEXOFF_FALLBACK=1: vk_sampler_test enables no VK_KHR_maintenance8)") | ||
| 1728 | shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", ps)] | ||
| 1691 | for path in shaders: | 1729 | for path in shaders: |
| 1692 | if not os.path.isfile(path): | 1730 | if not os.path.isfile(path): |
| 1693 | return f"missing {os.path.basename(path)}" | 1731 | return f"missing {os.path.basename(path)}" |
| @@ -1695,14 +1733,16 @@ def sampler_test(tools, spirv): | |||
| 1695 | for name, words, view in SAMPLER_CASES: | 1733 | for name, words, view in SAMPLER_CASES: |
| 1696 | raw = Path(tmp) / "pixels.raw" | 1734 | raw = Path(tmp) / "pixels.raw" |
| 1697 | raw.unlink(missing_ok=True) | 1735 | raw.unlink(missing_ok=True) |
| 1698 | code, out = run(os.path.join(tools, "vk_sampler_test" + EXE), *shaders, raw, | 1736 | if dref: |
| 1737 | words = (words[0] | SSHARP_LESS_EQUAL, *words[1:]) | ||
| 1738 | code, out = run(os.path.join(tools, "vk_sampler_test" + EXE), *mode, *shaders, raw, | ||
| 1699 | *(f"{w:x}" for w in words), *(str(v) for v in view)) | 1739 | *(f"{w:x}" for w in words), *(str(v) for v in view)) |
| 1700 | if code == UNSUPPORTED: | 1740 | if code == UNSUPPORTED: |
| 1701 | m = re.search(r"unsupported: .*", out) | 1741 | m = re.search(r"unsupported: .*", out) |
| 1702 | return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") | 1742 | return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") |
| 1703 | if code or not raw.is_file(): | 1743 | if code or not raw.is_file(): |
| 1704 | return f"{name}: {failure(code, out, 3)}" | 1744 | return f"{name}: {failure(code, out, 3)}" |
| 1705 | problem = sampler_mismatch(raw.read_bytes(), words, view) | 1745 | problem = (sampler_compare_mismatch if dref else sampler_mismatch)(raw.read_bytes(), words, view) |
| 1706 | if problem: | 1746 | if problem: |
| 1707 | return f"{name}: {problem}" | 1747 | return f"{name}: {problem}" |
| 1708 | return "" | 1748 | return "" |
| @@ -2372,7 +2412,8 @@ def main(): | |||
| 2372 | results.append((name, texture_constant_test(tools, spirv, name))) | 2412 | results.append((name, texture_constant_test(tools, spirv, name))) |
| 2373 | results.append(("vs_base_ids", base_ids_test(tools, spirv))) | 2413 | results.append(("vs_base_ids", base_ids_test(tools, spirv))) |
| 2374 | results.append(("ps_tex", bindless_test(tools, spirv))) | 2414 | results.append(("ps_tex", bindless_test(tools, spirv))) |
| 2375 | results.append(("ps_ssharp", sampler_test(tools, spirv))) | 2415 | for name in SAMPLER_FIXTURES: |
| 2416 | results.append((name, sampler_test(tools, spirv, name))) | ||
| 2376 | results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) | 2417 | results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) |
| 2377 | for name in MIP_TEST_PASSES: | 2418 | for name in MIP_TEST_PASSES: |
| 2378 | results.append((name, texture_mip_test(tools, spirv, name))) | 2419 | results.append((name, texture_mip_test(tools, spirv, name))) |
diff --git a/runtime/test/shaders/cs_exec_copy.asm b/runtime/test/shaders/cs_exec_copy.asm new file mode 100644 index 000000000..8fb72dfa6 --- /dev/null +++ b/runtime/test/shaders/cs_exec_copy.asm | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | ; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm | ||
| 2 | ; EXEC restored through an SGPR copy keeps the narrowing's identity (mask-regs EXEC tracking, #1397 review): | ||
| 3 | ; s7 = 0xffffffff comes from v_readfirstlane_b32, so the translator can't fold it; s_mov_b32 exec_lo, s7 is an | ||
| 4 | ; EXEC write the analysis can only name as an unknown narrowing. s8 = the odd-lane mask is written under it, | ||
| 5 | ; s4 = exec_lo / exec_lo = s4 round-trips EXEC through an SGPR unchanged, and the mask-word read must still | ||
| 6 | ; gather — lanes return the wave's mask word, not this lane's 0 / ~0 bit, exactly as s_mov_b32 exec_lo, -1 gives. | ||
| 7 | ; Before the fix the copy lost the narrowing's tag, the restore minted a fresh one, mask_exec_sigs coverage | ||
| 8 | ; failed and every lane stored its own bit (0 or ~0) instead of 0xAAAAAAAA. | ||
| 9 | ; Per lane (stride 16 bytes): out[0] = s8's mask word after the SGPR round-trip (0xAAAAAAAA), | ||
| 10 | ; out[1] = exec_lo's word (0xFFFFFFFF: EXEC really is all-ones), out[2] = the same mask word after the | ||
| 11 | ; literal -1 restore, out[3] = the lane id. | ||
| 12 | ; Lane 0 stores words 0..3, lane 1 words 4..7 (checked by the dump's first eight words). | ||
| 13 | ; group: 32,1,1 | ||
| 14 | ; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_exec_copy.spv 1 dump -> out[0..7] = aaaaaaaa ffffffff aaaaaaaa 0 aaaaaaaa ffffffff aaaaaaaa 1 | ||
| 15 | ; mattr: +wavefrontsize32,-wavefrontsize64 | ||
| 16 | v_mov_b32_e32 v7, -1 | ||
| 17 | v_readfirstlane_b32 s7, v7 | ||
| 18 | s_mov_b32 exec_lo, s7 | ||
| 19 | v_and_b32 v1, 1, v0 | ||
| 20 | v_cmp_ne_u32_e64 s8, v1, 0 | ||
| 21 | s_mov_b32 s4, exec_lo | ||
| 22 | s_mov_b32 exec_lo, s4 | ||
| 23 | v_mov_b32_e32 v2, s8 | ||
| 24 | v_mov_b32_e32 v4, exec_lo | ||
| 25 | s_mov_b32 exec_lo, -1 | ||
| 26 | v_mov_b32_e32 v5, s8 | ||
| 27 | v_lshlrev_b32_e32 v3, 4, v0 | ||
| 28 | v_mov_b32_e32 v20, v2 | ||
| 29 | v_mov_b32_e32 v21, v3 | ||
| 30 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 31 | v_mov_b32_e32 v20, v4 | ||
| 32 | v_add_nc_u32_e32 v21, 4, v3 | ||
| 33 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 34 | v_mov_b32_e32 v20, v5 | ||
| 35 | v_add_nc_u32_e32 v21, 8, v3 | ||
| 36 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 37 | v_mov_b32_e32 v20, v0 | ||
| 38 | v_add_nc_u32_e32 v21, 12, v3 | ||
| 39 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 40 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_3d.asm b/runtime/test/shaders/ps_ssharp_3d.asm new file mode 100644 index 000000000..d1284ce9e --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_3d.asm | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | ; The S# mip fields on a 3D sample, as ps_ssharp.asm does them on 2D (--explicit-lod-bias on images_3d, binding 6). | ||
| 2 | ; Same descriptor path and target: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. | ||
| 3 | ; Run: vk_sampler_test --3d vs_ids.spv ps_ssharp_3d.spv out.raw <S# words> [<base level> <last level>] | ||
| 4 | ; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_3d")). The volume is 128x128x2 then 64x64x1 with every | ||
| 5 | ; slice the same, sampled at (u, v, 0.25): the third coordinate doesn't vary across the target, so image_sample sees | ||
| 6 | ; LOD 1 and image_sample_lz LOD 0, as in ps_ssharp. -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g). | ||
| 7 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 8 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 9 | s_waitcnt lgkmcnt(0) | ||
| 10 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 11 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 12 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 13 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 14 | v_mov_b32_e32 v10, v2 | ||
| 15 | v_mov_b32_e32 v11, v3 | ||
| 16 | v_mov_b32_e32 v12, 0.25 | ||
| 17 | image_sample v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_3D | ||
| 18 | image_sample_lz v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_3D | ||
| 19 | s_waitcnt vmcnt(0) | ||
| 20 | exp mrt0 v4, v5, v6, v7 done vm | ||
| 21 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_b.asm b/runtime/test/shaders/ps_ssharp_b.asm new file mode 100644 index 000000000..92042abd5 --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_b.asm | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | ; The S# mip fields on image_sample_b, the implicit form with a bias in the address, which ps_ssharp doesn't run. | ||
| 2 | ; Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# | ||
| 3 | ; (4 dwords) 32 bytes after it. | ||
| 4 | ; Run: vk_sampler_test vs_ids.spv ps_ssharp_b.spv out.raw <S# words> [<base level> <last level>] (check.py: | ||
| 5 | ; SAMPLER_CASES, through sampler_test(..., "ps_ssharp_b")) | ||
| 6 | ; image_sample_lz as in ps_ssharp, then image_sample_b with an address bias of 0 (v4): it sees LOD 1 like | ||
| 7 | ; ps_ssharp's implicit sample, so check.py judges (lz.r, lz.g, b.r, b.g) exactly like ps_ssharp's, and the S#'s | ||
| 8 | ; LOD_BIAS adds to the address bias. | ||
| 9 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 10 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 11 | s_waitcnt lgkmcnt(0) | ||
| 12 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 13 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 14 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 15 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 16 | v_mov_b32_e32 v10, 0 | ||
| 17 | v_mov_b32_e32 v11, v2 | ||
| 18 | v_mov_b32_e32 v12, v3 | ||
| 19 | image_sample_b v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 20 | image_sample_lz v[4:5], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 21 | s_waitcnt vmcnt(0) | ||
| 22 | exp mrt0 v4, v5, v6, v7 done vm | ||
| 23 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_c.asm b/runtime/test/shaders/ps_ssharp_c.asm new file mode 100644 index 000000000..b8f6a6119 --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_c.asm | |||
| @@ -0,0 +1,22 @@ | |||
| 1 | ; The S# mip fields on depth-compare samples, image_sample_c_lz and image_sample_c (--explicit-lod-bias's _c forms). | ||
| 2 | ; Same descriptor path and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) | ||
| 3 | ; 32 bytes after it; the S# carries DEPTH_COMPARE_FUNC = LESS_EQUAL. | ||
| 4 | ; Run: vk_sampler_test --dref vs_ids.spv ps_ssharp_c.spv out.raw <S# words> [<base level> <last level>] | ||
| 5 | ; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_c"), with the compare function added). The D32 texture | ||
| 6 | ; holds 0.25 in level 0 and 0.75 in level 1, and the reference is 0.5: a compare reads 0 on level 0 and 1 on level 1. | ||
| 7 | ; image_sample_c_lz is at LOD 0 and image_sample_c at LOD 1, as in ps_ssharp. -> mrt0 = (c_lz, c_lz, c, c). | ||
| 8 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 9 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 10 | s_waitcnt lgkmcnt(0) | ||
| 11 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 12 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 13 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 14 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 15 | v_mov_b32_e32 v10, 0.5 | ||
| 16 | v_mov_b32_e32 v11, v2 | ||
| 17 | v_mov_b32_e32 v12, v3 | ||
| 18 | image_sample_c v6, v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D | ||
| 19 | image_sample_c_lz v4, v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D | ||
| 20 | s_waitcnt vmcnt(0) | ||
| 21 | exp mrt0 v4, v4, v6, v6 done vm | ||
| 22 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_cube.asm b/runtime/test/shaders/ps_ssharp_cube.asm new file mode 100644 index 000000000..7b97b358f --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_cube.asm | |||
| @@ -0,0 +1,22 @@ | |||
| 1 | ; The S# mip fields on a cube sample, as ps_ssharp.asm does them on 2D (--explicit-lod-bias on images_arr, binding 3). | ||
| 2 | ; Same descriptor path and target: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. | ||
| 3 | ; Run: vk_sampler_test --cube vs_ids.spv ps_ssharp_cube.spv out.raw <S# words> [<base level> <last level>] | ||
| 4 | ; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_cube")). The cube face coordinates are the way the | ||
| 5 | ; hardware takes them, s, t = 1 + (u, v) on face 0 (ps_cube_sample.asm), so face 0 is read exactly where ps_ssharp | ||
| 6 | ; reads the 2D texture: image_sample_lz at LOD 0 and image_sample at LOD 1. Every face holds the same levels. | ||
| 7 | ; -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g), judged like ps_ssharp. | ||
| 8 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 9 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 10 | s_waitcnt lgkmcnt(0) | ||
| 11 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 12 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 13 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 14 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 15 | v_add_f32_e32 v10, 1.0, v2 | ||
| 16 | v_add_f32_e32 v11, 1.0, v3 | ||
| 17 | v_mov_b32_e32 v12, 0 | ||
| 18 | image_sample v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_CUBE | ||
| 19 | image_sample_lz v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_CUBE | ||
| 20 | s_waitcnt vmcnt(0) | ||
| 21 | exp mrt0 v4, v5, v6, v7 done vm | ||
| 22 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_ld.asm b/runtime/test/shaders/ps_ssharp_ld.asm new file mode 100644 index 000000000..9895301dc --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_ld.asm | |||
| @@ -0,0 +1,30 @@ | |||
| 1 | ; The S# mip fields on the two explicit forms ps_ssharp doesn't run: image_sample_l (an LOD in the address) and | ||
| 2 | ; image_sample_d (gradients in the address). Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the | ||
| 3 | ; console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. | ||
| 4 | ; Run: vk_sampler_test vs_ids.spv ps_ssharp_ld.spv out.raw <S# words> [<base level> <last level>] (check.py: | ||
| 5 | ; SAMPLER_CASES, through sampler_test(..., "ps_ssharp_ld")) | ||
| 6 | ; image_sample_l takes LOD 0 from v18. image_sample_d takes dU/dx = dV/dy = 1/64 and dU/dy = dV/dx = 0 (v8..v11, then U and V in v12, v13): | ||
| 7 | ; on the 128x128 level 0 that is two texels per pixel, LOD 1, which is what ps_ssharp's implicit sample sees on the | ||
| 8 | ; 64x64 target. So check.py judges (l.r, l.g, d.r, d.g) exactly like ps_ssharp's (lz.r, lz.g, implicit.r, | ||
| 9 | ; implicit.g), and the S#'s LOD_BIAS, MIN_LOD, MAX_LOD and MIP_FILTER apply to both forms. | ||
| 10 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 11 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 12 | s_waitcnt lgkmcnt(0) | ||
| 13 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 14 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 15 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 16 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 17 | v_mov_b32_e32 v16, v2 | ||
| 18 | v_mov_b32_e32 v17, v3 | ||
| 19 | v_mov_b32_e32 v18, 0 | ||
| 20 | v_mov_b32_e32 v8, 0x3c800000 | ||
| 21 | v_mov_b32_e32 v9, 0 | ||
| 22 | v_mov_b32_e32 v10, 0 | ||
| 23 | v_mov_b32_e32 v11, 0x3c800000 | ||
| 24 | v_mov_b32_e32 v12, v2 | ||
| 25 | v_mov_b32_e32 v13, v3 | ||
| 26 | image_sample_l v[4:5], v[16:18], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 27 | image_sample_d v[6:7], v[8:13], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 28 | s_waitcnt vmcnt(0) | ||
| 29 | exp mrt0 v4, v5, v6, v7 done vm | ||
| 30 | s_endpgm | ||
diff --git a/runtime/test/shaders/ps_ssharp_o.asm b/runtime/test/shaders/ps_ssharp_o.asm new file mode 100644 index 000000000..d2f948e5b --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_o.asm | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | ; The S# mip fields on the texel-offset forms under --texel-offset-fallback, where the offset is folded into the | ||
| 2 | ; coordinate and an implicit sample becomes a Grad sample (the derivatives --explicit-lod-bias scales). | ||
| 3 | ; Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# | ||
| 4 | ; (4 dwords) 32 bytes after it. | ||
| 5 | ; Run: vk_sampler_test vs_ids.spv ps_ssharp_o.spv out.raw <S# words> [<base level> <last level>] with the shaders | ||
| 6 | ; translated under LEONIDA_TEXOFF_FALLBACK=1 (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_o"); it | ||
| 7 | ; is a SKIP otherwise, since vk_sampler_test doesn't enable VK_KHR_maintenance8 for a non-constant Offset). | ||
| 8 | ; image_sample_lz_o and image_sample_o with an offset dword of 0 (v10), so the texels are ps_ssharp's: | ||
| 9 | ; -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g), judged like ps_ssharp. | ||
| 10 | s_load_dwordx8 s[8:15], s[0:1], 0x0 | ||
| 11 | s_load_dwordx4 s[16:19], s[0:1], 0x20 | ||
| 12 | s_waitcnt lgkmcnt(0) | ||
| 13 | v_interp_p1_f32_e32 v2, v0, attr0.x | ||
| 14 | v_interp_p2_f32_e32 v2, v1, attr0.x | ||
| 15 | v_interp_p1_f32_e32 v3, v0, attr0.y | ||
| 16 | v_interp_p2_f32_e32 v3, v1, attr0.y | ||
| 17 | v_mov_b32_e32 v10, 0 | ||
| 18 | v_mov_b32_e32 v11, v2 | ||
| 19 | v_mov_b32_e32 v12, v3 | ||
| 20 | image_sample_o v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 21 | image_sample_lz_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D | ||
| 22 | s_waitcnt vmcnt(0) | ||
| 23 | exp mrt0 v4, v5, v6, v7 done vm | ||
| 24 | s_endpgm | ||
diff --git a/runtime/test/texel_copy_test.cpp b/runtime/test/texel_copy_test.cpp new file mode 100644 index 000000000..09ee3bdf5 --- /dev/null +++ b/runtime/test/texel_copy_test.cpp | |||
| @@ -0,0 +1,157 @@ | |||
| 1 | // copy_elements (shims/xg_xs_layout.h) copies each texel or block with a compile-time-sized memcpy for element sizes | ||
| 2 | // 1/2/4/8/16 and with a runtime-sized one for every other size. This compares it, byte for byte over the whole | ||
| 3 | // destination buffer, with the original runtime-sized loop kept here as the reference: tiled and linear layouts, every | ||
| 4 | // mip (tails included), array slices, volumes, both directions, and unaligned pointers and pitches. Synthetic textures | ||
| 5 | // only; no game files and no GPU. | ||
| 6 | #include <cstdint> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | #include "xg_xs_layout.h" | ||
| 12 | |||
| 13 | namespace { | ||
| 14 | |||
| 15 | using namespace rt::xg_xs; | ||
| 16 | |||
| 17 | int g_checks = 0, g_failures = 0; | ||
| 18 | |||
| 19 | void check(bool condition, const char* what) { | ||
| 20 | ++g_checks; | ||
| 21 | if (condition) return; | ||
| 22 | ++g_failures; | ||
| 23 | std::printf("FAIL: %s\n", what); | ||
| 24 | } | ||
| 25 | |||
| 26 | // The loop as it was before the element size was dispatched: std::memcpy with `bytes` read at run time. | ||
| 27 | template<bool Into, class Byte> | ||
| 28 | void reference_copy(const Texture& t, uint32_t level, uint32_t slice, const Byte* source, Byte* destination, | ||
| 29 | uint32_t row_pitch, uint32_t slice_pitch, std::vector<uint64_t>& columns) { | ||
| 30 | const auto& mip = t.layout.plane[0].mips[level]; | ||
| 31 | const uint32_t bytes = t.format.bytes; | ||
| 32 | const uint32_t row_bytes = mip.width_elements * bytes; | ||
| 33 | const uint32_t depth = t.layout.dimension == kTexture3D ? mip.depth : 1; | ||
| 34 | const ElementAddress address(t); | ||
| 35 | const auto tail = address.tail_origin(mip); | ||
| 36 | columns.resize(mip.width_elements); | ||
| 37 | for (uint32_t x = 0; x < mip.width_elements; ++x) columns[x] = address.column(mip, tail, x); | ||
| 38 | for (uint32_t z = 0; z < depth; ++z) { | ||
| 39 | for (uint32_t y = 0; y < mip.height_elements; ++y) { | ||
| 40 | const uint64_t linear = uint64_t(z) * slice_pitch + uint64_t(y) * row_pitch; | ||
| 41 | const uint64_t tiled = address.row(mip, tail, y, slice + z); | ||
| 42 | if (t.mode == kLinear) { | ||
| 43 | std::memcpy(destination + (Into ? tiled : linear), source + (Into ? linear : tiled), row_bytes); | ||
| 44 | continue; | ||
| 45 | } | ||
| 46 | for (uint32_t x = 0; x < mip.width_elements; ++x) { | ||
| 47 | const uint64_t at = tiled + columns[x]; | ||
| 48 | const uint64_t to = linear + uint64_t(x) * bytes; | ||
| 49 | std::memcpy(destination + (Into ? at : to), source + (Into ? to : at), bytes); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | uint32_t g_seed = 12345; | ||
| 56 | uint8_t next_byte() { | ||
| 57 | g_seed = g_seed * 1664525u + 1013904223u; | ||
| 58 | return uint8_t(g_seed >> 24); | ||
| 59 | } | ||
| 60 | |||
| 61 | // `misalign` moves every buffer start off its allocation's natural alignment; `extra` pads the pitches. | ||
| 62 | void compare_texture(const Texture& t, const char* what, uint32_t misalign, uint32_t extra) { | ||
| 63 | for (uint32_t slice = 0; slice < t.array; ++slice) { | ||
| 64 | for (uint32_t level = 0; level < t.layout.mips; ++level) { | ||
| 65 | const auto& mip = t.layout.plane[0].mips[level]; | ||
| 66 | const uint32_t depth = t.layout.dimension == kTexture3D ? mip.depth : 1; | ||
| 67 | const uint32_t pitch = mip.width_elements * t.format.bytes + extra; | ||
| 68 | const uint32_t slice_pitch = depth > 1 ? pitch * mip.height_elements + extra : 0; | ||
| 69 | const size_t linear_size = size_t(slice_pitch) * depth + size_t(pitch) * mip.height_elements + 64; | ||
| 70 | // Slack: a non-specialized width wider than the built one may read past the layout's last row. | ||
| 71 | const size_t tiled_size = size_t(t.layout.size) + size_t(mip.width_elements) * 16 + 64; | ||
| 72 | for (int direction = 0; direction < 2; ++direction) { | ||
| 73 | const bool into = direction == 0; | ||
| 74 | const size_t source_size = into ? linear_size : tiled_size; | ||
| 75 | const size_t destination_size = into ? tiled_size : linear_size; | ||
| 76 | std::vector<uint8_t> source(source_size + misalign), want(destination_size + misalign); | ||
| 77 | for (auto& b : source) b = next_byte(); | ||
| 78 | for (auto& b : want) b = next_byte(); // the bytes a copy must leave alone | ||
| 79 | std::vector<uint8_t> got = want; | ||
| 80 | std::vector<uint64_t> columns, reference_columns; | ||
| 81 | if (into) { | ||
| 82 | reference_copy<true>(t, level, slice, source.data() + misalign, want.data() + misalign, pitch, | ||
| 83 | slice_pitch, reference_columns); | ||
| 84 | copy_elements<true>(t, level, slice, source.data() + misalign, got.data() + misalign, pitch, | ||
| 85 | slice_pitch, columns); | ||
| 86 | } else { | ||
| 87 | reference_copy<false>(t, level, slice, source.data() + misalign, want.data() + misalign, pitch, | ||
| 88 | slice_pitch, reference_columns); | ||
| 89 | copy_elements<false>(t, level, slice, source.data() + misalign, got.data() + misalign, pitch, | ||
| 90 | slice_pitch, columns); | ||
| 91 | } | ||
| 92 | if (want != got) { | ||
| 93 | std::printf(" %s slice %u level %u %s misalign %u extra %u\n", what, slice, level, | ||
| 94 | into ? "into" : "from", misalign, extra); | ||
| 95 | check(false, "copy_elements matches the runtime-sized reference byte for byte"); | ||
| 96 | return; | ||
| 97 | } | ||
| 98 | } | ||
| 99 | } | ||
| 100 | } | ||
| 101 | check(true, what); | ||
| 102 | } | ||
| 103 | |||
| 104 | struct Case { | ||
| 105 | const char* name; | ||
| 106 | uint32_t dimension, width, height, depth_or_array, mips, format, layout; | ||
| 107 | }; | ||
| 108 | |||
| 109 | void run_case(const Case& c, bool non_specialized) { | ||
| 110 | ResourceDesc desc{c.dimension, 0, c.width, c.height, uint16_t(c.depth_or_array), uint16_t(c.mips), c.format, 1, 0, | ||
| 111 | c.layout, 0}; | ||
| 112 | Texture t; | ||
| 113 | if (!build_texture(desc, t)) { | ||
| 114 | check(false, c.name); | ||
| 115 | return; | ||
| 116 | } | ||
| 117 | if (non_specialized) { | ||
| 118 | // Same addressing, an element size the dispatch does not specialize (the tiled offsets stay inside the | ||
| 119 | // resource because the element is no wider than the one it was built for). | ||
| 120 | const uint32_t widths[17] = {0, 3, 3, 0, 3, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 12}; | ||
| 121 | t.format.bytes = widths[t.format.bytes]; | ||
| 122 | } | ||
| 123 | char name[160]; | ||
| 124 | std::snprintf(name, sizeof name, "%s: %u-byte elements, %s", c.name, t.format.bytes, | ||
| 125 | t.mode == kLinear ? "linear" : "tiled"); | ||
| 126 | for (uint32_t misalign : {0u, 1u, 3u}) | ||
| 127 | for (uint32_t extra : {0u, 1u, 7u}) compare_texture(t, name, misalign, extra); | ||
| 128 | } | ||
| 129 | |||
| 130 | } // namespace | ||
| 131 | |||
| 132 | int main() { | ||
| 133 | const Case cases[] = { | ||
| 134 | {"R8 2D tiled 64kb", kTexture2D, 61, 35, 1, 6, DXGI_FORMAT_R8_UNORM, kSwizzled | k64kbS}, | ||
| 135 | {"R16 2D tiled 64kb", kTexture2D, 100, 60, 1, 7, DXGI_FORMAT_R16_UNORM, kSwizzled | k64kbS}, | ||
| 136 | {"RGBA8 2D tiled 64kb", kTexture2D, 130, 70, 1, 8, DXGI_FORMAT_R8G8B8A8_UNORM, kSwizzled | k64kbD}, | ||
| 137 | {"RGBA16F 2D tiled", kTexture2D, 67, 33, 1, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, kSwizzled | k64kbS}, | ||
| 138 | {"RGBA32F 2D tiled", kTexture2D, 40, 36, 1, 6, DXGI_FORMAT_R32G32B32A32_FLOAT, kSwizzled | k4kbS}, | ||
| 139 | {"BC1 blocks tiled", kTexture2D, 109, 71, 1, 6, DXGI_FORMAT_BC1_UNORM, kSwizzled | k64kbS}, | ||
| 140 | {"BC3 blocks tiled", kTexture2D, 109, 71, 1, 6, DXGI_FORMAT_BC3_UNORM, kSwizzled | k64kbS}, | ||
| 141 | {"RGBA8 array tiled", kTexture2D, 70, 70, 3, 5, DXGI_FORMAT_R8G8B8A8_UNORM, kSwizzled | k4kbS}, | ||
| 142 | {"BC5 array tiled", kTexture2D, 64, 64, 4, 7, DXGI_FORMAT_BC5_UNORM, kSwizzled | k64kbS}, | ||
| 143 | {"R8 1D linear", kTexture1D, 300, 1, 1, 4, DXGI_FORMAT_R8_UNORM, 1}, | ||
| 144 | {"RGBA8 volume", kTexture3D, 61, 35, 20, 6, DXGI_FORMAT_R8G8B8A8_UNORM, kSwizzled | k4kbS}, | ||
| 145 | {"R8 volume", kTexture3D, 33, 17, 9, 5, DXGI_FORMAT_R8_UNORM, kSwizzled | k4kbS}, | ||
| 146 | {"RGBA16F volume", kTexture3D, 61, 35, 67, 7, DXGI_FORMAT_R16G16B16A16_FLOAT, kSwizzled | k4kbS}, | ||
| 147 | {"RGBA32F volume", kTexture3D, 30, 20, 11, 5, DXGI_FORMAT_R32G32B32A32_FLOAT, kSwizzled | k4kbS}, | ||
| 148 | {"RGBA8 linear", kTexture2D, 83, 31, 1, 6, DXGI_FORMAT_R8G8B8A8_UNORM, 1}, | ||
| 149 | {"RGBA16F linear array", kTexture2D, 50, 20, 3, 4, DXGI_FORMAT_R16G16B16A16_FLOAT, 1}, | ||
| 150 | {"BC1 linear", kTexture2D, 64, 64, 1, 5, DXGI_FORMAT_BC1_UNORM, 1}, | ||
| 151 | }; | ||
| 152 | for (const Case& c : cases) run_case(c, false); | ||
| 153 | // Element sizes outside 1/2/4/8/16 take the runtime-sized path. | ||
| 154 | for (const Case& c : cases) run_case(c, true); | ||
| 155 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | ||
| 156 | return g_failures ? 1 : 0; | ||
| 157 | } | ||
diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp index a35806d8f..dbcfa6398 100644 --- a/runtime/test/vk_sampler_test.cpp +++ b/runtime/test/vk_sampler_test.cpp | |||
| @@ -3,7 +3,15 @@ | |||
| 3 | // and sampler those keys name. Unlike vk_texture_test, which binds a fixed nearest sampler and one level, the | 3 | // and sampler those keys name. Unlike vk_texture_test, which binds a fixed nearest sampler and one level, the |
| 4 | // VkSampler here is vulkan_sampler(decode(S#)) and the view's levels come from decode(T#). | 4 | // VkSampler here is vulkan_sampler(decode(S#)) and the view's levels come from decode(T#). |
| 5 | // | 5 | // |
| 6 | // vk_sampler_test <vs_ids.spv> <ps_ssharp.spv> <out.raw> <s0> <s1> <s2> <s3> [<base level> <last level>] | 6 | // vk_sampler_test [--cube|--3d|--dref] <vs_ids.spv> <ps_ssharp.spv> <out.raw> <s0> <s1> <s2> <s3> [<base> <last>] |
| 7 | // | ||
| 8 | // The mode picks the texture and the binding the translator reads it from (--explicit-lod-bias's forms): | ||
| 9 | // (none) 2D RGBA8 at binding 0, as described below. | ||
| 10 | // --cube a cube-compatible 2D RGBA8 image with 6 layers, every layer the same, viewed as the 6-layer 2D array the | ||
| 11 | // translator samples a cube through (binding 3). | ||
| 12 | // --3d a 3D RGBA8 image, 128x128x2 then 64x64x1, every slice the same (binding 6). | ||
| 13 | // --dref a 2D D32_SFLOAT image whose level 0 holds 0.25 and level 1 0.75 (binding 0, depth aspect); the S# carries | ||
| 14 | // the compare function, so a reference of 0.5 with LESS_OR_EQUAL reads 0 on level 0 and 1 on level 1. | ||
| 7 | // | 15 | // |
| 8 | // S# words are hex. The T# is encode() of a 128x128 RGBA8 image with two levels, with BASE_LEVEL and LAST_LEVEL as | 16 | // S# words are hex. The T# is encode() of a 128x128 RGBA8 image with two levels, with BASE_LEVEL and LAST_LEVEL as |
| 9 | // given (default 0 and 1). Level 0 has four solid quadrants: red, green, blue and yellow. Level 1 is solid grey | 17 | // given (default 0 and 1). Level 0 has four solid quadrants: red, green, blue and yellow. Level 1 is solid grey |
| @@ -20,6 +28,7 @@ | |||
| 20 | #include "../src/descriptor_table.h" | 28 | #include "../src/descriptor_table.h" |
| 21 | #include "../src/gfx10_descriptors.h" | 29 | #include "../src/gfx10_descriptors.h" |
| 22 | 30 | ||
| 31 | #include <algorithm> | ||
| 23 | #include <cstdio> | 32 | #include <cstdio> |
| 24 | #include <cstdlib> | 33 | #include <cstdlib> |
| 25 | #include <cstring> | 34 | #include <cstring> |
| @@ -52,8 +61,18 @@ std::vector<std::uint32_t> read_spv(const char* path) { | |||
| 52 | } // namespace | 61 | } // namespace |
| 53 | 62 | ||
| 54 | int main(int argc, char** argv) { | 63 | int main(int argc, char** argv) { |
| 64 | enum class Mode { flat, cube, volume, dref } mode = Mode::flat; | ||
| 65 | if (argc > 1 && argv[1][0] == '-' && argv[1][1] == '-') { | ||
| 66 | if (!std::strcmp(argv[1], "--cube")) mode = Mode::cube; | ||
| 67 | else if (!std::strcmp(argv[1], "--3d")) mode = Mode::volume; | ||
| 68 | else if (!std::strcmp(argv[1], "--dref")) mode = Mode::dref; | ||
| 69 | else { std::fprintf(stderr, "unknown mode %s\n", argv[1]); return 2; } | ||
| 70 | --argc; | ||
| 71 | ++argv; | ||
| 72 | } | ||
| 55 | if (argc != 8 && argc != 10) { | 73 | if (argc != 8 && argc != 10) { |
| 56 | std::fprintf(stderr, "usage: vk_sampler_test <vs.spv> <fs.spv> <out.raw> <s0> <s1> <s2> <s3> [<base> <last>]\n"); | 74 | std::fprintf(stderr, "usage: vk_sampler_test [--cube|--3d|--dref] <vs.spv> <fs.spv> <out.raw> <s0> <s1> <s2> <s3> " |
| 75 | "[<base> <last>]\n"); | ||
| 57 | return 2; | 76 | return 2; |
| 58 | } | 77 | } |
| 59 | namespace gfx10 = leonida::gfx10; | 78 | namespace gfx10 = leonida::gfx10; |
| @@ -266,9 +285,10 @@ int main(int argc, char** argv) { | |||
| 266 | address_info.buffer = heap; | 285 | address_info.buffer = heap; |
| 267 | const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); | 286 | const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); |
| 268 | // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The | 287 | // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The |
| 269 | // module is tagged (build.py), so the T# entry names the array its index is bound in: a sampled 2D image. | 288 | // module is tagged (build.py), so the T# entry names the array its index is bound in: the sampled 2D images, |
| 289 | // or with --cube / --3d the 2D-array or 3D images the texture sits in (dimension 1 or 2; see texture_binding). | ||
| 270 | leonida::DescriptorTable table(16); | 290 | leonida::DescriptorTable table(16); |
| 271 | table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(0)); | 291 | table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(mode == Mode::cube ? 1u : mode == Mode::volume ? 2u : 0u)); |
| 272 | table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); | 292 | table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); |
| 273 | const auto table_words = table.build_gpu_buffer(true); | 293 | const auto table_words = table.build_gpu_buffer(true); |
| 274 | VkBuffer table_buffer; | 294 | VkBuffer table_buffer; |
| @@ -276,20 +296,84 @@ int main(int argc, char** argv) { | |||
| 276 | CHECK(make_buffer(table_words.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &table_buffer, &table_map)); | 296 | CHECK(make_buffer(table_words.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &table_buffer, &table_map)); |
| 277 | std::memcpy(table_map, table_words.data(), table_words.size() * 4); | 297 | std::memcpy(table_map, table_words.data(), table_words.size() * 4); |
| 278 | 298 | ||
| 279 | // Textures. RGBA8 in memory order; level 1 grey has r = g = 128/255, unlike every level-0 colour. | 299 | // Textures. RGBA8 in memory order; level 1 grey has r = g = 128/255, unlike every level-0 colour. Every cube |
| 280 | constexpr VkFormat texture_format = VK_FORMAT_R8G8B8A8_UNORM; | 300 | // layer and 3D slice holds the same level, so a layer or slice coordinate can't change the colour. --dref: depth |
| 301 | // 0.25 in level 0 and 0.75 in level 1. | ||
| 302 | const bool depth_mode = mode == Mode::dref; | ||
| 303 | const VkFormat texture_format = depth_mode ? VK_FORMAT_D32_SFLOAT : VK_FORMAT_R8G8B8A8_UNORM; | ||
| 304 | const VkImageAspectFlags aspect = depth_mode ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 305 | const std::uint32_t layers = mode == Mode::cube ? 6 : 1; | ||
| 306 | const std::uint32_t depth0 = mode == Mode::volume ? 2 : 1; | ||
| 307 | const auto level_depth = [&](std::uint32_t level) { return std::max(depth0 >> level, 1u); }; | ||
| 281 | constexpr std::uint32_t quadrant[2][2] = {{0xff0000ffu, 0xff00ff00u}, {0xffff0000u, 0xff00ffffu}}; | 308 | constexpr std::uint32_t quadrant[2][2] = {{0xff0000ffu, 0xff00ff00u}, {0xffff0000u, 0xff00ffffu}}; |
| 282 | constexpr std::uint32_t grey = 0xff808080u, magenta = 0xffff00ffu; | 309 | constexpr std::uint32_t grey = 0xff808080u, magenta = 0xffff00ffu; |
| 310 | std::uint32_t depth_words[2]; | ||
| 311 | { | ||
| 312 | const float d[2] = {0.25f, 0.75f}; | ||
| 313 | std::memcpy(depth_words, d, sizeof d); | ||
| 314 | } | ||
| 283 | std::vector<std::uint32_t> texels; | 315 | std::vector<std::uint32_t> texels; |
| 284 | for (std::uint32_t y = 0; y < TW; y++) | 316 | for (std::uint32_t level = 0; level < levels; ++level) { |
| 285 | for (std::uint32_t x = 0; x < TW; x++) texels.push_back(quadrant[y >= TW / 2][x >= TW / 2]); | 317 | const std::uint32_t side = TW >> level; |
| 286 | texels.resize(texels.size() + (TW / 2) * (TW / 2), grey); | 318 | for (std::uint32_t copy = 0; copy < layers * level_depth(level); ++copy) |
| 287 | VkImage fallback, texture; | 319 | for (std::uint32_t y = 0; y < side; y++) |
| 288 | VkImageView fallback_view, texture_view; | 320 | for (std::uint32_t x = 0; x < side; x++) |
| 289 | CHECK(make_image(texture_format, 1, 1, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &fallback)); | 321 | texels.push_back(depth_mode ? depth_words[level] |
| 290 | CHECK(make_view(fallback, texture_format, 0, 1, &fallback_view)); | 322 | : level ? grey : quadrant[y >= side / 2][x >= side / 2]); |
| 291 | CHECK(make_image(texture_format, TW, TW, levels, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &texture)); | 323 | } |
| 292 | CHECK(make_view(texture, gfx10::vulkan_format(view_of.format), view_of.first_mip, view_of.mip_count, &texture_view)); | 324 | const auto make_texture = [&](VkImageType type, VkFormat format, VkExtent3D extent, std::uint32_t mips, |
| 325 | std::uint32_t array_layers, VkImageCreateFlags flags, VkImage* img) { | ||
| 326 | VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 327 | ii.flags = flags; | ||
| 328 | ii.imageType = type; | ||
| 329 | ii.format = format; | ||
| 330 | ii.extent = extent; | ||
| 331 | ii.mipLevels = mips; | ||
| 332 | ii.arrayLayers = array_layers; | ||
| 333 | ii.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 334 | ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; | ||
| 335 | VkResult r = vkCreateImage(dev, &ii, nullptr, img); | ||
| 336 | if (r) return r; | ||
| 337 | VkMemoryRequirements mr; | ||
| 338 | vkGetImageMemoryRequirements(dev, *img, &mr); | ||
| 339 | VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 340 | ai.allocationSize = mr.size; | ||
| 341 | ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); | ||
| 342 | VkDeviceMemory m; | ||
| 343 | r = vkAllocateMemory(dev, &ai, nullptr, &m); | ||
| 344 | return r ? r : vkBindImageMemory(dev, *img, m, 0); | ||
| 345 | }; | ||
| 346 | const auto make_texture_view = [&](VkImage img, VkImageViewType type, VkFormat format, VkImageAspectFlags view_aspect, | ||
| 347 | std::uint32_t base, std::uint32_t count, std::uint32_t array_layers, | ||
| 348 | VkImageView* view) { | ||
| 349 | VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 350 | vi.image = img; | ||
| 351 | vi.viewType = type; | ||
| 352 | vi.format = format; | ||
| 353 | vi.subresourceRange = {view_aspect, base, count, 0, array_layers}; | ||
| 354 | return vkCreateImageView(dev, &vi, nullptr, view); | ||
| 355 | }; | ||
| 356 | // Index 0 of every bound array is a magenta 1x1 fallback of the array's dimension. | ||
| 357 | VkImage fallback, fallback3d = VK_NULL_HANDLE, texture; | ||
| 358 | VkImageView fallback_view, fallback_extra = VK_NULL_HANDLE, texture_view; | ||
| 359 | CHECK(make_texture(VK_IMAGE_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM, {1, 1, 1}, 1, 1, 0, &fallback)); | ||
| 360 | CHECK(make_view(fallback, VK_FORMAT_R8G8B8A8_UNORM, 0, 1, &fallback_view)); | ||
| 361 | if (mode == Mode::cube) | ||
| 362 | CHECK(make_texture_view(fallback, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, | ||
| 363 | 0, 1, 1, &fallback_extra)); | ||
| 364 | if (mode == Mode::volume) { | ||
| 365 | CHECK(make_texture(VK_IMAGE_TYPE_3D, VK_FORMAT_R8G8B8A8_UNORM, {1, 1, 1}, 1, 1, 0, &fallback3d)); | ||
| 366 | CHECK(make_texture_view(fallback3d, VK_IMAGE_VIEW_TYPE_3D, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, | ||
| 367 | 1, &fallback_extra)); | ||
| 368 | } | ||
| 369 | CHECK(make_texture(mode == Mode::volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D, texture_format, {TW, TW, depth0}, | ||
| 370 | levels, layers, mode == Mode::cube ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u, &texture)); | ||
| 371 | const VkImageViewType view_type = mode == Mode::cube ? VK_IMAGE_VIEW_TYPE_2D_ARRAY | ||
| 372 | : mode == Mode::volume ? VK_IMAGE_VIEW_TYPE_3D : VK_IMAGE_VIEW_TYPE_2D; | ||
| 373 | CHECK(make_texture_view(texture, view_type, depth_mode ? texture_format : gfx10::vulkan_format(view_of.format), | ||
| 374 | aspect, view_of.first_mip, view_of.mip_count, layers, &texture_view)); | ||
| 375 | // The binding the translator reads this dimension from (set 0): images (0), images_arr (3) or images_3d (6). | ||
| 376 | const std::uint32_t texture_binding = mode == Mode::cube ? 3u : mode == Mode::volume ? 6u : 0u; | ||
| 293 | VkBuffer upload; | 377 | VkBuffer upload; |
| 294 | void* upload_map; | 378 | void* upload_map; |
| 295 | const VkDeviceSize texture_offset = 256, texture_bytes = texels.size() * 4; | 379 | const VkDeviceSize texture_offset = 256, texture_bytes = texels.size() * 4; |
| @@ -347,17 +431,20 @@ int main(int argc, char** argv) { | |||
| 347 | VkFramebuffer framebuffer; | 431 | VkFramebuffer framebuffer; |
| 348 | CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); | 432 | CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); |
| 349 | 433 | ||
| 350 | // Set 0 as the translator expects it: binding 0 images[], 1 samplers[], 2 the descriptor hash table. | 434 | // Set 0 as the translator expects it: binding 0 images[], 1 samplers[], 2 the descriptor hash table, and for |
| 351 | VkDescriptorSetLayoutBinding b[3]{}; | 435 | // --cube / --3d the array the texture sits in, images_arr (3) or images_3d (6). |
| 436 | const bool extra = texture_binding != 0; | ||
| 437 | VkDescriptorSetLayoutBinding b[4]{}; | ||
| 352 | b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; | 438 | b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; |
| 353 | b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; | 439 | b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; |
| 354 | b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; | 440 | b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; |
| 441 | b[3] = {texture_binding, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; | ||
| 355 | VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | 442 | VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; |
| 356 | dli.bindingCount = 3; | 443 | dli.bindingCount = extra ? 4 : 3; |
| 357 | dli.pBindings = b; | 444 | dli.pBindings = b; |
| 358 | VkDescriptorSetLayout dsl; | 445 | VkDescriptorSetLayout dsl; |
| 359 | CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); | 446 | CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); |
| 360 | const VkDescriptorPoolSize sizes[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, | 447 | const VkDescriptorPoolSize sizes[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, |
| 361 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; | 448 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; |
| 362 | VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | 449 | VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; |
| 363 | dpi.maxSets = 1; | 450 | dpi.maxSets = 1; |
| @@ -371,11 +458,15 @@ int main(int argc, char** argv) { | |||
| 371 | dai.pSetLayouts = &dsl; | 458 | dai.pSetLayouts = &dsl; |
| 372 | VkDescriptorSet ds; | 459 | VkDescriptorSet ds; |
| 373 | CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); | 460 | CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); |
| 461 | // Image 1 is the texture in its own array; binding 0 keeps the 2D fallback there when the texture sits elsewhere. | ||
| 374 | const VkDescriptorImageInfo images[2]{{VK_NULL_HANDLE, fallback_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, | 462 | const VkDescriptorImageInfo images[2]{{VK_NULL_HANDLE, fallback_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, |
| 375 | {VK_NULL_HANDLE, texture_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; | 463 | {VK_NULL_HANDLE, extra ? fallback_view : texture_view, |
| 464 | VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; | ||
| 465 | const VkDescriptorImageInfo extra_images[2]{{VK_NULL_HANDLE, fallback_extra, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, | ||
| 466 | {VK_NULL_HANDLE, texture_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; | ||
| 376 | const VkDescriptorImageInfo sampler_infos[2]{{samplers[0]}, {samplers[1]}}; | 467 | const VkDescriptorImageInfo sampler_infos[2]{{samplers[0]}, {samplers[1]}}; |
| 377 | const VkDescriptorBufferInfo table_info{table_buffer, 0, VK_WHOLE_SIZE}; | 468 | const VkDescriptorBufferInfo table_info{table_buffer, 0, VK_WHOLE_SIZE}; |
| 378 | VkWriteDescriptorSet writes[3]{}; | 469 | VkWriteDescriptorSet writes[4]{}; |
| 379 | for (auto& w : writes) { | 470 | for (auto& w : writes) { |
| 380 | w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; | 471 | w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; |
| 381 | w.dstSet = ds; | 472 | w.dstSet = ds; |
| @@ -386,7 +477,10 @@ int main(int argc, char** argv) { | |||
| 386 | writes[1].pImageInfo = sampler_infos; | 477 | writes[1].pImageInfo = sampler_infos; |
| 387 | writes[2].dstBinding = 2; writes[2].descriptorCount = 1; writes[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; | 478 | writes[2].dstBinding = 2; writes[2].descriptorCount = 1; writes[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; |
| 388 | writes[2].pBufferInfo = &table_info; | 479 | writes[2].pBufferInfo = &table_info; |
| 389 | vkUpdateDescriptorSets(dev, 3, writes, 0, nullptr); | 480 | writes[3].dstBinding = texture_binding; writes[3].descriptorCount = 2; |
| 481 | writes[3].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; | ||
| 482 | writes[3].pImageInfo = extra_images; | ||
| 483 | vkUpdateDescriptorSets(dev, extra ? 4 : 3, writes, 0, nullptr); | ||
| 390 | 484 | ||
| 391 | // Pipeline. | 485 | // Pipeline. |
| 392 | VkShaderModule modules[2]; | 486 | VkShaderModule modules[2]; |
| @@ -480,25 +574,30 @@ int main(int argc, char** argv) { | |||
| 480 | CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); | 574 | CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); |
| 481 | const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | 575 | const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; |
| 482 | CHECK(vkBeginCommandBuffer(cmd, &begin)); | 576 | CHECK(vkBeginCommandBuffer(cmd, &begin)); |
| 483 | for (int t = 0; t < 2; ++t) { | 577 | // The fallbacks take the magenta word at offset 0; the texture every level, all layers or slices at once. |
| 484 | const std::uint32_t mips = t ? levels : 1; | 578 | struct Upload { VkImage image; std::uint32_t mips, layers; VkImageAspectFlags aspect; bool texture; }; |
| 579 | std::vector<Upload> uploads{{fallback, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT, false}}; | ||
| 580 | if (fallback3d) uploads.push_back({fallback3d, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT, false}); | ||
| 581 | uploads.push_back({texture, levels, layers, aspect, true}); | ||
| 582 | for (const Upload& u : uploads) { | ||
| 485 | VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; | 583 | VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; |
| 486 | ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; | 584 | ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; |
| 487 | ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; | 585 | ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; |
| 488 | ib.image = t ? texture : fallback; | 586 | ib.image = u.image; |
| 489 | ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1}; | 587 | ib.subresourceRange = {u.aspect, 0, u.mips, 0, u.layers}; |
| 490 | ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | 588 | ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; |
| 491 | ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 589 | ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 492 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); | 590 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); |
| 493 | VkDeviceSize offset = t ? texture_offset : 0; | 591 | VkDeviceSize offset = u.texture ? texture_offset : 0; |
| 494 | for (std::uint32_t level = 0; level < mips; ++level) { | 592 | for (std::uint32_t level = 0; level < u.mips; ++level) { |
| 495 | const std::uint32_t side = t ? TW >> level : 1; | 593 | const std::uint32_t side = u.texture ? TW >> level : 1; |
| 594 | const std::uint32_t slices = u.texture ? level_depth(level) : 1; | ||
| 496 | VkBufferImageCopy c{}; | 595 | VkBufferImageCopy c{}; |
| 497 | c.bufferOffset = offset; | 596 | c.bufferOffset = offset; |
| 498 | c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; | 597 | c.imageSubresource = {u.aspect, level, 0, u.layers}; |
| 499 | c.imageExtent = {side, side, 1}; | 598 | c.imageExtent = {side, side, slices}; |
| 500 | vkCmdCopyBufferToImage(cmd, upload, ib.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); | 599 | vkCmdCopyBufferToImage(cmd, upload, ib.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); |
| 501 | offset += VkDeviceSize(side) * side * 4; | 600 | offset += VkDeviceSize(side) * side * slices * u.layers * 4; |
| 502 | } | 601 | } |
| 503 | ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; | 602 | ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; |
| 504 | ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; | 603 | ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; |
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index 387a77d83..97015a9db 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 | |||
| @@ -7,11 +7,17 @@ | |||
| 7 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 | 7 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 |
| 8 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv | 8 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv |
| 9 | # | 9 | # |
| 10 | # -Version defaults to 23.1.5, the release the shader corpus was measured with. LLVM 21.1.8's gfx1013 decoder | ||
| 11 | # cannot decode 840 of the 2,684 pipeline-library compute programs: their listings carry 79,490 undecodable words and | ||
| 12 | # the translator refuses them ("fall-through into undecodable words"), which leaves the shaders stage at 1,844 of | ||
| 13 | # 2,684. llvm-mc 23.1.5 disassembles those 840 with no rejected word, and the stage then translates 2,683 of 2,684 | ||
| 14 | # (the last wants s_sethalt, which the translator does not implement). docs/design.md, "Disassembling shaders". | ||
| 15 | # | ||
| 10 | # The default -Dest is outside AppData on purpose: `python` from the Python install manager (the app execution alias | 16 | # The default -Dest is outside AppData on purpose: `python` from the Python install manager (the app execution alias |
| 11 | # in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%, so an llvm-mc.exe | 17 | # in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%, so an llvm-mc.exe |
| 12 | # there looks missing to make_game.py and the tools, although LLVM_MC names it. | 18 | # there looks missing to make_game.py and the tools, although LLVM_MC names it. |
| 13 | param( | 19 | param( |
| 14 | [string]$Version = "21.1.8", | 20 | [string]$Version = "23.1.5", |
| 15 | [string]$Dest = (Join-Path $env:USERPROFILE ".leonida\llvm-mc"), | 21 | [string]$Dest = (Join-Path $env:USERPROFILE ".leonida\llvm-mc"), |
| 16 | [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"), | 22 | [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"), |
| 17 | [switch]$NoEnv, # don't set LLVM_MC for the current user | 23 | [switch]$NoEnv, # don't set LLVM_MC for the current user |
diff --git a/scripts/merge_check.py b/scripts/merge_check.py index 5499da29c..be2b69176 100644 --- a/scripts/merge_check.py +++ b/scripts/merge_check.py | |||
| @@ -35,15 +35,18 @@ REVERT_SUBJECT = re.compile(r"^Revert\b", re.IGNORECASE) | |||
| 35 | # Where a doubled block is the repeated-merge damage. In code, three equal lines in two functions are ordinary, so a | 35 | # Where a doubled block is the repeated-merge damage. In code, three equal lines in two functions are ordinary, so a |
| 36 | # block there is listed but does not change the verdict. | 36 | # block there is listed but does not change the verdict. |
| 37 | TEXT_SUFFIXES = (".md", ".txt", ".rst") | 37 | TEXT_SUFFIXES = (".md", ".txt", ".rst") |
| 38 | GIT_TIMEOUT = 120 | ||
| 38 | 39 | ||
| 39 | 40 | ||
| 40 | class GitError(Exception): | 41 | class GitError(Exception): |
| 41 | pass | 42 | pass |
| 42 | 43 | ||
| 43 | 44 | ||
| 44 | def git(repo, *args, check=True, stdout_errors="replace"): | 45 | def git(repo, *args, check=True, stdout_errors="replace", timeout=GIT_TIMEOUT): |
| 45 | try: | 46 | try: |
| 46 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True) | 47 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True, timeout=timeout) |
| 48 | except subprocess.TimeoutExpired: | ||
| 49 | raise GitError(f"git {' '.join(args)}: timed out after {timeout}s") from None | ||
| 47 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback | 50 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback |
| 48 | raise GitError(f"cannot run git: {e.strerror or e}") from None | 51 | raise GitError(f"cannot run git: {e.strerror or e}") from None |
| 49 | # Decode without universal-newline translation: a bare CR inside a Git line is content. | 52 | # Decode without universal-newline translation: a bare CR inside a Git line is content. |
| @@ -179,20 +182,40 @@ def check(repo, main, number, ref, min_length, merges): | |||
| 179 | "duplicate_samples": {p: v[:3] for p, v in dups.items()}} | 182 | "duplicate_samples": {p: v[:3] for p, v in dups.items()}} |
| 180 | 183 | ||
| 181 | 184 | ||
| 185 | def _positive_int(text): | ||
| 186 | try: | ||
| 187 | value = int(text) | ||
| 188 | except ValueError: | ||
| 189 | raise argparse.ArgumentTypeError(f"expected a positive integer, got {text!r}") from None | ||
| 190 | if value < 1: | ||
| 191 | raise argparse.ArgumentTypeError(f"must be at least 1, got {text!r}") | ||
| 192 | return value | ||
| 193 | |||
| 194 | |||
| 195 | def _validate_ref(ref, label): | ||
| 196 | if not ref or ref != ref.strip() or ref.startswith("-"): | ||
| 197 | raise argparse.ArgumentTypeError(f"invalid {label} ref: {ref!r}") | ||
| 198 | return ref | ||
| 199 | |||
| 200 | |||
| 182 | def parse_pair(text): | 201 | def parse_pair(text): |
| 183 | number, sep, ref = text.partition("=") | 202 | number, sep, ref = text.partition("=") |
| 184 | if not sep or not number.lstrip("#").isdigit() or not ref: | 203 | raw_num = number[1:] if number.startswith("#") else number |
| 204 | if not sep or not raw_num.isascii() or not raw_num.isdigit() or int(raw_num) < 1: | ||
| 185 | raise argparse.ArgumentTypeError(f"expected PR=REF, got {text!r}") | 205 | raise argparse.ArgumentTypeError(f"expected PR=REF, got {text!r}") |
| 186 | return int(number.lstrip("#")), ref | 206 | return int(raw_num), _validate_ref(ref, "PR target") |
| 187 | 207 | ||
| 188 | 208 | ||
| 189 | def main(argv=None): | 209 | def main(argv=None): |
| 190 | ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) | 210 | ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) |
| 191 | ap.add_argument("pairs", nargs="+", type=parse_pair, metavar="PR=REF") | 211 | ap.add_argument("pairs", nargs="+", type=parse_pair, metavar="PR=REF") |
| 192 | ap.add_argument("--main", default="origin/main", help="the branch the round merges into (default origin/main)") | 212 | ap.add_argument("--main", default="origin/main", type=lambda s: _validate_ref(s, "--main"), |
| 213 | help="the branch the round merges into (default origin/main)") | ||
| 193 | ap.add_argument("--repo", default=".", help="repository folder (default: the current one)") | 214 | ap.add_argument("--repo", default=".", help="repository folder (default: the current one)") |
| 194 | ap.add_argument("--min-length", type=int, default=40, help="shortest stripped line counted as a duplicate (40)") | 215 | ap.add_argument("--min-length", type=_positive_int, default=40, |
| 195 | ap.add_argument("--depth", type=int, default=5000, help="first-parent commits searched for earlier merges (5000)") | 216 | help="shortest stripped line counted as a duplicate (40)") |
| 217 | ap.add_argument("--depth", type=_positive_int, default=5000, | ||
| 218 | help="first-parent commits searched for earlier merges (5000)") | ||
| 196 | ap.add_argument("--json", action="store_true", help="one JSON report instead of text") | 219 | ap.add_argument("--json", action="store_true", help="one JSON report instead of text") |
| 197 | args = ap.parse_args(argv) | 220 | args = ap.parse_args(argv) |
| 198 | try: | 221 | try: |
diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh index e7d48d78e..35a44256f 100755 --- a/scripts/play-linux.sh +++ b/scripts/play-linux.sh | |||
| @@ -66,6 +66,9 @@ set_default LEONIDA_COMPOSE 1 | |||
| 66 | set_default LEONIDA_NAN_SCRUB 1 | 66 | set_default LEONIDA_NAN_SCRUB 1 |
| 67 | set_default LEONIDA_AMBIENT_AIR 1.5 | 67 | set_default LEONIDA_AMBIENT_AIR 1.5 |
| 68 | set_default LEONIDA_AMBIENT_MOST 2 | 68 | set_default LEONIDA_AMBIENT_MOST 2 |
| 69 | # Match the Windows launcher defaults; explicit 0 keeps either path off for comparisons. | ||
| 70 | set_default LEONIDA_COPY_SCOPED 1 | ||
| 71 | set_default LEONIDA_PORT_DESCRIPTORS 1 | ||
| 69 | 72 | ||
| 70 | echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))" | 73 | echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))" |
| 71 | exec wine "$runtime" run "$game_exe" --execute --console "$console" | 74 | exec wine "$runtime" run "$game_exe" --execute --console "$console" |
diff --git a/scripts/run_game_wine.sh b/scripts/run_game_wine.sh index cc60d6767..96daae6d0 100755 --- a/scripts/run_game_wine.sh +++ b/scripts/run_game_wine.sh | |||
| @@ -34,6 +34,10 @@ Options: | |||
| 34 | --device VID:DID the Vulkan device, as MESA_VK_DEVICE_SELECT=VID:DID! (e.g. 1002:744c); without it Mesa picks | 34 | --device VID:DID the Vulkan device, as MESA_VK_DEVICE_SELECT=VID:DID! (e.g. 1002:744c); without it Mesa picks |
| 35 | --screenshot-every S capture the game window into <out>/shots every S seconds (needs ImageMagick's import and | 35 | --screenshot-every S capture the game window into <out>/shots every S seconds (needs ImageMagick's import and |
| 36 | xprop); the shots are game content and stay local | 36 | xprop); the shots are game content and stay local |
| 37 | --cache DIR|fresh XDG_CACHE_HOME of the run, where the drivers keep their shader caches (NVIDIA's GLCache, | ||
| 38 | Mesa's shader cache): DIR is kept from run to run, fresh is a new one in the run folder | ||
| 39 | (default: the caller's XDG_CACHE_HOME when it is set, otherwise fresh); fresh also | ||
| 40 | unsets MESA_SHADER_CACHE_DIR, MESA_GLSL_CACHE_DIR and __GL_SHADER_DISK_CACHE_PATH | ||
| 37 | --lock FILE the lock that allows one run at a time (default $XDG_RUNTIME_DIR/leonida-run-game-wine.lock, | 41 | --lock FILE the lock that allows one run at a time (default $XDG_RUNTIME_DIR/leonida-run-game-wine.lock, |
| 38 | or <out>/run.lock without XDG_RUNTIME_DIR) | 42 | or <out>/run.lock without XDG_RUNTIME_DIR) |
| 39 | -h, --help this text | 43 | -h, --help this text |
| @@ -108,7 +112,7 @@ if [ "${1:-}" = --inner ]; then | |||
| 108 | fi | 112 | fi |
| 109 | 113 | ||
| 110 | # ---- arguments ---- | 114 | # ---- arguments ---- |
| 111 | SRC= BUILD_DIR= OUT= PREFIX=${WINEPREFIX:-} LIMIT=600 VISIBLE=0 DEVICE= SHOT_EVERY=0 LOCK= | 115 | SRC= BUILD_DIR= OUT= PREFIX=${WINEPREFIX:-} LIMIT=600 VISIBLE=0 DEVICE= SHOT_EVERY=0 LOCK= CACHE=${XDG_CACHE_HOME:-fresh} |
| 112 | EXE=${LEONIDA_GAME_EXE:-} GAME=${LEONIDA_GAME_DIR:-} SHADERS=${LEONIDA_SHADERS:-} | 116 | EXE=${LEONIDA_GAME_EXE:-} GAME=${LEONIDA_GAME_DIR:-} SHADERS=${LEONIDA_SHADERS:-} |
| 113 | need() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value (see --help)"; } | 117 | need() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value (see --help)"; } |
| 114 | while [ $# -gt 0 ]; do | 118 | while [ $# -gt 0 ]; do |
| @@ -126,6 +130,7 @@ while [ $# -gt 0 ]; do | |||
| 126 | --device) need "$@"; DEVICE=$2; shift 2 ;; | 130 | --device) need "$@"; DEVICE=$2; shift 2 ;; |
| 127 | --screenshot-every) need "$@"; SHOT_EVERY=$2; shift 2 ;; | 131 | --screenshot-every) need "$@"; SHOT_EVERY=$2; shift 2 ;; |
| 128 | --lock) need "$@"; LOCK=$2; shift 2 ;; | 132 | --lock) need "$@"; LOCK=$2; shift 2 ;; |
| 133 | --cache) need "$@"; CACHE=$2; shift 2 ;; | ||
| 129 | --) shift; break ;; | 134 | --) shift; break ;; |
| 130 | *) die "unknown argument: $1 (see --help)" ;; | 135 | *) die "unknown argument: $1 (see --help)" ;; |
| 131 | esac | 136 | esac |
| @@ -144,6 +149,10 @@ fi | |||
| 144 | [ -e "$SRC" ] || die "no build path at $SRC" | 149 | [ -e "$SRC" ] || die "no build path at $SRC" |
| 145 | [ -f "$EXE" ] || die "no game executable at $EXE" | 150 | [ -f "$EXE" ] || die "no game executable at $EXE" |
| 146 | [ -d "$GAME" ] || die "no package folder at $GAME" | 151 | [ -d "$GAME" ] || die "no package folder at $GAME" |
| 152 | if [ "$CACHE" != fresh ]; then | ||
| 153 | mkdir -p "$CACHE" || die "cannot create the cache folder $CACHE" | ||
| 154 | CACHE=$(readlink -f "$CACHE") | ||
| 155 | fi | ||
| 147 | if [ "$SHADERS" != none ]; then | 156 | if [ "$SHADERS" != none ]; then |
| 148 | SHADERS=${SHADERS#Z:} | 157 | SHADERS=${SHADERS#Z:} |
| 149 | [ -d "$SHADERS" ] || die "no shader library at $SHADERS" | 158 | [ -d "$SHADERS" ] || die "no shader library at $SHADERS" |
| @@ -212,9 +221,20 @@ unset LEONIDA_GAME_EXE LEONIDA_GAME_DIR # launcher inputs; LEONIDA_GAME_DIR als | |||
| 212 | export WINE | 221 | export WINE |
| 213 | export XDG_RUNTIME_DIR=$RUN/xdg | 222 | export XDG_RUNTIME_DIR=$RUN/xdg |
| 214 | rm -rf "$XDG_RUNTIME_DIR"; mkdir -p -m 700 "$XDG_RUNTIME_DIR" | 223 | rm -rf "$XDG_RUNTIME_DIR"; mkdir -p -m 700 "$XDG_RUNTIME_DIR" |
| 215 | export XDG_CONFIG_HOME=$RUN/session/config XDG_DATA_HOME=$RUN/session/data XDG_CACHE_HOME=$RUN/session/cache \ | 224 | # The cache folder alone may outlive the run: a fresh one makes every launch compile its pipelines again in the driver. |
| 225 | # A driver's own cache variable wins over XDG_CACHE_HOME, so a fresh run drops them, and an accepted run folder's old | ||
| 226 | # session/cache goes too: fresh means empty. With a kept cache the caller's variables stay, and win. | ||
| 227 | if [ "$CACHE" = fresh ]; then | ||
| 228 | XDG_CACHE_HOME=$RUN/session/cache | ||
| 229 | rm -rf "$XDG_CACHE_HOME" | ||
| 230 | unset MESA_SHADER_CACHE_DIR MESA_GLSL_CACHE_DIR __GL_SHADER_DISK_CACHE_PATH | ||
| 231 | else | ||
| 232 | XDG_CACHE_HOME=$CACHE | ||
| 233 | fi | ||
| 234 | export XDG_CONFIG_HOME=$RUN/session/config XDG_DATA_HOME=$RUN/session/data XDG_CACHE_HOME \ | ||
| 216 | XDG_STATE_HOME=$RUN/session/state | 235 | XDG_STATE_HOME=$RUN/session/state |
| 217 | mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" | 236 | mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" |
| 237 | if [ "$CACHE" = fresh ]; then echo "shader cache: fresh"; else echo "shader cache: kept in $CACHE"; fi > "$RUN/session.txt" | ||
| 218 | unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS | 238 | unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS |
| 219 | if [ "$VISIBLE" = 1 ]; then | 239 | if [ "$VISIBLE" = 1 ]; then |
| 220 | if command -v xdpyinfo >/dev/null 2>&1 && ! xdpyinfo >/dev/null 2>&1; then | 240 | if command -v xdpyinfo >/dev/null 2>&1 && ! xdpyinfo >/dev/null 2>&1; then |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 7f299b0be..c9f8bfd65 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -28,7 +28,7 @@ from build import CLIP_CASES, clip_container, shader_source | |||
| 28 | from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, | 28 | from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, |
| 29 | fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) | 29 | fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) |
| 30 | from compute_fixture import compute_header | 30 | from compute_fixture import compute_header |
| 31 | from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) | 31 | from check import SAMPLER_CASES, SAMPLER_FIXTURES, sampler_test # ps_ssharp*: the S#/T# mip fields (vk_sampler_test) |
| 32 | from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, PK_MUL_LO_ENV, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, | 32 | from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, PK_MUL_LO_ENV, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, |
| 33 | TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, | 33 | TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, |
| 34 | pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) | 34 | pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) |
| @@ -378,6 +378,7 @@ def no_ftz32() -> bool: | |||
| 378 | 378 | ||
| 379 | _PER_VERTEX = [] | 379 | _PER_VERTEX = [] |
| 380 | _BARYCENTRIC_FALLBACK = [] | 380 | _BARYCENTRIC_FALLBACK = [] |
| 381 | _EXPLICIT_LOD_BIAS = [] | ||
| 381 | _DENORM_FTZ_F32 = [] | 382 | _DENORM_FTZ_F32 = [] |
| 382 | 383 | ||
| 383 | 384 | ||
| @@ -414,6 +415,33 @@ def _device_barycentric_fallback(): | |||
| 414 | return _BARYCENTRIC_FALLBACK[0] | 415 | return _BARYCENTRIC_FALLBACK[0] |
| 415 | 416 | ||
| 416 | 417 | ||
| 418 | def _device_explicit_lod_bias(build: str | None): | ||
| 419 | """tools/lod_bias_probe.py's answer for the device the tests run on (cached per suite), or None: vk_subgroup_info.py | ||
| 420 | --lod-bias's compute measurement, else (with the test programs) ps_ssharp drawn without the flag.""" | ||
| 421 | if not _EXPLICIT_LOD_BIAS: | ||
| 422 | answer = None | ||
| 423 | try: | ||
| 424 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "lod_bias_probe.py"), | ||
| 425 | *(["--build", build] if build else [])], capture_output=True, text=True, timeout=300) | ||
| 426 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") | ||
| 427 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | ||
| 428 | pass | ||
| 429 | _EXPLICIT_LOD_BIAS.append(answer) | ||
| 430 | return _EXPLICIT_LOD_BIAS[0] | ||
| 431 | |||
| 432 | |||
| 433 | def explicit_lod_bias(build: str | None) -> bool: | ||
| 434 | """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0): translate with --explicit-lod-bias, so samples take the S# LOD_BIAS in the | ||
| 435 | shader. Unset, it is on where tools/lod_bias_probe.py measures that the sampler drops mipLodBias (MoltenVK on an | ||
| 436 | Apple M3, not on an M5 Pro: a driver ID can't tell); a probe without an answer leaves it off.""" | ||
| 437 | v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() | ||
| 438 | if v in ("1", "true", "yes", "on"): | ||
| 439 | return True | ||
| 440 | if v in ("0", "false", "no", "off"): | ||
| 441 | return False | ||
| 442 | return _device_explicit_lod_bias(build) is True | ||
| 443 | |||
| 444 | |||
| 417 | def _device_denorm_ftz_f32(): | 445 | def _device_denorm_ftz_f32(): |
| 418 | """denorm_flush_to_zero_f32 from tools/vk_subgroup_info.py for the device the tests run on (cached), or None.""" | 446 | """denorm_flush_to_zero_f32 from tools/vk_subgroup_info.py for the device the tests run on (cached), or None.""" |
| 419 | if not _DENORM_FTZ_F32: | 447 | if not _DENORM_FTZ_F32: |
| @@ -494,6 +522,7 @@ CS_DUMP_WANTS: dict[str, list[int]] = { | |||
| 494 | "cs_dpp_row": [0, 0, 1, 2, 3, 4, 5, 6], | 522 | "cs_dpp_row": [0, 0, 1, 2, 3, 4, 5, 6], |
| 495 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], | 523 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], |
| 496 | "cs_exec_const": [16, 8, 2, 16, 0, 16], | 524 | "cs_exec_const": [16, 8, 2, 16, 0, 16], |
| 525 | "cs_exec_copy": [0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 0, 0xAAAAAAAA, 0xFFFFFFFF, 0xAAAAAAAA, 1], | ||
| 497 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | 526 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], |
| 498 | "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004, 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC], | 527 | "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004, 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC], |
| 499 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | 528 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], |
| @@ -576,6 +605,7 @@ CS_DUMP_NON_WAVE64: frozenset[str] = frozenset({ | |||
| 576 | "cs_dpp_ops", | 605 | "cs_dpp_ops", |
| 577 | "cs_dpp_row", | 606 | "cs_dpp_row", |
| 578 | "cs_exec_const", | 607 | "cs_exec_const", |
| 608 | "cs_exec_copy", | ||
| 579 | "cs_lds_atomics_ext", | 609 | "cs_lds_atomics_ext", |
| 580 | "cs_lds_b64_cmpst", | 610 | "cs_lds_b64_cmpst", |
| 581 | "cs_lds_xchg64_ext", | 611 | "cs_lds_xchg64_ext", |
| @@ -887,7 +917,7 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "ps_m15_dual": "d3d12_t | |||
| 887 | DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_persp_bary": "vs_persp.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", | 917 | DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_persp_bary": "vs_persp.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", |
| 888 | "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", | 918 | "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", |
| 889 | "ps_table_fetch": "vs_ids.asm", "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm", | 919 | "ps_table_fetch": "vs_ids.asm", "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm", |
| 890 | **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", | 920 | **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, **{name: "vs_ids.asm" for name in SAMPLER_FIXTURES}, "ps_imgatomic": "vs_ids.asm", |
| 891 | **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", | 921 | **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", |
| 892 | "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", | 922 | "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", |
| 893 | "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", | 923 | "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", |
| @@ -1154,6 +1184,8 @@ def run_suite(a, work: str) -> int: | |||
| 1154 | cmd.append("--no-ftz32") | 1184 | cmd.append("--no-ftz32") |
| 1155 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 | 1185 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 |
| 1156 | cmd.append("--texel-offset-fallback") | 1186 | cmd.append("--texel-offset-fallback") |
| 1187 | if explicit_lod_bias(getattr(a, "build", None)): # the S# LOD bias in the shader, where the sampler drops it (measured) | ||
| 1188 | cmd.append("--explicit-lod-bias") | ||
| 1157 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py | 1189 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py |
| 1158 | cmd.append("--mesh-compute") | 1190 | cmd.append("--mesh-compute") |
| 1159 | if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave | 1191 | if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave |
| @@ -1536,9 +1568,9 @@ def run_suite(a, work: str) -> int: | |||
| 1536 | results.append((name, None, f"SKIP ({reason})")) | 1568 | results.append((name, None, f"SKIP ({reason})")) |
| 1537 | else: | 1569 | else: |
| 1538 | results.append((name, rc == 0, verdict_line(rc, msg))) | 1570 | results.append((name, rc == 0, verdict_line(rc, msg))) |
| 1539 | elif name == "ps_ssharp": | 1571 | elif name in SAMPLER_FIXTURES: |
| 1540 | # The S#/T# mip fields through vulkan_sampler() and the view range (check.py's SAMPLER_CASES). | 1572 | # The S#/T# mip fields through vulkan_sampler() and the view range (check.py's SAMPLER_CASES). |
| 1541 | problem = sampler_test(a.build, spirv_dir) | 1573 | problem = sampler_test(a.build, spirv_dir, name) |
| 1542 | results.append((name, None if isinstance(problem, Skip) else not problem, | 1574 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 1543 | problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) | 1575 | problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) |
| 1544 | elif name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"): | 1576 | elif name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"): |
diff --git a/tests/Rpf9DumpDiagnostics/Program.cs b/tests/Rpf9DumpDiagnostics/Program.cs index 69feefcb2..87e96b817 100644 --- a/tests/Rpf9DumpDiagnostics/Program.cs +++ b/tests/Rpf9DumpDiagnostics/Program.cs | |||
| @@ -103,12 +103,21 @@ Console.WriteLine("Mesh key tests passed."); | |||
| 103 | var pastEnd = Entry(new ArchiveSegment(32, file.Length, system.Length)); | 103 | var pastEnd = Entry(new ArchiveSegment(32, file.Length, system.Length)); |
| 104 | try { RecoveredResource.Read(path, pastEnd); Check(false, "block past the end is rejected"); } | 104 | try { RecoveredResource.Read(path, pastEnd); Check(false, "block past the end is rejected"); } |
| 105 | catch (InvalidDataException) { } | 105 | catch (InvalidDataException) { } |
| 106 | var overflow = Entry(new ArchiveSegment(32, long.MaxValue, system.Length)); | ||
| 107 | try { RecoveredResource.Read(path, overflow); Check(false, "an overflowing block size is rejected"); } | ||
| 108 | catch (InvalidDataException) { } | ||
| 106 | // A raw block reads its own bytes; the 6-byte minimum is the smallest block the recovery step records. | 109 | // A raw block reads its own bytes; the 6-byte minimum is the smallest block the recovery step records. |
| 107 | var shortRaw = Entry(new ArchiveSegment(32 + zblock.Length + 16, 8, 8) { IsRaw = true }); | 110 | var shortRaw = Entry(new ArchiveSegment(32 + zblock.Length + 16, 8, 8) { IsRaw = true }); |
| 108 | Check(RecoveredResource.Read(path, shortRaw).SequenceEqual(gfx[..8]), "a raw block reads its own bytes"); | 111 | Check(RecoveredResource.Read(path, shortRaw).SequenceEqual(gfx[..8]), "a raw block reads its own bytes"); |
| 109 | var tooSmall = Entry(new ArchiveSegment(32 + zblock.Length + 16, 4, 4) { IsRaw = true }); | 112 | var tooSmall = Entry(new ArchiveSegment(32 + zblock.Length + 16, 4, 4) { IsRaw = true }); |
| 110 | try { RecoveredResource.Read(path, tooSmall); Check(false, "a block under six bytes is rejected"); } | 113 | try { RecoveredResource.Read(path, tooSmall); Check(false, "a block under six bytes is rejected"); } |
| 111 | catch (InvalidDataException) { } | 114 | catch (InvalidDataException) { } |
| 115 | var rawLargerStored = Entry(new ArchiveSegment(32 + zblock.Length + 16, 16, 8) { IsRaw = true }); | ||
| 116 | try { RecoveredResource.Read(path, rawLargerStored); Check(false, "a raw block with StoredSize > Size is rejected"); } | ||
| 117 | catch (InvalidDataException) { } | ||
| 118 | var rawSmallerStored = Entry(new ArchiveSegment(32 + zblock.Length + 16, 8, 16) { IsRaw = true }); | ||
| 119 | try { RecoveredResource.Read(path, rawSmallerStored); Check(false, "a raw block with StoredSize < Size is rejected"); } | ||
| 120 | catch (InvalidDataException) { } | ||
| 112 | // An entry that records no blocks is rejected rather than returning an empty resource. | 121 | // An entry that records no blocks is rejected rather than returning an empty resource. |
| 113 | var oversize = new ArchiveEntry("recovered/models/x.r9modeldata", 1, 1, 32, false, false, false, "Recovered model", 0); | 122 | var oversize = new ArchiveEntry("recovered/models/x.r9modeldata", 1, 1, 32, false, false, false, "Recovered model", 0); |
| 114 | try { RecoveredResource.Read(path, oversize); Check(false, "an entry without blocks is rejected"); } | 123 | try { RecoveredResource.Read(path, oversize); Check(false, "an entry without blocks is rejected"); } |
diff --git a/tests/semantic/fixtures/disasm/cs_exec_copy.s b/tests/semantic/fixtures/disasm/cs_exec_copy.s new file mode 100644 index 000000000..d5b885661 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_exec_copy.s | |||
| @@ -0,0 +1,26 @@ | |||
| 1 | ; cs_exec_copy test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_exec_copy.asm | ||
| 2 | v_mov_b32_e32 v7, -1 | ||
| 3 | v_readfirstlane_b32 s7, v7 | ||
| 4 | s_mov_b32 exec_lo, s7 | ||
| 5 | v_and_b32 v1, 1, v0 | ||
| 6 | v_cmp_ne_u32_e64 s8, v1, 0 | ||
| 7 | s_mov_b32 s4, exec_lo | ||
| 8 | s_mov_b32 exec_lo, s4 | ||
| 9 | v_mov_b32_e32 v2, s8 | ||
| 10 | v_mov_b32_e32 v4, exec_lo | ||
| 11 | s_mov_b32 exec_lo, -1 | ||
| 12 | v_mov_b32_e32 v5, s8 | ||
| 13 | v_lshlrev_b32_e32 v3, 4, v0 | ||
| 14 | v_mov_b32_e32 v20, v2 | ||
| 15 | v_mov_b32_e32 v21, v3 | ||
| 16 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 17 | v_mov_b32_e32 v20, v4 | ||
| 18 | v_add_nc_u32_e32 v21, 4, v3 | ||
| 19 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 20 | v_mov_b32_e32 v20, v5 | ||
| 21 | v_add_nc_u32_e32 v21, 8, v3 | ||
| 22 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 23 | v_mov_b32_e32 v20, v0 | ||
| 24 | v_add_nc_u32_e32 v21, 12, v3 | ||
| 25 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 26 | s_endpgm | ||
diff --git a/tests/semantic/test_alu_add_sub_i16.py b/tests/semantic/test_alu_add_sub_i16.py index 5e2227278..792ebe9d6 100644 --- a/tests/semantic/test_alu_add_sub_i16.py +++ b/tests/semantic/test_alu_add_sub_i16.py | |||
| @@ -266,24 +266,13 @@ class AluAddSubI16Tests(unittest.TestCase): | |||
| 266 | ], | 266 | ], |
| 267 | ) | 267 | ) |
| 268 | self.assertEqual(si.run_fragment(spv_mask)["%out_mrt0"][0], 0x0000FFFE) | 268 | self.assertEqual(si.run_fragment(spv_mask)["%out_mrt0"][0], 0x0000FFFE) |
| 269 | const_match = re.search( | 269 | # Remove the low-half extract that feeds the store to v0. |
| 270 | r"^(%\S+)\s*=\s*OpConstant\s+%uint\s+65535\b", spv_mask, re.MULTILINE | 270 | spv_mask_mut, count = re.subn( |
| 271 | ) | 271 | r"(%\w+) = OpBitFieldUExtract %uint (%\w+) %c0 %c10(?=\n[ \t]*OpStore %reg_v0 \1\b)", |
| 272 | self.assertIsNotNone(const_match) | 272 | r"\1 = OpCopyObject %uint \2", |
| 273 | c65535 = const_match.group(1) | 273 | spv_mask, |
| 274 | mask_matches = list( | ||
| 275 | re.finditer( | ||
| 276 | rf"= OpBitwiseAnd %uint (%\S+) {re.escape(c65535)}\b", spv_mask | ||
| 277 | ) | ||
| 278 | ) | ||
| 279 | # one 16-bit mask at least: SHADER-315's constant folding removed the ones on the literal operands | ||
| 280 | self.assertGreaterEqual(len(mask_matches), 1) | ||
| 281 | last = mask_matches[-1] | ||
| 282 | spv_mask_mut = ( | ||
| 283 | spv_mask[: last.start()] | ||
| 284 | + f"= OpCopyObject %uint {last.group(1)}" | ||
| 285 | + spv_mask[last.end() :] | ||
| 286 | ) | 274 | ) |
| 275 | self.assertEqual(count, 1) | ||
| 287 | self.assertEqual(si.run_fragment(spv_mask_mut)["%out_mrt0"][0], 0xFFFFFFFE) | 276 | self.assertEqual(si.run_fragment(spv_mask_mut)["%out_mrt0"][0], 0xFFFFFFFE) |
| 288 | 277 | ||
| 289 | 278 | ||
diff --git a/tests/semantic/test_explicit_lod_bias.py b/tests/semantic/test_explicit_lod_bias.py new file mode 100644 index 000000000..d71785b7c --- /dev/null +++ b/tests/semantic/test_explicit_lod_bias.py | |||
| @@ -0,0 +1,159 @@ | |||
| 1 | """rdna2spirv.py --explicit-lod-bias: the S# LOD_BIAS applied in the shader, for a driver whose sampler drops | ||
| 2 | VkSamplerCreateInfo::mipLodBias (MoltenVK 1.4.2; docs/design.md, "S# LOD bias without the sampler's mipLodBias"). | ||
| 3 | |||
| 4 | The bias is the S#'s word 2 [13:0], signed 5.8 fixed point. With the flag: | ||
| 5 | * an explicit-LOD sample (image_sample_lz, _l, and the implicit forms outside the PS) adds it to its Lod; | ||
| 6 | * image_sample_b adds it to its own bias; | ||
| 7 | * an implicit sample in the PS that reads through Grad (the typed 2D read) scales both derivatives by 2^bias, and | ||
| 8 | one that stays implicit (3D) takes it as a Bias operand; | ||
| 9 | * a literal S# folds the bias to a constant, a zero bias adds nothing, and an S# loaded at run time is decoded from | ||
| 10 | its SGPR; | ||
| 11 | * without the flag nothing changes. | ||
| 12 | The GPU check is runtime/test/shaders/ps_ssharp (check.py SAMPLER_CASES, whose +-0.26 cases tell a bias counted once | ||
| 13 | from twice); scripts/run_gpu_tests.py turns the flag on where tools/vk_subgroup_info.py reports explicit_lod_bias. | ||
| 14 | Standard library only; no GPU, no game files. | ||
| 15 | """ | ||
| 16 | import re | ||
| 17 | import struct | ||
| 18 | import unittest | ||
| 19 | |||
| 20 | import support | ||
| 21 | |||
| 22 | D2 = "dim:SQ_RSRC_IMG_2D" | ||
| 23 | D3 = "dim:SQ_RSRC_IMG_3D" | ||
| 24 | CS_FSSM = bytearray(0x148) | ||
| 25 | struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) | ||
| 26 | CS_FSSM = bytes(CS_FSSM) | ||
| 27 | |||
| 28 | |||
| 29 | def literal_ssharp(bias_256): | ||
| 30 | """s_movs for a T# in s[8:15] and a point-mip S# in s[16:19] with LOD_BIAS = bias_256 / 256.""" | ||
| 31 | t = [0x2000, 0x1400000, 0, 0, 0, 0, 0, 0] | ||
| 32 | s = [0, 0, (bias_256 & 0x3fff) | 1 << 26, 0] | ||
| 33 | return [f"s_mov_b32 s{8 + i}, 0x{w:x}" for i, w in enumerate(t)] + \ | ||
| 34 | [f"s_mov_b32 s{16 + i}, 0x{w:x}" for i, w in enumerate(s)] | ||
| 35 | |||
| 36 | |||
| 37 | LOADED = ["s_load_dwordx8 s[8:15], s[0:1], 0x0", "s_load_dwordx4 s[16:19], s[0:1], 0x20", "s_waitcnt lgkmcnt(0)"] | ||
| 38 | COORDS = ["v_mov_b32 v2, 0.5", "v_mov_b32 v3, 0.25", "v_mov_b32 v4, 0.75", "v_mov_b32 v5, 1.0"] | ||
| 39 | |||
| 40 | |||
| 41 | def translate(name, prologue, line, flag): | ||
| 42 | fssm = CS_FSSM if name.startswith("cs_") else None | ||
| 43 | body = prologue + COORDS + [line] + (["s_waitcnt vmcnt(0)", "exp mrt0 v6, v7, v6, v7 done vm"] | ||
| 44 | if name.startswith("ps_") else []) + ["s_endpgm"] | ||
| 45 | prev = support.rdna2spirv.EXPLICIT_LOD_BIAS | ||
| 46 | support.rdna2spirv.EXPLICIT_LOD_BIAS = flag | ||
| 47 | try: | ||
| 48 | return support.translate_lines(name, body, fssm=fssm) | ||
| 49 | finally: | ||
| 50 | support.rdna2spirv.EXPLICIT_LOD_BIAS = prev | ||
| 51 | |||
| 52 | |||
| 53 | def samples(spv): | ||
| 54 | return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] | ||
| 55 | |||
| 56 | |||
| 57 | def defn(spv, ident): | ||
| 58 | """The right-hand side of `ident = ...`, or ''.""" | ||
| 59 | m = re.search(rf"^\s*{re.escape(ident)} = (.*)$", spv, re.M) | ||
| 60 | return m.group(1).strip() if m else "" | ||
| 61 | |||
| 62 | |||
| 63 | def float_const(spv, ident): | ||
| 64 | """The value of a float constant: the translator writes it as OpBitcast %float of a uint constant %c<hex>.""" | ||
| 65 | m = re.match(r"OpBitcast %float %c([0-9a-f]+)$", defn(spv, ident)) | ||
| 66 | if m: | ||
| 67 | return struct.unpack("<f", struct.pack("<I", int(m.group(1), 16)))[0] | ||
| 68 | m = re.match(r"OpConstant %float (\S+)$", defn(spv, ident)) | ||
| 69 | return float(m.group(1)) if m else None | ||
| 70 | |||
| 71 | |||
| 72 | def lod_operand(line): | ||
| 73 | m = re.search(r" Lod (%\w+)", line) | ||
| 74 | return m.group(1) if m else None | ||
| 75 | |||
| 76 | |||
| 77 | class ExplicitLodBias(unittest.TestCase): | ||
| 78 | def test_lz_literal_bias_is_added_to_the_lod(self): | ||
| 79 | line = f"image_sample_lz v[6:7], v[2:3], s[8:15], s[16:19] dmask:0x3 {D2}" | ||
| 80 | off = samples(translate("ps_lb_lz_off", literal_ssharp(0x100), line, False)) | ||
| 81 | on_spv = translate("ps_lb_lz_on", literal_ssharp(0x100), line, True) | ||
| 82 | on = samples(on_spv) | ||
| 83 | self.assertTrue(off and all(lod_operand(s) == "%f0" for s in off), off) | ||
| 84 | lods = {lod_operand(s) for s in on} | ||
| 85 | self.assertEqual(len(lods), 1, on) | ||
| 86 | rhs = defn(on_spv, lods.pop()) | ||
| 87 | m = re.match(r"OpFAdd %float %f0 (%\w+)$", rhs) | ||
| 88 | self.assertTrue(m, rhs) | ||
| 89 | self.assertEqual(float_const(on_spv, m.group(1)), 1.0) | ||
| 90 | |||
| 91 | def test_negative_fraction_and_zero_bias(self): | ||
| 92 | line = f"image_sample_lz v[6:7], v[2:3], s[8:15], s[16:19] dmask:0x3 {D2}" | ||
| 93 | spv = translate("ps_lb_neg", literal_ssharp(-77), line, True) # -77 / 256 | ||
| 94 | rhs = defn(spv, lod_operand(samples(spv)[0])) | ||
| 95 | m = re.match(r"OpFAdd %float %f0 (%\w+)$", rhs) | ||
| 96 | self.assertTrue(m, rhs) | ||
| 97 | self.assertAlmostEqual(float_const(spv, m.group(1)), -77 / 256) | ||
| 98 | zero = samples(translate("ps_lb_zero", literal_ssharp(0), line, True)) | ||
| 99 | self.assertTrue(all(lod_operand(s) == "%f0" for s in zero), zero) | ||
| 100 | |||
| 101 | def test_runtime_ssharp_is_decoded_from_word_2(self): | ||
| 102 | line = f"image_sample_l v[6:7], v[2:4], s[8:15], s[16:19] dmask:0x3 {D2}" | ||
| 103 | spv = translate("ps_lb_rt", LOADED, line, True) | ||
| 104 | self.assertRegex(spv, r"OpBitFieldSExtract %uint %\w+ %\w+ %\w+") | ||
| 105 | lod = lod_operand(samples(spv)[0]) | ||
| 106 | self.assertRegex(defn(spv, lod), r"^OpFAdd %float %\w+ %\w+$") | ||
| 107 | plain = translate("ps_lb_rt_off", LOADED, line, False) | ||
| 108 | self.assertNotIn("OpBitFieldSExtract", plain.split("OpImageSample")[0][-2000:]) | ||
| 109 | |||
| 110 | def test_typed_implicit_scales_the_derivatives(self): | ||
| 111 | line = f"image_sample v[6:7], v[2:3], s[8:15], s[16:19] dmask:0x3 {D2}" | ||
| 112 | off = translate("ps_lb_grad_off", literal_ssharp(0x100), line, False) | ||
| 113 | on = translate("ps_lb_grad_on", literal_ssharp(0x100), line, True) | ||
| 114 | self.assertNotIn("Exp2", off) | ||
| 115 | self.assertIn("Exp2", on) | ||
| 116 | grads = [re.search(r" Grad (%\w+) (%\w+)", s) for s in samples(on)] | ||
| 117 | self.assertTrue(grads and all(grads), samples(on)) | ||
| 118 | for g in grads: | ||
| 119 | for ident in g.groups(): | ||
| 120 | self.assertTrue(defn(on, ident).startswith("OpVectorTimesScalar %v2float"), defn(on, ident)) | ||
| 121 | |||
| 122 | def test_implicit_3d_takes_a_bias_operand(self): | ||
| 123 | line = f"image_sample v[6:7], v[2:4], s[8:15], s[16:19] dmask:0x3 {D3}" | ||
| 124 | off = samples(translate("ps_lb_3d_off", literal_ssharp(0x100), line, False)) | ||
| 125 | on = samples(translate("ps_lb_3d_on", literal_ssharp(0x100), line, True)) | ||
| 126 | self.assertTrue(off and not any(" Bias " in s for s in off), off) | ||
| 127 | self.assertTrue(on and all("ImplicitLod" in s and " Bias " in s for s in on), on) | ||
| 128 | |||
| 129 | def test_sample_b_adds_to_its_own_bias(self): | ||
| 130 | line = f"image_sample_b v[6:7], v[2:5], s[8:15], s[16:19] dmask:0x3 {D3}" | ||
| 131 | spv = translate("ps_lb_b", literal_ssharp(0x100), line, True) | ||
| 132 | on = samples(spv) | ||
| 133 | m = re.search(r" Bias (%\w+)", on[0]) | ||
| 134 | self.assertTrue(m, on) | ||
| 135 | self.assertRegex(defn(spv, m.group(1)), r"^OpFAdd %float %\w+ %\w+$") | ||
| 136 | |||
| 137 | def test_compute_implicit_sample_adds_to_lod_zero(self): | ||
| 138 | line = f"image_sample v[6:7], v[2:4], s[8:15], s[16:19] dmask:0x3 {D3}" | ||
| 139 | off = samples(translate("cs_lb_off", literal_ssharp(0x100), line, False)) | ||
| 140 | spv = translate("cs_lb_on", literal_ssharp(0x100), line, True) | ||
| 141 | on = samples(spv) | ||
| 142 | self.assertTrue(all(lod_operand(s) == "%f0" for s in off), off) | ||
| 143 | self.assertRegex(defn(spv, lod_operand(on[0])), r"^OpFAdd %float %f0 %\w+$") | ||
| 144 | |||
| 145 | def test_compute_cl_clamps_after_the_bias(self): | ||
| 146 | # Vulkan clamps the biased LOD: max(0 + bias, minlod), as _b_cl's max(bias, minlod), not max(0, minlod) + bias | ||
| 147 | for op, vaddr in (("image_sample_cl", "v[2:4]"), ("image_sample_c_cl", "v[2:5]")): | ||
| 148 | with self.subTest(op=op): | ||
| 149 | line = f"{op} v[6:7], {vaddr}, s[8:15], s[16:19] dmask:0x3 {D2}" | ||
| 150 | off = translate("cs_lb_cl_off", literal_ssharp(0x100), line, False) | ||
| 151 | self.assertRegex(defn(off, lod_operand(samples(off)[0])), r"^OpExtInst %float %glsl FMax %f0 %\w+$") | ||
| 152 | spv = translate("cs_lb_cl_on", literal_ssharp(0x100), line, True) | ||
| 153 | m = re.match(r"^OpExtInst %float %glsl FMax (%\w+) %\w+$", defn(spv, lod_operand(samples(spv)[0]))) | ||
| 154 | self.assertTrue(m, samples(spv)) | ||
| 155 | self.assertRegex(defn(spv, m.group(1)), r"^OpFAdd %float %f0 %\w+$") | ||
| 156 | |||
| 157 | |||
| 158 | if __name__ == "__main__": | ||
| 159 | unittest.main() | ||
diff --git a/tests/semantic/test_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py index d4adde9a5..f61813e5c 100644 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ b/tests/semantic/test_lane_masks_vector_bitwise.py | |||
| @@ -144,6 +144,32 @@ def _bitwise_mask_lines(wave_size): | |||
| 144 | return lines | 144 | return lines |
| 145 | 145 | ||
| 146 | 146 | ||
| 147 | def _readfirstlane_vgpr_dst_lines(wave_size): | ||
| 148 | """v_readfirstlane_b32 into a VGPR of a mask-holding VGPR, stored back as data. The | ||
| 149 | destination is plain data — VGPR writes are never mask-tracked — so every lane must get | ||
| 150 | the broadcast wave mask word, not this lane's 0 / ~0 bit (the mask word here is the low | ||
| 151 | word in wave64, which is all v2 holds).""" | ||
| 152 | is64 = wave_size == 64 | ||
| 153 | r = { | ||
| 154 | "exec": "exec" if is64 else "exec_lo", | ||
| 155 | "mov": "s_mov_b64" if is64 else "s_mov_b32", | ||
| 156 | "s6": "s[6:7]" if is64 else "s6", | ||
| 157 | "s8": "s[8:9]" if is64 else "s8", | ||
| 158 | "s10": "s[10:11]" if is64 else "s10", | ||
| 159 | } | ||
| 160 | return [ | ||
| 161 | f"{r['mov']} {r['exec']}, -1", | ||
| 162 | "v_and_b32 v1, 1, v0", | ||
| 163 | f"v_cmp_eq_u32_e64 {r['s6']}, v1, 0", # even lanes | ||
| 164 | f"v_cmp_lt_u32_e64 {r['s8']}, v0, 10", # lanes < 10 | ||
| 165 | f"v_cmp_lt_u32_e64 {r['s10']}, v0, 20", # lanes < 20 | ||
| 166 | "v_and_or_b32 v2, s6, s8, s10", # mask VGPR: (even & <10) | <20 | ||
| 167 | "v_readfirstlane_b32 v3, v2", # VGPR dst: the broadcast mask word | ||
| 168 | "v_mul_lo_u32 v14, v0, 36", | ||
| 169 | "buffer_store_dword v3, v14, s[0:3], 0 offen", | ||
| 170 | ] | ||
| 171 | |||
| 172 | |||
| 147 | def _vgpr_stores(spv): | 173 | def _vgpr_stores(spv): |
| 148 | """Return mapping `vgpr_idx -> [rhs_expression, ...]` for constant-index `%vgpr` OpStores.""" | 174 | """Return mapping `vgpr_idx -> [rhs_expression, ...]` for constant-index `%vgpr` OpStores.""" |
| 149 | const_uint = {} | 175 | const_uint = {} |
| @@ -187,20 +213,41 @@ class _VectorBitwiseMixin: | |||
| 187 | want_andor = [((i & 1 == 0) and i < 10) or (i & 2 == 0) for i in range(self.wave_size)] | 213 | want_andor = [((i & 1 == 0) and i < 10) or (i & 2 == 0) for i in range(self.wave_size)] |
| 188 | want_xnor = [(i & 1 == 0) == (i < 10) for i in range(self.wave_size)] | 214 | want_xnor = [(i & 1 == 0) == (i < 10) for i in range(self.wave_size)] |
| 189 | want_bfi = [(i < 10) if (i & 1 == 0) else (i & 2 == 0) for i in range(self.wave_size)] | 215 | want_bfi = [(i < 10) if (i & 1 == 0) else (i & 2 == 0) for i in range(self.wave_size)] |
| 190 | cnt_andor = sum(want_andor) | ||
| 191 | cnt_xnor = sum(want_xnor) | ||
| 192 | cnt_bfi = sum(want_bfi) | ||
| 193 | for lane in range(self.wave_size): | 216 | for lane in range(self.wave_size): |
| 194 | base = lane * 36 | 217 | base = lane * 36 |
| 195 | self.assertEqual(mem[base], 0xFFFFFFFF if want_andor[lane] else 0, f"lane {lane} raw and_or") | 218 | # The mask reads run while EXEC is narrowed to lanes < 10. Hardware SGPRs hold the |
| 196 | self.assertEqual(mem[base + 4], 0xFFFFFFFF if want_xnor[lane] else 0, f"lane {lane} raw xnor") | 219 | # whole wave's mask word, and the eager gather sees the lanes EXEC has off too, so the |
| 197 | self.assertEqual(mem[base + 8], 0xFFFFFFFF if want_bfi[lane] else 0, f"lane {lane} raw bfi") | 220 | # bitwise VALU op composes the 32-bit mask words themselves. The VGPR result is that |
| 198 | self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, f"lane {lane} cndmask and_or") | 221 | # wave-uniform word in every lane (for the low-half SGPRs in wave64 as well). |
| 199 | self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, f"lane {lane} cndmask xnor") | 222 | andor_word = sum((1 << i) for i, b in enumerate(want_andor[:32]) if b) |
| 200 | self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, f"lane {lane} cndmask bfi") | 223 | xnor_word = sum((1 << i) for i, b in enumerate(want_xnor[:32]) if b) |
| 201 | self.assertEqual(mem[base + 24], cnt_andor, f"lane {lane} bcnt and_or") | 224 | bfi_word = sum((1 << i) for i, b in enumerate(want_bfi[:32]) if b) |
| 202 | self.assertEqual(mem[base + 28], cnt_xnor, f"lane {lane} bcnt xnor") | 225 | self.assertEqual(mem[base], andor_word, f"lane {lane} raw and_or") |
| 203 | self.assertEqual(mem[base + 32], cnt_bfi, f"lane {lane} bcnt bfi") | 226 | self.assertEqual(mem[base + 4], xnor_word, f"lane {lane} raw xnor") |
| 227 | self.assertEqual(mem[base + 8], bfi_word, f"lane {lane} raw bfi") | ||
| 228 | # readfirstlane broadcasts lane 0's copy of the composed wave mask word. Mask consumers | ||
| 229 | # extract each lane's own bit again: cndmask follows that lane's membership, and bcnt | ||
| 230 | # counts the set bits of the composed masks (low plus high halves in wave64). | ||
| 231 | self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, | ||
| 232 | f"lane {lane} cndmask and_or") | ||
| 233 | self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, | ||
| 234 | f"lane {lane} cndmask xnor") | ||
| 235 | self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, | ||
| 236 | f"lane {lane} cndmask bfi") | ||
| 237 | self.assertEqual(mem[base + 24], sum(want_andor), f"lane {lane} bcnt and_or") | ||
| 238 | self.assertEqual(mem[base + 28], sum(want_xnor), f"lane {lane} bcnt xnor") | ||
| 239 | self.assertEqual(mem[base + 32], sum(want_bfi), f"lane {lane} bcnt bfi") | ||
| 240 | |||
| 241 | def test_readfirstlane_mask_vgpr_dst_gets_wave_word(self): | ||
| 242 | mem = _run_cs( | ||
| 243 | f"cs_rfl_vgpr_w{self.wave_size}", | ||
| 244 | _readfirstlane_vgpr_dst_lines(self.wave_size), | ||
| 245 | wave_size=self.wave_size, | ||
| 246 | ) | ||
| 247 | # (even & lane < 10) | lane < 20 -> lanes 0..19 of the low word, the same in every lane. | ||
| 248 | want = sum(1 << i for i in range(32) if ((i & 1) == 0 and i < 10) or i < 20) | ||
| 249 | for lane in range(self.wave_size): | ||
| 250 | self.assertEqual(mem[lane * 36], want, f"lane {lane} readfirstlane dst") | ||
| 204 | 251 | ||
| 205 | 252 | ||
| 206 | class TestVectorBitwiseMasksWave32(_VectorBitwiseMixin, unittest.TestCase): | 253 | class TestVectorBitwiseMasksWave32(_VectorBitwiseMixin, unittest.TestCase): |
| @@ -223,7 +270,9 @@ class TestVectorBitwiseMasksWave64Emulated(unittest.TestCase): | |||
| 223 | ) | 270 | ) |
| 224 | self.assertTrue(gen.wave64 and gen.emulate) | 271 | self.assertTrue(gen.wave64 and gen.emulate) |
| 225 | self.assertEqual(len(gen.mask_writes), 6) | 272 | self.assertEqual(len(gen.mask_writes), 6) |
| 226 | self.assertNotIn("FindILsb", spv) | 273 | # Emulation exchanges through %x_buf instead of subgroup ops; FindILsb (GLSL extinst) is fine — |
| 274 | # the readfirstlane of a mask VGPR now takes the exchange path like any other readfirstlane. | ||
| 275 | self.assertNotIn("OpGroupNonUniform", spv) | ||
| 227 | self.assertIn("OpControlBarrier", spv) | 276 | self.assertIn("OpControlBarrier", spv) |
| 228 | self.assertIn("OpStore %x_it", spv) | 277 | self.assertIn("OpStore %x_it", spv) |
| 229 | stores = _vgpr_stores(spv) | 278 | stores = _vgpr_stores(spv) |
| @@ -234,6 +283,16 @@ class TestVectorBitwiseMasksWave64Emulated(unittest.TestCase): | |||
| 234 | for vreg in (4, 7): # v_bfi_b32 -> final OpBitwiseOr | 283 | for vreg in (4, 7): # v_bfi_b32 -> final OpBitwiseOr |
| 235 | self.assertTrue(stores[vreg][-1].startswith("OpBitwiseOr %uint "), stores[vreg][-1]) | 284 | self.assertTrue(stores[vreg][-1].startswith("OpBitwiseOr %uint "), stores[vreg][-1]) |
| 236 | 285 | ||
| 286 | def test_readfirstlane_vgpr_dst_emulate_structure(self): | ||
| 287 | spv, gen = _translate_cs( | ||
| 288 | "cs_rfl_vgpr_w64_emu", | ||
| 289 | _readfirstlane_vgpr_dst_lines(64), | ||
| 290 | wave_size=64, | ||
| 291 | emulate=True, | ||
| 292 | ) | ||
| 293 | self.assertTrue(gen.wave64 and gen.emulate) | ||
| 294 | self.assertNotIn("OpGroupNonUniform", spv) | ||
| 295 | |||
| 237 | 296 | ||
| 238 | class TestVectorBitwiseDataControl(unittest.TestCase): | 297 | class TestVectorBitwiseDataControl(unittest.TestCase): |
| 239 | def test_non_mask_data_stays_exec_gated_wave32(self): | 298 | def test_non_mask_data_stays_exec_gated_wave32(self): |
| @@ -269,5 +328,213 @@ class TestVectorBitwiseDataControl(unittest.TestCase): | |||
| 269 | self.assertEqual(mem[base + 8], SENTINEL, f"inactive lane {lane} bfi") | 328 | self.assertEqual(mem[base + 8], SENTINEL, f"inactive lane {lane} bfi") |
| 270 | 329 | ||
| 271 | 330 | ||
| 331 | class TestScalarMaskNumberReads(unittest.TestCase): | ||
| 332 | """A scalar ALU op that reads a lane mask as a number gets the wave's mask word, not this | ||
| 333 | lane's 0 / ~0 bit (MASK_NUMBER_READERS, ported from #1043's NUMBER_READERS). Mask moves and | ||
| 334 | mask logic ops keep the bit so the saveexec/restore and mask-copy idioms still work.""" | ||
| 335 | |||
| 336 | def _run(self, lines, wave_size=32, emulate=False): | ||
| 337 | prologue = ["s_mov_b64 exec, -1"] if wave_size == 64 else [] | ||
| 338 | body = prologue + lines + [ | ||
| 339 | "v_lshlrev_b32_e32 v9, 2, v0", | ||
| 340 | "buffer_store_dword v4, v9, s[0:3], 0 offen", | ||
| 341 | "s_endpgm", | ||
| 342 | ] | ||
| 343 | mem = _run_cs("cs_scalar_masknum", body, wave_size=wave_size, emulate=emulate) | ||
| 344 | return {mem[4 * lane] for lane in range(wave_size) if 4 * lane in mem} | ||
| 345 | |||
| 346 | def test_scalar_add_reads_mask_word(self): | ||
| 347 | # wave32: mask of lanes < 10 -> word 0x3FF. wave64: mask of lanes < 43 -> the s10 operand | ||
| 348 | # is the low half, all 32 low lanes set -> 0xFFFFFFFF. The scalar op is uniform: every | ||
| 349 | # lane's v4 is the same word + 0x1234. | ||
| 350 | for wave, lanes, dst, word in ((32, 10, "s10", 0x3FF), (64, 43, "s[10:11]", 0xFFFFFFFF)): | ||
| 351 | with self.subTest(wave=wave): | ||
| 352 | got = self._run( | ||
| 353 | [f"v_cmp_gt_u32_e64 {dst}, {lanes}, v0", | ||
| 354 | "s_add_u32 s20, s10, 0x1234", | ||
| 355 | "v_mov_b32_e32 v4, s20"], wave_size=wave) | ||
| 356 | self.assertEqual(got, {(word + 0x1234) & 0xFFFFFFFF}) | ||
| 357 | |||
| 358 | def test_scalar_readers_table(self): | ||
| 359 | # A representative slice of MASK_NUMBER_READERS on wave32: mask of lanes < 10 -> 0x3FF. | ||
| 360 | setup = ["v_cmp_gt_u32_e64 s10, 10, v0"] | ||
| 361 | cases = { | ||
| 362 | "s_add_u32 s20, s10, 0x1234": (0x3FF + 0x1234) & 0xFFFFFFFF, | ||
| 363 | "s_sub_u32 s20, s10, 0x1234": (0x3FF - 0x1234) & 0xFFFFFFFF, | ||
| 364 | "s_mul_i32 s20, s10, 0x1234": (0x3FF * 0x1234) & 0xFFFFFFFF, | ||
| 365 | "s_lshl_b32 s20, s10, 3": (0x3FF << 3) & 0xFFFFFFFF, | ||
| 366 | "s_lshr_b32 s20, s10, 3": 0x3FF >> 3, | ||
| 367 | "s_brev_b32 s20, s10": int(f"{0x3FF:032b}"[::-1], 2), | ||
| 368 | "s_min_u32 s20, s10, 0x1234": min(0x3FF, 0x1234), | ||
| 369 | "s_max_u32 s20, s10, 0x1234": max(0x3FF, 0x1234), | ||
| 370 | } | ||
| 371 | for op, want in cases.items(): | ||
| 372 | with self.subTest(op=op): | ||
| 373 | got = self._run(setup + [op, "v_mov_b32_e32 v4, s20"]) | ||
| 374 | self.assertEqual(got, {want}) | ||
| 375 | |||
| 376 | def test_mask_copy_keeps_bit_then_scalar_reads_word(self): | ||
| 377 | # s_mov_b32 is not a number reader: the copy stays a mask (per-lane bit), and the scalar | ||
| 378 | # add on the copy still gathers the word because lane_masks tracks s11 as a mask. | ||
| 379 | got = self._run(["v_cmp_gt_u32_e64 s10, 10, v0", "s_mov_b32 s11, s10", | ||
| 380 | "s_add_u32 s20, s11, 1", "v_mov_b32_e32 v4, s20"]) | ||
| 381 | self.assertEqual(got, {0x400}) | ||
| 382 | |||
| 383 | def test_exec_as_data_gathers_exec_word(self): | ||
| 384 | # exec_lo narrowed to lanes < 10 by saveexec: the EXEC operand's own word still gathers — | ||
| 385 | # lanes off in EXEC contribute 0 either way, so every driver agrees. | ||
| 386 | got = self._run(["v_cmp_gt_u32_e64 s10, 10, v0", | ||
| 387 | "s_and_saveexec_b32 s12, s10", | ||
| 388 | "s_add_u32 s20, exec_lo, 1", | ||
| 389 | "s_mov_b32 exec_lo, s12", | ||
| 390 | "v_mov_b32_e32 v4, s20"]) | ||
| 391 | self.assertEqual(got, {0x3FF + 1}) | ||
| 392 | |||
| 393 | |||
| 394 | class TestMaskDataReadExecGate(unittest.TestCase): | ||
| 395 | """A lane-mask data read gathers the wave's mask word even while EXEC is narrowed. EXEC is a | ||
| 396 | per-lane value in the translator's model, not SPIR-V control flow; the mask-data reader is kept | ||
| 397 | out of lane-local `if (active)` runs and wave_mask's eager store keeps drivers from moving the | ||
| 398 | subgroup gather into an EXEC-selected arm. Thus lanes EXEC has off still contribute the bits they | ||
| 399 | hold, as hardware's wave-wide mask register does.""" | ||
| 400 | |||
| 401 | def _lines(self, tail): | ||
| 402 | return [ | ||
| 403 | "v_and_b32 v1, 1, v0", | ||
| 404 | "v_cmp_eq_u32_e64 vcc_lo, v1, 1", # VCC = odd lanes, 0xAAAAAAAA | ||
| 405 | f"v_mov_b32_e32 v2, {SENTINEL:#x}", # sentinel: lanes EXEC leaves off keep it | ||
| 406 | "s_mov_b32 exec_lo, 0x55555555", # EXEC = even lanes | ||
| 407 | ] + tail + [ | ||
| 408 | "v_lshlrev_b32_e32 v3, 2, v0", | ||
| 409 | "buffer_store_dword v2, v3, s[0:3], 0 offen", | ||
| 410 | "s_endpgm", | ||
| 411 | ] | ||
| 412 | |||
| 413 | def test_vcc_read_under_narrowed_exec_gathers_mask_word(self): | ||
| 414 | lines = self._lines(["v_mov_b32_e32 v2, vcc_lo"]) | ||
| 415 | spv, _ = _translate_cs("cs_maskdata_narrowed", lines, wave_size=32, emulate=False) | ||
| 416 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 417 | mem = _run_cs("cs_maskdata_narrowed_run", lines, wave_size=32, emulate=False) | ||
| 418 | for lane in range(32): | ||
| 419 | # EXEC-active even lanes store the whole odd-lane VCC word; odd lanes are off in EXEC, | ||
| 420 | # so the store doesn't run for them. | ||
| 421 | if lane & 1: | ||
| 422 | self.assertNotIn(lane * 4, mem, f"lane {lane}") | ||
| 423 | else: | ||
| 424 | self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") | ||
| 425 | |||
| 426 | def test_sgpr_read_under_narrowed_exec_gathers_mask_word(self): | ||
| 427 | # Gefik23's crosslane_fuzz family: a compare-written SGPR mask read after EXEC narrows. | ||
| 428 | lines = [ | ||
| 429 | "v_and_b32 v1, 1, v0", | ||
| 430 | "v_cmp_eq_u32_e64 s10, v1, 1", # s10 = odd lanes, 0xAAAAAAAA | ||
| 431 | f"v_mov_b32_e32 v2, {SENTINEL:#x}", | ||
| 432 | "s_mov_b32 exec_lo, 0x55555555", # EXEC = even lanes | ||
| 433 | "v_mov_b32_e32 v2, s10", | ||
| 434 | "v_lshlrev_b32_e32 v3, 2, v0", | ||
| 435 | "buffer_store_dword v2, v3, s[0:3], 0 offen", | ||
| 436 | "s_endpgm", | ||
| 437 | ] | ||
| 438 | spv, _ = _translate_cs("cs_maskdata_sgpr_narrowed", lines, wave_size=32, emulate=False) | ||
| 439 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 440 | mem = _run_cs("cs_maskdata_sgpr_narrowed_run", lines, wave_size=32, emulate=False) | ||
| 441 | for lane in range(32): | ||
| 442 | if lane & 1: | ||
| 443 | self.assertNotIn(lane * 4, mem, f"lane {lane}") | ||
| 444 | else: | ||
| 445 | self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") | ||
| 446 | |||
| 447 | def test_sgpr_read_after_independent_full_exec_restore_gathers(self): | ||
| 448 | # ecox982745's independent-SGPR restore: s7 is runtime-all-ones but is not an EXEC alias. | ||
| 449 | # The mask word is still the wave-wide value; no EXEC provenance proof is needed. | ||
| 450 | lines = [ | ||
| 451 | "v_mov_b32_e32 v7, -1", | ||
| 452 | "v_readfirstlane_b32 s7, v7", | ||
| 453 | "v_and_b32 v1, 1, v0", | ||
| 454 | "v_cmp_ne_u32_e64 s10, v1, 0", # odd lanes | ||
| 455 | "s_mov_b32 exec_lo, s7", | ||
| 456 | "v_mov_b32_e32 v2, s10", | ||
| 457 | "v_lshlrev_b32_e32 v3, 2, v0", | ||
| 458 | "buffer_store_dword v2, v3, s[0:3], 0 offen", | ||
| 459 | "s_endpgm", | ||
| 460 | ] | ||
| 461 | spv, _ = _translate_cs("cs_maskdata_independent_exec", lines, wave_size=32, emulate=False) | ||
| 462 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 463 | mem = _run_cs("cs_maskdata_independent_exec_run", lines, wave_size=32, emulate=False) | ||
| 464 | for lane in range(32): | ||
| 465 | self.assertEqual(mem[lane * 4], 0xAAAAAAAA, f"lane {lane}") | ||
| 466 | |||
| 467 | def test_vcc_read_after_exec_restore_gathers(self): | ||
| 468 | lines = self._lines(["s_mov_b32 exec_lo, -1", "v_mov_b32_e32 v2, vcc_lo"]) | ||
| 469 | spv, _ = _translate_cs("cs_maskdata_restored", lines, wave_size=32, emulate=False) | ||
| 470 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 471 | mem = _run_cs("cs_maskdata_restored_run", lines, wave_size=32, emulate=False) | ||
| 472 | want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, every lane | ||
| 473 | for lane in range(32): | ||
| 474 | self.assertEqual(mem[lane * 4], want, f"lane {lane}") | ||
| 475 | |||
| 476 | def test_exec_read_under_narrowed_exec_still_gathers(self): | ||
| 477 | lines = self._lines(["v_mov_b32_e32 v2, exec_lo"]) | ||
| 478 | spv, _ = _translate_cs("cs_execdata_narrowed", lines, wave_size=32, emulate=False) | ||
| 479 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 480 | mem = _run_cs("cs_execdata_narrowed_run", lines, wave_size=32, emulate=False) | ||
| 481 | for lane in range(32): | ||
| 482 | # EXEC's word is 0x55555555; only the even lanes EXEC leaves on store it. | ||
| 483 | if lane & 1: | ||
| 484 | self.assertNotIn(lane * 4, mem, f"lane {lane}") | ||
| 485 | else: | ||
| 486 | self.assertEqual(mem[lane * 4], 0x55555555, f"lane {lane}") | ||
| 487 | |||
| 488 | def test_exec_copy_roundtrip_keeps_mask_gather(self): | ||
| 489 | # `s_mov_b32 s4, exec_lo` copies EXEC under an unknown narrowing and `s_mov_b32 exec_lo, s4` | ||
| 490 | # restores the same value — EXEC is unchanged, so a mask written under that narrowing must | ||
| 491 | # still gather. The copy has to carry the narrowing's tag into `alias`: without it the | ||
| 492 | # restore minted a fresh tag in _exec_src_ex, mask_exec_sigs coverage failed and the read | ||
| 493 | # kept this lane's 0 / ~0 bit where `s_mov_b32 exec_lo, -1` gathered the word (#1397 review). | ||
| 494 | lines = [ | ||
| 495 | "v_mov_b32_e32 v7, -1", | ||
| 496 | "v_readfirstlane_b32 s7, v7", # s7 = 0xffffffff, not a tracked constant | ||
| 497 | "s_mov_b32 exec_lo, s7", # EXEC = unknown narrowing, runtime all-ones | ||
| 498 | "v_and_b32 v1, 1, v0", | ||
| 499 | "v_cmp_ne_u32_e64 s10, v1, 0", # odd-lane mask written under that EXEC | ||
| 500 | "s_mov_b32 s4, exec_lo", | ||
| 501 | "s_mov_b32 exec_lo, s4", | ||
| 502 | "v_mov_b32_e32 v2, s10", | ||
| 503 | "v_lshlrev_b32_e32 v3, 2, v0", | ||
| 504 | "buffer_store_dword v2, v3, s[0:3], 0 offen", | ||
| 505 | "s_endpgm", | ||
| 506 | ] | ||
| 507 | spv, _ = _translate_cs("cs_maskdata_exec_copy", lines, wave_size=32, emulate=False) | ||
| 508 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 509 | mem = _run_cs("cs_maskdata_exec_copy_run", lines, wave_size=32, emulate=False) | ||
| 510 | want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, every lane | ||
| 511 | for lane in range(32): | ||
| 512 | self.assertEqual(mem[lane * 4], want, f"lane {lane}") | ||
| 513 | |||
| 514 | def test_exec_copy_roundtrip_keeps_mask_gather_wave64(self): | ||
| 515 | # Same round-trip on the exec_lo half of a wave64 EXEC: the VCC mask's low word must still | ||
| 516 | # gather while exec_hi stays clean. | ||
| 517 | lines = [ | ||
| 518 | "s_mov_b64 exec, -1", # wave64 marker (and a clean EXEC to start) | ||
| 519 | "v_mov_b32_e32 v7, -1", | ||
| 520 | "v_readfirstlane_b32 s7, v7", | ||
| 521 | "s_mov_b32 exec_lo, s7", # exec_lo = unknown narrowing, runtime all-ones | ||
| 522 | "v_and_b32 v1, 1, v0", | ||
| 523 | "v_cmp_ne_u32_e64 vcc, v1, 0", | ||
| 524 | "s_mov_b32 s4, exec_lo", | ||
| 525 | "s_mov_b32 exec_lo, s4", | ||
| 526 | "v_mov_b32_e32 v2, vcc_lo", | ||
| 527 | "v_lshlrev_b32_e32 v3, 2, v0", | ||
| 528 | "buffer_store_dword v2, v3, s[0:3], 0 offen", | ||
| 529 | "s_endpgm", | ||
| 530 | ] | ||
| 531 | spv, _ = _translate_cs("cs_maskdata_exec_copy_w64", lines, wave_size=64, emulate=False) | ||
| 532 | self.assertIn("OpGroupNonUniformBitwiseOr", spv) | ||
| 533 | mem = _run_cs("cs_maskdata_exec_copy_w64_run", lines, wave_size=64, emulate=False) | ||
| 534 | want = sum(1 << i for i in range(1, 32, 2)) # 0xAAAAAAAA, the vcc_lo word | ||
| 535 | for lane in range(64): | ||
| 536 | self.assertEqual(mem[lane * 4], want, f"lane {lane}") | ||
| 537 | |||
| 538 | |||
| 272 | if __name__ == "__main__": | 539 | if __name__ == "__main__": |
| 273 | unittest.main() | 540 | unittest.main() |
diff --git a/tests/semantic/test_lds_src2.py b/tests/semantic/test_lds_src2.py index 74adc4f9a..7c28e9ea9 100644 --- a/tests/semantic/test_lds_src2.py +++ b/tests/semantic/test_lds_src2.py | |||
| @@ -22,7 +22,6 @@ import os | |||
| 22 | import struct | 22 | import struct |
| 23 | import subprocess | 23 | import subprocess |
| 24 | import sys | 24 | import sys |
| 25 | import tempfile | ||
| 26 | import unittest | 25 | import unittest |
| 27 | 26 | ||
| 28 | sys.dont_write_bytecode = True | 27 | sys.dont_write_bytecode = True |
| @@ -88,13 +87,13 @@ MC = _llvm_mc() | |||
| 88 | 87 | ||
| 89 | 88 | ||
| 90 | def assemble(cpu, text): | 89 | def assemble(cpu, text): |
| 91 | """(returncode, stdout, stderr) of llvm-mc assembling `text` for `cpu`, through a file (no BOM, no pipe).""" | 90 | """(returncode, stdout, stderr) of llvm-mc assembling `text` for `cpu`, read from stdin. |
| 92 | with tempfile.TemporaryDirectory() as tmp: | 91 | |
| 93 | path = os.path.join(tmp, "in.s") | 92 | Not through a temporary file: LLVM_MC can be a WSL command (`wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc`, see |
| 94 | with open(path, "w", encoding="ascii", newline="\n") as f: | 93 | tools/mc_command.py), and llvm-mc inside WSL cannot open a Windows path. tools/shader_disasm.py feeds llvm-mc |
| 95 | f.write(text) | 94 | the same way.""" |
| 96 | r = subprocess.run(MC + ["-triple=amdgcn", f"-mcpu={cpu}", "-show-encoding", path], | 95 | r = subprocess.run(MC + ["-triple=amdgcn", f"-mcpu={cpu}", "-show-encoding"], input=text, |
| 97 | capture_output=True, text=True, timeout=60) | 96 | capture_output=True, text=True, encoding="ascii", errors="replace", timeout=60) |
| 98 | return r.returncode, r.stdout, r.stderr | 97 | return r.returncode, r.stdout, r.stderr |
| 99 | 98 | ||
| 100 | 99 | ||
diff --git a/tests/semantic/test_salu64_bitwise_data.py b/tests/semantic/test_salu64_bitwise_data.py index c8e3f1838..76ca1c8d3 100644 --- a/tests/semantic/test_salu64_bitwise_data.py +++ b/tests/semantic/test_salu64_bitwise_data.py | |||
| @@ -558,9 +558,11 @@ class LaneMaskPreservationTests(unittest.TestCase): | |||
| 558 | "v_mov_b32 v3, 0", | 558 | "v_mov_b32 v3, 0", |
| 559 | ] | 559 | ] |
| 560 | outs, _ = run_ps_wave(lines, wave=32) | 560 | outs, _ = run_ps_wave(lines, wave=32) |
| 561 | # v2 = v_mov_b32 of the mask result s[6:7]: a data read gives the whole wave's mask | ||
| 562 | # word, the same in every lane, not this lane's 0 / ~0 bit. | ||
| 563 | want_word = sum(1 << l for l in range(32) if pred(l)) | ||
| 561 | for lane in range(32): | 564 | for lane in range(32): |
| 562 | want_bit = MASK32 if pred(lane) else 0 | 565 | self.assertEqual(outs[lane], (want_cnt, want_scc, want_word, 0), f"lane={lane}") |
| 563 | self.assertEqual(outs[lane], (want_cnt, want_scc, want_bit, 0), f"lane={lane}") | ||
| 564 | 566 | ||
| 565 | # Empty mask intersection -> SCC=0 across all lanes, and null dst on lane-mask path sets SCC. | 567 | # Empty mask intersection -> SCC=0 across all lanes, and null dst on lane-mask path sets SCC. |
| 566 | lines = [ | 568 | lines = [ |
diff --git a/tests/semantic/test_salu_movrels_lane_mask.py b/tests/semantic/test_salu_movrels_lane_mask.py index 15a791609..71b213651 100644 --- a/tests/semantic/test_salu_movrels_lane_mask.py +++ b/tests/semantic/test_salu_movrels_lane_mask.py | |||
| @@ -80,7 +80,9 @@ class MovrelsLaneMaskWave32(unittest.TestCase): | |||
| 80 | with self.subTest(lane=lane): | 80 | with self.subTest(lane=lane): |
| 81 | self.assertEqual((d, bits), (5, 2)) | 81 | self.assertEqual((d, bits), (5, 2)) |
| 82 | self.assertEqual(ctl_bits, 2) | 82 | self.assertEqual(ctl_bits, 2) |
| 83 | self.assertEqual(ctl_d, 0xFFFFFFFF if lane in (0, 2) else 0) # a copy stays a mask | 83 | # The copy stays a mask (ctl_bits), but the VALU read of it is a data read: every lane gets |
| 84 | # the whole wave's mask word 5, not its own 0 / ~0 bit. | ||
| 85 | self.assertEqual(ctl_d, 5) | ||
| 84 | 86 | ||
| 85 | def test_index_from_m0_hits_mask_and_data_neighbours(self): | 87 | def test_index_from_m0_hits_mask_and_data_neighbours(self): |
| 86 | # s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9. | 88 | # s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9. |
diff --git a/tests/semantic/test_scselect_b64_data.py b/tests/semantic/test_scselect_b64_data.py index 2dd7032b3..85a631e28 100644 --- a/tests/semantic/test_scselect_b64_data.py +++ b/tests/semantic/test_scselect_b64_data.py | |||
| @@ -380,10 +380,12 @@ class LaneMaskPreservationTests(unittest.TestCase): | |||
| 380 | ] | 380 | ] |
| 381 | outs, _ = run_ps_wave(lines, wave=32) | 381 | outs, _ = run_ps_wave(lines, wave=32) |
| 382 | want_cnt = 10 if scc else 16 | 382 | want_cnt = 10 if scc else 16 |
| 383 | # v3 = v_mov_b32 of mask SGPR s4: a data read gives the whole wave's mask word, | ||
| 384 | # the same in every lane, not this lane's 0 / ~0 bit. | ||
| 385 | want_s4 = sum(1 << l for l in range(32) if ((l < 10) if scc else (l >= 16))) | ||
| 383 | for lane in range(32): | 386 | for lane in range(32): |
| 384 | in_mask = (lane < 10) if scc else (lane >= 16) | 387 | in_mask = (lane < 10) if scc else (lane >= 16) |
| 385 | want_v1 = 0x55 if (scc == 0 or in_mask) else 0xAA | 388 | want_v1 = 0x55 if (scc == 0 or in_mask) else 0xAA |
| 386 | want_s4 = MASK32 if in_mask else 0 | ||
| 387 | self.assertEqual(outs[lane], (want_cnt, want_v1, scc, want_s4), f"lane={lane}") | 389 | self.assertEqual(outs[lane], (want_cnt, want_v1, scc, want_s4), f"lane={lane}") |
| 388 | 390 | ||
| 389 | def test_wave64_vcc_exec_and_sgpr_masks(self): | 391 | def test_wave64_vcc_exec_and_sgpr_masks(self): |
diff --git a/tests/semantic/test_slot67_operand_forms.py b/tests/semantic/test_slot67_operand_forms.py index e54188c71..af9978058 100644 --- a/tests/semantic/test_slot67_operand_forms.py +++ b/tests/semantic/test_slot67_operand_forms.py | |||
| @@ -20,9 +20,7 @@ class Slot67OperandForms(unittest.TestCase): | |||
| 20 | 20 | ||
| 21 | # The merge into main kept main's wave32 VCC_HI model (47494e725: VCC_HI that holds a compare result is a | 21 | # The merge into main kept main's wave32 VCC_HI model (47494e725: VCC_HI that holds a compare result is a |
| 22 | # per-lane mask), not this branch's packed-word form (1f001c739). On hardware `s_mov_b32 s8, vcc_hi` copies the | 22 | # per-lane mask), not this branch's packed-word form (1f001c739). On hardware `s_mov_b32 s8, vcc_hi` copies the |
| 23 | # packed 32-bit word (0x80000004 here); main's translator gives each lane its own mask value instead, so this | 23 | # packed 32-bit word (0x80000004 here); the mask-as-data read gives each lane that word, so this passes. |
| 24 | # case fails there. Kept as the expectation the translator should meet. | ||
| 25 | @unittest.expectedFailure | ||
| 26 | def test_wave32_compare_high_word_preserves_low_and_clears_inactive_bits(self): | 24 | def test_wave32_compare_high_word_preserves_low_and_clears_inactive_bits(self): |
| 27 | lines = [ | 25 | lines = [ |
| 28 | "v_cmp_lt_u32_e64 vcc_lo, v0, 6", | 26 | "v_cmp_lt_u32_e64 vcc_lo, v0, 6", |
diff --git a/tests/semantic/test_valu_int16.py b/tests/semantic/test_valu_int16.py index 13b1b242c..80d0bc228 100644 --- a/tests/semantic/test_valu_int16.py +++ b/tests/semantic/test_valu_int16.py | |||
| @@ -452,7 +452,9 @@ class ValuInt16NegativeControlsTests(unittest.TestCase): | |||
| 452 | ref_word("v_sub_nc_u16", 0x0000000A, 0x00000005)), | 452 | ref_word("v_sub_nc_u16", 0x0000000A, 0x00000005)), |
| 453 | ("v_mul_lo_u16 drops 16-bit result mask", | 453 | ("v_mul_lo_u16 drops 16-bit result mask", |
| 454 | "v_mul_lo_u16_e64 v0, v1, v2", 0x00000101, 0x00000101, | 454 | "v_mul_lo_u16_e64 v0, v1, v2", 0x00000101, 0x00000101, |
| 455 | r"(%\w+) = OpIMul %uint (%\w+) (%\w+)\n(\s*%\w+) = OpBitwiseAnd %uint \1 %cffff", | 455 | # The low-16 mask is OpBitFieldUExtract, not OpBitwiseAnd & 0xFFFF: NVIDIA's shader |
| 456 | # compiler miscompiles the And on %int-derived values feeding the high-half merge. | ||
| 457 | r"(%\w+) = OpIMul %uint (%\w+) (%\w+)\n(\s*%\w+) = OpBitFieldUExtract %uint \1 %c0 %c10\b", | ||
| 456 | r"\1 = OpIMul %uint \2 \3\n\4 = OpCopyObject %uint \1", 1, | 458 | r"\1 = OpIMul %uint \2 \3\n\4 = OpCopyObject %uint \1", 1, |
| 457 | ref_word("v_mul_lo_u16", 0x00000101, 0x00000101)), | 459 | ref_word("v_mul_lo_u16", 0x00000101, 0x00000101)), |
| 458 | ("v_min_u16 drops high-half preservation", | 460 | ("v_min_u16 drops high-half preservation", |
diff --git a/tests/test_amd_swizzle.py b/tests/test_amd_swizzle.py index bd7f86ce5..8ea62dac6 100644 --- a/tests/test_amd_swizzle.py +++ b/tests/test_amd_swizzle.py | |||
| @@ -6,6 +6,7 @@ import io | |||
| 6 | import os | 6 | import os |
| 7 | import pathlib | 7 | import pathlib |
| 8 | import sys | 8 | import sys |
| 9 | import subprocess | ||
| 9 | import tempfile | 10 | import tempfile |
| 10 | import types | 11 | import types |
| 11 | import unittest | 12 | import unittest |
| @@ -23,7 +24,7 @@ if TOOLS_DIR not in sys.path: | |||
| 23 | 24 | ||
| 24 | try: | 25 | try: |
| 25 | import amd_swizzle as A # noqa: E402 | 26 | import amd_swizzle as A # noqa: E402 |
| 26 | HAVE_NUMPY = True | 27 | HAVE_NUMPY = A.np is not None |
| 27 | except ModuleNotFoundError as e: | 28 | except ModuleNotFoundError as e: |
| 28 | if e.name != "numpy": | 29 | if e.name != "numpy": |
| 29 | raise | 30 | raise |
| @@ -39,6 +40,26 @@ else: | |||
| 39 | return fn | 40 | return fn |
| 40 | 41 | ||
| 41 | 42 | ||
| 43 | |||
| 44 | |||
| 45 | def _numpy_visible_to_the_tool() -> bool: | ||
| 46 | """Whether the tool itself can import numpy: it runs with -I, which hides the user site, and this process does | ||
| 47 | not. The two disagree when numpy came from `pip install --user`, which is exactly when the gate matters.""" | ||
| 48 | probe = subprocess.run([sys.executable, "-I", "-c", "import numpy"], capture_output=True) | ||
| 49 | return probe.returncode == 0 | ||
| 50 | |||
| 51 | |||
| 52 | needs_numpy_in_subprocess = (pytest.mark.skipif(not _numpy_visible_to_the_tool(), | ||
| 53 | reason="the tool runs with -I, which cannot see this numpy") | ||
| 54 | if pytest is not None else lambda fn: fn) | ||
| 55 | needs_pillow_in_subprocess = ( | ||
| 56 | pytest.mark.skipif( | ||
| 57 | subprocess.run([sys.executable, "-I", "-c", "from PIL import Image"], capture_output=True).returncode != 0, | ||
| 58 | reason="the tool runs with -I, which cannot import Pillow", | ||
| 59 | ) if pytest is not None else lambda fn: fn | ||
| 60 | ) | ||
| 61 | |||
| 62 | |||
| 42 | def table(name, rows): | 63 | def table(name, rows): |
| 43 | body = "\n".join(" {" + ", ".join(r) + ", }, // " + str(i) for i, r in enumerate(rows)) | 64 | body = "\n".join(" {" + ", ".join(r) + ", }, // " + str(i) for i, r in enumerate(rows)) |
| 44 | return f"const UINT_64 GFX10_SW_PATTERN_{name}[][{len(rows[0])}] =\n{{\n{body}\n}};\n" | 65 | return f"const UINT_64 GFX10_SW_PATTERN_{name}[][{len(rows[0])}] =\n{{\n{body}\n}};\n" |
| @@ -167,6 +188,7 @@ class AmdSwizzleCliGuardTests(unittest.TestCase): | |||
| 167 | 188 | ||
| 168 | fake_tables = {"GFX10_SW_64K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")]} | 189 | fake_tables = {"GFX10_SW_64K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")]} |
| 169 | with mock.patch.dict(sys.modules, {"PIL": fake_pil, "PIL.Image": fake_pil_image}), \ | 190 | with mock.patch.dict(sys.modules, {"PIL": fake_pil, "PIL.Image": fake_pil_image}), \ |
| 191 | mock.patch.object(self.mod, "_require_numpy"), \ | ||
| 170 | mock.patch.object(self.mod, "load", return_value=({}, fake_tables)), \ | 192 | mock.patch.object(self.mod, "load", return_value=({}, fake_tables)), \ |
| 171 | mock.patch.object(self.mod, "equation", return_value=[]), \ | 193 | mock.patch.object(self.mod, "equation", return_value=[]), \ |
| 172 | mock.patch.object(self.mod, "detile", return_value=fake_lin), \ | 194 | mock.patch.object(self.mod, "detile", return_value=fake_lin), \ |
| @@ -256,6 +278,8 @@ def test_uncompressed_feature_uses_raw_rgb_bytes(): | |||
| 256 | (2, bytes((17, 33, 63, 94, 129, 159, 245, 200)), [(17, 33, 0), (63, 94, 0), (129, 159, 0), (245, 200, 0)]), | 278 | (2, bytes((17, 33, 63, 94, 129, 159, 245, 200)), [(17, 33, 0), (63, 94, 0), (129, 159, 0), (245, 200, 0)]), |
| 257 | ], ids=["r8", "rg8"]) | 279 | ], ids=["r8", "rg8"]) |
| 258 | @needs_numpy | 280 | @needs_numpy |
| 281 | @needs_numpy_in_subprocess | ||
| 282 | @needs_pillow_in_subprocess | ||
| 259 | def test_cli_previews_uncompressed_r8_and_rg8( | 283 | def test_cli_previews_uncompressed_r8_and_rg8( |
| 260 | tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, bpe: int, texels: bytes, pixels: list[tuple[int, int, int]], | 284 | tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, bpe: int, texels: bytes, pixels: list[tuple[int, int, int]], |
| 261 | ) -> None: | 285 | ) -> None: |
| @@ -287,6 +311,7 @@ def test_cli_previews_uncompressed_r8_and_rg8( | |||
| 287 | 311 | ||
| 288 | 312 | ||
| 289 | @needs_numpy | 313 | @needs_numpy |
| 314 | @needs_numpy_in_subprocess | ||
| 290 | def test_cli_detiles_4k_tables_with_4k_blocks(): | 315 | def test_cli_detiles_4k_tables_with_4k_blocks(): |
| 291 | # A 128x128 RGBA gradient tiled in 4 KB blocks (32x32 elements, row-major). The same pattern entry under | 316 | # A 128x128 RGBA gradient tiled in 4 KB blocks (32x32 elements, row-major). The same pattern entry under |
| 292 | # a 64K table name must not be picked by --modes 4K, and the 4K table must detile with 12-bit, 4 KB blocks. | 317 | # a 64K table name must not be picked by --modes 4K, and the 4K table must detile with 12-bit, 4 KB blocks. |
| @@ -325,6 +350,8 @@ def test_cli_detiles_4k_tables_with_4k_blocks(): | |||
| 325 | 350 | ||
| 326 | 351 | ||
| 327 | @needs_numpy | 352 | @needs_numpy |
| 353 | @needs_numpy_in_subprocess | ||
| 354 | @needs_pillow_in_subprocess | ||
| 328 | def test_preview_keeps_partial_bc_blocks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: | 355 | def test_preview_keeps_partial_bc_blocks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 329 | import struct | 356 | import struct |
| 330 | 357 | ||
| @@ -408,6 +435,7 @@ def test_rejects_offset_past_the_end(tmp_path, monkeypatch): | |||
| 408 | assert "past the end" in result.stderr, result.stderr | 435 | assert "past the end" in result.stderr, result.stderr |
| 409 | 436 | ||
| 410 | 437 | ||
| 438 | @needs_numpy_in_subprocess | ||
| 411 | def test_reports_when_no_pattern_matches(tmp_path, monkeypatch): | 439 | def test_reports_when_no_pattern_matches(tmp_path, monkeypatch): |
| 412 | # Before: a --modes value that matches no table printed nothing and still exited 0. | 440 | # Before: a --modes value that matches no table printed nothing and still exited 0. |
| 413 | synthetic_case(tmp_path, monkeypatch) | 441 | synthetic_case(tmp_path, monkeypatch) |
| @@ -433,6 +461,8 @@ def test_reports_a_missing_or_malformed_header(tmp_path, monkeypatch): | |||
| 433 | 461 | ||
| 434 | 462 | ||
| 435 | @needs_numpy | 463 | @needs_numpy |
| 464 | @needs_numpy_in_subprocess | ||
| 465 | @needs_pillow_in_subprocess | ||
| 436 | def test_a_valid_run_still_succeeds(tmp_path, monkeypatch): | 466 | def test_a_valid_run_still_succeeds(tmp_path, monkeypatch): |
| 437 | synthetic_case(tmp_path, monkeypatch) | 467 | synthetic_case(tmp_path, monkeypatch) |
| 438 | result = cli(tmp_path, "--width", "4", "--height", "4", "--out", str(tmp_path / "out.png")) | 468 | result = cli(tmp_path, "--width", "4", "--height", "4", "--out", str(tmp_path / "out.png")) |
diff --git a/tests/test_awc_markers.py b/tests/test_awc_markers.py index 36fa00c64..426222741 100644 --- a/tests/test_awc_markers.py +++ b/tests/test_awc_markers.py | |||
| @@ -96,6 +96,25 @@ class MusicCueSheetTest(unittest.TestCase): | |||
| 96 | self.assertEqual(result.returncode, 0 if failure == "parse" else 1) | 96 | self.assertEqual(result.returncode, 0 if failure == "parse" else 1) |
| 97 | self.assertEqual(json.loads(sheet.read_bytes()), {"sample_rate": 48000, "regions": []}) | 97 | self.assertEqual(json.loads(sheet.read_bytes()), {"sample_rate": 48000, "regions": []}) |
| 98 | 98 | ||
| 99 | def test_skip_existing_keeps_the_cue_sheet_complete(self): | ||
| 100 | from rsc8_audio import MARKER_VALUE_START, MARKER_VALUE_END | ||
| 101 | |||
| 102 | cues = event(1, MARKER_VALUE_START, 10) + event(1, MARKER_VALUE_END, 30) | ||
| 103 | with tempfile.TemporaryDirectory() as tmp: | ||
| 104 | src = Path(tmp) / "music.awc" | ||
| 105 | out = Path(tmp) / "out" | ||
| 106 | sheet = out / "music" / "cue_regions.json" | ||
| 107 | src.write_bytes(music_bank(7, 200, 0xFC, cues)) | ||
| 108 | args = [sys.executable, "-I", Path(TOOL).with_name("awc_opus.py"), src, out, "--cue-sheet", "--jobs", "1"] | ||
| 109 | subprocess.run(args, check=True, capture_output=True) | ||
| 110 | written = json.loads(sheet.read_bytes()) | ||
| 111 | self.assertTrue(written["regions"], "the first run must write a region for the cue it exported") | ||
| 112 | # The Oggs are kept and only the sheet is missing, so the sheet has to be rebuilt from what is on disk. | ||
| 113 | # The early `continue` on a kept Ogg used to leave its frame limit unset, and the rebuilt sheet lost it. | ||
| 114 | sheet.unlink() | ||
| 115 | subprocess.run(args + ["--skip-existing"], check=True, capture_output=True) | ||
| 116 | self.assertEqual(json.loads(sheet.read_bytes()), written) | ||
| 117 | |||
| 99 | def test_exported_frame_coordinates_and_ambiguous_inputs(self): | 118 | def test_exported_frame_coordinates_and_ambiguous_inputs(self): |
| 100 | import awc_opus | 119 | import awc_opus |
| 101 | from rsc8_audio import MARKER_VALUE_START as start, MARKER_VALUE_END as end, parse_adat_header_bytes | 120 | from rsc8_audio import MARKER_VALUE_START as start, MARKER_VALUE_END as end, parse_adat_header_bytes |
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py index dd09e9060..7e8f91691 100644 --- a/tests/test_awc_opus.py +++ b/tests/test_awc_opus.py | |||
| @@ -398,6 +398,52 @@ class ExportBankTest(unittest.TestCase): | |||
| 398 | f.write(bank) | 398 | f.write(bank) |
| 399 | return path, pcm16, floats | 399 | return path, pcm16, floats |
| 400 | 400 | ||
| 401 | def test_skip_existing_leaves_written_files_alone(self): | ||
| 402 | path, _, _ = self.make_bank() | ||
| 403 | awc.export_bank(path, self.out) | ||
| 404 | written = {} | ||
| 405 | for root, _, files in os.walk(self.out): | ||
| 406 | for name in files: | ||
| 407 | full = os.path.join(root, name) | ||
| 408 | written[full] = os.stat(full).st_mtime_ns | ||
| 409 | self.assertEqual(len(written), 3, written) | ||
| 410 | # Freeze one output so a rewrite is visible, then export again with the flag. | ||
| 411 | target = sorted(written)[0] | ||
| 412 | os.utime(target, ns=(0, 0)) | ||
| 413 | counts = awc.export_bank(path, self.out, skip_existing=True) | ||
| 414 | self.assertEqual(os.stat(target).st_mtime_ns, 0, "an existing file was rewritten") | ||
| 415 | for full, mtime in written.items(): | ||
| 416 | if full != target: | ||
| 417 | self.assertEqual(os.stat(full).st_mtime_ns, mtime, full) | ||
| 418 | self.assertEqual((counts["opus"], counts["pcm"]), (1, 2), counts) | ||
| 419 | # Control: the same export without the flag does rewrite the frozen file. | ||
| 420 | awc.export_bank(path, self.out) | ||
| 421 | self.assertNotEqual(os.stat(target).st_mtime_ns, 0, | ||
| 422 | "a plain export should have rewritten the file, so the flag is what spares it") | ||
| 423 | |||
| 424 | def test_skip_existing_reaches_the_parallel_workers(self): | ||
| 425 | # The test above calls export_bank() directly, which is the function and not the CLI: the flag also has to | ||
| 426 | # survive main() and cross into the pool, and it did not - the submit call passed four arguments where the | ||
| 427 | # serial one passed five, so --jobs 2 rewrote every existing output. This runs the tool as a subprocess, | ||
| 428 | # like the parallel test below, because the pool cannot pickle a module imported under a test-only name. | ||
| 429 | path, _, _ = self.make_bank() | ||
| 430 | for jobs in (1, 2): | ||
| 431 | with self.subTest(jobs=jobs): | ||
| 432 | out = Path(self.out) / str(jobs) | ||
| 433 | awc.export_bank(path, str(out)) | ||
| 434 | files = sorted(str(p) for p in out.rglob("*") if p.is_file()) | ||
| 435 | self.assertEqual(len(files), 3, files) | ||
| 436 | os.utime(files[0], ns=(0, 0)) | ||
| 437 | subprocess.run([sys.executable, "-I", awc.__file__, path, str(out), "--skip-existing", | ||
| 438 | "--jobs", str(jobs)], check=True, capture_output=True) | ||
| 439 | self.assertEqual(os.stat(files[0]).st_mtime_ns, 0, | ||
| 440 | f"--skip-existing was lost with --jobs {jobs}: an existing file was rewritten") | ||
| 441 | # Control: the same command without the flag does rewrite the frozen file, so the assertion above is | ||
| 442 | # about the flag and not about the export being unable to write. | ||
| 443 | subprocess.run([sys.executable, "-I", awc.__file__, path, str(out), "--jobs", str(jobs)], | ||
| 444 | check=True, capture_output=True) | ||
| 445 | self.assertNotEqual(os.stat(files[0]).st_mtime_ns, 0, | ||
| 446 | f"--jobs {jobs}: the control did not rewrite the file") | ||
| 401 | def test_recursive_cli_preserves_bank_paths(self): | 447 | def test_recursive_cli_preserves_bank_paths(self): |
| 402 | src = Path(self.tmp.name) / "banks" | 448 | src = Path(self.tmp.name) / "banks" |
| 403 | samples = {"north/shared": 11, "south/shared": 22, "flat": 33} | 449 | samples = {"north/shared": 11, "south/shared": 22, "flat": 33} |
diff --git a/tests/test_bench_translate.py b/tests/test_bench_translate.py index 4a94c8d6b..aead9008b 100644 --- a/tests/test_bench_translate.py +++ b/tests/test_bench_translate.py | |||
| @@ -102,12 +102,18 @@ class BenchTranslateTest(unittest.TestCase): | |||
| 102 | written = run("--runs", "1", "--size", "20", "--write-baseline", path) | 102 | written = run("--runs", "1", "--size", "20", "--write-baseline", path) |
| 103 | self.assertEqual(written.returncode, 0, written.stderr) | 103 | self.assertEqual(written.returncode, 0, written.stderr) |
| 104 | self.assertTrue(os.path.isfile(path)) | 104 | self.assertTrue(os.path.isfile(path)) |
| 105 | result = run("--runs", "1", "--size", "20", "--baseline", path, "--max-slowdown", "5", "--json") | 105 | # What this case is about is that a local baseline replaces the committed one, and the way to say that without |
| 106 | # measuring CPU contention is to compare the numbers back against the file that was just written. The limit | ||
| 107 | # behaviour has its own deterministic test (--max-slowdown 0.01 must report one). | ||
| 108 | with open(path, encoding="utf-8") as handle: | ||
| 109 | written = json.load(handle)["measured"] | ||
| 110 | result = run("--runs", "1", "--size", "20", "--baseline", path, "--json") | ||
| 106 | self.assertEqual(result.returncode, 0, result.stderr) | 111 | self.assertEqual(result.returncode, 0, result.stderr) |
| 107 | report = json.loads(result.stdout) | 112 | report = json.loads(result.stdout) |
| 108 | self.assertEqual(report["baseline_source"], os.path.abspath(path)) | 113 | self.assertEqual(report["baseline_source"], os.path.abspath(path)) |
| 109 | self.assertEqual(sorted(report["baseline"]), sorted(report["measured"])) | 114 | self.assertEqual(sorted(report["baseline"]), sorted(report["measured"])) |
| 110 | self.assertEqual(report["over_limit"], []) | 115 | # The baseline is that file's own numbers, not the committed ones: substituting the latter fails here. |
| 116 | self.assertEqual(report["baseline"], written) | ||
| 111 | 117 | ||
| 112 | def test_compare_runs_two_trees_and_prints_a_ratio(self): | 118 | def test_compare_runs_two_trees_and_prints_a_ratio(self): |
| 113 | tools = os.path.join(ROOT, "tools") | 119 | tools = os.path.join(ROOT, "tools") |
diff --git a/tests/test_cfg_structure_extra.py b/tests/test_cfg_structure_extra.py new file mode 100644 index 000000000..4df3ebc67 --- /dev/null +++ b/tests/test_cfg_structure_extra.py | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | """Additional nested-loop and sibling-order tests for tools/cfg_structure.py.""" | ||
| 2 | from __future__ import annotations | ||
| 3 | |||
| 4 | import sys | ||
| 5 | from pathlib import Path | ||
| 6 | |||
| 7 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools")) | ||
| 8 | |||
| 9 | import cfg_structure as cs | ||
| 10 | |||
| 11 | |||
| 12 | def test_nested_loop_with_early_exit_uses_cfg_run(): | ||
| 13 | succ = {0: [1], 1: [2, 4], 2: [3, 2], 3: [1, 4], 4: []} | ||
| 14 | tree = cs.structure(succ) | ||
| 15 | assert tree is not None | ||
| 16 | |||
| 17 | b2_calls = 0 | ||
| 18 | |||
| 19 | def choose(b): | ||
| 20 | nonlocal b2_calls | ||
| 21 | if b == 0: | ||
| 22 | return 1 | ||
| 23 | if b == 1: | ||
| 24 | return 2 if b2_calls == 0 else 4 | ||
| 25 | if b == 2: | ||
| 26 | b2_calls += 1 | ||
| 27 | return 2 if b2_calls == 1 else 3 | ||
| 28 | if b == 3: | ||
| 29 | return 1 | ||
| 30 | if b == 4: | ||
| 31 | return cs.END | ||
| 32 | raise AssertionError(b) | ||
| 33 | |||
| 34 | assert cs.run(tree, choose, 32) == [0, 1, 2, 2, 3, 1, 4] | ||
| 35 | |||
| 36 | |||
| 37 | def test_sibling_order_diamond_then_tail_executes_every_branch(): | ||
| 38 | # Block 0 branches to 1 or 2, both merge at 3, which exits at 4. | ||
| 39 | # Reversing region children puts 3 before 1/2 and misses 3 on the second pass. | ||
| 40 | succ = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: []} | ||
| 41 | tree = cs.structure(succ) | ||
| 42 | assert tree is not None | ||
| 43 | |||
| 44 | for branch in (1, 2): | ||
| 45 | def choose(b, pick=branch): | ||
| 46 | if b == 0: | ||
| 47 | return pick | ||
| 48 | if b in (1, 2): | ||
| 49 | return 3 | ||
| 50 | if b == 3: | ||
| 51 | return 4 | ||
| 52 | if b == 4: | ||
| 53 | return cs.END | ||
| 54 | raise AssertionError(b) | ||
| 55 | |||
| 56 | assert cs.run(tree, choose, 16) == [0, branch, 3, 4] | ||
| 57 | |||
| 58 | |||
| 59 | if __name__ == "__main__": | ||
| 60 | test_nested_loop_with_early_exit_uses_cfg_run() | ||
| 61 | test_sibling_order_diamond_then_tail_executes_every_branch() | ||
diff --git a/tests/test_chain_check.py b/tests/test_chain_check.py new file mode 100644 index 000000000..635b46123 --- /dev/null +++ b/tests/test_chain_check.py | |||
| @@ -0,0 +1,421 @@ | |||
| 1 | """tools/chain_check.py on synthetic work folders: verdicts per link, the weakest link, and no program name or log | ||
| 2 | line printed. | ||
| 3 | |||
| 4 | python -I tests/test_chain_check.py | ||
| 5 | |||
| 6 | Each test writes a small work folder in make_game.py's layout (index files, listings, modules, build records, | ||
| 7 | logs/shaders.log) and, for the runtime block, a small gta6rt log by hand; no game files, no llvm-mc, no GPU. The | ||
| 8 | checks run with probing off, so nothing is launched. | ||
| 9 | """ | ||
| 10 | import contextlib | ||
| 11 | import io | ||
| 12 | import json | ||
| 13 | import os | ||
| 14 | import sys | ||
| 15 | import tempfile | ||
| 16 | import unittest | ||
| 17 | |||
| 18 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 19 | ROOT = os.path.dirname(HERE) | ||
| 20 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 21 | |||
| 22 | import chain_check # noqa: E402 | ||
| 23 | |||
| 24 | # A program name and a title line the report must never print: they stand for game data. | ||
| 25 | SECRET = "SyntheticProgramName42" | ||
| 26 | TITLE_LINE = "[rt] title: Synthetic Title Text 42" | ||
| 27 | |||
| 28 | |||
| 29 | def signature(version: str) -> str: | ||
| 30 | """make_game.py's llvm_mc_signature(): the command and the --version text, as a JSON pair.""" | ||
| 31 | return json.dumps([["llvm-mc"], f"LLVM version {version}\n Registered Targets:\n amdgcn - AMD GCN GPUs\n"]) | ||
| 32 | |||
| 33 | |||
| 34 | def write(path: str, data) -> None: | ||
| 35 | os.makedirs(os.path.dirname(path), exist_ok=True) | ||
| 36 | mode = "wb" if isinstance(data, bytes) else "w" | ||
| 37 | with open(path, mode, **({} if isinstance(data, bytes) else {"encoding": "utf-8", "newline": "\n"})) as f: | ||
| 38 | f.write(data if isinstance(data, (str, bytes)) else json.dumps(data)) | ||
| 39 | |||
| 40 | |||
| 41 | def make_work(root: str, *, llvm: str = "21.1.8", digest: str = "0" * 64, table: str | None = None, | ||
| 42 | library_ok: int = 6, library_total: int = 10) -> str: | ||
| 43 | """A work folder with 4 game programs (all translated), a library of library_total programs (library_ok | ||
| 44 | translated, the rest refused for undecodable words) and no FSPX, BVH or executable programs.""" | ||
| 45 | sh = os.path.join(root, "shaders") | ||
| 46 | game = [f"{SECRET}_g{i}" for i in range(4)] | ||
| 47 | write(os.path.join(sh, "dxbc", "index.json"), [{"name": n, "file": n + ".dxbc"} for n in game]) | ||
| 48 | write(os.path.join(sh, "dxbc", "fssm_index.json"), [{"name": n} for n in game]) | ||
| 49 | for n in game: | ||
| 50 | write(os.path.join(sh, "dxbc", "disasm", n + ".s"), "s_endpgm\n") | ||
| 51 | write(os.path.join(sh, "dxbc", "disasm.done"), {"llvm": signature(llvm), "listings": game}) | ||
| 52 | meta = {"stage": "cs", **({"descriptor_table": table} if table else {})} | ||
| 53 | write(os.path.join(sh, "spirv", "index.json"), {n: meta for n in game}) | ||
| 54 | for n in game: | ||
| 55 | write(os.path.join(sh, "spirv", n + ".spv"), b"\x00") | ||
| 56 | write(os.path.join(sh, "spirv", "translation_sources.sha256"), digest + "\n") | ||
| 57 | lib = [f"{SECRET}_lib{i}" for i in range(library_total)] | ||
| 58 | write(os.path.join(sh, "library", "index.json"), | ||
| 59 | [{"file": n + ".dxbc", "invalid_words": 0 if i < library_ok else 3} for i, n in enumerate(lib)]) | ||
| 60 | for n in lib: | ||
| 61 | write(os.path.join(sh, "library", "disasm", n + ".s"), "s_endpgm\n") | ||
| 62 | write(os.path.join(sh, "spirv", "library", "index.json"), | ||
| 63 | {n: {**meta, "fspx_code_sha256": "ab" * 32} for n in lib[:library_ok]}) | ||
| 64 | for n in lib[:library_ok]: | ||
| 65 | write(os.path.join(sh, "spirv", "library", n + ".spv"), b"\x00") | ||
| 66 | write(os.path.join(sh, "spirv", "library", "library_build.json"), | ||
| 67 | {"llvm_mc": signature(llvm), "translator": digest}) | ||
| 68 | failed = library_total - library_ok | ||
| 69 | write(os.path.join(root, "logs", "shaders.log"), "\n".join([ | ||
| 70 | f"20:00:00 rdna2spirv.py {root}/shaders/dxbc/disasm --out {root}/shaders/spirv --shard 0..1/2", | ||
| 71 | "2 shaders: 2 translated, 2 pass spirv-val", | ||
| 72 | "2 shaders: 2 translated, 2 pass spirv-val", | ||
| 73 | f"20:01:00 python.exe -I rdna2spirv.py {root}/shaders/dxbc/disasm --out {root}/shaders/spirv --merge", | ||
| 74 | f"20:02:00 rdna2spirv.py {root}/shaders/library/disasm --out {root}/shaders/spirv/library --shard 0..0/1", | ||
| 75 | f"{library_total} shaders: {library_ok} translated, {library_ok} pass spirv-val", | ||
| 76 | *([f"{failed} fall-through into undecodable words"] if failed else []), | ||
| 77 | f"20:03:00 shaders: {SECRET} done", | ||
| 78 | ""])) | ||
| 79 | return root | ||
| 80 | |||
| 81 | |||
| 82 | def runtime_log(path: str, *, slot_failures: int = 3, loaded: int = 10, encoding: str = "utf-8", | ||
| 83 | extra: tuple = ()) -> str: | ||
| 84 | lines = [f"[rt] d3d12: {loaded} translated shaders (6 fspx, 0 fspx_compute, 0 fspx_gfx, 0 bvh, 0 exe) from X", | ||
| 85 | "[rt] d3d12: descriptor table: plain (all 10 modules)", TITLE_LINE] | ||
| 86 | for i in range(slot_failures): | ||
| 87 | lines.append(f"[rt] d3d12: no translated compute shader for {SECRET} sha256 {'ab' * 32}") | ||
| 88 | lines.append(f"[rt] d3d12_xs: slot 67 call {i + 1} failed with 0x80070057 (kind 0 1 B, kind 1 2 B, ...)") | ||
| 89 | lines += [f"[rt] d3d12: compute pipeline library/{SECRET} (100 B SPIR-V, wave32) build starts at t=1.000 s", | ||
| 90 | "[d3d12-trace] #7 ID3D12Device2::CreatePipelineState failed", | ||
| 91 | "[d3d12-trace] #8 ID3D12Device2::CreatePipelineState ok", | ||
| 92 | *extra, | ||
| 93 | "game exited with code 0"] | ||
| 94 | with open(path, "w", encoding=encoding, newline="\n") as f: | ||
| 95 | f.write("\n".join(lines) + "\n") | ||
| 96 | return path | ||
| 97 | |||
| 98 | |||
| 99 | def block(report: dict, name: str) -> dict: | ||
| 100 | return next(b for b in report["blocks"] if b["name"] == name) | ||
| 101 | |||
| 102 | |||
| 103 | class ChainCheckTest(unittest.TestCase): | ||
| 104 | def setUp(self): | ||
| 105 | self.tmp = tempfile.TemporaryDirectory() | ||
| 106 | self.addCleanup(self.tmp.cleanup) | ||
| 107 | self.root = self.tmp.name | ||
| 108 | |||
| 109 | def printed(self, *argv) -> str: | ||
| 110 | out = io.StringIO() | ||
| 111 | with contextlib.redirect_stdout(out): | ||
| 112 | self.assertEqual(chain_check.main([*argv, "--no-probe"]), 0) | ||
| 113 | return out.getvalue() | ||
| 114 | |||
| 115 | def test_broken_chain_names_each_link(self): | ||
| 116 | work = make_work(os.path.join(self.root, "w")) | ||
| 117 | log = runtime_log(os.path.join(self.root, "run.log")) | ||
| 118 | report = chain_check.check(work, log, probe=False) | ||
| 119 | tools = block(report, "tools") | ||
| 120 | self.assertEqual(tools["verdict"], "WARN") | ||
| 121 | self.assertEqual(tools["llvm_mc_recorded"], {"21.1.8": 2}) | ||
| 122 | self.assertEqual(tools["translator_stale"], ["game", "library"]) | ||
| 123 | self.assertIn("#1923", tools["cause"]) | ||
| 124 | game, lib = block(report, "game"), block(report, "library") | ||
| 125 | self.assertEqual((game["verdict"], game["expected"], game["translated"]), ("OK", 4, 4)) | ||
| 126 | self.assertEqual((lib["verdict"], lib["expected"], lib["translated"], lib["failed"]), ("FAIL", 10, 6, 4)) | ||
| 127 | self.assertEqual(lib["listings_with_rejected_words"], 4) | ||
| 128 | self.assertEqual(lib["reasons"], [[4, "fall-through into undecodable words"]]) | ||
| 129 | self.assertIn("llvm-mc 21.x", lib["cause"]) | ||
| 130 | for name in ("fspx", "bvh", "exe"): | ||
| 131 | self.assertEqual(block(report, name)["verdict"], "n/a") | ||
| 132 | contract = block(report, "contract") | ||
| 133 | self.assertEqual(contract["verdict"], "WARN") | ||
| 134 | self.assertEqual(contract["modules"], {"plain": 10}) | ||
| 135 | self.assertIn("fspx_compute", contract["folders_absent"]) | ||
| 136 | rt = block(report, "runtime") | ||
| 137 | self.assertEqual(rt["verdict"], "FAIL") | ||
| 138 | self.assertEqual(rt["slot_failures"], {"slot 67 0x80070057": 3}) | ||
| 139 | self.assertEqual(rt["no_translated_compute"], 3) | ||
| 140 | self.assertEqual(rt["d3d12_problems"], {"ID3D12Device2::CreatePipelineState failed": 1}) | ||
| 141 | self.assertEqual((rt["loaded"]["total"], rt["exit_code"], rt["compute_builds"]), (10, 0, 1)) | ||
| 142 | self.assertIn("against 4 untranslated library programs", rt["cause"]) | ||
| 143 | self.assertEqual(report["weakest"]["name"], "library") | ||
| 144 | |||
| 145 | def test_clean_chain_is_ok(self): | ||
| 146 | work = make_work(os.path.join(self.root, "w"), llvm="23.1.5", digest=chain_check.repo_translation_digest(), | ||
| 147 | table="tagged", library_ok=10) | ||
| 148 | log = runtime_log(os.path.join(self.root, "run.log"), slot_failures=0, loaded=14) | ||
| 149 | report = chain_check.check(work, log, probe=False) | ||
| 150 | verdicts = {b["name"]: b["verdict"] for b in report["blocks"]} | ||
| 151 | self.assertEqual(verdicts, {"tools": "OK", "game": "OK", "library": "OK", "fspx": "n/a", "bvh": "n/a", | ||
| 152 | "exe": "n/a", "contract": "OK", "runtime": "WARN"}) | ||
| 153 | self.assertEqual(report["weakest"]["name"], "runtime") # the one failed CreatePipelineState | ||
| 154 | |||
| 155 | def test_mixed_llvm_names_the_old_one(self): | ||
| 156 | work = make_work(os.path.join(self.root, "w"), llvm="21.1.8") | ||
| 157 | write(os.path.join(work, "shaders", "dxbc", "disasm.done"), {"llvm": signature("23.1.5"), "listings": []}) | ||
| 158 | report = chain_check.check(work, probe=False) | ||
| 159 | tools = block(report, "tools") | ||
| 160 | self.assertIn("llvm-mc 21.1.8 (used for library) predates 23", tools["cause"]) | ||
| 161 | self.assertIn("different llvm-mc versions", tools["cause"]) | ||
| 162 | self.assertIn("llvm-mc 21.x", block(report, "library")["cause"]) | ||
| 163 | |||
| 164 | def test_untranslated_without_build_log(self): | ||
| 165 | work = make_work(os.path.join(self.root, "w")) | ||
| 166 | os.remove(os.path.join(work, "logs", "shaders.log")) | ||
| 167 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 168 | self.assertEqual((lib["verdict"], lib["reasons"]), ("FAIL", [])) | ||
| 169 | self.assertIn("no reason", lib["cause"]) | ||
| 170 | |||
| 171 | def test_missing_translation_fails(self): | ||
| 172 | work = make_work(os.path.join(self.root, "w")) | ||
| 173 | os.remove(os.path.join(work, "shaders", "spirv", "library", "index.json")) | ||
| 174 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 175 | self.assertEqual(lib["verdict"], "FAIL") | ||
| 176 | self.assertIn("never finished", lib["cause"]) | ||
| 177 | write(os.path.join(work, "shaders", "spirv", "library", "shard0.json"), {"count": 1, "index": 0}) | ||
| 178 | write(os.path.join(work, "shaders", "spirv", "library", "index.part0.json"), {}) | ||
| 179 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 180 | self.assertIn("translation in progress or interrupted (2 shard files)", lib["cause"]) | ||
| 181 | |||
| 182 | def test_entry_without_module_is_not_translated(self): | ||
| 183 | work = make_work(os.path.join(self.root, "w"), library_ok=10) | ||
| 184 | os.remove(os.path.join(work, "shaders", "spirv", "library", f"{SECRET}_lib3.spv")) | ||
| 185 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 186 | self.assertEqual((lib["translated"], lib["modules_missing"], lib["failed"]), (9, 1, 1)) | ||
| 187 | self.assertEqual(lib["verdict"], "FAIL") | ||
| 188 | |||
| 189 | def test_threshold_bounds(self): | ||
| 190 | for ok, total, verdict in ((100, 100, "OK"), (99, 100, "WARN"), (198, 200, "WARN"), (197, 200, "FAIL")): | ||
| 191 | with self.subTest(ok=ok, total=total): | ||
| 192 | work = make_work(os.path.join(self.root, f"w{ok}_{total}"), library_ok=ok, library_total=total) | ||
| 193 | self.assertEqual(block(chain_check.check(work, probe=False), "library")["verdict"], verdict) | ||
| 194 | |||
| 195 | def test_more_modules_than_programs_warns(self): | ||
| 196 | work = make_work(os.path.join(self.root, "w"), library_ok=10) | ||
| 197 | spirv = os.path.join(work, "shaders", "spirv", "library") | ||
| 198 | with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: | ||
| 199 | index = json.load(f) | ||
| 200 | for i in range(10): | ||
| 201 | index[f"extra{i}"] = {"stage": "cs"} | ||
| 202 | write(os.path.join(spirv, f"extra{i}.spv"), b"\x00") | ||
| 203 | write(os.path.join(spirv, "index.json"), index) | ||
| 204 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 205 | self.assertEqual((lib["verdict"], lib["translated"], lib["expected"]), ("WARN", 20, 10)) | ||
| 206 | self.assertIn("more modules than unpacked programs", lib["cause"]) | ||
| 207 | |||
| 208 | def test_no_llvm_record_renders_na(self): | ||
| 209 | work = make_work(os.path.join(self.root, "w")) | ||
| 210 | os.remove(os.path.join(work, "shaders", "dxbc", "disasm.done")) | ||
| 211 | write(os.path.join(work, "shaders", "spirv", "library", "library_build.json"), {"translator": "0" * 64}) | ||
| 212 | tools = block(chain_check.check(work, probe=False), "tools") | ||
| 213 | self.assertEqual((tools["verdict"], tools["llvm_mc_amdgpu"]), ("FAIL", None)) | ||
| 214 | self.assertIn("amdgcn n/a, via n/a", self.printed(work)) | ||
| 215 | |||
| 216 | def test_utf16_log(self): | ||
| 217 | work = make_work(os.path.join(self.root, "w")) | ||
| 218 | for encoding in ("utf-16", "utf-16-le", "utf-16-be"): | ||
| 219 | with self.subTest(encoding=encoding): | ||
| 220 | log = runtime_log(os.path.join(self.root, f"run-{encoding}.log"), encoding=encoding) | ||
| 221 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 222 | self.assertEqual((rt["no_translated_compute"], rt["loaded"]["total"]), (3, 10)) | ||
| 223 | |||
| 224 | def test_trace_and_digest_names_are_closed(self): | ||
| 225 | work = make_work(os.path.join(self.root, "w")) | ||
| 226 | log = runtime_log(os.path.join(self.root, "run.log"), extra=( | ||
| 227 | "[d3d12-trace] #9 PS_Secret_deadbeef failed", | ||
| 228 | f"[d3d12-trace] #10 {SECRET}::Create failed", | ||
| 229 | "[d3d12-trace] #11 XboxID3D12Fence::Slot12 failed", | ||
| 230 | "[d3d12-trace] #12 PS_Secret::Slot12 failed")) | ||
| 231 | write(os.path.join(self.root, "run.digest.txt"), f"== boot run: {SECRET} ran its full time limit\n") | ||
| 232 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 233 | self.assertEqual(rt["d3d12_problems"], {"(other) failed": 3, "ID3D12Device2::CreatePipelineState failed": 1, | ||
| 234 | "XboxID3D12Fence::Slot12 failed": 1}) | ||
| 235 | self.assertEqual(rt["ending"], "other") | ||
| 236 | for ending, code in (("ran its full time limit (783 s), stopped", 0), | ||
| 237 | ("exited by itself after 12 s, exit code -1073741819 (0xc0000005)", 0), | ||
| 238 | ("exited by itself after 12 s, exit code unknown", 0), | ||
| 239 | ("digest of an earlier run (-DigestOnly)", 0)): | ||
| 240 | with self.subTest(ending=ending): | ||
| 241 | write(os.path.join(self.root, "run.digest.txt"), f"== boot run: {ending}\n") | ||
| 242 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 243 | self.assertEqual((rt["ending"], rt["exit_code"]), (ending, code)) # the log's own exit line wins | ||
| 244 | self.assertNotIn(SECRET, self.printed(work, "--log", log)) | ||
| 245 | self.assertNotIn("PS_Secret", self.printed(work, "--log", log, "--json")) | ||
| 246 | |||
| 247 | def test_digest_exit_code_without_log_exit_line(self): | ||
| 248 | work = make_work(os.path.join(self.root, "w")) | ||
| 249 | log = os.path.join(self.root, "run.log") | ||
| 250 | with open(log, "w", encoding="utf-8", newline="\n") as f: | ||
| 251 | f.write("[rt] d3d12: 10 translated shaders (6 fspx, 0 fspx_compute, 0 fspx_gfx, 0 bvh, 0 exe) from X\n") | ||
| 252 | write(os.path.join(self.root, "run.digest.txt"), | ||
| 253 | "== boot run: exited by itself after 12 s, exit code -1073741819 (0xc0000005)\n") | ||
| 254 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 255 | self.assertEqual((rt["exit_code"], rt["verdict"]), (-1073741819, "FAIL")) | ||
| 256 | |||
| 257 | def test_stall_lines_warn_and_faults_fail(self): | ||
| 258 | work = make_work(os.path.join(self.root, "w"), llvm="23.1.5", digest=chain_check.repo_translation_digest(), | ||
| 259 | table="tagged", library_ok=10) | ||
| 260 | stall = ("[rt] device-fault: enabled (fault info on, checkpoints on, NVIDIA diagnostics config off)", | ||
| 261 | "[rt] device-fault: submitted dispatch seq=1 execute=2 groups=1,1,1") | ||
| 262 | log = runtime_log(os.path.join(self.root, "stall.log"), slot_failures=0, loaded=14, extra=stall) | ||
| 263 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 264 | self.assertEqual((rt["stalled_dispatch_lines"], rt["device_fault_lines"], rt["verdict"]), (1, 0, "WARN")) | ||
| 265 | self.assertIn("device lost, faulted or stalled", rt["cause"]) | ||
| 266 | log = runtime_log(os.path.join(self.root, "lost.log"), slot_failures=0, loaded=14, | ||
| 267 | extra=("[rt] device-fault: VK_ERROR_DEVICE_LOST from vkQueueSubmit2",)) | ||
| 268 | rt = block(chain_check.check(work, log, probe=False), "runtime") | ||
| 269 | self.assertEqual((rt["device_lost_lines"], rt["device_fault_lines"], rt["verdict"]), (1, 1, "FAIL")) | ||
| 270 | |||
| 271 | def test_descriptor_table_lines(self): | ||
| 272 | work = make_work(os.path.join(self.root, "w")) | ||
| 273 | cases = (("[rt] d3d12: descriptor table: 3 tagged / 2 plain modules; using tagged", | ||
| 274 | "tagged (3 tagged / 2 plain)"), | ||
| 275 | ("[rt] d3d12: descriptor table: plain (LEONIDA_DESCRIPTOR_TABLE; 3 tagged / 2 plain modules)", | ||
| 276 | "plain forced by LEONIDA_DESCRIPTOR_TABLE (3 tagged / 2 plain)")) | ||
| 277 | for line, expected in cases: | ||
| 278 | with self.subTest(line=line): | ||
| 279 | log = runtime_log(os.path.join(self.root, "t.log"), extra=(line,)) | ||
| 280 | self.assertEqual(block(chain_check.check(work, log, probe=False), "runtime")["descriptor_table"], | ||
| 281 | expected) | ||
| 282 | |||
| 283 | def test_only_compiles_count_as_slow_builds(self): | ||
| 284 | work = make_work(os.path.join(self.root, "w")) | ||
| 285 | name = "[rt] d3d12: compute pipeline library/aaaa took 4.2 s to " | ||
| 286 | cases = (("build (100 B SPIR-V)", 1), | ||
| 287 | ("obtain from a compile (100 B SPIR-V; hit 0, seeded 0, written 1)", 1), | ||
| 288 | ("obtain from the shared cache (100 B SPIR-V; hit 1, seeded 0, written 0)", 0), | ||
| 289 | ("obtain from its journal file (100 B SPIR-V; hit 1, seeded 1, written 0)", 0)) | ||
| 290 | for line, expected in cases: | ||
| 291 | with self.subTest(line=line): | ||
| 292 | base = runtime_log(os.path.join(self.root, "b.log")) | ||
| 293 | log = runtime_log(os.path.join(self.root, "t.log"), extra=(name + line,)) | ||
| 294 | slow = [block(chain_check.check(work, x, probe=False), "runtime")["slow_compute_builds"] | ||
| 295 | for x in (base, log)] | ||
| 296 | self.assertEqual(slow[1] - slow[0], expected) | ||
| 297 | |||
| 298 | def test_runtime_sources_still_print_what_the_regexes_read(self): | ||
| 299 | # Every runtime line the report counts, pinned to the source that prints it: a reworded message would make | ||
| 300 | # its count fall to 0 and the runtime block pass in silence. | ||
| 301 | pins = { | ||
| 302 | "runtime/shims/d3d12_xs_device.cpp": ["[rt] d3d12_xs: slot 67 call %llu failed with 0x%08lx", | ||
| 303 | "[rt] d3d12_xs: slot 57 call %llu failed with 0x%08lx"], | ||
| 304 | "runtime/shims/d3d12_vulkan_device.cpp": [ | ||
| 305 | "[rt] d3d12: %zu translated shaders (%zu fspx, %zu fspx_compute, ", | ||
| 306 | "%zu fspx_gfx, %zu bvh, %zu exe) from %s", | ||
| 307 | "[rt] d3d12: no translated compute shader for %s sha256", | ||
| 308 | "[rt] d3d12: compute pipeline %s (%zu B SPIR-V, %s) build starts at t=", | ||
| 309 | "[rt] d3d12: compute pipeline %s took %.1f s to obtain from %s (%zu B SPIR-V; hit %d,", | ||
| 310 | 'out.journal_hit ? "its journal file" : out.from_shared ? "the shared cache" : "a compile"', | ||
| 311 | "[rt] d3d12: descriptor table: %s (all %zu modules)", | ||
| 312 | "[rt] d3d12: descriptor table: %zu tagged / %zu plain modules; using %s", | ||
| 313 | "[rt] d3d12: descriptor table: %s (LEONIDA_DESCRIPTOR_TABLE; %zu tagged / %zu plain modules)"], | ||
| 314 | "runtime/shims/d3d12_trace.h": ["[d3d12-trace] #%llu %s %s"], | ||
| 315 | "runtime/src/vulkan_device_fault.h": ["[rt] submit-lock: thread %u is waiting at the compile gate", | ||
| 316 | "[rt] device-fault: submitted dispatch seq=", | ||
| 317 | "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s", | ||
| 318 | "[rt] device-fault: enabled ("], | ||
| 319 | "runtime/src/main.cpp": ["game exited with code %d"], | ||
| 320 | "scripts/windows-boot/boot.ps1": ["== boot ${Name}: $verdict", | ||
| 321 | '$verdict = "digest of an earlier run (-DigestOnly)"', | ||
| 322 | '$verdict = "ran its full time limit ($ran s), stopped"', | ||
| 323 | '$verdict = "exited by itself after $ran s, exit code unknown"', | ||
| 324 | '"exited by itself after {0} s, exit code {1} (0x{2:x8})"'], | ||
| 325 | } | ||
| 326 | for rel, fragments in pins.items(): | ||
| 327 | with open(os.path.join(ROOT, rel), encoding="utf-8") as f: | ||
| 328 | text = f.read() | ||
| 329 | for fragment in fragments: | ||
| 330 | with self.subTest(source=rel, fragment=fragment): | ||
| 331 | self.assertIn(fragment, text) | ||
| 332 | |||
| 333 | def test_no_names_or_log_text_printed(self): | ||
| 334 | work = make_work(os.path.join(self.root, "w")) | ||
| 335 | log = runtime_log(os.path.join(self.root, "run.log")) | ||
| 336 | for extra in ((), ("--json",)): | ||
| 337 | text = self.printed(work, "--log", log, *extra) | ||
| 338 | self.assertNotIn(SECRET, text) | ||
| 339 | self.assertNotIn("Synthetic Title Text", text) | ||
| 340 | self.assertIn("weakest", text) | ||
| 341 | |||
| 342 | def test_paths_only_with_show_paths(self): | ||
| 343 | work = make_work(os.path.join(self.root, "w")) | ||
| 344 | log = runtime_log(os.path.join(self.root, "run.log")) | ||
| 345 | for extra in ((), ("--json",)): | ||
| 346 | text = self.printed(work, "--log", log, *extra) | ||
| 347 | self.assertNotIn(self.root, text.replace("\\\\", "\\")) | ||
| 348 | self.assertNotIn("run.log", text) | ||
| 349 | self.assertTrue(self.printed(work, "--log", log).startswith("chain check\n")) | ||
| 350 | shown = self.printed(work, "--log", log, "--show-paths") | ||
| 351 | self.assertIn(work, shown) | ||
| 352 | self.assertIn(log, shown) | ||
| 353 | |||
| 354 | def test_reasons_are_the_translator_messages(self): | ||
| 355 | work = make_work(os.path.join(self.root, "w")) | ||
| 356 | with open(os.path.join(work, "logs", "shaders.log"), "a", encoding="utf-8", newline="\n") as f: | ||
| 357 | f.write(f"20:04:00 rdna2spirv.py {work}/shaders/library/disasm --out {work}/shaders/spirv/library\n" | ||
| 358 | "10 shaders: 4 translated, 4 pass spirv-val\n" | ||
| 359 | "2 s_sethalt\n" | ||
| 360 | f"2 {SECRET} source\n" | ||
| 361 | f"1 E:\\work\\{SECRET}.s\n" | ||
| 362 | "1 translator error KeyError\n" | ||
| 363 | "1 translator error SecretError\n" | ||
| 364 | "1 secret_program_name\n") | ||
| 365 | lib = block(chain_check.check(work, probe=False), "library") | ||
| 366 | self.assertEqual(dict((r, n) for n, r in lib["reasons"]), | ||
| 367 | {"s_sethalt": 2, "# source": 2, "other": 2, "translator error KeyError": 1, | ||
| 368 | "translator error #": 1}) | ||
| 369 | |||
| 370 | def test_empty_and_partial_folders_are_na(self): | ||
| 371 | empty = os.path.join(self.root, "empty") | ||
| 372 | os.makedirs(empty) | ||
| 373 | report = chain_check.check(empty, probe=False) | ||
| 374 | self.assertEqual({b["verdict"] for b in report["blocks"]}, {"n/a"}) | ||
| 375 | self.assertEqual(report["weakest"]["name"], "none") | ||
| 376 | self.assertIn("weakest link: none", self.printed(empty)) | ||
| 377 | partial = os.path.join(self.root, "partial") | ||
| 378 | write(os.path.join(partial, "shaders", "dxbc", "fssm_index.json"), "{not json") | ||
| 379 | write(os.path.join(partial, "shaders", "library", "index.json"), [1, "x", None]) | ||
| 380 | write(os.path.join(partial, "shaders", "spirv", "library", "index.json"), {"": 3, "a": [1]}) | ||
| 381 | write(os.path.join(partial, "shaders", "spirv", "library", "library_build.json"), {"llvm_mc": 5}) | ||
| 382 | report = chain_check.check(partial, os.path.join(partial, "missing.log"), probe=False) | ||
| 383 | verdicts = {b["name"]: b["verdict"] for b in report["blocks"]} | ||
| 384 | self.assertEqual((verdicts["game"], verdicts["library"], verdicts["fspx"]), ("FAIL", "FAIL", "n/a")) | ||
| 385 | self.assertEqual(verdicts["runtime"], "FAIL") # no translated-shaders line in an unreadable log | ||
| 386 | self.printed(partial) | ||
| 387 | |||
| 388 | def test_strict_exit_code(self): | ||
| 389 | work = make_work(os.path.join(self.root, "w")) | ||
| 390 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 391 | self.assertEqual(chain_check.main([work, "--no-probe"]), 0) | ||
| 392 | self.assertEqual(chain_check.main([work, "--no-probe", "--strict"]), 1) | ||
| 393 | clean = make_work(os.path.join(self.root, "c"), llvm="23.1.5", digest=chain_check.repo_translation_digest(), | ||
| 394 | table="tagged", library_ok=10) | ||
| 395 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 396 | self.assertEqual(chain_check.main([clean, "--no-probe", "--strict"]), 0) | ||
| 397 | |||
| 398 | def test_help_names_the_thresholds(self): | ||
| 399 | out = io.StringIO() | ||
| 400 | with contextlib.redirect_stdout(out), self.assertRaises(SystemExit): | ||
| 401 | chain_check.main(["--help"]) | ||
| 402 | text = " ".join(out.getvalue().split()) | ||
| 403 | self.assertIn("WARN up to 1% untranslated", text) | ||
| 404 | self.assertIn("older than 23", text) | ||
| 405 | self.assertIn("--strict", text) | ||
| 406 | |||
| 407 | def test_repo_digest_matches_make_game(self): | ||
| 408 | sys.path.insert(0, ROOT) | ||
| 409 | import make_game | ||
| 410 | self.assertEqual(chain_check.repo_translation_digest(), make_game.translation_sources_digest()) | ||
| 411 | |||
| 412 | def test_bad_arguments_fail(self): | ||
| 413 | for argv in ([os.path.join(self.root, "none")], [self.root, "--log", os.path.join(self.root, "x.log")]): | ||
| 414 | with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()): | ||
| 415 | with self.assertRaises(SystemExit) as raised: | ||
| 416 | chain_check.main(argv) | ||
| 417 | self.assertEqual(raised.exception.code, 2) | ||
| 418 | |||
| 419 | |||
| 420 | if __name__ == "__main__": | ||
| 421 | unittest.main() | ||
diff --git a/tests/test_conformance_compare.py b/tests/test_conformance_compare.py new file mode 100644 index 000000000..2d58abc43 --- /dev/null +++ b/tests/test_conformance_compare.py | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | """Unit tests for tools/conformance/compare.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import sys | ||
| 6 | import unittest | ||
| 7 | from pathlib import Path | ||
| 8 | |||
| 9 | REPO = Path(__file__).resolve().parent.parent | ||
| 10 | sys.path.insert(0, str(REPO / "tools" / "conformance")) | ||
| 11 | |||
| 12 | import compare # noqa: E402 | ||
| 13 | |||
| 14 | |||
| 15 | class TestConformanceCompare(unittest.TestCase): | ||
| 16 | def test_raster_rgb_and_rgba_pixel_access(self) -> None: | ||
| 17 | rgb = compare.Raster( | ||
| 18 | width=2, | ||
| 19 | height=1, | ||
| 20 | colour_type=compare.PNG_COLOUR_TYPE_RGB, | ||
| 21 | pixels=bytearray([10, 20, 30, 40, 50, 60]), | ||
| 22 | source_path="rgb.png", | ||
| 23 | ) | ||
| 24 | self.assertEqual(rgb.channels(), 3) | ||
| 25 | self.assertEqual(rgb.colour_name(), "RGB") | ||
| 26 | self.assertEqual(rgb.stored_pixel(1, 0), (40, 50, 60)) | ||
| 27 | self.assertEqual(rgb.pixel_rgba(1, 0), (40, 50, 60, 255)) | ||
| 28 | |||
| 29 | rgba = compare.Raster( | ||
| 30 | width=1, | ||
| 31 | height=1, | ||
| 32 | colour_type=compare.PNG_COLOUR_TYPE_RGBA, | ||
| 33 | pixels=bytearray([1, 2, 3, 128]), | ||
| 34 | source_path="rgba.png", | ||
| 35 | ) | ||
| 36 | self.assertEqual(rgba.channels(), 4) | ||
| 37 | self.assertEqual(rgba.colour_name(), "RGBA") | ||
| 38 | self.assertEqual(rgba.pixel_rgba(0, 0), (1, 2, 3, 128)) | ||
| 39 | |||
| 40 | def test_raster_bounds_and_colour_type_errors(self) -> None: | ||
| 41 | rgb = compare.Raster( | ||
| 42 | width=1, | ||
| 43 | height=1, | ||
| 44 | colour_type=compare.PNG_COLOUR_TYPE_RGB, | ||
| 45 | pixels=bytearray([0, 0, 0]), | ||
| 46 | source_path="tiny.png", | ||
| 47 | ) | ||
| 48 | with self.assertRaises(compare.ToolError): | ||
| 49 | rgb.stored_pixel(1, 0) | ||
| 50 | with self.assertRaises(compare.ToolError): | ||
| 51 | compare.channels_for_colour_type(99, "bad.png") | ||
| 52 | |||
| 53 | def test_built_in_selftest_passes(self) -> None: | ||
| 54 | self.assertEqual(compare.main(["selftest"]), compare.EXIT_PASSED) | ||
| 55 | |||
| 56 | |||
| 57 | if __name__ == "__main__": | ||
| 58 | unittest.main() | ||
diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index d79116f8d..e2b147351 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py | |||
| @@ -590,6 +590,7 @@ class FeatureScanAtomicOutputTests(unittest.TestCase): | |||
| 590 | preexec_fn=self.fail_file_writes if fail_writes else None, | 590 | preexec_fn=self.fail_file_writes if fail_writes else None, |
| 591 | ) | 591 | ) |
| 592 | 592 | ||
| 593 | @unittest.skipIf(os.name == "nt", "preexec_fn, which these two cases need, is POSIX-only") | ||
| 593 | def test_failed_write_keeps_existing_report(self): | 594 | def test_failed_write_keeps_existing_report(self): |
| 594 | with tempfile.TemporaryDirectory() as root: | 595 | with tempfile.TemporaryDirectory() as root: |
| 595 | shaders = self.make_shaders(root) | 596 | shaders = self.make_shaders(root) |
| @@ -604,6 +605,7 @@ class FeatureScanAtomicOutputTests(unittest.TestCase): | |||
| 604 | with open(report, "rb") as stream: | 605 | with open(report, "rb") as stream: |
| 605 | self.assertEqual(stream.read(), original) | 606 | self.assertEqual(stream.read(), original) |
| 606 | 607 | ||
| 608 | @unittest.skipIf(os.name == "nt", "preexec_fn, which these two cases need, is POSIX-only") | ||
| 607 | def test_failed_write_leaves_no_temporary_file(self): | 609 | def test_failed_write_leaves_no_temporary_file(self): |
| 608 | with tempfile.TemporaryDirectory() as root: | 610 | with tempfile.TemporaryDirectory() as root: |
| 609 | shaders = self.make_shaders(root) | 611 | shaders = self.make_shaders(root) |
| @@ -633,7 +635,12 @@ class FeatureScanAtomicOutputTests(unittest.TestCase): | |||
| 633 | if __name__ == "__main__": | 635 | if __name__ == "__main__": |
| 634 | # Every test_* function in the file, in file order, so a new test can't be left out of the script run. | 636 | # Every test_* function in the file, in file order, so a new test can't be left out of the script run. |
| 635 | raised = run_tests([fn for name, fn in list(globals().items()) if name.startswith("test_") and callable(fn)]) | 637 | raised = run_tests([fn for name, fn in list(globals().items()) if name.startswith("test_") and callable(fn)]) |
| 636 | ok = not failures and not raised | 638 | # The class's cases are unittest methods, so the `test_*` scan above cannot see them: without this the script run |
| 639 | # (CI's standard-library job) skips them silently. | ||
| 640 | class_result = unittest.TextTestRunner(verbosity=0).run( | ||
| 641 | unittest.defaultTestLoader.loadTestsFromTestCase(FeatureScanAtomicOutputTests)) | ||
| 642 | class_failed = len(class_result.failures) + len(class_result.errors) | ||
| 643 | ok = not failures and not raised and not class_failed | ||
| 637 | print(f"test_feature_scan: {'OK' if ok else 'FAILED'} ({failures} failed check{'s' if failures != 1 else ''}, " | 644 | print(f"test_feature_scan: {'OK' if ok else 'FAILED'} ({failures} failed check{'s' if failures != 1 else ''}, " |
| 638 | f"{len(raised)} failed test{'s' if len(raised) != 1 else ''})") | 645 | f"{len(raised)} failed test{'s' if len(raised) != 1 else ''})") |
| 639 | sys.exit(0 if ok else 1) | 646 | sys.exit(0 if ok else 1) |
diff --git a/tests/test_fmisc_diff.py b/tests/test_fmisc_diff.py index e5d67ab8a..90e49bf98 100644 --- a/tests/test_fmisc_diff.py +++ b/tests/test_fmisc_diff.py | |||
| @@ -123,6 +123,31 @@ class Reference(unittest.TestCase): | |||
| 123 | self.assertIsNone(d._diff(["", "", "", "v_mov_b32_e32 v8, v1"] * 1, [QNAN] + [0] * 3, | 123 | self.assertIsNone(d._diff(["", "", "", "v_mov_b32_e32 v8, v1"] * 1, [QNAN] + [0] * 3, |
| 124 | [0xFFC00001] + [0] * 3, "x")) | 124 | [0xFFC00001] + [0] * 3, "x")) |
| 125 | 125 | ||
| 126 | def test_class_of_a_computed_nan(self): | ||
| 127 | # v_fmamk_f32 with a signalling-NaN operand: on gfx1036 (IEEE off) the hardware mostly passes the NaN | ||
| 128 | # source through unchanged but sometimes quiets it, so the result's class bits are not judged. A quiet | ||
| 129 | # NaN input gives a quiet result either way, and a pass-through op keeps an exact NaN's bits. | ||
| 130 | with self.assertRaises(d.Uncertain): | ||
| 131 | run("v_fmamk_f32 v1, v3, 0x3f800000, v2", | ||
| 132 | "v_cmp_class_f32_e64 s20, v1, 0x2", | ||
| 133 | "v_cndmask_b32_e64 v4, 0, 1.0, s20", | ||
| 134 | v={2: 0, 3: SNAN}) | ||
| 135 | with self.assertRaises(d.Uncertain): # the fuzziness survives a pass-through | ||
| 136 | run("v_fmamk_f32 v1, v3, 0x3f800000, v2", "v_fract_f32_e64 v5, v1", | ||
| 137 | "v_cmp_class_f32_e64 s20, v5, 0x2", | ||
| 138 | "v_cndmask_b32_e64 v4, 0, 1.0, s20", | ||
| 139 | v={2: 0, 3: SNAN}) | ||
| 140 | # a quiet NaN operand gives a quiet NaN result: class bit 1 (quiet NaN) still judged | ||
| 141 | self.assertEqual(run("v_fmamk_f32 v1, v3, 0x3f800000, v2", | ||
| 142 | "v_cmp_class_f32_e64 s20, v1, 0x2", | ||
| 143 | "v_cndmask_b32_e64 v4, 0, 1.0, s20", | ||
| 144 | v={2: 0, 3: QNAN})[3], 0x3F800000) | ||
| 145 | # a pass-through NaN keeps its bits: fract of a signalling NaN stays signalling, class bit 0 | ||
| 146 | self.assertEqual(run("v_fract_f32_e64 v1, v2", | ||
| 147 | "v_cmp_class_f32_e64 s20, v1, 0x1", | ||
| 148 | "v_cndmask_b32_e64 v4, 0, 1.0, s20", | ||
| 149 | v={2: SNAN})[3], 0x3F800000) | ||
| 150 | |||
| 126 | 151 | ||
| 127 | class Generator(unittest.TestCase): | 152 | class Generator(unittest.TestCase): |
| 128 | def lines(self, known=False, literals=True, n=3000, seed=1): | 153 | def lines(self, known=False, literals=True, n=3000, seed=1): |
diff --git a/tests/test_fssm_header_bindings_extra.py b/tests/test_fssm_header_bindings_extra.py new file mode 100644 index 000000000..514f098a6 --- /dev/null +++ b/tests/test_fssm_header_bindings_extra.py | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | """Additional edge-case tests for tools/fssm_header.py.""" | ||
| 2 | from __future__ import annotations | ||
| 3 | |||
| 4 | import struct | ||
| 5 | import sys | ||
| 6 | from pathlib import Path | ||
| 7 | |||
| 8 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools")) | ||
| 9 | |||
| 10 | import fssm_header as fh | ||
| 11 | |||
| 12 | |||
| 13 | def test_wave_size_handles_short_non_magic_and_wave32_flag(): | ||
| 14 | assert fh.wave_size(b"FSSM" + b"\x00" * 16) is None | ||
| 15 | non_magic = bytearray(0x100) | ||
| 16 | assert fh.wave_size(bytes(non_magic)) is None | ||
| 17 | |||
| 18 | w64 = bytearray(0x100) | ||
| 19 | w64[0:4] = fh.MAGIC | ||
| 20 | assert fh.wave_size(bytes(w64)) == 64 | ||
| 21 | |||
| 22 | w32 = bytearray(0x100) | ||
| 23 | w32[0:4] = fh.MAGIC | ||
| 24 | struct.pack_into("<I", w32, fh.WAVE_FLAGS_OFFSET, fh.FLAG_WAVE32) | ||
| 25 | assert fh.wave_size(bytes(w32)) == 32 | ||
| 26 | |||
| 27 | |||
| 28 | def test_binding_table_with_unset_code_end_and_trailing_bytes(): | ||
| 29 | code_off = 0x160 | ||
| 30 | code_sz = 0x20 | ||
| 31 | tail_off = code_off + code_sz | ||
| 32 | name = b"PS_ClearF32_Wrapped" | ||
| 33 | tail = ( | ||
| 34 | struct.pack("<4I", *([fh.TAIL_FILLER] * 4)) | ||
| 35 | + struct.pack("<2I", 1, 0) | ||
| 36 | + struct.pack("<5I", 2, 0, 8, 0, 0) | ||
| 37 | + struct.pack("<IIHH", fh.BINDING_SENTINEL, 0, 0, len(name)) | ||
| 38 | + name | ||
| 39 | + b"\xaa\xbb" | ||
| 40 | ) | ||
| 41 | blob = bytearray(tail_off) | ||
| 42 | blob[0:4] = fh.MAGIC | ||
| 43 | struct.pack_into("<Q", blob, fh.CODE_OFFSET, code_off) | ||
| 44 | struct.pack_into("<Q", blob, fh.CODE_SIZE, code_sz) | ||
| 45 | struct.pack_into("<Q", blob, fh.CODE_END, fh.CODE_END_UNSET) | ||
| 46 | full = bytes(blob) + tail | ||
| 47 | |||
| 48 | parsed = fh.binding_table(full) | ||
| 49 | assert parsed is not None | ||
| 50 | assert parsed["code_end"] == tail_off | ||
| 51 | assert parsed["header"] == 1 | ||
| 52 | assert parsed["records"] == [(2, 0, 8, 0, 0)] | ||
| 53 | assert parsed["name"] == "PS_ClearF32_Wrapped" | ||
| 54 | assert parsed["trailing"] == 2 | ||
| 55 | |||
| 56 | # Missing filler must return None. | ||
| 57 | broken = bytearray(full) | ||
| 58 | broken[tail_off] = 1 | ||
| 59 | assert fh.binding_table(bytes(broken)) is None | ||
| 60 | |||
| 61 | |||
| 62 | def test_interpolants_and_read_methods_multi_entry(): | ||
| 63 | blob = bytearray(fh.TABLE_OFFSET + 3 * fh.RECORD_SIZE) | ||
| 64 | blob[0:4] = fh.MAGIC | ||
| 65 | # Entry 0: flat (READ_MOV), 32-bit | ||
| 66 | blob[fh.TABLE_OFFSET : fh.TABLE_OFFSET + 8] = bytes([fh.RECORD_KIND, 1, 0xF, 0, 0, 0, 1, fh.READ_MOV]) | ||
| 67 | # Entry 1: interpolated (READ_INTERP), 16-bit (FLAG_FP16) | ||
| 68 | blob[fh.TABLE_OFFSET + 8 : fh.TABLE_OFFSET + 16] = bytes( | ||
| 69 | [fh.RECORD_KIND, 2, 0x3, 0, 0, 0, 2, fh.READ_INTERP | fh.FLAG_FP16] | ||
| 70 | ) | ||
| 71 | # Sentinel non-6 record stops table parsing | ||
| 72 | blob[fh.TABLE_OFFSET + 16] = 0 | ||
| 73 | |||
| 74 | count, fp16_mask = fh.interpolants(bytes(blob)) | ||
| 75 | assert count == 2 | ||
| 76 | assert fp16_mask == 0b10 | ||
| 77 | assert fh.read_methods(bytes(blob)) == [fh.READ_MOV, fh.READ_INTERP] | ||
| 78 | |||
| 79 | |||
| 80 | if __name__ == "__main__": | ||
| 81 | test_wave_size_handles_short_non_magic_and_wave32_flag() | ||
| 82 | test_binding_table_with_unset_code_end_and_trailing_bytes() | ||
| 83 | test_interpolants_and_read_methods_multi_entry() | ||
diff --git a/tests/test_hw_oracle_asm.py b/tests/test_hw_oracle_asm.py new file mode 100644 index 000000000..088be6a96 --- /dev/null +++ b/tests/test_hw_oracle_asm.py | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | """Unit tests for tools/hw_oracle/asm.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import sys | ||
| 6 | import unittest | ||
| 7 | from pathlib import Path | ||
| 8 | |||
| 9 | REPO = Path(__file__).resolve().parent.parent | ||
| 10 | sys.path.insert(0, str(REPO / "tools" / "hw_oracle")) | ||
| 11 | |||
| 12 | import asm # noqa: E402 | ||
| 13 | |||
| 14 | |||
| 15 | class TestHwOracleAsm(unittest.TestCase): | ||
| 16 | def test_family_classification_and_invalid_arch(self) -> None: | ||
| 17 | self.assertEqual(asm.family("gfx1010"), "gfx10") | ||
| 18 | self.assertEqual(asm.family("gfx1150"), "gfx11") | ||
| 19 | self.assertEqual(asm.family("gfx1201"), "gfx12") | ||
| 20 | for bad in ("gfx900", "gfx1300", "invalid", "gfx11"): | ||
| 21 | with self.assertRaises(ValueError): | ||
| 22 | asm.family(bad) | ||
| 23 | |||
| 24 | def test_literals_inline_vs_distinct_32bit(self) -> None: | ||
| 25 | self.assertEqual(asm.literals("s_mov_b32 s4, 64"), set()) | ||
| 26 | self.assertEqual(asm.literals("s_mov_b32 s4, -16"), set()) | ||
| 27 | self.assertEqual(asm.literals("s_movk_i32 s4, 0x1234"), set()) | ||
| 28 | self.assertEqual(asm.literals("s_cmpk_eq_i32 s4, 100"), set()) | ||
| 29 | self.assertEqual(asm.literals("s_add_i32 s4, -1, 0xffffffff"), {0xFFFFFFFF}) | ||
| 30 | self.assertEqual(asm.literals("s_add_i32 s4, 0x12345678, 0x87654321"), {0x12345678, 0x87654321}) | ||
| 31 | |||
| 32 | def test_skip_reason_per_family_and_two_literals(self) -> None: | ||
| 33 | self.assertIsNone(asm.skip_reason(["s_ff0_i32_b32 s4, s5"], "gfx1010")) | ||
| 34 | self.assertIn("GFX11", asm.skip_reason(["s_ff0_i32_b32 s4, s5"], "gfx1150")) | ||
| 35 | self.assertIsNone(asm.skip_reason(["s_cmpk_eq_i32 s4, 100"], "gfx1150")) | ||
| 36 | self.assertIn("GFX12", asm.skip_reason(["s_cmpk_eq_i32 s4, 100"], "gfx1201")) | ||
| 37 | self.assertIn( | ||
| 38 | "two different literals", | ||
| 39 | asm.skip_reason(["s_add_i32 s4, 0x12345678, 0x87654321"], "gfx1010"), | ||
| 40 | ) | ||
| 41 | |||
| 42 | |||
| 43 | if __name__ == "__main__": | ||
| 44 | unittest.main() | ||
diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py index fb1843834..1e512f657 100644 --- a/tests/test_image_load_typed.py +++ b/tests/test_image_load_typed.py | |||
| @@ -531,8 +531,9 @@ class TypedGatherShaders(unittest.TestCase): | |||
| 531 | ((sat, clamp),) = uses("OpExtInst", signed) | 531 | ((sat, clamp),) = uses("OpExtInst", signed) |
| 532 | self.assertEqual(clamp[2], "SClamp") | 532 | self.assertEqual(clamp[2], "SClamp") |
| 533 | ((bits, _),) = uses("OpBitcast", sat) | 533 | ((bits, _),) = uses("OpBitcast", sat) |
| 534 | ((half, mask),) = uses("OpBitwiseAnd", bits) | 534 | ((half, extract),) = uses("OpBitFieldUExtract", bits) |
| 535 | self.assertEqual(m.value(mask[2], 0, 0), 0xffff) | 535 | self.assertEqual(m.value(extract[2], 0, 0), 0) |
| 536 | self.assertEqual(m.value(extract[3], 0, 0), 16) | ||
| 536 | else: | 537 | else: |
| 537 | ((half, clamp),) = uses("OpExtInst", taps[tap]) | 538 | ((half, clamp),) = uses("OpExtInst", taps[tap]) |
| 538 | self.assertEqual(clamp[2], "UMin") | 539 | self.assertEqual(clamp[2], "UMin") |
diff --git a/tests/test_llvm_source_version.py b/tests/test_llvm_source_version.py index c68fc8160..64c35d866 100644 --- a/tests/test_llvm_source_version.py +++ b/tests/test_llvm_source_version.py | |||
| @@ -10,6 +10,17 @@ import unittest | |||
| 10 | SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_llvm_mc.ps1" | 10 | SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_llvm_mc.ps1" |
| 11 | 11 | ||
| 12 | 12 | ||
| 13 | class DefaultVersionTest(unittest.TestCase): | ||
| 14 | """The version the script builds when the caller names none: LLVM 23 for | ||
| 15 | the `shaders` stage (1844 of 2684 compute programs do not disassemble with | ||
| 16 | 21's listings), so an accidental revert to 21 fails here instead of | ||
| 17 | silently in a translation run.""" | ||
| 18 | |||
| 19 | def test_the_default_source_version_is_23(self): | ||
| 20 | text = SCRIPT.read_text(encoding="utf-8") | ||
| 21 | self.assertIn('[string]$Version = "23.1.5"', text) | ||
| 22 | |||
| 23 | |||
| 13 | @unittest.skipUnless(os.name == "nt" and shutil.which("git"), "Windows and Git required") | 24 | @unittest.skipUnless(os.name == "nt" and shutil.which("git"), "Windows and Git required") |
| 14 | class SourceVersionTest(unittest.TestCase): | 25 | class SourceVersionTest(unittest.TestCase): |
| 15 | def setUp(self): | 26 | def setUp(self): |
diff --git a/tests/test_lod_bias_probe.py b/tests/test_lod_bias_probe.py new file mode 100644 index 000000000..952418485 --- /dev/null +++ b/tests/test_lod_bias_probe.py | |||
| @@ -0,0 +1,128 @@ | |||
| 1 | """tools/lod_bias_probe.py: tools/vk_subgroup_info.py --lod-bias first, else three vk_sampler_test draws. | ||
| 2 | |||
| 3 | No GPU: vk_subgroup_info.py, build.py and vk_sampler_test are replaced by fakes. An answer from vk_subgroup_info.py | ||
| 4 | is used as it is, with no draw. Without one, the draw answers True only when LOD_BIAS +1 and -1 both read the | ||
| 5 | no-bias levels, False when both move as check.py expects, and None for a wrong no-bias draw, a mixed answer, a | ||
| 6 | failed draw or missing test programs. | ||
| 7 | Standard library only; no game files. | ||
| 8 | """ | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | import struct | ||
| 12 | import subprocess | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | from pathlib import Path | ||
| 17 | from unittest import mock | ||
| 18 | |||
| 19 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 20 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 21 | sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) | ||
| 22 | import check # noqa: E402 | ||
| 23 | import lod_bias_probe # noqa: E402 | ||
| 24 | |||
| 25 | |||
| 26 | def image(level_lz, level_implicit): | ||
| 27 | return b"".join(struct.pack("<4f", *check.sampler_texel(level_lz, x, y), *check.sampler_texel(level_implicit, x, y)) | ||
| 28 | for y in range(check.SAMPLER_SIZE) for x in range(check.SAMPLER_SIZE)) | ||
| 29 | |||
| 30 | |||
| 31 | class FakeRuns: | ||
| 32 | """subprocess.run for the probe: build.py writes the two modules, vk_sampler_test the levels `levels(bias)`.""" | ||
| 33 | |||
| 34 | def __init__(self, levels, draw_rc=0, info=None): | ||
| 35 | self.levels, self.draw_rc, self.info, self.draws = levels, draw_rc, info, 0 | ||
| 36 | |||
| 37 | def __call__(self, cmd, **kw): | ||
| 38 | if cmd[-1] == "--lod-bias": # vk_subgroup_info.py --lod-bias | ||
| 39 | return subprocess.CompletedProcess(cmd, 0, json.dumps(self.info or {"explicit_lod_bias": None}), "") | ||
| 40 | self.draws += 1 | ||
| 41 | if cmd[-2:] == ["vs_ids", "ps_ssharp"]: | ||
| 42 | spirv = Path(cmd[-3]) / "spirv" | ||
| 43 | spirv.mkdir(parents=True, exist_ok=True) | ||
| 44 | for n in ("vs_ids", "ps_ssharp"): | ||
| 45 | (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") | ||
| 46 | return subprocess.CompletedProcess(cmd, 0, "", "") | ||
| 47 | words = [int(w, 16) for w in cmd[4:8]] # vk_sampler_test vs ps raw <4 S# words> <base> <last> | ||
| 48 | bias = (((words[2] & 0x3fff) ^ 0x2000) - 0x2000) / 256 | ||
| 49 | if not self.draw_rc: | ||
| 50 | Path(cmd[3]).write_bytes(image(*self.levels(bias))) | ||
| 51 | return subprocess.CompletedProcess(cmd, self.draw_rc, "", "device lost" if self.draw_rc else "") | ||
| 52 | |||
| 53 | |||
| 54 | def applied(bias): # check.py's expectation: LOD 0 / LOD 1 plus the bias, on two levels | ||
| 55 | return (min(max(round(0 + bias), 0), 1), min(max(round(1 + bias), 0), 1)) | ||
| 56 | |||
| 57 | |||
| 58 | class ProbeTest(unittest.TestCase): | ||
| 59 | def setUp(self): | ||
| 60 | self.build = tempfile.TemporaryDirectory() | ||
| 61 | self.addCleanup(self.build.cleanup) | ||
| 62 | Path(self.build.name, "vk_sampler_test" + lod_bias_probe.EXE).write_bytes(b"") | ||
| 63 | |||
| 64 | def run_probe(self, fake): | ||
| 65 | with mock.patch.object(lod_bias_probe.subprocess, "run", fake): | ||
| 66 | return lod_bias_probe.probe(self.build.name) | ||
| 67 | |||
| 68 | def run_draw(self, fake): | ||
| 69 | with mock.patch.object(lod_bias_probe.subprocess, "run", fake): | ||
| 70 | return lod_bias_probe.draw_probe(self.build.name) | ||
| 71 | |||
| 72 | def test_a_driver_that_applies_the_bias(self): | ||
| 73 | self.assertIs(self.run_probe(FakeRuns(applied))[0], False) | ||
| 74 | |||
| 75 | def test_a_driver_that_drops_the_bias(self): | ||
| 76 | answer, reason = self.run_probe(FakeRuns(lambda bias: (0, 1))) | ||
| 77 | self.assertIs(answer, True) | ||
| 78 | self.assertIn("drops", reason) | ||
| 79 | |||
| 80 | def test_a_mixed_answer_is_unknown(self): | ||
| 81 | # +1 applied, -1 dropped: neither rule fits, so the flag must not be chosen from it. | ||
| 82 | self.assertIsNone(self.run_probe(FakeRuns(lambda bias: applied(bias) if bias > 0 else (0, 1)))[0]) | ||
| 83 | |||
| 84 | def test_a_wrong_no_bias_draw_is_unknown(self): | ||
| 85 | self.assertIsNone(self.run_probe(FakeRuns(lambda bias: (1, 0)))[0]) | ||
| 86 | |||
| 87 | def test_a_failed_draw_is_unknown(self): | ||
| 88 | self.assertIsNone(self.run_probe(FakeRuns(applied, draw_rc=1))[0]) | ||
| 89 | |||
| 90 | def test_no_test_programs_is_unknown(self): | ||
| 91 | with tempfile.TemporaryDirectory() as empty: | ||
| 92 | answer, reason = lod_bias_probe.draw_probe(empty) | ||
| 93 | self.assertIsNone(answer) | ||
| 94 | self.assertIn("vk_sampler_test", reason) | ||
| 95 | |||
| 96 | def test_a_measured_answer_needs_no_draw(self): | ||
| 97 | for answer in (True, False): | ||
| 98 | with self.subTest(answer=answer): | ||
| 99 | fake = FakeRuns(lambda bias: (1, 0), info={"explicit_lod_bias": answer, "explicit_lod_bias_reason": "m"}) | ||
| 100 | self.assertEqual(self.run_probe(fake), (answer, "m")) | ||
| 101 | self.assertEqual(fake.draws, 0) | ||
| 102 | |||
| 103 | def test_an_error_from_vk_subgroup_info_falls_back_to_the_draw(self): | ||
| 104 | fake = FakeRuns(lambda bias: (0, 1), info={"error": "RuntimeError: no Vulkan device"}) | ||
| 105 | self.assertIs(self.run_probe(fake)[0], True) | ||
| 106 | self.assertGreater(fake.draws, 0) | ||
| 107 | |||
| 108 | def test_without_test_programs_only_the_measurement_answers(self): | ||
| 109 | fake = FakeRuns(applied) | ||
| 110 | with mock.patch.object(lod_bias_probe.subprocess, "run", fake): | ||
| 111 | answer, _ = lod_bias_probe.probe(None) | ||
| 112 | self.assertIsNone(answer) | ||
| 113 | self.assertEqual(fake.draws, 0) | ||
| 114 | |||
| 115 | def test_the_probe_translates_without_the_flag(self): | ||
| 116 | seen = {} | ||
| 117 | fake = FakeRuns(applied) | ||
| 118 | |||
| 119 | def spy(cmd, **kw): | ||
| 120 | if cmd[-2:] == ["vs_ids", "ps_ssharp"]: | ||
| 121 | seen["env"] = kw.get("env", {}).get("LEONIDA_EXPLICIT_LOD_BIAS") | ||
| 122 | return fake(cmd, **kw) | ||
| 123 | self.run_probe(spy) | ||
| 124 | self.assertEqual(seen["env"], "0") | ||
| 125 | |||
| 126 | |||
| 127 | if __name__ == "__main__": | ||
| 128 | unittest.main() | ||
diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py index a92934bff..735a2f7b7 100644 --- a/tests/test_make_game_argparse.py +++ b/tests/test_make_game_argparse.py | |||
| @@ -364,6 +364,7 @@ class JobsHandlingTest(unittest.TestCase): | |||
| 364 | patch("make_game.wave64_settings", return_value=(True, True)) as probe, \ | 364 | patch("make_game.wave64_settings", return_value=(True, True)) as probe, \ |
| 365 | patch("make_game.runtime_gpu_per_vertex", return_value=None), \ | 365 | patch("make_game.runtime_gpu_per_vertex", return_value=None), \ |
| 366 | patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ | 366 | patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ |
| 367 | patch("make_game.runtime_gpu_explicit_lod_bias", return_value=None), \ | ||
| 367 | patch("make_game.runtime_gpu_max_push_constants", return_value=None), \ | 368 | patch("make_game.runtime_gpu_max_push_constants", return_value=None), \ |
| 368 | patch("make_game.runtime_gpu_mesh_draws_crash", return_value=None), \ | 369 | patch("make_game.runtime_gpu_mesh_draws_crash", return_value=None), \ |
| 369 | patch("make_game.runtime_gpu_integer_dot_product", return_value=None), \ | 370 | patch("make_game.runtime_gpu_integer_dot_product", return_value=None), \ |
| @@ -570,7 +571,8 @@ class WavValidationTest(unittest.TestCase): | |||
| 570 | with patch("make_game.rpf9dump", return_value="fake_dump"), patch("make_game.log"), \ | 571 | with patch("make_game.rpf9dump", return_value="fake_dump"), patch("make_game.log"), \ |
| 571 | patch("make_game.py") as mock_py: | 572 | patch("make_game.py") as mock_py: |
| 572 | make_game.assets(game, work, wav=False, jobs=3) | 573 | make_game.assets(game, work, wav=False, jobs=3) |
| 573 | mock_py.assert_any_call("awc_opus.py", os.path.join(audio, "awc"), os.path.join(audio, "ogg"), "--jobs", "3") | 574 | mock_py.assert_any_call("awc_opus.py", os.path.join(audio, "awc"), os.path.join(audio, "ogg"), "--jobs", "3", |
| 575 | "--skip-existing") | ||
| 574 | 576 | ||
| 575 | def test_assets_without_wav_skips_audio_wav(self): | 577 | def test_assets_without_wav_skips_audio_wav(self): |
| 576 | with tempfile.TemporaryDirectory() as tmp: | 578 | with tempfile.TemporaryDirectory() as tmp: |
diff --git a/tests/test_make_game_pipeline_preflight.py b/tests/test_make_game_pipeline_preflight.py index 227f52bbc..390e61a0d 100644 --- a/tests/test_make_game_pipeline_preflight.py +++ b/tests/test_make_game_pipeline_preflight.py | |||
| @@ -167,7 +167,7 @@ class PipelinePreflightTest(PreflightEnv, unittest.TestCase): | |||
| 167 | mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ | 167 | mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ |
| 168 | mock.patch.object(make_game, "pipeline_check_exe", return_value=None): | 168 | mock.patch.object(make_game, "pipeline_check_exe", return_value=None): |
| 169 | err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") | 169 | err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") |
| 170 | self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) | 170 | self.assertIn("llvm-mc (LLVM 23+ with the AMDGPU target)", err) |
| 171 | self.assertEqual(err.count("vk_pipeline_check"), 1) | 171 | self.assertEqual(err.count("vk_pipeline_check"), 1) |
| 172 | 172 | ||
| 173 | 173 | ||
diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index c705a23e6..a6af114b7 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py | |||
| @@ -553,7 +553,7 @@ class PreflightPrerequisiteTest(PreflightTestBase): | |||
| 553 | err = self.assert_fails(make_game.preflight, ["shaders", "assets", "runtime"], tmp_work, wav=True, | 553 | err = self.assert_fails(make_game.preflight, ["shaders", "assets", "runtime"], tmp_work, wav=True, |
| 554 | match="Install these first, then run the build again:") | 554 | match="Install these first, then run the build again:") |
| 555 | self.assertIn("ffmpeg (needed for --wav)", err) | 555 | self.assertIn("ffmpeg (needed for --wav)", err) |
| 556 | self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) | 556 | self.assertIn("llvm-mc (LLVM 23+ with the AMDGPU target)", err) |
| 557 | self.assertIn("spirv-as:", err) | 557 | self.assertIn("spirv-as:", err) |
| 558 | self.assertIn("spirv-val:", err) | 558 | self.assertIn("spirv-val:", err) |
| 559 | self.assertIn(".NET 8 SDK", err) | 559 | self.assertIn(".NET 8 SDK", err) |
| @@ -579,7 +579,7 @@ class PreflightPrerequisiteTest(PreflightTestBase): | |||
| 579 | mock.patch("shutil.which", side_effect=available.get), \ | 579 | mock.patch("shutil.which", side_effect=available.get), \ |
| 580 | mock.patch("os.path.isfile", return_value=False): | 580 | mock.patch("os.path.isfile", return_value=False): |
| 581 | err = self.assert_fails(make_game.preflight, ["shaders"], tmp_work, | 581 | err = self.assert_fails(make_game.preflight, ["shaders"], tmp_work, |
| 582 | match="llvm-mc (LLVM 21+ with the AMDGPU target)") | 582 | match="llvm-mc (LLVM 23+ with the AMDGPU target)") |
| 583 | self.assertIn("LLVM_MC points into %LOCALAPPDATA%", err) | 583 | self.assertIn("LLVM_MC points into %LOCALAPPDATA%", err) |
| 584 | 584 | ||
| 585 | def test_preflight_rejects_visual_studio_installer_without_cpp_tools(self): | 585 | def test_preflight_rejects_visual_studio_installer_without_cpp_tools(self): |
diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index 76b6a6884..fb46eb1d4 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py | |||
| @@ -198,7 +198,7 @@ class MainWiringTest(unittest.TestCase): | |||
| 198 | """main() parses the fallback flags and hands the same tuple to preflight() and shaders().""" | 198 | """main() parses the fallback flags and hands the same tuple to preflight() and shaders().""" |
| 199 | 199 | ||
| 200 | def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_push_constants=None, | 200 | def run_main(self, *extra_argv, per_vertex=None, barycentric_fallback=None, max_push_constants=None, |
| 201 | mesh_crash=False, integer_dot=True, denorm_ftz_f32=True): | 201 | mesh_crash=False, drops_lod_bias=False, integer_dot=True, denorm_ftz_f32=True): |
| 202 | # An empty --out: main() reads the flags an existing translation was made with, and the default folder | 202 | # An empty --out: main() reads the flags an existing translation was made with, and the default folder |
| 203 | # is the user's own. | 203 | # is the user's own. |
| 204 | out = tempfile.TemporaryDirectory() | 204 | out = tempfile.TemporaryDirectory() |
| @@ -211,6 +211,7 @@ class MainWiringTest(unittest.TestCase): | |||
| 211 | mock.patch("make_game.wave64_settings", return_value=(False, True)), \ | 211 | mock.patch("make_game.wave64_settings", return_value=(False, True)), \ |
| 212 | mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ | 212 | mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ |
| 213 | mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=barycentric_fallback), \ | 213 | mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=barycentric_fallback), \ |
| 214 | mock.patch("make_game.runtime_gpu_explicit_lod_bias", return_value=drops_lod_bias), \ | ||
| 214 | mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ | 215 | mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ |
| 215 | mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \ | 216 | mock.patch("make_game.runtime_gpu_mesh_draws_crash", return_value=mesh_crash), \ |
| 216 | mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=integer_dot), \ | 217 | mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=integer_dot), \ |
| @@ -231,6 +232,12 @@ class MainWiringTest(unittest.TestCase): | |||
| 231 | self.assertEqual(pre, ()) | 232 | self.assertEqual(pre, ()) |
| 232 | self.assertEqual(sh, ()) | 233 | self.assertEqual(sh, ()) |
| 233 | 234 | ||
| 235 | def test_explicit_lod_bias_follows_the_moltenvk_probe(self): | ||
| 236 | """MoltenVK drops the sampler's mipLodBias: the shaders take the S# bias themselves there, nowhere else.""" | ||
| 237 | self.assertEqual(self.run_main(drops_lod_bias=True), (("--explicit-lod-bias",),) * 2) | ||
| 238 | self.assertEqual(self.run_main(drops_lod_bias=False), ((), ())) | ||
| 239 | self.assertEqual(self.run_main("--explicit-lod-bias", drops_lod_bias=False), (("--explicit-lod-bias",),) * 2) | ||
| 240 | |||
| 234 | def test_mesh_serial_waves_is_opt_in_and_forwarded(self): | 241 | def test_mesh_serial_waves_is_opt_in_and_forwarded(self): |
| 235 | # #2435's translator switch: nothing passes it unless asked, and asking forwards it like the other flags. | 242 | # #2435's translator switch: nothing passes it unless asked, and asking forwards it like the other flags. |
| 236 | pre, sh = self.run_main("--mesh-serial-waves") | 243 | pre, sh = self.run_main("--mesh-serial-waves") |
| @@ -394,6 +401,7 @@ class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest): | |||
| 394 | mock.patch("make_game.wave64_settings", return_value=(False, True)), \ | 401 | mock.patch("make_game.wave64_settings", return_value=(False, True)), \ |
| 395 | mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ | 402 | mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ |
| 396 | mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ | 403 | mock.patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ |
| 404 | mock.patch("make_game.runtime_gpu_explicit_lod_bias", return_value=False), \ | ||
| 397 | mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=True), \ | 405 | mock.patch("make_game.runtime_gpu_integer_dot_product", return_value=True), \ |
| 398 | mock.patch("make_game.runtime_gpu_denorm_ftz_f32", return_value=denorm_ftz_f32), \ | 406 | mock.patch("make_game.runtime_gpu_denorm_ftz_f32", return_value=denorm_ftz_f32), \ |
| 399 | mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ | 407 | mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ |
diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py index ff9209f89..4de7f1524 100644 --- a/tests/test_mc_command.py +++ b/tests/test_mc_command.py | |||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU target): | 3 | Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU target): |
| 4 | 4 | ||
| 5 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc | 5 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc |
| 6 | 6 | ||
| 7 | python -I tests/test_mc_command.py | 7 | python -I tests/test_mc_command.py |
| 8 | """ | 8 | """ |
| @@ -198,7 +198,7 @@ class VersionedLlvmMcTest(unittest.TestCase): | |||
| 198 | def test_the_message_names_the_distribution_package_off_windows(self): | 198 | def test_the_message_names_the_distribution_package_off_windows(self): |
| 199 | with mock.patch.object(mc_command.sys, "platform", "linux"): | 199 | with mock.patch.object(mc_command.sys, "platform", "linux"): |
| 200 | message = mc_command.not_found("llvm-mc", FileNotFoundError(2, "No such file")) | 200 | message = mc_command.not_found("llvm-mc", FileNotFoundError(2, "No such file")) |
| 201 | self.assertIn("apt install llvm-21", message) | 201 | self.assertIn("apt install llvm-23", message) |
| 202 | self.assertNotIn("build_llvm_mc.ps1", message) | 202 | self.assertNotIn("build_llvm_mc.ps1", message) |
| 203 | 203 | ||
| 204 | 204 | ||
| @@ -245,7 +245,7 @@ class MissingLlvmMcTest(unittest.TestCase): | |||
| 245 | with mock.patch.object(mc_command.os, "name", "nt"): | 245 | with mock.patch.object(mc_command.os, "name", "nt"): |
| 246 | hint = mc_command.install_hint() | 246 | hint = mc_command.install_hint() |
| 247 | self.assertIn("build_llvm_mc.ps1", hint) | 247 | self.assertIn("build_llvm_mc.ps1", hint) |
| 248 | self.assertIn("LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc", hint) | 248 | self.assertIn("LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc", hint) |
| 249 | 249 | ||
| 250 | def test_run_names_the_tools_own_option(self): | 250 | def test_run_names_the_tools_own_option(self): |
| 251 | with self.assertRaises(SystemExit) as cm: | 251 | with self.assertRaises(SystemExit) as cm: |
diff --git a/tests/test_merge_check_safety.py b/tests/test_merge_check_safety.py new file mode 100644 index 000000000..43f39ce01 --- /dev/null +++ b/tests/test_merge_check_safety.py | |||
| @@ -0,0 +1,66 @@ | |||
| 1 | """Unit tests for scripts/merge_check.py ref validation, bounds, and git timeout handling. | ||
| 2 | |||
| 3 | python -I tests/test_merge_check_safety.py | ||
| 4 | """ | ||
| 5 | from __future__ import annotations | ||
| 6 | |||
| 7 | import contextlib | ||
| 8 | import io | ||
| 9 | import subprocess | ||
| 10 | import sys | ||
| 11 | import unittest | ||
| 12 | from pathlib import Path | ||
| 13 | from unittest import mock | ||
| 14 | |||
| 15 | ROOT = Path(__file__).resolve().parents[1] | ||
| 16 | SCRIPTS = ROOT / "scripts" | ||
| 17 | if str(SCRIPTS) not in sys.path: | ||
| 18 | sys.path.insert(0, str(SCRIPTS)) | ||
| 19 | |||
| 20 | import merge_check as mc # noqa: E402 | ||
| 21 | |||
| 22 | |||
| 23 | class MergeCheckSafetyTests(unittest.TestCase): | ||
| 24 | def test_parse_pair_and_cli_reject_invalid_bounds_and_option_injection(self) -> None: | ||
| 25 | self.assertEqual(mc.parse_pair("#12=main"), (12, "main")) | ||
| 26 | self.assertEqual(mc.parse_pair("12=refs/pull/12/head"), (12, "refs/pull/12/head")) | ||
| 27 | |||
| 28 | bad_argvs = ( | ||
| 29 | ["--depth", "0", "12=main"], | ||
| 30 | ["--depth", "-1", "12=main"], | ||
| 31 | ["--min-length", "0", "12=main"], | ||
| 32 | ["--min-length", "-1", "12=main"], | ||
| 33 | ["0=main"], | ||
| 34 | ["##12=main"], | ||
| 35 | ["12=--all"], | ||
| 36 | ["12= "], | ||
| 37 | ["--main=--exec=bad", "12=main"], | ||
| 38 | ["--main", "", "12=main"], | ||
| 39 | ) | ||
| 40 | for argv in bad_argvs: | ||
| 41 | with self.subTest(argv=argv): | ||
| 42 | err = io.StringIO() | ||
| 43 | with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: | ||
| 44 | mc.main(argv) | ||
| 45 | self.assertEqual(cm.exception.code, 2) | ||
| 46 | |||
| 47 | def test_git_timeout_raises_git_error_and_main_returns_2(self) -> None: | ||
| 48 | with mock.patch.object( | ||
| 49 | mc.subprocess, | ||
| 50 | "run", | ||
| 51 | side_effect=subprocess.TimeoutExpired(["git"], mc.GIT_TIMEOUT), | ||
| 52 | ): | ||
| 53 | with self.assertRaises(mc.GitError) as cm: | ||
| 54 | mc.git(".", "status") | ||
| 55 | self.assertIn("timed out", str(cm.exception)) | ||
| 56 | |||
| 57 | err = io.StringIO() | ||
| 58 | with contextlib.redirect_stderr(err): | ||
| 59 | rc = mc.main(["--repo", ".", "12=main"]) | ||
| 60 | self.assertEqual(rc, 2) | ||
| 61 | self.assertIn("merge_check:", err.getvalue()) | ||
| 62 | self.assertIn("timed out", err.getvalue()) | ||
| 63 | |||
| 64 | |||
| 65 | if __name__ == "__main__": | ||
| 66 | unittest.main() | ||
diff --git a/tests/test_picture_metrics.py b/tests/test_picture_metrics.py new file mode 100644 index 000000000..52f4ef5a6 --- /dev/null +++ b/tests/test_picture_metrics.py | |||
| @@ -0,0 +1,414 @@ | |||
| 1 | """tools/picture_metrics.py on synthetic frames: every pixel is drawn here, no game data. | ||
| 2 | |||
| 3 | python -I tests/test_picture_metrics.py | ||
| 4 | |||
| 5 | The frames are built in memory and written as PNG by the small encoder below (all five filter types, RGB and RGBA, | ||
| 6 | 8 bits, not interlaced); each test checks that the tool gives back the parameters it was drawn with. | ||
| 7 | """ | ||
| 8 | import io | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | import random | ||
| 12 | import struct | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | import zlib | ||
| 17 | from contextlib import redirect_stderr, redirect_stdout | ||
| 18 | |||
| 19 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 20 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 21 | |||
| 22 | import picture_metrics as pm # noqa: E402 | ||
| 23 | |||
| 24 | |||
| 25 | # ---- a small PNG encoder --------------------------------------------------------------------------------------- | ||
| 26 | |||
| 27 | def _paeth(a, b, c): | ||
| 28 | p = a + b - c | ||
| 29 | pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) | ||
| 30 | if pa <= pb and pa <= pc: | ||
| 31 | return a | ||
| 32 | return b if pb <= pc else c | ||
| 33 | |||
| 34 | |||
| 35 | def _filter_row(kind, row, prev, bpp): | ||
| 36 | out = bytearray([kind]) | ||
| 37 | for i, x in enumerate(row): | ||
| 38 | a = row[i - bpp] if i >= bpp else 0 | ||
| 39 | b = prev[i] | ||
| 40 | c = prev[i - bpp] if i >= bpp else 0 | ||
| 41 | pred = (0, a, b, (a + b) // 2, _paeth(a, b, c))[kind] | ||
| 42 | out.append((x - pred) & 0xFF) | ||
| 43 | return out | ||
| 44 | |||
| 45 | |||
| 46 | def _chunk(kind, data): | ||
| 47 | return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) | ||
| 48 | |||
| 49 | |||
| 50 | def png_bytes(width, height, pixels, channels=3, filters=(0,), bit_depth=8, color_type=None, interlace=0): | ||
| 51 | """A PNG of row-major 8-bit ``pixels`` (``channels`` bytes each); row y uses filter ``filters[y % len]``.""" | ||
| 52 | if color_type is None: | ||
| 53 | color_type = {1: 0, 2: 4, 3: 2, 4: 6}[channels] | ||
| 54 | stride = width * channels | ||
| 55 | prev = bytearray(stride) | ||
| 56 | raw = bytearray() | ||
| 57 | for y in range(height): | ||
| 58 | row = bytearray(pixels[y * stride:(y + 1) * stride]) | ||
| 59 | raw += _filter_row(filters[y % len(filters)], row, prev, channels) | ||
| 60 | prev = row | ||
| 61 | ihdr = struct.pack(">IIBBBBB", width, height, bit_depth, color_type, 0, 0, interlace) | ||
| 62 | return (b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(raw))) | ||
| 63 | + _chunk(b"IEND", b"")) | ||
| 64 | |||
| 65 | |||
| 66 | # ---- synthetic frames ------------------------------------------------------------------------------------------ | ||
| 67 | |||
| 68 | def gray_frame(width, height, value): | ||
| 69 | """A grey RGB frame as a list of luma values, which ``rgb()`` turns into pixel bytes.""" | ||
| 70 | return [value] * (width * height) | ||
| 71 | |||
| 72 | |||
| 73 | def rgb(lumas): | ||
| 74 | """Grey pixels: R = G = B, so the luma of each is the value itself.""" | ||
| 75 | out = bytearray() | ||
| 76 | for v in lumas: | ||
| 77 | out += bytes((v, v, v)) | ||
| 78 | return bytes(out) | ||
| 79 | |||
| 80 | |||
| 81 | def lattice_frame(width, height, period, phase, diagonal, corner, tile=8, back=128, dark=0): | ||
| 82 | """Small dark triangles in the tiles on one diagonal in ``period``: ``(tx +/- ty) % period == phase``.""" | ||
| 83 | lumas = gray_frame(width, height, back) | ||
| 84 | for ty in range(height // tile): | ||
| 85 | for tx in range(width // tile): | ||
| 86 | d = (tx + ty) if diagonal == "+" else (tx - ty) | ||
| 87 | if d % period != phase: | ||
| 88 | continue | ||
| 89 | for ly in range(tile): | ||
| 90 | for lx in range(tile): | ||
| 91 | u = lx if corner in ("TL", "BL") else tile - 1 - lx | ||
| 92 | v = ly if corner in ("TL", "TR") else tile - 1 - ly | ||
| 93 | if u + v < tile // 2: | ||
| 94 | lumas[(ty * tile + ly) * width + tx * tile + lx] = dark | ||
| 95 | return lumas | ||
| 96 | |||
| 97 | |||
| 98 | def smooth_frame(width, height): | ||
| 99 | """A slow grey ramp, 64..127, with no step of more than one level and no dark pixel.""" | ||
| 100 | return [64 + (x + y) // 4 for y in range(height) for x in range(width)] | ||
| 101 | |||
| 102 | |||
| 103 | def blocks_frame(width, height, bw, bh, foreign, other=230): | ||
| 104 | """``smooth_frame`` with the ``bw`` x ``bh`` blocks at ``foreign`` (block column, block row) copied from a flat | ||
| 105 | frame of ``other``.""" | ||
| 106 | lumas = smooth_frame(width, height) | ||
| 107 | for bx, by in foreign: | ||
| 108 | for y in range(by * bh, (by + 1) * bh): | ||
| 109 | for x in range(bx * bw, (bx + 1) * bw): | ||
| 110 | lumas[y * width + x] = other | ||
| 111 | return lumas | ||
| 112 | |||
| 113 | |||
| 114 | def sparse_dark_frame(width, height, count, seed, back=128): | ||
| 115 | """A plain grey frame with ``count`` dark pixels at places drawn from ``seed``.""" | ||
| 116 | rng = random.Random(seed) | ||
| 117 | lumas = gray_frame(width, height, back) | ||
| 118 | for _ in range(count): | ||
| 119 | lumas[rng.randrange(height) * width + rng.randrange(width)] = 0 | ||
| 120 | return lumas | ||
| 121 | |||
| 122 | |||
| 123 | def frame_of(lumas, width, height): | ||
| 124 | return pm.Frame(width, height, rgb(lumas)) | ||
| 125 | |||
| 126 | |||
| 127 | class PngReader(unittest.TestCase): | ||
| 128 | def test_every_filter_rgb_and_rgba(self): | ||
| 129 | w, h = 7, 6 | ||
| 130 | rgb_px = bytes((x * 37 + y * 11 + c * 90) & 0xFF for y in range(h) for x in range(w) for c in range(3)) | ||
| 131 | rgba_px = bytes((x * 53 + y * 7 + c * 61) & 0xFF for y in range(h) for x in range(w) for c in range(4)) | ||
| 132 | for kind in range(5): | ||
| 133 | with self.subTest(filter=kind): | ||
| 134 | f = pm.decode_png(png_bytes(w, h, rgb_px, 3, (kind,))) | ||
| 135 | self.assertEqual((f.width, f.height, f.rgb), (w, h, rgb_px)) | ||
| 136 | f = pm.decode_png(png_bytes(w, h, rgba_px, 4, (kind,))) | ||
| 137 | self.assertEqual(f.rgb, bytes(b for i, b in enumerate(rgba_px) if i % 4 != 3)) | ||
| 138 | mixed = pm.decode_png(png_bytes(w, h, rgb_px, 3, (0, 1, 2, 3, 4))) | ||
| 139 | self.assertEqual(mixed.rgb, rgb_px) | ||
| 140 | |||
| 141 | def test_grey_and_split_idat(self): | ||
| 142 | w, h = 5, 3 | ||
| 143 | grey = bytes(range(w * h)) | ||
| 144 | self.assertEqual(pm.decode_png(png_bytes(w, h, grey, 1, (4,))).rgb, rgb(grey)) | ||
| 145 | data = png_bytes(w, h, rgb(grey), 3, (2,)) | ||
| 146 | start = data.index(b"IDAT") - 4 | ||
| 147 | length = struct.unpack(">I", data[start:start + 4])[0] | ||
| 148 | body = data[start + 8:start + 8 + length] | ||
| 149 | split = _chunk(b"IDAT", body[:5]) + _chunk(b"IDAT", body[5:]) | ||
| 150 | data = data[:start] + split + data[start + 12 + length:] | ||
| 151 | self.assertEqual(pm.decode_png(data).rgb, rgb(grey)) | ||
| 152 | |||
| 153 | def test_refuses_what_it_does_not_read(self): | ||
| 154 | px = bytes(12) | ||
| 155 | cases = { | ||
| 156 | "interlaced": png_bytes(2, 2, px, 3, interlace=1), | ||
| 157 | "16-bit": png_bytes(2, 2, px, 3, bit_depth=16), | ||
| 158 | "palette": png_bytes(2, 2, bytes(4), 1, color_type=3), | ||
| 159 | "not a PNG": b"GIF89a" + bytes(40), | ||
| 160 | "truncated": png_bytes(2, 2, px, 3)[:30], | ||
| 161 | } | ||
| 162 | bad_crc = bytearray(png_bytes(2, 2, px, 3)) | ||
| 163 | bad_crc[29] ^= 0xFF # last byte of the IHDR CRC | ||
| 164 | cases["bad CRC"] = bytes(bad_crc) | ||
| 165 | bad_filter = bytearray(png_bytes(2, 2, px, 3)) | ||
| 166 | cases["filter 5"] = bytes(bad_filter[:33]) + _chunk( | ||
| 167 | b"IDAT", zlib.compress(b"\x05" + bytes(6) + b"\x00" + bytes(6))) + _chunk(b"IEND", b"") | ||
| 168 | for name, data in cases.items(): | ||
| 169 | with self.subTest(name), self.assertRaises(ValueError): | ||
| 170 | pm.decode_png(data) | ||
| 171 | |||
| 172 | def test_ppm(self): | ||
| 173 | px = bytes(range(18)) | ||
| 174 | f = pm.decode_image(b"P6\n# a comment\n3 2\n255\n" + px) | ||
| 175 | self.assertEqual((f.width, f.height, f.rgb), (3, 2, px)) | ||
| 176 | f = pm.decode_image(b"P5 3 2 255\n" + bytes(range(6))) | ||
| 177 | self.assertEqual(f.rgb, rgb(range(6))) | ||
| 178 | with self.assertRaises(ValueError): | ||
| 179 | pm.decode_image(b"P6 3 2 65535\n" + bytes(36)) | ||
| 180 | with self.assertRaises(ValueError): | ||
| 181 | pm.decode_image(b"P6 3 2 255\n" + bytes(5)) | ||
| 182 | |||
| 183 | |||
| 184 | class Luma(unittest.TestCase): | ||
| 185 | def test_weights(self): | ||
| 186 | f = pm.Frame(3, 1, bytes((255, 0, 0, 0, 255, 0, 0, 0, 255))) | ||
| 187 | self.assertEqual(list(pm.luma(f)), [76, 150, 29]) | ||
| 188 | |||
| 189 | def test_stats_of_a_known_frame(self): | ||
| 190 | lumas = [0, 200] * 32 # 8x8, half 0 and half 200 | ||
| 191 | s = pm.luma_stats(pm.luma(frame_of(lumas, 8, 8))) | ||
| 192 | self.assertEqual(s, {"mean": 100.0, "min": 0, "max": 200, "sd": 100.0, "dark": 0.5}) | ||
| 193 | s = pm.luma_stats(pm.luma(frame_of([10, 20, 30, 40], 2, 2))) | ||
| 194 | self.assertEqual((s["mean"], s["min"], s["max"], s["sd"], s["dark"]), (25.0, 10, 40, 11.18, 0.5)) | ||
| 195 | |||
| 196 | def test_dark_share_per_region(self): | ||
| 197 | w = h = 64 | ||
| 198 | lumas = gray_frame(w, h, 128) | ||
| 199 | for y in range(h): | ||
| 200 | for x in range(w): | ||
| 201 | if (x < 16 and y < 16) or (x >= 56 and y >= 48): # region (0,0) all, region (3,3) half | ||
| 202 | lumas[y * w + x] = 3 | ||
| 203 | grid = pm.dark_regions(pm.luma(frame_of(lumas, w, h)), w, h) | ||
| 204 | expected = [[0.0] * 4 for _ in range(4)] | ||
| 205 | expected[0][0], expected[3][3] = 1.0, 0.5 | ||
| 206 | self.assertEqual(grid, expected) | ||
| 207 | uneven = pm.dark_regions(bytes(10 * 6), 10, 6) # regions of 2 or 3 pixels a side | ||
| 208 | self.assertEqual(uneven, [[1.0] * 4 for _ in range(4)]) | ||
| 209 | |||
| 210 | |||
| 211 | class Lattice(unittest.TestCase): | ||
| 212 | def test_recovers_tile_period_phase(self): | ||
| 213 | w = h = 256 | ||
| 214 | for period, phase, diagonal, corner in ((16, 5, "+", "TL"), (16, 11, "-", "BR"), (16, 0, "+", "BL"), | ||
| 215 | (8, 3, "+", "TR")): | ||
| 216 | with self.subTest(period=period, phase=phase, diagonal=diagonal, corner=corner): | ||
| 217 | lumas = lattice_frame(w, h, period, phase, diagonal, corner) | ||
| 218 | found = pm.find_lattice(pm.luma(frame_of(lumas, w, h)), w, h) | ||
| 219 | self.assertIsNotNone(found) | ||
| 220 | self.assertEqual((found["tile"], found["period"], found["phase"], found["diagonal"], | ||
| 221 | found["corner"]), (8, period, phase, diagonal, corner)) | ||
| 222 | self.assertEqual(found["cover"], 1.0) | ||
| 223 | marked = sum(1 for ty in range(32) for tx in range(32) | ||
| 224 | if ((tx + ty) if diagonal == "+" else (tx - ty)) % period == phase) | ||
| 225 | self.assertEqual(found["tiles"], marked) | ||
| 226 | |||
| 227 | def test_720p_frame(self): | ||
| 228 | w, h = 1280, 720 | ||
| 229 | lumas = lattice_frame(w, h, 16, 9, "+", "TL") | ||
| 230 | found = pm.find_lattice(pm.luma(frame_of(lumas, w, h)), w, h) | ||
| 231 | self.assertEqual((found["tile"], found["period"], found["phase"]), (8, 16, 9)) | ||
| 232 | |||
| 233 | def test_none_on_plain_frames(self): | ||
| 234 | for lumas, w, h in ((gray_frame(64, 64, 128), 64, 64), (smooth_frame(128, 128), 128, 128), | ||
| 235 | (gray_frame(64, 64, 4), 64, 64)): | ||
| 236 | self.assertIsNone(pm.find_lattice(pm.luma(frame_of(lumas, w, h)), w, h)) | ||
| 237 | |||
| 238 | def test_none_on_sparse_dark_pixels(self): | ||
| 239 | # A few dark pixels anywhere must not read as a lattice: a corner diagonal of one or two tiles covers | ||
| 240 | # fully at a large period, which is no repetition at all. | ||
| 241 | cases = [(256, 256, n, seed) for n in (8, 15, 50) for seed in range(10)] | ||
| 242 | cases += [(320, 180, n, seed) for n in (10, 20, 50) for seed in range(10)] | ||
| 243 | cases += [(640, 360, n, seed) for n in (20, 50) for seed in range(5)] | ||
| 244 | cases += [(1280, 720, n, seed) for n in (4, 50) for seed in range(2)] | ||
| 245 | for w, h, n, seed in cases: | ||
| 246 | with self.subTest(size=(w, h), pixels=n, seed=seed): | ||
| 247 | self.assertIsNone(pm.find_lattice(pm.luma(frame_of(sparse_dark_frame(w, h, n, seed), w, h)), w, h)) | ||
| 248 | |||
| 249 | def test_none_on_noise_and_rows(self): | ||
| 250 | rng = random.Random(7) | ||
| 251 | noise = [min(255, max(0, round(rng.gauss(128, 30)))) for _ in range(256 * 256)] | ||
| 252 | self.assertIsNone(pm.find_lattice(pm.luma(frame_of(noise, 256, 256)), 256, 256)) | ||
| 253 | rows = gray_frame(256, 256, 128) # marks on every tile of rows 5 and 21 | ||
| 254 | for y in range(256): | ||
| 255 | if (y // 8) % 16 == 5 and y % 8 < 4: | ||
| 256 | for x in range(256): | ||
| 257 | if x % 8 + y % 8 < 4: | ||
| 258 | rows[y * 256 + x] = 0 | ||
| 259 | self.assertIsNone(pm.find_lattice(pm.luma(frame_of(rows, 256, 256)), 256, 256)) | ||
| 260 | |||
| 261 | def test_recovers_through_noise(self): | ||
| 262 | rng = random.Random(3) | ||
| 263 | lumas = [min(255, max(0, v + rng.randint(-20, 20))) for v in lattice_frame(256, 256, 16, 7, "-", "TR")] | ||
| 264 | found = pm.find_lattice(pm.luma(frame_of(lumas, 256, 256)), 256, 256) | ||
| 265 | self.assertEqual((found["tile"], found["period"], found["phase"], found["diagonal"]), (8, 16, 7, "-")) | ||
| 266 | |||
| 267 | |||
| 268 | class Blocks(unittest.TestCase): | ||
| 269 | FOREIGN = ((1, 1), (2, 1), (5, 3), (3, 7), (6, 10), (1, 13), (4, 12), (4, 13)) | ||
| 270 | |||
| 271 | def test_recovers_block_size_and_share(self): | ||
| 272 | w = h = 128 | ||
| 273 | for bw, bh in ((16, 8), (16, 16), (32, 8)): | ||
| 274 | foreign = [(bx, by) for bx, by in self.FOREIGN if bx < w // bw and by < h // bh] | ||
| 275 | with self.subTest(block=(bw, bh)): | ||
| 276 | lumas = blocks_frame(w, h, bw, bh, foreign) | ||
| 277 | found = pm.find_blocks(pm.luma(frame_of(lumas, w, h)), w, h) | ||
| 278 | self.assertIsNotNone(found) | ||
| 279 | total = (w // bw) * (h // bh) | ||
| 280 | self.assertEqual((found["width"], found["height"]), (bw, bh)) | ||
| 281 | self.assertEqual((found["blocks"], found["of"]), (len(foreign), total)) | ||
| 282 | self.assertEqual(found["share"], round(len(foreign) / total, 4)) | ||
| 283 | |||
| 284 | def test_none_on_plain_frames(self): | ||
| 285 | for lumas in (gray_frame(128, 128, 128), smooth_frame(128, 128)): | ||
| 286 | self.assertIsNone(pm.find_blocks(pm.luma(frame_of(lumas, 128, 128)), 128, 128)) | ||
| 287 | |||
| 288 | def test_none_on_a_checkerboard_or_one_rectangle(self): | ||
| 289 | # A checkerboard texture has no picture around its squares; one sharp rectangle (a HUD panel) gives two | ||
| 290 | # edges a side, too few to tell a grid from the rectangle's own size. | ||
| 291 | board = [40 if (x // 8 + y // 8) % 2 else 200 for y in range(128) for x in range(128)] | ||
| 292 | self.assertIsNone(pm.find_blocks(pm.luma(frame_of(board, 128, 128)), 128, 128)) | ||
| 293 | panel = smooth_frame(256, 256) | ||
| 294 | for y in range(100, 132): | ||
| 295 | for x in range(90, 150): | ||
| 296 | panel[y * 256 + x] = 230 | ||
| 297 | self.assertIsNone(pm.find_blocks(pm.luma(frame_of(panel, 256, 256)), 256, 256)) | ||
| 298 | |||
| 299 | |||
| 300 | class Diff(unittest.TestCase): | ||
| 301 | def test_changed_tiles(self): | ||
| 302 | w, h = 64, 48 | ||
| 303 | a = rgb(smooth_frame(w, h)) | ||
| 304 | b = bytearray(a) | ||
| 305 | for x, y in ((3 * 8 + 7, 1 * 8), (5 * 8, 5 * 8 + 7), (5 * 8 + 1, 5 * 8 + 2), (0, 0)): | ||
| 306 | b[(y * w + x) * 3 + 1] ^= 0x40 # one green byte: luma moves too | ||
| 307 | d = pm.tile_diff(pm.Frame(w, h, a), pm.Frame(w, h, bytes(b))) | ||
| 308 | self.assertEqual((d["changed"], d["of"]), (3, 48)) | ||
| 309 | self.assertEqual(d["tiles"], [[0, 0], [3, 1], [5, 5]]) | ||
| 310 | self.assertEqual(d["box"], [0, 0, 5, 5]) | ||
| 311 | self.assertEqual(d["share"], round(3 / 48, 4)) | ||
| 312 | same = pm.tile_diff(pm.Frame(w, h, a), pm.Frame(w, h, a)) | ||
| 313 | self.assertEqual((same["changed"], same["tiles"], same["box"]), (0, [], None)) | ||
| 314 | |||
| 315 | def test_tolerance_is_off_by_default(self): | ||
| 316 | a = rgb(gray_frame(16, 8, 100)) | ||
| 317 | b = rgb([101] + [100] * 127) | ||
| 318 | self.assertEqual(pm.tile_diff(pm.Frame(16, 8, a), pm.Frame(16, 8, b))["changed"], 1) | ||
| 319 | self.assertEqual(pm.tile_diff(pm.Frame(16, 8, a), pm.Frame(16, 8, b), tolerance=1)["changed"], 0) | ||
| 320 | |||
| 321 | def test_sizes_must_match(self): | ||
| 322 | with self.assertRaises(ValueError): | ||
| 323 | pm.tile_diff(pm.Frame(8, 8, bytes(192)), pm.Frame(16, 8, bytes(384))) | ||
| 324 | |||
| 325 | |||
| 326 | class Classes(unittest.TestCase): | ||
| 327 | def measure(self, lumas, w, h, ref=None): | ||
| 328 | ref_frame = frame_of(ref, w, h) if ref is not None else None | ||
| 329 | return pm.measure(frame_of(lumas, w, h), ref_frame) | ||
| 330 | |||
| 331 | def test_measured_classes(self): | ||
| 332 | self.assertEqual(self.measure(gray_frame(64, 64, 128), 64, 64)["class"]["measured"], "OK") | ||
| 333 | self.assertEqual(self.measure(smooth_frame(64, 64), 64, 64)["class"]["measured"], "OK") | ||
| 334 | self.assertEqual(self.measure(gray_frame(64, 64, 6), 64, 64)["class"]["measured"], "BLACK-NEAR") | ||
| 335 | self.assertEqual(self.measure(lattice_frame(256, 256, 16, 5, "+", "TL"), 256, 256)["class"]["measured"], | ||
| 336 | "LATTICE") | ||
| 337 | self.assertEqual(self.measure(blocks_frame(128, 128, 16, 8, Blocks.FOREIGN), 128, 128)["class"]["measured"], | ||
| 338 | "BLOCKS") | ||
| 339 | flash = self.measure(gray_frame(64, 64, 230), 64, 64, ref=gray_frame(64, 64, 40)) | ||
| 340 | self.assertEqual(flash["class"]["measured"], "FLASH") | ||
| 341 | steady = self.measure(gray_frame(64, 64, 130), 64, 64, ref=gray_frame(64, 64, 128)) | ||
| 342 | self.assertEqual(steady["class"]["measured"], "OK") | ||
| 343 | |||
| 344 | def test_scene_classes_are_only_given(self): | ||
| 345 | self.assertEqual(set(pm.CLASSES), {"LATTICE", "BLACK-NEAR", "BLOCKS", "FLASH", "CHAR-BLACK", | ||
| 346 | "CHAR-MISSING", "2D-MISSING", "STRAY-GEO", "SMEAR", "OK"}) | ||
| 347 | self.assertEqual(set(pm.GIVEN_ONLY), {"CHAR-BLACK", "CHAR-MISSING", "2D-MISSING", "STRAY-GEO", "SMEAR"}) | ||
| 348 | r = pm.measure(frame_of(gray_frame(64, 64, 128), 64, 64), None, given="CHAR-BLACK") | ||
| 349 | self.assertEqual(r["class"], {"measured": "OK", "given": "CHAR-BLACK"}) | ||
| 350 | |||
| 351 | |||
| 352 | class CommandLine(unittest.TestCase): | ||
| 353 | def run_main(self, argv): | ||
| 354 | out, err = io.StringIO(), io.StringIO() | ||
| 355 | with redirect_stdout(out), redirect_stderr(err): | ||
| 356 | try: | ||
| 357 | code = pm.main(argv) | ||
| 358 | except SystemExit as e: | ||
| 359 | code = e.code | ||
| 360 | return code, out.getvalue(), err.getvalue() | ||
| 361 | |||
| 362 | def write(self, tmp, name, data): | ||
| 363 | path = os.path.join(tmp, name) | ||
| 364 | with open(path, "wb") as fh: | ||
| 365 | fh.write(data) | ||
| 366 | return path | ||
| 367 | |||
| 368 | def test_one_frame_block(self): | ||
| 369 | with tempfile.TemporaryDirectory() as tmp: | ||
| 370 | path = self.write(tmp, "secret_name_frame.png", | ||
| 371 | png_bytes(256, 256, rgb(lattice_frame(256, 256, 16, 5, "+", "TL")), 3, (4,))) | ||
| 372 | code, out, err = self.run_main([path, "--region", "40,0,8,8"]) | ||
| 373 | self.assertEqual(code, 0, err) | ||
| 374 | lines = out.splitlines() | ||
| 375 | self.assertTrue(lines[0].startswith("PICTURE | ")) | ||
| 376 | self.assertIn("AI-assisted", lines[0]) | ||
| 377 | fields = [line.split(":", 1)[0].strip() for line in lines[1:]] | ||
| 378 | self.assertEqual(fields, ["FRAME", "LUMA", "DARK 4x4", "LATTICE", "BLOCKS", "DIFF", "REGION", "CLASS", | ||
| 379 | "EVIDENCE"]) | ||
| 380 | self.assertIn("tile 8 | period 16 | phase 5 | diagonal + | corner TL", out) | ||
| 381 | self.assertIn("CLASS: LATTICE (measured) | given: none", out) | ||
| 382 | self.assertIn("REGION: 8x8 | mean 108.0", out) | ||
| 383 | self.assertNotIn("secret_name_frame", out) | ||
| 384 | self.assertNotIn(tmp, out) | ||
| 385 | |||
| 386 | def test_two_frames_json_and_given_class(self): | ||
| 387 | with tempfile.TemporaryDirectory() as tmp: | ||
| 388 | a = self.write(tmp, "a.png", png_bytes(64, 64, rgb(gray_frame(64, 64, 230)), 3)) | ||
| 389 | b = self.write(tmp, "b.ppm", b"P6 64 64 255\n" + rgb(gray_frame(64, 64, 40))) | ||
| 390 | code, out, err = self.run_main([a, b, "--json", "--class", "SMEAR"]) | ||
| 391 | self.assertEqual(code, 0, err) | ||
| 392 | data = json.loads(out) | ||
| 393 | self.assertEqual(data["class"], {"measured": "FLASH", "given": "SMEAR"}) | ||
| 394 | self.assertEqual((data["diff"]["changed"], data["diff"]["of"]), (64, 64)) | ||
| 395 | self.assertEqual(data["reference"]["luma"]["mean"], 40.0) | ||
| 396 | self.assertNotIn(tmp, out) | ||
| 397 | self.assertNotIn("a.png", out) | ||
| 398 | |||
| 399 | def test_errors(self): | ||
| 400 | with tempfile.TemporaryDirectory() as tmp: | ||
| 401 | bad = self.write(tmp, "bad.png", b"not an image") | ||
| 402 | code, out, err = self.run_main([bad]) | ||
| 403 | self.assertEqual((code, out), (2, "")) | ||
| 404 | self.assertNotIn(tmp, err) | ||
| 405 | small = self.write(tmp, "s.png", png_bytes(8, 8, bytes(192), 3)) | ||
| 406 | big = self.write(tmp, "b.png", png_bytes(16, 8, bytes(384), 3)) | ||
| 407 | self.assertEqual(self.run_main([small, big])[0], 2) | ||
| 408 | self.assertEqual(self.run_main([small, "--class", "PURPLE"])[0], 2) | ||
| 409 | self.assertEqual(self.run_main([small, "--region", "4,4,8,8"])[0], 2) | ||
| 410 | self.assertEqual(self.run_main([os.path.join(tmp, "missing.png")])[0], 2) | ||
| 411 | |||
| 412 | |||
| 413 | if __name__ == "__main__": | ||
| 414 | unittest.main() | ||
diff --git a/tests/test_play_linux_defaults.py b/tests/test_play_linux_defaults.py new file mode 100644 index 000000000..0c5b21527 --- /dev/null +++ b/tests/test_play_linux_defaults.py | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | """Check Linux launcher defaults without Wine, a GPU, or game data.""" | ||
| 2 | |||
| 3 | import os | ||
| 4 | from pathlib import Path | ||
| 5 | import shutil | ||
| 6 | import subprocess | ||
| 7 | import tempfile | ||
| 8 | import unittest | ||
| 9 | |||
| 10 | |||
| 11 | LAUNCHER = Path(__file__).resolve().parents[1] / "scripts" / "play-linux.sh" | ||
| 12 | SH = shutil.which("sh") if os.name == "posix" else None | ||
| 13 | FLAGS = ("LEONIDA_COPY_SCOPED", "LEONIDA_PORT_DESCRIPTORS") | ||
| 14 | |||
| 15 | |||
| 16 | @unittest.skipUnless(SH, "POSIX shell required") | ||
| 17 | class PlayLinuxDefaultsTest(unittest.TestCase): | ||
| 18 | def run_launcher(self, values): | ||
| 19 | with tempfile.TemporaryDirectory(prefix="linux-launcher-test-") as directory: | ||
| 20 | root = Path(directory) | ||
| 21 | system32 = root / "prefix" / "drive_c" / "windows" / "system32" | ||
| 22 | system32.mkdir(parents=True) | ||
| 23 | bin_dir = root / "mock-bin" | ||
| 24 | bin_dir.mkdir() | ||
| 25 | wine = bin_dir / "wine" | ||
| 26 | wine.write_bytes( | ||
| 27 | b"#!/bin/sh\n" | ||
| 28 | b'if [ "$1" = --version ]; then echo wine-test; exit 0; fi\n' | ||
| 29 | b'printf "%s\\n" "${LEONIDA_COPY_SCOPED-unset}" ' | ||
| 30 | b'"${LEONIDA_PORT_DESCRIPTORS-unset}" > "$LAUNCHER_TEST_CAPTURE"\n', | ||
| 31 | ) | ||
| 32 | wine.chmod(0o755) | ||
| 33 | game = root / "placeholder-title" | ||
| 34 | runtime = root / "placeholder-runtime" | ||
| 35 | for name in (game, runtime, root / "d3d12.dll", root / "dxgi.dll", | ||
| 36 | root / "d3dcompiler_47.dll"): | ||
| 37 | name.touch() | ||
| 38 | (root / "d3d12core.dll").write_bytes(b"legacy_structurizer\n") | ||
| 39 | capture = root / "capture" | ||
| 40 | env = { | ||
| 41 | "PATH": str(bin_dir) + os.pathsep + os.defpath, | ||
| 42 | "HOME": str(root), | ||
| 43 | "LEONIDA_WINE": str(wine), | ||
| 44 | "LEONIDA_WINEPREFIX": str(root / "prefix"), | ||
| 45 | "LEONIDA_RUNTIME": str(runtime), | ||
| 46 | "LEONIDA_VKD3D": str(root), | ||
| 47 | "LEONIDA_DXVK": str(root), | ||
| 48 | "LEONIDA_D3DCOMPILER": str(root), | ||
| 49 | "LAUNCHER_TEST_CAPTURE": str(capture), | ||
| 50 | } | ||
| 51 | env.update(dict(zip(FLAGS, values))) | ||
| 52 | result = subprocess.run( | ||
| 53 | [SH, str(LAUNCHER), str(game)], env=env, | ||
| 54 | capture_output=True, text=True, timeout=10, | ||
| 55 | ) | ||
| 56 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 57 | return capture.read_text(encoding="utf-8").splitlines() | ||
| 58 | |||
| 59 | def test_unset_flags_default_to_enabled(self): | ||
| 60 | self.assertEqual(self.run_launcher(()), ["1", "1"]) | ||
| 61 | |||
| 62 | def test_explicit_zero_is_respected(self): | ||
| 63 | for flags in (("0", "1"), ("1", "0"), ("0", "0")): | ||
| 64 | with self.subTest(flags=flags): | ||
| 65 | self.assertEqual(self.run_launcher(flags), list(flags)) | ||
| 66 | |||
| 67 | |||
| 68 | if __name__ == "__main__": | ||
| 69 | unittest.main() | ||
diff --git a/tests/test_rdna2_decode.py b/tests/test_rdna2_decode.py index 2808b2638..9706e29a8 100644 --- a/tests/test_rdna2_decode.py +++ b/tests/test_rdna2_decode.py | |||
| @@ -339,6 +339,47 @@ class Rdna2DecodeUnitTests(unittest.TestCase): | |||
| 339 | self.assertEqual(info["insns"][4]["args"][2]["t"], "off") | 339 | self.assertEqual(info["insns"][4]["args"][2]["t"], "off") |
| 340 | self.assertEqual(info["insns"][4]["mods"], ["offset:-4"]) | 340 | self.assertEqual(info["insns"][4]["mods"], ["offset:-4"]) |
| 341 | 341 | ||
| 342 | def test_ds_condxchg32_single_offset_and_swizzle_modes_match_llvm(self): | ||
| 343 | # ds_condxchg32_rtn_b64 uses a single 16-bit offset (not offset0/offset1); "2_" substring in "32_" must not | ||
| 344 | # classify it as a 2-address DS instruction (LLVM gfx10_ds.txt). | ||
| 345 | cases = [ | ||
| 346 | (bytes([0x04, 0x00, 0xF8, 0xD9, 0x01, 0x02, 0x00, 0x05]), | ||
| 347 | "ds_condxchg32_rtn_b64", ["offset:4"]), | ||
| 348 | (bytes([0xFF, 0xFF, 0xF8, 0xD9, 0x01, 0x02, 0x00, 0x05]), | ||
| 349 | "ds_condxchg32_rtn_b64", ["offset:65535"]), | ||
| 350 | (bytes([0xFF, 0xFF, 0xFA, 0xD9, 0x01, 0x02, 0x00, 0x05]), | ||
| 351 | "ds_condxchg32_rtn_b64", ["offset:65535", "gds"]), | ||
| 352 | # Control: true 2-address DS instruction keeps offset0 / offset1. | ||
| 353 | (bytes([0x04, 0x08, 0xDC, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 354 | "ds_read2_b32", ["offset0:4", "offset1:8"]), | ||
| 355 | # ds_swizzle_b32: LLVM AMDGPUInstPrinter::printSwizzle omits offset when 0, prints ROTATE for | ||
| 356 | # 0xC000..0xDFFF, and prints FFT for 0xE000..0xFFFF. | ||
| 357 | (bytes([0x00, 0x00, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 358 | "ds_swizzle_b32", []), | ||
| 359 | (bytes([0x00, 0xC0, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 360 | "ds_swizzle_b32", ["offset:swizzle(ROTATE,0,0)"]), | ||
| 361 | (bytes([0x20, 0xC4, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 362 | "ds_swizzle_b32", ["offset:swizzle(ROTATE,1,1)"]), | ||
| 363 | (bytes([0xE0, 0xC7, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 364 | "ds_swizzle_b32", ["offset:swizzle(ROTATE,1,31)"]), | ||
| 365 | (bytes([0x00, 0xE0, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 366 | "ds_swizzle_b32", ["offset:swizzle(FFT,0)"]), | ||
| 367 | (bytes([0x10, 0xE0, 0xD4, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 368 | "ds_swizzle_b32", ["offset:swizzle(FFT,16)"]), | ||
| 369 | (bytes([0xFF, 0xFF, 0xD6, 0xD8, 0x01, 0x00, 0x00, 0x05]), | ||
| 370 | "ds_swizzle_b32", ["offset:swizzle(FFT,31)", "gds"]), | ||
| 371 | ] | ||
| 372 | for raw, expected_op, expected_mods in cases: | ||
| 373 | with self.subTest(op=expected_op, mods=expected_mods): | ||
| 374 | info = rdna2_decode.decode_bytes(raw) | ||
| 375 | self.assertEqual(info["invalid"], 0) | ||
| 376 | ins = info["insns"][0] | ||
| 377 | self.assertEqual(ins["op"], expected_op) | ||
| 378 | self.assertEqual(ins["mods"], expected_mods) | ||
| 379 | reparsed = shader_ir.parse_line(rdna2_decode.format_insn(ins)) | ||
| 380 | self.assertEqual(reparsed["op"], expected_op) | ||
| 381 | self.assertEqual(reparsed["mods"], expected_mods) | ||
| 382 | |||
| 342 | def test_sdwa_inline_sources(self): | 383 | def test_sdwa_inline_sources(self): |
| 343 | values = list(range(65)) + list(range(-1, -17, -1)) | 384 | values = list(range(65)) + list(range(-1, -17, -1)) |
| 344 | floats = [0.5, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0, 0.15915494] | 385 | floats = [0.5, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0, 0.15915494] |
diff --git a/tests/test_rpf9dump_exit_codes.py b/tests/test_rpf9dump_exit_codes.py index 4caad1823..6f3630a44 100644 --- a/tests/test_rpf9dump_exit_codes.py +++ b/tests/test_rpf9dump_exit_codes.py | |||
| @@ -187,6 +187,34 @@ class Rpf9dumpExitCodeTest(unittest.TestCase): | |||
| 187 | manifest = json.loads((out / f"tiny_{size}" / mode / "manifest.json").read_text(encoding="utf-8")) | 187 | manifest = json.loads((out / f"tiny_{size}" / mode / "manifest.json").read_text(encoding="utf-8")) |
| 188 | self.assertEqual(manifest["Count"], 0) | 188 | self.assertEqual(manifest["Count"], 0) |
| 189 | 189 | ||
| 190 | def test_unknown_option_reports_unknown_option_before_creating_output(self): | ||
| 191 | with tempfile.TemporaryDirectory() as tmp: | ||
| 192 | root = Path(tmp) | ||
| 193 | src = root / "tiny.rpf" | ||
| 194 | src.write_bytes(bytes(16)) | ||
| 195 | for idx, extra in enumerate((("--bogus",), ("--bogus", "notanumber"))): | ||
| 196 | with self.subTest(extra=extra): | ||
| 197 | out = root / f"out-{idx}" | ||
| 198 | done = run("models", src, out, *extra) | ||
| 199 | self.assertEqual(done.returncode, 2, done.stdout + done.stderr) | ||
| 200 | self.assertIn("Unknown option --bogus", done.stderr) | ||
| 201 | self.assertNotIn("needs a non-negative byte count", done.stderr) | ||
| 202 | self.assertFalse(out.exists(), f"unknown option {extra} created {out}") | ||
| 203 | |||
| 204 | def test_jobs_rejects_signed_or_nonpositive_values(self): | ||
| 205 | with tempfile.TemporaryDirectory() as tmp: | ||
| 206 | root = Path(tmp) | ||
| 207 | src = root / "tiny.rpf" | ||
| 208 | src.write_bytes(bytes(16)) | ||
| 209 | for idx, extra in enumerate((("--jobs", "0"), ("--jobs", "-1"), ("--jobs", "+2"), ("--jobs", "abc"), ("--jobs",))): | ||
| 210 | with self.subTest(extra=extra): | ||
| 211 | out = root / f"out-{idx}" | ||
| 212 | done = run("ttpf", src, out, *extra) | ||
| 213 | self.assertEqual(done.returncode, 2, done.stdout + done.stderr) | ||
| 214 | self.assertIn("--jobs", done.stderr) | ||
| 215 | self.assertNotIn("Unhandled exception", done.stderr) | ||
| 216 | self.assertFalse(out.exists(), f"bad --jobs {extra} created {out}") | ||
| 217 | |||
| 190 | 218 | ||
| 191 | if __name__ == "__main__": | 219 | if __name__ == "__main__": |
| 192 | unittest.main() | 220 | unittest.main() |
diff --git a/tests/test_run_game_wine.py b/tests/test_run_game_wine.py index 7dd976ffc..4dad47f35 100644 --- a/tests/test_run_game_wine.py +++ b/tests/test_run_game_wine.py | |||
| @@ -28,8 +28,9 @@ REAL = ("bash", "dirname", "readlink", "mkdir", "rm", "cat", "env", "grep", "sor | |||
| 28 | WINE_STUB = """#!/bin/sh | 28 | WINE_STUB = """#!/bin/sh |
| 29 | if [ "$1" = wineboot ]; then exit 0; fi | 29 | if [ "$1" = wineboot ]; then exit 0; fi |
| 30 | for a in "$@"; do printf '%s\\n' "$a"; done > "$STUB_LOG/wine.args" | 30 | for a in "$@"; do printf '%s\\n' "$a"; done > "$STUB_LOG/wine.args" |
| 31 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|WINEPREFIX|PULSE_SERVER|PIPEWIRE_REMOTE|DISPLAY)' | sort > "$STUB_LOG/wine.env" | 31 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|WINEPREFIX|PULSE_SERVER|PIPEWIRE_REMOTE|DISPLAY|XDG_CACHE_HOME|MESA_SHADER_CACHE_DIR|MESA_GLSL_CACHE_DIR|__GL_SHADER_DISK_CACHE_PATH)' | sort > "$STUB_LOG/wine.env" |
| 32 | pwd > "$STUB_LOG/wine.cwd" | 32 | pwd > "$STUB_LOG/wine.cwd" |
| 33 | if [ -n "${XDG_CACHE_HOME:-}" ]; then mkdir -p "$XDG_CACHE_HOME/nvidia" && echo x >> "$XDG_CACHE_HOME/nvidia/GLCache"; fi | ||
| 33 | echo "[rt] audio: serving the silent output endpoint (LEONIDA_AUDIO=silent): 48 kHz float 7.1" >&2 | 34 | echo "[rt] audio: serving the silent output endpoint (LEONIDA_AUDIO=silent): 48 kHz float 7.1" >&2 |
| 34 | echo "[d3d12-trace] #1 XboxID3D12CommandQueue::PresentX ok" >&2 | 35 | echo "[d3d12-trace] #1 XboxID3D12CommandQueue::PresentX ok" >&2 |
| 35 | exit 0 | 36 | exit 0 |
| @@ -85,8 +86,8 @@ class RunGameWineTest(unittest.TestCase): | |||
| 85 | flat += [flag, str(value)] | 86 | flat += [flag, str(value)] |
| 86 | return flat | 87 | return flat |
| 87 | 88 | ||
| 88 | def run_script(self, *args, display=":99"): | 89 | def run_script(self, *args, display=":99", **extra): |
| 89 | env = {"PATH": str(self.bin), "HOME": str(self.tmp), "STUB_LOG": str(self.log)} | 90 | env = {"PATH": str(self.bin), "HOME": str(self.tmp), "STUB_LOG": str(self.log), **extra} |
| 90 | if display: | 91 | if display: |
| 91 | env["DISPLAY"] = display | 92 | env["DISPLAY"] = display |
| 92 | return subprocess.run([str(self.bin / "bash"), str(SCRIPT), *args], cwd=self.tmp, env=env, capture_output=True, text=True, | 93 | return subprocess.run([str(self.bin / "bash"), str(SCRIPT), *args], cwd=self.tmp, env=env, capture_output=True, text=True, |
| @@ -200,6 +201,66 @@ class RunGameWineTest(unittest.TestCase): | |||
| 200 | env = (self.log / "wine.env").read_text(encoding="utf-8") | 201 | env = (self.log / "wine.env").read_text(encoding="utf-8") |
| 201 | self.assertNotIn("MESA_VK_DEVICE_SELECT", env) | 202 | self.assertNotIn("MESA_VK_DEVICE_SELECT", env) |
| 202 | 203 | ||
| 204 | def wine_env(self): | ||
| 205 | return dict(line.split("=", 1) for line in (self.log / "wine.env").read_text(encoding="utf-8").splitlines()) | ||
| 206 | |||
| 207 | def run_with_cache(self, out, *args, **extra): | ||
| 208 | self.out = self.tmp / out | ||
| 209 | p = self.run_script(*self.inputs(), "--visible", "--device", "1002:744C", "--seconds", "30", *args, **extra) | ||
| 210 | self.assertEqual(p.returncode, 0, p.stdout + p.stderr) | ||
| 211 | return p, self.wine_env()["XDG_CACHE_HOME"] | ||
| 212 | |||
| 213 | def test_without_a_cache_each_run_gets_a_fresh_one(self): | ||
| 214 | p, cache = self.run_with_cache("run1") | ||
| 215 | self.assertEqual(cache, str(self.tmp / "run1" / "session" / "cache")) | ||
| 216 | self.assertIn("shader cache: fresh", p.stdout) | ||
| 217 | |||
| 218 | def test_the_callers_cache_is_kept_from_run_to_run(self): | ||
| 219 | # The drivers' shader caches (NVIDIA's GLCache here) live under XDG_CACHE_HOME: a caller's one is used, so | ||
| 220 | # the second launch finds what the first compiled. | ||
| 221 | kept = self.tmp / "cache" | ||
| 222 | for n in (1, 2): | ||
| 223 | p, cache = self.run_with_cache(f"run{n}", XDG_CACHE_HOME=str(kept)) | ||
| 224 | self.assertEqual(cache, str(kept)) | ||
| 225 | self.assertIn(f"shader cache: kept in {kept}", p.stdout) | ||
| 226 | self.assertEqual((kept / "nvidia" / "GLCache").read_text(encoding="utf-8"), "x\nx\n") | ||
| 227 | |||
| 228 | def test_cache_option_names_the_folder_or_fresh(self): | ||
| 229 | named = self.tmp / "named-cache" | ||
| 230 | _, cache = self.run_with_cache("run1", "--cache", str(named), XDG_CACHE_HOME=str(self.tmp / "other")) | ||
| 231 | self.assertEqual(cache, str(named)) | ||
| 232 | self.assertTrue((named / "nvidia" / "GLCache").is_file()) | ||
| 233 | _, cache = self.run_with_cache("run2", "--cache", "fresh", XDG_CACHE_HOME=str(self.tmp / "other")) | ||
| 234 | self.assertEqual(cache, str(self.tmp / "run2" / "session" / "cache")) | ||
| 235 | self.assertFalse((self.tmp / "other").exists()) | ||
| 236 | |||
| 237 | def test_a_fresh_cache_drops_the_drivers_own_cache_variables(self): | ||
| 238 | # A driver's own variable wins over XDG_CACHE_HOME: a fresh run must not hand a warm one to the driver. | ||
| 239 | warm = {"MESA_SHADER_CACHE_DIR": str(self.tmp / "warm-mesa"), "MESA_GLSL_CACHE_DIR": str(self.tmp / "warm-glsl"), | ||
| 240 | "__GL_SHADER_DISK_CACHE_PATH": str(self.tmp / "warm-nv")} | ||
| 241 | _, cache = self.run_with_cache("run1", "--cache", "fresh", **warm) | ||
| 242 | self.assertEqual(cache, str(self.tmp / "run1" / "session" / "cache")) | ||
| 243 | for name in warm: | ||
| 244 | self.assertNotIn(name, self.wine_env()) | ||
| 245 | # A kept cache leaves them to the caller, and they win. | ||
| 246 | self.run_with_cache("run2", "--cache", str(self.tmp / "kept"), **warm) | ||
| 247 | for name, value in warm.items(): | ||
| 248 | self.assertEqual(self.wine_env()[name], value) | ||
| 249 | |||
| 250 | def test_a_fresh_cache_is_empty_in_an_accepted_run_folder(self): | ||
| 251 | # A run folder whose earlier launch did not start is accepted again; its old cache is not reused, and the | ||
| 252 | # status line is written anew, not added to. | ||
| 253 | old = self.tmp / "run1" / "session" / "cache" / "nvidia" | ||
| 254 | old.mkdir(parents=True) | ||
| 255 | (old / "GLCache").write_text("old\n", encoding="utf-8") | ||
| 256 | (self.tmp / "run1" / "session.txt").write_text("shader cache: kept in /elsewhere\n", encoding="utf-8") | ||
| 257 | p, _ = self.run_with_cache("run1", "--cache", "fresh") | ||
| 258 | self.assertEqual((old / "GLCache").read_text(encoding="utf-8"), "x\n") | ||
| 259 | session = (self.tmp / "run1" / "session.txt").read_text(encoding="utf-8") | ||
| 260 | self.assertNotIn("kept in /elsewhere", session) | ||
| 261 | self.assertEqual(session.count("shader cache:"), 1) | ||
| 262 | self.assertIn("shader cache: fresh", p.stdout) | ||
| 263 | |||
| 203 | 264 | ||
| 204 | if __name__ == "__main__": | 265 | if __name__ == "__main__": |
| 205 | unittest.main() | 266 | unittest.main() |
diff --git a/tests/test_run_game_wine_safety.py b/tests/test_run_game_wine_safety.py index ce2d6a1c5..2c0e0b56d 100644 --- a/tests/test_run_game_wine_safety.py +++ b/tests/test_run_game_wine_safety.py | |||
| @@ -182,6 +182,8 @@ class RunGameWineSafetyTests(unittest.TestCase): | |||
| 182 | "--device", "1002:744C", | 182 | "--device", "1002:744C", |
| 183 | "--seconds", "5", | 183 | "--seconds", "5", |
| 184 | "--lock", _to_bash_path(lock), | 184 | "--lock", _to_bash_path(lock), |
| 185 | # The caller's XDG_CACHE_HOME (inherited below) would be the run's cache; a fresh one keeps it out. | ||
| 186 | "--cache", "fresh", | ||
| 185 | ] | 187 | ] |
| 186 | # Wrap via bash -c so our stub bin sits before /usr/bin on Git Bash too. | 188 | # Wrap via bash -c so our stub bin sits before /usr/bin on Git Bash too. |
| 187 | sbin_bash = _to_bash_path(sbin) | 189 | sbin_bash = _to_bash_path(sbin) |
diff --git a/tests/test_run_guest_scene.py b/tests/test_run_guest_scene.py new file mode 100644 index 000000000..18ab9f687 --- /dev/null +++ b/tests/test_run_guest_scene.py | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | """Unit tests for scripts/run_guest_scene.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import sys | ||
| 6 | import unittest | ||
| 7 | from pathlib import Path | ||
| 8 | from tempfile import TemporaryDirectory | ||
| 9 | |||
| 10 | REPO = Path(__file__).resolve().parent.parent | ||
| 11 | sys.path.insert(0, str(REPO / "scripts")) | ||
| 12 | |||
| 13 | import run_guest_scene as rgs # noqa: E402 | ||
| 14 | |||
| 15 | |||
| 16 | class TestRunGuestSceneHelpers(unittest.TestCase): | ||
| 17 | def test_fnv1a_32_and_64_vectors(self) -> None: | ||
| 18 | self.assertEqual(rgs.fnv1a(b"", 32), 0x811C9DC5) | ||
| 19 | self.assertEqual(rgs.fnv1a(b"foobar", 32), 0xBF9CF968) | ||
| 20 | self.assertEqual(rgs.fnv1a(b"", 64), 0xCBF29CE484222325) | ||
| 21 | self.assertEqual(rgs.fnv1a(b"foobar", 64), 0x85944171F73967E8) | ||
| 22 | |||
| 23 | def test_check_raises_fail_on_false(self) -> None: | ||
| 24 | rgs.check(True, "ok") | ||
| 25 | with self.assertRaises(rgs.Fail) as ctx: | ||
| 26 | rgs.check(False, "broken invariant") | ||
| 27 | self.assertEqual(str(ctx.exception), "broken invariant") | ||
| 28 | |||
| 29 | def test_tree_files_hashes_nested_files(self) -> None: | ||
| 30 | with TemporaryDirectory() as tmp: | ||
| 31 | root = Path(tmp) | ||
| 32 | (root / "sub").mkdir() | ||
| 33 | (root / "a.txt").write_bytes(b"hello") | ||
| 34 | (root / "sub" / "b.bin").write_bytes(b"world") | ||
| 35 | got = rgs.tree_files(root) | ||
| 36 | self.assertEqual( | ||
| 37 | got, | ||
| 38 | { | ||
| 39 | "a.txt": rgs.sha256(b"hello"), | ||
| 40 | "sub/b.bin": rgs.sha256(b"world"), | ||
| 41 | }, | ||
| 42 | ) | ||
| 43 | |||
| 44 | |||
| 45 | if __name__ == "__main__": | ||
| 46 | unittest.main() | ||
diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py new file mode 100644 index 000000000..bf50c814f --- /dev/null +++ b/tests/test_sandbox.py | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | """Unit tests for tools/sandbox.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import json | ||
| 6 | import sys | ||
| 7 | import unittest | ||
| 8 | from pathlib import Path | ||
| 9 | from tempfile import TemporaryDirectory | ||
| 10 | |||
| 11 | REPO = Path(__file__).resolve().parent.parent | ||
| 12 | sys.path.insert(0, str(REPO / "tools")) | ||
| 13 | |||
| 14 | import sandbox # noqa: E402 | ||
| 15 | |||
| 16 | |||
| 17 | class TestSandbox(unittest.TestCase): | ||
| 18 | def test_read_ppm_and_check_frame_coverage_and_colours(self) -> None: | ||
| 19 | with TemporaryDirectory() as tmp: | ||
| 20 | sky_only = Path(tmp) / "sky.ppm" | ||
| 21 | sky_only.write_bytes(b"P6\n10 10\n255\n" + sandbox.SKY * 100) | ||
| 22 | w, h, px = sandbox.read_ppm(sky_only) | ||
| 23 | self.assertEqual((w, h, len(px)), (10, 10, 300)) | ||
| 24 | ok, msg = sandbox.check_frame(sky_only, textured=False) | ||
| 25 | self.assertFalse(ok) | ||
| 26 | self.assertIn("0 of 100 pixels covered", msg) | ||
| 27 | |||
| 28 | covered = Path(tmp) / "covered.ppm" | ||
| 29 | pixels = bytearray(sandbox.SKY * 100) | ||
| 30 | pixels[0:3] = b"\x00\x00\x00" | ||
| 31 | pixels[3:6] = b"\xff\x00\x00" | ||
| 32 | covered.write_bytes(b"P6\n10 10\n255\n" + bytes(pixels)) | ||
| 33 | ok_untex, _ = sandbox.check_frame(covered, textured=False) | ||
| 34 | self.assertTrue(ok_untex) | ||
| 35 | ok_tex, _ = sandbox.check_frame(covered, textured=True) | ||
| 36 | self.assertFalse(ok_tex) | ||
| 37 | |||
| 38 | def test_pick_pair_matches_expected_vs_and_ps(self) -> None: | ||
| 39 | with TemporaryDirectory() as tmp: | ||
| 40 | shaders = Path(tmp) / "shaders" | ||
| 41 | spirv = shaders / "spirv" | ||
| 42 | disasm = shaders / "dxbc" / "disasm" | ||
| 43 | spirv.mkdir(parents=True) | ||
| 44 | disasm.mkdir(parents=True) | ||
| 45 | |||
| 46 | (spirv / "01_vs.spv").write_bytes(b"spv") | ||
| 47 | (spirv / "02_ps.spv").write_bytes(b"spv") | ||
| 48 | (disasm / "01_vs.s").write_text( | ||
| 49 | "\n".join( | ||
| 50 | [ | ||
| 51 | "s_load_dwordx4 s[0:3], s[8:9], 0", | ||
| 52 | "s_load_dwordx4 s[4:7], s[8:9], 0x40", | ||
| 53 | "s_load_dwordx4 s[12:15], s[8:9], 0x60", | ||
| 54 | "s_buffer_load_dwordx16 s[16:31], s[0:3], 0x160", | ||
| 55 | "s_buffer_load_dwordx4 s[32:35], s[0:3], 0x30", | ||
| 56 | ] | ||
| 57 | ), | ||
| 58 | encoding="utf-8", | ||
| 59 | ) | ||
| 60 | (disasm / "02_ps.s").write_text( | ||
| 61 | "s_load_dwordx8 s[0:7], s[8:9], 0x20\nimage_sample v[0:3], v[0:1], s[0:7], s[8:11]\nexp mrt0 v0, v1, v2, v3\n", | ||
| 62 | encoding="utf-8", | ||
| 63 | ) | ||
| 64 | index = { | ||
| 65 | "01_vs": { | ||
| 66 | "stage": "vs", | ||
| 67 | "bindings": [], | ||
| 68 | "user_sgpr_reads": [{"kind": "ptr32_lo", "sgpr": 8}], | ||
| 69 | "input_signature": [ | ||
| 70 | {"semantic": "POSITION", "semantic_index": 0, "mask": 7}, | ||
| 71 | {"semantic": "NORMAL", "semantic_index": 0, "mask": 7}, | ||
| 72 | {"semantic": "TEXCOORD", "semantic_index": 0, "mask": 3}, | ||
| 73 | ], | ||
| 74 | }, | ||
| 75 | "02_ps": { | ||
| 76 | "stage": "ps", | ||
| 77 | "bindings": [0, 1, 2], | ||
| 78 | "user_sgpr_reads": [{"kind": "ptr32_lo", "sgpr": 8}], | ||
| 79 | "input_signature": [ | ||
| 80 | {"semantic": "SV_Position", "semantic_index": 0, "mask": 15}, | ||
| 81 | {"semantic": "TEXCOORD", "semantic_index": 0, "mask": 3}, | ||
| 82 | {"semantic": "COLOR", "semantic_index": 0, "mask": 15}, | ||
| 83 | ], | ||
| 84 | }, | ||
| 85 | } | ||
| 86 | (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8") | ||
| 87 | |||
| 88 | pair = sandbox.pick_pair(str(shaders)) | ||
| 89 | self.assertEqual(pair, (str(spirv / "01_vs.spv"), str(spirv / "02_ps.spv"))) | ||
| 90 | |||
| 91 | |||
| 92 | if __name__ == "__main__": | ||
| 93 | unittest.main() | ||
diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py index 99ad67476..bc53ff625 100644 --- a/tests/test_shader_build_fallbacks.py +++ b/tests/test_shader_build_fallbacks.py | |||
| @@ -162,7 +162,7 @@ class BuildUnderFallbackTest(unittest.TestCase): | |||
| 162 | assembled = SimpleNamespace(stdout="\ts_endpgm\n", stderr="", returncode=0) | 162 | assembled = SimpleNamespace(stdout="\ts_endpgm\n", stderr="", returncode=0) |
| 163 | probe = SimpleNamespace(stdout=json.dumps(report), returncode=0) | 163 | probe = SimpleNamespace(stdout=json.dumps(report), returncode=0) |
| 164 | translator = SimpleNamespace(returncode=23) # stop after recording the translator command | 164 | translator = SimpleNamespace(returncode=23) # stop after recording the translator command |
| 165 | with mock.patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "0"}), \ | 165 | with mock.patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "0", "LEONIDA_EXPLICIT_LOD_BIAS": "0"}), \ |
| 166 | mock.patch.object(sys, "argv", ["build.py", tmp, "cs_store"]), \ | 166 | mock.patch.object(sys, "argv", ["build.py", tmp, "cs_store"]), \ |
| 167 | mock.patch.object(self.build.mc_command, "run", return_value=assembled), \ | 167 | mock.patch.object(self.build.mc_command, "run", return_value=assembled), \ |
| 168 | mock.patch.object(self.build.subprocess, "run", side_effect=[probe, translator]) as calls: | 168 | mock.patch.object(self.build.subprocess, "run", side_effect=[probe, translator]) as calls: |
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index d19379d4f..b4654cdb8 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py | |||
| @@ -38,8 +38,9 @@ TOTAL = (len(check.COMPUTE) + 8 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + | |||
| 38 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) | 38 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) |
| 39 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) | 39 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) |
| 40 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) | 40 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) |
| 41 | + len(check.TEXTURE_CONSTANTS) + 20) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, | 41 | + len(check.TEXTURE_CONSTANTS) + len(check.SAMPLER_FIXTURES) |
| 42 | # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, | 42 | + 19) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, |
| 43 | # vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, | ||
| 43 | # cs_w32_shift64, cs_w32_cmp_f64, cs_w32_round_f64 and cs_w32_frexp_ldexp | 44 | # cs_w32_shift64, cs_w32_cmp_f64, cs_w32_round_f64 and cs_w32_frexp_ldexp |
| 44 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} | 45 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} |
| 45 | 46 | ||
| @@ -1070,7 +1071,7 @@ class SamplerMipChecks(unittest.TestCase): | |||
| 1070 | 1071 | ||
| 1071 | def test_levels_follow_the_s_and_t_fields(self): | 1072 | def test_levels_follow_the_s_and_t_fields(self): |
| 1072 | want = {"point": (0, 1), "point max_lod 0": (0, 0), "point min_lod 1": (1, 1), "point bias +1": (1, 1), | 1073 | want = {"point": (0, 1), "point max_lod 0": (0, 0), "point min_lod 1": (1, 1), "point bias +1": (1, 1), |
| 1073 | "point bias -1": (0, 0), "none": (0, 0), "none min_lod 1": (0, 0), "point base 1": (1, 1)} | 1074 | "point bias -1": (0, 0), "point bias +0.26": (0, 1), "point bias -0.26": (0, 1), "none": (0, 0), "none min_lod 1": (0, 0), "point base 1": (1, 1)} |
| 1074 | self.assertEqual({name for name, _, _ in check.SAMPLER_CASES}, set(want)) | 1075 | self.assertEqual({name for name, _, _ in check.SAMPLER_CASES}, set(want)) |
| 1075 | for name, words, view in check.SAMPLER_CASES: | 1076 | for name, words, view in check.SAMPLER_CASES: |
| 1076 | with self.subTest(name=name): | 1077 | with self.subTest(name=name): |
diff --git a/tests/test_shaders_build.py b/tests/test_shaders_build.py new file mode 100644 index 000000000..550b1a1fd --- /dev/null +++ b/tests/test_shaders_build.py | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | """Unit tests for runtime/test/shaders/build.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import struct | ||
| 6 | import sys | ||
| 7 | import unittest | ||
| 8 | from pathlib import Path | ||
| 9 | from tempfile import TemporaryDirectory | ||
| 10 | |||
| 11 | REPO = Path(__file__).resolve().parent.parent | ||
| 12 | sys.path.insert(0, str(REPO / "runtime" / "test" / "shaders")) | ||
| 13 | |||
| 14 | import build as sb # noqa: E402 | ||
| 15 | |||
| 16 | |||
| 17 | class TestShadersBuild(unittest.TestCase): | ||
| 18 | def test_asm_mattr_and_shader_source(self) -> None: | ||
| 19 | with TemporaryDirectory() as tmp: | ||
| 20 | p = Path(tmp) / "test.asm" | ||
| 21 | p.write_text("; header\n; mattr: +wavefrontsize64\nv_mov_b32 v0, 0\n; mattr: ignored\n", encoding="utf-8") | ||
| 22 | self.assertEqual(sb.asm_mattr(p), "+wavefrontsize64") | ||
| 23 | |||
| 24 | p_none = Path(tmp) / "plain.asm" | ||
| 25 | p_none.write_text("v_mov_b32 v0, 0\n", encoding="utf-8") | ||
| 26 | self.assertIsNone(sb.asm_mattr(p_none)) | ||
| 27 | |||
| 28 | self.assertEqual(sb.shader_source("vs_clip_param4"), "vs_clip") | ||
| 29 | self.assertEqual(sb.shader_source("ps_mullit"), "ps_mullit") | ||
| 30 | self.assertEqual(sb.shader_source("cs_lds"), "cs_lds") | ||
| 31 | |||
| 32 | def test_asm_fssm_and_cs_fssm_extra(self) -> None: | ||
| 33 | with TemporaryDirectory() as tmp: | ||
| 34 | p = Path(tmp) / "fssm.asm" | ||
| 35 | p.write_text("; fssm-at: 0x10\n; fssm-data: 0x11223344 0x55667788\nv_mov_b32 v0, 0\n", encoding="utf-8") | ||
| 36 | self.assertEqual(sb.asm_fssm_fields(p), (0x10, [0x11223344, 0x55667788])) | ||
| 37 | blob = sb.asm_fssm(p) | ||
| 38 | self.assertIsNotNone(blob) | ||
| 39 | self.assertEqual(blob[:4], b"FSSM") | ||
| 40 | self.assertEqual(len(blob), 0x10 + 8) | ||
| 41 | self.assertEqual(struct.unpack_from("<2I", blob, 0x10), (0x11223344, 0x55667788)) | ||
| 42 | self.assertIsNone(sb.cs_fssm_extra(p)) | ||
| 43 | |||
| 44 | p_cs = Path(tmp) / "cs_fssm.asm" | ||
| 45 | p_cs.write_text("; fssm-at: 0x148\n; fssm-data: 0xdeadbeef\nv_mov_b32 v0, 0\n", encoding="utf-8") | ||
| 46 | extra = sb.cs_fssm_extra(p_cs) | ||
| 47 | self.assertEqual(extra, (0x148, struct.pack("<I", 0xDEADBEEF))) | ||
| 48 | |||
| 49 | |||
| 50 | if __name__ == "__main__": | ||
| 51 | unittest.main() | ||
diff --git a/tests/test_shaders_check.py b/tests/test_shaders_check.py new file mode 100644 index 000000000..61a0561d8 --- /dev/null +++ b/tests/test_shaders_check.py | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | """Unit tests for runtime/test/shaders/check.py.""" | ||
| 2 | |||
| 3 | from __future__ import annotations | ||
| 4 | |||
| 5 | import os | ||
| 6 | import sys | ||
| 7 | import time | ||
| 8 | import unittest | ||
| 9 | from pathlib import Path | ||
| 10 | from tempfile import TemporaryDirectory | ||
| 11 | |||
| 12 | REPO = Path(__file__).resolve().parent.parent | ||
| 13 | sys.path.insert(0, str(REPO / "runtime" / "test" / "shaders")) | ||
| 14 | |||
| 15 | import check as sc # noqa: E402 | ||
| 16 | |||
| 17 | |||
| 18 | class TestShadersCheckBuildDirs(unittest.TestCase): | ||
| 19 | def test_complete_and_resolve_build_dirs(self) -> None: | ||
| 20 | with TemporaryDirectory() as tmp: | ||
| 21 | build = Path(tmp) | ||
| 22 | progs = ["a.exe", "b.exe"] | ||
| 23 | self.assertEqual(sc.complete_build_dirs(str(build), progs), []) | ||
| 24 | self.assertEqual(sc.resolve_build_dir(str(build), progs), str(build)) | ||
| 25 | |||
| 26 | rel = build / "Release" | ||
| 27 | dbg = build / "Debug" | ||
| 28 | rel.mkdir() | ||
| 29 | dbg.mkdir() | ||
| 30 | for p in progs: | ||
| 31 | (rel / p).write_text("rel", encoding="utf-8") | ||
| 32 | (dbg / p).write_text("dbg", encoding="utf-8") | ||
| 33 | now = time.time() | ||
| 34 | os.utime(rel / "a.exe", (now - 10, now - 10)) | ||
| 35 | os.utime(rel / "b.exe", (now - 10, now - 10)) | ||
| 36 | os.utime(dbg / "a.exe", (now, now)) | ||
| 37 | os.utime(dbg / "b.exe", (now, now)) | ||
| 38 | |||
| 39 | self.assertEqual(sc.complete_build_dirs(str(build), progs), [str(rel), str(dbg)]) | ||
| 40 | self.assertEqual(sc.resolve_build_dir(str(build), progs), str(dbg)) | ||
| 41 | |||
| 42 | (build / "a.exe").write_text("root", encoding="utf-8") | ||
| 43 | (build / "b.exe").write_text("root", encoding="utf-8") | ||
| 44 | self.assertEqual(sc.resolve_build_dir(str(build), progs), str(build)) | ||
| 45 | |||
| 46 | def test_not_found_message_names_missing_and_build_dir(self) -> None: | ||
| 47 | msg = sc.not_found_message("/tmp/build", ["vk_compute_test"]) | ||
| 48 | self.assertIn("/tmp/build", msg) | ||
| 49 | self.assertIn("vk_compute_test", msg) | ||
| 50 | |||
| 51 | |||
| 52 | if __name__ == "__main__": | ||
| 53 | unittest.main() | ||
diff --git a/tests/test_swizzle_search.py b/tests/test_swizzle_search.py index ad41b6e14..f797f7b5d 100644 --- a/tests/test_swizzle_search.py +++ b/tests/test_swizzle_search.py | |||
| @@ -27,6 +27,12 @@ try: | |||
| 27 | except ImportError: | 27 | except ImportError: |
| 28 | HAVE_NUMPY = False | 28 | HAVE_NUMPY = False |
| 29 | 29 | ||
| 30 | # The CLI tests launch the tool with `python -I`, which does not see a --user install of numpy; ask the way it runs. | ||
| 31 | # HAVE_NUMPY (this process) stays for the tests that call numpy directly. | ||
| 32 | NUMPY_VISIBLE_TO_TOOL = subprocess.run([sys.executable, "-I", "-c", "import numpy"], | ||
| 33 | capture_output=True, check=False).returncode == 0 | ||
| 34 | PIL_VISIBLE_TO_TOOL = subprocess.run([sys.executable, "-I", "-c", "from PIL import Image"], | ||
| 35 | capture_output=True, check=False).returncode == 0 | ||
| 30 | try: | 36 | try: |
| 31 | from PIL import Image | 37 | from PIL import Image |
| 32 | HAVE_PIL = True | 38 | HAVE_PIL = True |
| @@ -368,7 +374,7 @@ class TestSwizzleSearchPermutationMatching(unittest.TestCase): | |||
| 368 | 374 | ||
| 369 | 375 | ||
| 370 | class TestSwizzleSearchCliAndRender(unittest.TestCase): | 376 | class TestSwizzleSearchCliAndRender(unittest.TestCase): |
| 371 | @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") | 377 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL and PIL_VISIBLE_TO_TOOL and HAVE_PIL, "isolated numpy and PIL required") |
| 372 | def test_default_tile_target_previews_a_short_complete_row(self) -> None: | 378 | def test_default_tile_target_previews_a_short_complete_row(self) -> None: |
| 373 | with tempfile.TemporaryDirectory() as td: | 379 | with tempfile.TemporaryDirectory() as td: |
| 374 | blob = Path(td) / "two_tiles.bin" | 380 | blob = Path(td) / "two_tiles.bin" |
| @@ -388,7 +394,6 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 388 | expected_row = bytes((255, 0, 0)) * 32 + bytes((0, 255, 0)) * 32 | 394 | expected_row = bytes((255, 0, 0)) * 32 + bytes((0, 255, 0)) * 32 |
| 389 | self.assertEqual(image.tobytes(), expected_row * 32) | 395 | self.assertEqual(image.tobytes(), expected_row * 32) |
| 390 | 396 | ||
| 391 | @unittest.skipUnless(HAVE_NUMPY, "numpy required") # the tool imports numpy before it parses arguments | ||
| 392 | def test_cli_bad_numeric_arguments_are_usage_errors(self): | 397 | def test_cli_bad_numeric_arguments_are_usage_errors(self): |
| 393 | """Bad --bpe/--tile/--widths/--tiles must be usage errors, not arithmetic tracebacks.""" | 398 | """Bad --bpe/--tile/--widths/--tiles must be usage errors, not arithmetic tracebacks.""" |
| 394 | cases = [ | 399 | cases = [ |
| @@ -415,7 +420,6 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 415 | self.assertIn(expected, result.stderr) | 420 | self.assertIn(expected, result.stderr) |
| 416 | self.assertNotIn("Traceback", result.stderr) | 421 | self.assertNotIn("Traceback", result.stderr) |
| 417 | 422 | ||
| 418 | @unittest.skipUnless(HAVE_NUMPY, "numpy required") | ||
| 419 | def test_cli_missing_input_is_an_error_not_a_traceback(self): | 423 | def test_cli_missing_input_is_an_error_not_a_traceback(self): |
| 420 | with tempfile.TemporaryDirectory() as tmp: | 424 | with tempfile.TemporaryDirectory() as tmp: |
| 421 | missing = os.path.join(tmp, "definitely_missing_path") | 425 | missing = os.path.join(tmp, "definitely_missing_path") |
| @@ -427,7 +431,7 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 427 | self.assertIn("definitely_missing_path", result.stderr) | 431 | self.assertIn("definitely_missing_path", result.stderr) |
| 428 | self.assertNotIn("Traceback", result.stderr) | 432 | self.assertNotIn("Traceback", result.stderr) |
| 429 | 433 | ||
| 430 | @unittest.skipUnless(HAVE_NUMPY, "numpy required") # the tool imports numpy before it parses arguments | 434 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "numpy required") # the tool imports numpy before it parses arguments |
| 431 | def test_preview_with_no_fitting_layout_reports_the_problem(self): | 435 | def test_preview_with_no_fitting_layout_reports_the_problem(self): |
| 432 | """CLI with tiny blob and --out must exit 1, report 'no layout', and not create file.""" | 436 | """CLI with tiny blob and --out must exit 1, report 'no layout', and not create file.""" |
| 433 | with tempfile.TemporaryDirectory() as td: | 437 | with tempfile.TemporaryDirectory() as td: |
| @@ -444,7 +448,7 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 444 | self.assertNotIn("Traceback", result.stderr) | 448 | self.assertNotIn("Traceback", result.stderr) |
| 445 | self.assertFalse(preview.exists()) | 449 | self.assertFalse(preview.exists()) |
| 446 | 450 | ||
| 447 | @unittest.skipUnless(HAVE_NUMPY, "numpy required") | 451 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "numpy required") |
| 448 | def test_cli_successful_search_output(self): | 452 | def test_cli_successful_search_output(self): |
| 449 | """CLI on valid synthetic buffer must exit 0 and print formatted scores and bit sequences.""" | 453 | """CLI on valid synthetic buffer must exit 0 and print formatted scores and bit sequences.""" |
| 450 | with tempfile.TemporaryDirectory() as td: | 454 | with tempfile.TemporaryDirectory() as td: |
| @@ -473,7 +477,6 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 473 | self.assertIn("bits(low->high)", result.stdout) | 477 | self.assertIn("bits(low->high)", result.stdout) |
| 474 | self.assertNotIn("Traceback", result.stderr) | 478 | self.assertNotIn("Traceback", result.stderr) |
| 475 | 479 | ||
| 476 | @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") | ||
| 477 | def test_preview_rejects_input_and_hardlink_alias(self): | 480 | def test_preview_rejects_input_and_hardlink_alias(self): |
| 478 | """A preview must not overwrite the input or a hard link to it.""" | 481 | """A preview must not overwrite the input or a hard link to it.""" |
| 479 | for hardlink in (False, True): | 482 | for hardlink in (False, True): |
| @@ -508,7 +511,7 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): | |||
| 508 | self.assertEqual(blob.read_bytes(), original) | 511 | self.assertEqual(blob.read_bytes(), original) |
| 509 | self.assertEqual(output.read_bytes(), original) | 512 | self.assertEqual(output.read_bytes(), original) |
| 510 | 513 | ||
| 511 | @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") | 514 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL and PIL_VISIBLE_TO_TOOL and HAVE_PIL, "isolated numpy and PIL required") |
| 512 | def test_preview_ranks_thin_candidates_by_their_existing_edges(self) -> None: | 515 | def test_preview_ranks_thin_candidates_by_their_existing_edges(self) -> None: |
| 513 | from PIL import Image | 516 | from PIL import Image |
| 514 | 517 | ||
| @@ -666,6 +669,7 @@ class TestSwizzleSearchOutGuard(unittest.TestCase): | |||
| 666 | self.assertNotIn("Traceback", err.getvalue()) | 669 | self.assertNotIn("Traceback", err.getvalue()) |
| 667 | 670 | ||
| 668 | 671 | ||
| 672 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "the tool runs with -I, which cannot see this numpy") | ||
| 669 | def test_preview_with_no_fitting_layout_reports_the_problem(tmp_path=None): | 673 | def test_preview_with_no_fitting_layout_reports_the_problem(tmp_path=None): |
| 670 | """Module-level compatibility wrapper for pytest with tmp_path fixture.""" | 674 | """Module-level compatibility wrapper for pytest with tmp_path fixture.""" |
| 671 | if not HAVE_NUMPY: | 675 | if not HAVE_NUMPY: |
diff --git a/tests/test_tile_probe.py b/tests/test_tile_probe.py index ef40bb5db..6f3dfd828 100644 --- a/tests/test_tile_probe.py +++ b/tests/test_tile_probe.py | |||
| @@ -15,6 +15,11 @@ import unittest | |||
| 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 16 | TOOL = os.path.join(ROOT, "tools", "tile_probe.py") | 16 | TOOL = os.path.join(ROOT, "tools", "tile_probe.py") |
| 17 | HAVE_NUMPY = importlib.util.find_spec("numpy") is not None | 17 | HAVE_NUMPY = importlib.util.find_spec("numpy") is not None |
| 18 | |||
| 19 | # The probe tests launch the tool with `python -I`, which does not see a --user install of numpy; ask the way it runs, | ||
| 20 | # as HAVE_PIL_ISOLATED below already does. Without this the gate opens and the child dies on a missing module. | ||
| 21 | NUMPY_VISIBLE_TO_TOOL = subprocess.run([sys.executable, "-I", "-c", "import numpy"], | ||
| 22 | capture_output=True, check=False).returncode == 0 | ||
| 18 | # the tool is documented as `python -I`, which does not see a --user install of Pillow | 23 | # the tool is documented as `python -I`, which does not see a --user install of Pillow |
| 19 | HAVE_PIL_ISOLATED = subprocess.run([sys.executable, "-I", "-c", "import PIL"], | 24 | HAVE_PIL_ISOLATED = subprocess.run([sys.executable, "-I", "-c", "import PIL"], |
| 20 | capture_output=True, check=False).returncode == 0 | 25 | capture_output=True, check=False).returncode == 0 |
| @@ -59,6 +64,7 @@ class TileProbeInputTest(unittest.TestCase): | |||
| 59 | self.assertNotIn("Traceback", p.stderr) | 64 | self.assertNotIn("Traceback", p.stderr) |
| 60 | self.assertEqual(p.stdout, "") | 65 | self.assertEqual(p.stdout, "") |
| 61 | 66 | ||
| 67 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "the tool runs with -I, which cannot see this numpy") | ||
| 62 | def test_empty_file_is_a_short_sample_not_a_bad_offset(self): | 68 | def test_empty_file_is_a_short_sample_not_a_bad_offset(self): |
| 63 | empty = os.path.join(self.tmp.name, "empty.bin") | 69 | empty = os.path.join(self.tmp.name, "empty.bin") |
| 64 | open(empty, "wb").close() | 70 | open(empty, "wb").close() |
| @@ -72,6 +78,7 @@ class TileProbeInputTest(unittest.TestCase): | |||
| 72 | self.assertIn("is past the end of blob", p.stderr) | 78 | self.assertIn("is past the end of blob", p.stderr) |
| 73 | self.assertIn("(0 bytes)", p.stderr) | 79 | self.assertIn("(0 bytes)", p.stderr) |
| 74 | 80 | ||
| 81 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "the tool runs with -I, which cannot see this numpy") | ||
| 75 | def test_a_sample_with_no_candidate_layout_is_an_error(self): | 82 | def test_a_sample_with_no_candidate_layout_is_an_error(self): |
| 76 | # Before: an 8-byte or 4 KiB blob printed nothing, wrote no preview and exited 0. | 83 | # Before: an 8-byte or 4 KiB blob printed nothing, wrote no preview and exited 0. |
| 77 | tiny = os.path.join(self.tmp.name, "tiny.bin") | 84 | tiny = os.path.join(self.tmp.name, "tiny.bin") |
| @@ -120,6 +127,7 @@ class TileProbeInputTest(unittest.TestCase): | |||
| 120 | self.assertTrue(os.path.isdir(os.path.dirname(preview)), "the preview's folder is created") | 127 | self.assertTrue(os.path.isdir(os.path.dirname(preview)), "the preview's folder is created") |
| 121 | 128 | ||
| 122 | @unittest.skipIf(HAVE_PIL_ISOLATED, "this interpreter's -I can import Pillow") | 129 | @unittest.skipIf(HAVE_PIL_ISOLATED, "this interpreter's -I can import Pillow") |
| 130 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "the tool runs with -I, which cannot see this numpy") | ||
| 123 | def test_preview_without_pillow_is_a_message_not_a_traceback(self): | 131 | def test_preview_without_pillow_is_a_message_not_a_traceback(self): |
| 124 | # Before: the probe ran, then render()'s lazy PIL import raised after all the work was done. | 132 | # Before: the probe ran, then render()'s lazy PIL import raised after all the work was done. |
| 125 | p = self.run_tool(self.blob, "--out", os.path.join(self.tmp.name, "preview.png")) | 133 | p = self.run_tool(self.blob, "--out", os.path.join(self.tmp.name, "preview.png")) |
| @@ -127,6 +135,7 @@ class TileProbeInputTest(unittest.TestCase): | |||
| 127 | self.assertIn("Pillow", p.stderr) | 135 | self.assertIn("Pillow", p.stderr) |
| 128 | self.assertNotIn("Traceback", p.stderr) | 136 | self.assertNotIn("Traceback", p.stderr) |
| 129 | 137 | ||
| 138 | @unittest.skipUnless(NUMPY_VISIBLE_TO_TOOL, "the tool runs with -I, which cannot see this numpy") | ||
| 130 | def test_offset_inside_the_file_still_probes(self): | 139 | def test_offset_inside_the_file_still_probes(self): |
| 131 | p = self.run_tool(self.blob, "--offset", "0") | 140 | p = self.run_tool(self.blob, "--offset", "0") |
| 132 | self.assertEqual(p.returncode, 0, p.stderr) | 141 | self.assertEqual(p.returncode, 0, p.stderr) |
diff --git a/tests/test_tool_startup.py b/tests/test_tool_startup.py index eb1eb6509..341f4cf33 100644 --- a/tests/test_tool_startup.py +++ b/tests/test_tool_startup.py | |||
| @@ -53,7 +53,10 @@ class ToolStartupTests(unittest.TestCase): | |||
| 53 | def test_each_sibling_importing_tool_starts(self): | 53 | def test_each_sibling_importing_tool_starts(self): |
| 54 | paths = sibling_importers() | 54 | paths = sibling_importers() |
| 55 | self.assertGreater(len(paths), 20, "the sibling-import scan found almost nothing") | 55 | self.assertGreater(len(paths), 20, "the sibling-import scan found almost nothing") |
| 56 | have_numpy = importlib.util.find_spec("numpy") is not None | 56 | # Ask the way the tools are launched: `-I` does not see a --user install, so find_spec in this process can |
| 57 | # say yes while the child gets ModuleNotFoundError (tests/test_tile_probe.py carries the same correction). | ||
| 58 | have_numpy = subprocess.run([sys.executable, "-I", "-c", "import numpy"], | ||
| 59 | capture_output=True, check=False).returncode == 0 | ||
| 57 | for path in paths: | 60 | for path in paths: |
| 58 | name = os.path.splitext(os.path.basename(path))[0] | 61 | name = os.path.splitext(os.path.basename(path))[0] |
| 59 | if name in NUMERIC and not have_numpy: | 62 | if name in NUMERIC and not have_numpy: |
| @@ -61,6 +64,10 @@ class ToolStartupTests(unittest.TestCase): | |||
| 61 | with self.subTest(tool=name): | 64 | with self.subTest(tool=name): |
| 62 | proc = subprocess.run([sys.executable, "-I", path, "--help"], capture_output=True, text=True, | 65 | proc = subprocess.run([sys.executable, "-I", path, "--help"], capture_output=True, text=True, |
| 63 | timeout=TIMEOUT, errors="replace") | 66 | timeout=TIMEOUT, errors="replace") |
| 67 | # A sibling that is not numeric itself can still import a numeric one: a list of names cannot cover | ||
| 68 | # those, and a missing third-party module is not a startup failure. CI has numpy, so it never fires. | ||
| 69 | if not have_numpy and "No module named 'numpy'" in proc.stderr: | ||
| 70 | continue | ||
| 64 | self.assertEqual(proc.returncode, 0, proc.stderr[-2000:]) | 71 | self.assertEqual(proc.returncode, 0, proc.stderr[-2000:]) |
| 65 | self.assertNotIn("Traceback", proc.stderr) | 72 | self.assertNotIn("Traceback", proc.stderr) |
| 66 | 73 | ||
diff --git a/tests/test_vk_fuzz_run.py b/tests/test_vk_fuzz_run.py index 39b275566..6aef6b878 100644 --- a/tests/test_vk_fuzz_run.py +++ b/tests/test_vk_fuzz_run.py | |||
| @@ -137,7 +137,7 @@ class ProgramText(unittest.TestCase): | |||
| 137 | self.assertFalse(R.all_skipped({"match": 1, "skip: x": 2})) | 137 | self.assertFalse(R.all_skipped({"match": 1, "skip: x": 2})) |
| 138 | self.assertFalse(R.all_skipped({"denormal": 1, "skip: x": 2})) | 138 | self.assertFalse(R.all_skipped({"denormal": 1, "skip: x": 2})) |
| 139 | 139 | ||
| 140 | def _run_with_fake_gpu(self, tmp, outcomes, calls, run, retries=0): | 140 | def _run_with_fake_gpu(self, tmp, outcomes, calls, run, retries=0, translate_cmds=None, envs=None): |
| 141 | """Run the real assembly/translation/GPU orchestration with synthetic child procedures.""" | 141 | """Run the real assembly/translation/GPU orchestration with synthetic child procedures.""" |
| 142 | if R.SHADERS not in sys.path: | 142 | if R.SHADERS not in sys.path: |
| 143 | sys.path.insert(0, R.SHADERS) | 143 | sys.path.insert(0, R.SHADERS) |
| @@ -148,6 +148,8 @@ class ProgramText(unittest.TestCase): | |||
| 148 | 148 | ||
| 149 | def child(cmd, *, env=None, **_kwargs): | 149 | def child(cmd, *, env=None, **_kwargs): |
| 150 | if "--out" in cmd: | 150 | if "--out" in cmd: |
| 151 | if translate_cmds is not None: | ||
| 152 | translate_cmds.append(cmd) | ||
| 151 | out = Path(cmd[cmd.index("--out") + 1]) | 153 | out = Path(cmd[cmd.index("--out") + 1]) |
| 152 | out.mkdir() | 154 | out.mkdir() |
| 153 | (out / "index.json").write_text(json.dumps({f"cs_vkfuzz_{i}": {} for i in range(len(outcomes))}), | 155 | (out / "index.json").write_text(json.dumps({f"cs_vkfuzz_{i}": {} for i in range(len(outcomes))}), |
| @@ -157,6 +159,8 @@ class ProgramText(unittest.TestCase): | |||
| 157 | return subprocess.CompletedProcess(cmd, 0, "", "") | 159 | return subprocess.CompletedProcess(cmd, 0, "", "") |
| 158 | i = int(Path(cmd[1]).stem.rsplit("_", 1)[1]) | 160 | i = int(Path(cmd[1]).stem.rsplit("_", 1)[1]) |
| 159 | calls.append(i) | 161 | calls.append(i) |
| 162 | if envs is not None: | ||
| 163 | envs.append(dict(env)) | ||
| 160 | Path(env["VKC_DUMP"]).write_bytes(bytes(128)) # fresh, complete 32-lane, one-word dump | 164 | Path(env["VKC_DUMP"]).write_bytes(bytes(128)) # fresh, complete 32-lane, one-word dump |
| 161 | rc, stdout, stderr = outcomes[i] | 165 | rc, stdout, stderr = outcomes[i] |
| 162 | return subprocess.CompletedProcess(cmd, rc, stdout, stderr) | 166 | return subprocess.CompletedProcess(cmd, rc, stdout, stderr) |
| @@ -197,6 +201,72 @@ class ProgramText(unittest.TestCase): | |||
| 197 | self.assertEqual(got, ["the device can't run 32-lane subgroups (8 lanes)", | 201 | self.assertEqual(got, ["the device can't run 32-lane subgroups (8 lanes)", |
| 198 | "vk_compute_test: unsupported: no matching device", [0]]) | 202 | "vk_compute_test: unsupported: no matching device", [0]]) |
| 199 | 203 | ||
| 204 | def test_pc_tail_ubo_env_passes_the_flag_and_propagates_to_vk_compute_test(self): | ||
| 205 | outcomes = [(0, "compute subgroup size: 32\n", "")] | ||
| 206 | with tempfile.TemporaryDirectory() as tmp: | ||
| 207 | translate_cmds, envs = [], [] | ||
| 208 | with mock.patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": "yes"}): | ||
| 209 | got = self._run_with_fake_gpu( | ||
| 210 | tmp, outcomes, [], translate_cmds=translate_cmds, envs=envs, | ||
| 211 | run=lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 212 | build=folder, work_parent=folder, retries=retries)) | ||
| 213 | self.assertEqual(got, [[0]]) | ||
| 214 | self.assertEqual(len(translate_cmds), 1) | ||
| 215 | self.assertIn("--pc-tail-ubo", translate_cmds[0]) | ||
| 216 | # vk_compute_test reads the same variable for its own push-constant range. | ||
| 217 | self.assertEqual(envs[0].get("LEONIDA_PC_TAIL_UBO"), "yes") | ||
| 218 | # The unset case passes no flag. | ||
| 219 | with tempfile.TemporaryDirectory() as tmp2: | ||
| 220 | translate_cmds2 = [] | ||
| 221 | with mock.patch.dict(os.environ, {}, clear=False): | ||
| 222 | os.environ.pop("LEONIDA_PC_TAIL_UBO", None) | ||
| 223 | got2 = self._run_with_fake_gpu( | ||
| 224 | tmp2, outcomes, [], translate_cmds=translate_cmds2, | ||
| 225 | run=lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 226 | build=folder, work_parent=folder, | ||
| 227 | retries=retries)) | ||
| 228 | self.assertEqual(got2, [[0]]) | ||
| 229 | self.assertNotIn("--pc-tail-ubo", translate_cmds2[0]) | ||
| 230 | |||
| 231 | def test_skip_crash_records_a_crash_as_a_skip_but_keeps_harness_errors_fatal(self): | ||
| 232 | crash = (3221225477, "", "") # 0xC0000005-style driver crash exit | ||
| 233 | with tempfile.TemporaryDirectory() as tmp: | ||
| 234 | with mock.patch.dict(os.environ, {"VK_FUZZ_SKIP_CRASH": "1"}): | ||
| 235 | calls = [] | ||
| 236 | got = self._run_with_fake_gpu( | ||
| 237 | tmp, [crash], calls, | ||
| 238 | lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 239 | build=folder, work_parent=folder, retries=retries)) | ||
| 240 | self.assertEqual(got, ["vk_compute_test: crashed (exit 3221225477)"]) | ||
| 241 | self.assertEqual(calls, [0]) # the retries are spent first, then it is skipped | ||
| 242 | # A signal death is a negative subprocess returncode on POSIX; it is a crash skip too. | ||
| 243 | with tempfile.TemporaryDirectory() as tmp: | ||
| 244 | with mock.patch.dict(os.environ, {"VK_FUZZ_SKIP_CRASH": "1"}): | ||
| 245 | got = self._run_with_fake_gpu( | ||
| 246 | tmp, [(-11, "", "")], [], | ||
| 247 | lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 248 | build=folder, work_parent=folder, retries=retries)) | ||
| 249 | self.assertEqual(got, ["vk_compute_test: crashed (exit -11)"]) | ||
| 250 | # Both harness errors stay fatal under VK_FUZZ_SKIP_CRASH: 1 is a CHECK failure, 2 a usage error. | ||
| 251 | for fatal in ((1, "", "FAILED vkCreateShaderModule"), (2, "", "usage: ...")): | ||
| 252 | with self.subTest(exit=fatal[0]), tempfile.TemporaryDirectory() as tmp: | ||
| 253 | with mock.patch.dict(os.environ, {"VK_FUZZ_SKIP_CRASH": "1"}): | ||
| 254 | with self.assertRaisesRegex(RuntimeError, rf"vk_compute_test exit {fatal[0]}"): | ||
| 255 | self._run_with_fake_gpu( | ||
| 256 | tmp, [fatal], [], | ||
| 257 | lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 258 | build=folder, work_parent=folder, | ||
| 259 | retries=retries)) | ||
| 260 | # And without the variable a crash is still fatal. | ||
| 261 | with tempfile.TemporaryDirectory() as tmp: | ||
| 262 | with mock.patch.dict(os.environ): | ||
| 263 | os.environ.pop("VK_FUZZ_SKIP_CRASH", None) | ||
| 264 | with self.assertRaisesRegex(RuntimeError, r"vk_compute_test exit 3221225477"): | ||
| 265 | self._run_with_fake_gpu( | ||
| 266 | tmp, [crash], [], | ||
| 267 | lambda folder, retries: R.run_programs([["v_mov_b32 v8, 0"]], words=1, wave=32, | ||
| 268 | build=folder, work_parent=folder, retries=retries)) | ||
| 269 | |||
| 200 | 270 | ||
| 201 | def test_encoded_listings_skip_llvm_mc_and_follow_the_wave64_emulation_switch(self): | 271 | def test_encoded_listings_skip_llvm_mc_and_follow_the_wave64_emulation_switch(self): |
| 202 | listing = "; cs_vkfuzz_0\n; encoding: [0x00,0x00,0x80,0xbf]\ns_endpgm\n" | 272 | listing = "; cs_vkfuzz_0\n; encoding: [0x00,0x00,0x80,0xbf]\ns_endpgm\n" |
diff --git a/tests/test_vk_lod_bias.py b/tests/test_vk_lod_bias.py new file mode 100644 index 000000000..702ee7d50 --- /dev/null +++ b/tests/test_vk_lod_bias.py | |||
| @@ -0,0 +1,66 @@ | |||
| 1 | """tools/vk_lod_bias.py: the mipLodBias measurement tools/vk_subgroup_info.py --lod-bias runs. | ||
| 2 | |||
| 3 | No GPU: the verdict is checked from the three texels the compute shader returns (with the LOD 1 control), a Vulkan library without the calls | ||
| 4 | gives "unknown", and the embedded SPIR-V is checked for its header (and with spirv-val when it is on PATH). | ||
| 5 | Standard library only; no game files. | ||
| 6 | """ | ||
| 7 | import os | ||
| 8 | import shutil | ||
| 9 | import struct | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | import unittest | ||
| 14 | |||
| 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 16 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 17 | import vk_lod_bias # noqa: E402 | ||
| 18 | |||
| 19 | |||
| 20 | class VerdictTest(unittest.TestCase): | ||
| 21 | def test_the_texels_decide(self): | ||
| 22 | # level 0 holds 0.0 and level 1 holds 1.0; the shader samples LOD 0 with mipLodBias 0 and +1, and LOD 1 | ||
| 23 | self.assertIs(vk_lod_bias.verdict(0.0, 1.0, 1.0)[0], False) # the sampler applies the bias | ||
| 24 | self.assertIs(vk_lod_bias.verdict(0.0, 0.0, 1.0)[0], True) # the sampler drops it | ||
| 25 | for plain, biased in ((1.0, 1.0), (1.0, 0.0), (0.0, 0.5), (float("nan"), 0.0)): | ||
| 26 | with self.subTest(plain=plain, biased=biased): | ||
| 27 | answer, reason = vk_lod_bias.verdict(plain, biased, 1.0) | ||
| 28 | self.assertIsNone(answer) | ||
| 29 | self.assertIn("unexpected", reason) | ||
| 30 | |||
| 31 | def test_the_lod1_control_must_read_one(self): | ||
| 32 | # a level 1 that was never cleared also gives a biased 0.0: without the control it would look like a drop | ||
| 33 | for level1 in (0.0, 0.5, float("nan")): | ||
| 34 | for plain, biased in ((0.0, 0.0), (0.0, 1.0)): | ||
| 35 | with self.subTest(level1=level1, plain=plain, biased=biased): | ||
| 36 | answer, reason = vk_lod_bias.verdict(plain, biased, level1) | ||
| 37 | self.assertIsNone(answer) | ||
| 38 | self.assertIn("control read at LOD 1", reason) | ||
| 39 | |||
| 40 | |||
| 41 | class MeasureTest(unittest.TestCase): | ||
| 42 | def test_a_library_without_the_calls_is_unknown(self): | ||
| 43 | answer, reason = vk_lod_bias.measure(object(), 0x1) | ||
| 44 | self.assertIsNone(answer) | ||
| 45 | self.assertIn("lacks a call", reason) | ||
| 46 | |||
| 47 | |||
| 48 | class ShaderTest(unittest.TestCase): | ||
| 49 | def test_the_words_are_a_spirv_module(self): | ||
| 50 | words = vk_lod_bias.SHADER_WORDS | ||
| 51 | self.assertEqual(words[0], 0x07230203) # SPIR-V magic | ||
| 52 | self.assertLessEqual(words[1], 0x00010000) # SPIR-V 1.0, so any Vulkan 1.0 device takes it | ||
| 53 | self.assertTrue(all(0 <= w <= 0xFFFFFFFF for w in words)) | ||
| 54 | |||
| 55 | @unittest.skipUnless(shutil.which("spirv-val"), "spirv-val not on PATH") | ||
| 56 | def test_spirv_val_accepts_it(self): | ||
| 57 | with tempfile.TemporaryDirectory() as tmp: | ||
| 58 | path = os.path.join(tmp, "lod_bias.spv") | ||
| 59 | with open(path, "wb") as f: | ||
| 60 | f.write(struct.pack(f"<{len(vk_lod_bias.SHADER_WORDS)}I", *vk_lod_bias.SHADER_WORDS)) | ||
| 61 | r = subprocess.run(["spirv-val", "--target-env", "vulkan1.0", path], capture_output=True, text=True) | ||
| 62 | self.assertEqual(r.returncode, 0, r.stdout + r.stderr) | ||
| 63 | |||
| 64 | |||
| 65 | if __name__ == "__main__": | ||
| 66 | unittest.main() | ||
diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 6636d4861..2f141e7f4 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py | |||
| @@ -902,6 +902,29 @@ class QueryTest(unittest.TestCase): | |||
| 902 | self.assertIs(res["barycentric_fallback"], want) | 902 | self.assertIs(res["barycentric_fallback"], want) |
| 903 | self.assertEqual(vk_info.VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 6) | 903 | self.assertEqual(vk_info.VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 6) |
| 904 | 904 | ||
| 905 | def test_lod_bias_is_measured_only_when_asked(self): | ||
| 906 | """--lod-bias adds tools/vk_lod_bias.py's answer for the chosen device; without it nothing runs on the GPU.""" | ||
| 907 | import vk_lod_bias | ||
| 908 | with mock.patch.object(vk_lod_bias, "measure", return_value=(True, "drops")) as measure: | ||
| 909 | res, _vk = self._run_query(FakeDevice()) | ||
| 910 | self.assertNotIn("explicit_lod_bias", res) | ||
| 911 | measure.assert_not_called() | ||
| 912 | vk = FakeVulkan(devices=(FakeDevice(),)) | ||
| 913 | with mock.patch.object(vk_info, "load_vulkan", return_value=vk): | ||
| 914 | res = vk_info.query(lod_bias=True) | ||
| 915 | self.assertIs(res["explicit_lod_bias"], True) | ||
| 916 | self.assertEqual(res["explicit_lod_bias_reason"], "drops") | ||
| 917 | self.assertEqual(measure.call_args.args[1].value, 0x20000001) # the chosen device's handle | ||
| 918 | |||
| 919 | def test_a_lod_bias_measurement_that_fails_is_unknown(self): | ||
| 920 | import vk_lod_bias | ||
| 921 | vk = FakeVulkan(devices=(FakeDevice(),)) | ||
| 922 | with mock.patch.object(vk_lod_bias, "measure", side_effect=OSError("device lost")), \ | ||
| 923 | mock.patch.object(vk_info, "load_vulkan", return_value=vk): | ||
| 924 | res = vk_info.query(lod_bias=True) | ||
| 925 | self.assertIsNone(res["explicit_lod_bias"]) | ||
| 926 | self.assertIn("device lost", res["explicit_lod_bias_reason"]) | ||
| 927 | |||
| 905 | def test_barycentric_fallback_rejects_an_intel_windows_fake(self): | 928 | def test_barycentric_fallback_rejects_an_intel_windows_fake(self): |
| 906 | """Intel Windows uses its Windows driver ID, not ANV; the fake must carry Intel's vendor ID.""" | 929 | """Intel Windows uses its Windows driver ID, not ANV; the fake must carry Intel's vendor ID.""" |
| 907 | res, _vk = self._run_query(FakeDevice(name="Intel Arc", vendor_id=0x8086, device_id=0xE20B, | 930 | res, _vk = self._run_query(FakeDevice(name="Intel Arc", vendor_id=0x8086, device_id=0xE20B, |
diff --git a/tools/amd_swizzle.py b/tools/amd_swizzle.py index 5f0cd42f0..9096049b5 100644 --- a/tools/amd_swizzle.py +++ b/tools/amd_swizzle.py | |||
| @@ -16,7 +16,20 @@ import os | |||
| 16 | import re | 16 | import re |
| 17 | import sys | 17 | import sys |
| 18 | 18 | ||
| 19 | import numpy as np | 19 | # numpy is imported late on purpose: argument and header validation must report their own errors on a machine where |
| 20 | # numpy is missing or hidden, and only the computation needs it. | ||
| 21 | try: | ||
| 22 | import numpy as np | ||
| 23 | except ModuleNotFoundError as exc: | ||
| 24 | if exc.name != "numpy": | ||
| 25 | raise | ||
| 26 | np = None | ||
| 27 | |||
| 28 | |||
| 29 | def _require_numpy(): | ||
| 30 | """Exits with the actionable message when the computation needs numpy and it is not importable.""" | ||
| 31 | if np is None: | ||
| 32 | raise SystemExit("ERROR: amd_swizzle.py needs numpy (python -m pip install numpy)") | ||
| 20 | 33 | ||
| 21 | HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"<ref>\mesa-addrlib\gfx10SwizzlePattern.h") | 34 | HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"<ref>\mesa-addrlib\gfx10SwizzlePattern.h") |
| 22 | BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} | 35 | BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} |
| @@ -241,6 +254,7 @@ def main(argv=None): | |||
| 241 | except (AttributeError, ValueError) as e: | 254 | except (AttributeError, ValueError) as e: |
| 242 | print(f"ERROR: {HEADER!r} does not look like addrlib's gfx10SwizzlePattern.h ({e})", file=sys.stderr) | 255 | print(f"ERROR: {HEADER!r} does not look like addrlib's gfx10SwizzlePattern.h ({e})", file=sys.stderr) |
| 243 | return 2 | 256 | return 2 |
| 257 | _require_numpy() # every check above must report its own error without numpy | ||
| 244 | # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element. | 258 | # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element. |
| 245 | block = 4 if a.bpe in (8, 16) else 1 | 259 | block = 4 if a.bpe in (8, 16) else 1 |
| 246 | wb = (a.width + block - 1) // block | 260 | wb = (a.width + block - 1) // block |
diff --git a/tools/awc_opus.py b/tools/awc_opus.py index be3cd9aaf..9907566f4 100644 --- a/tools/awc_opus.py +++ b/tools/awc_opus.py | |||
| @@ -105,6 +105,22 @@ def opus_samples(packet: bytes | memoryview) -> int: | |||
| 105 | OPUS_PRE_SKIP = 312 | 105 | OPUS_PRE_SKIP = 312 |
| 106 | 106 | ||
| 107 | 107 | ||
| 108 | def ogg_last_granule(path: str): | ||
| 109 | """The granule of the last Ogg page in `path`, or None when the file has no complete page header. | ||
| 110 | |||
| 111 | `--skip-existing` keeps an Ogg written by an earlier run, so that file's own EOS granule is the authority for | ||
| 112 | the cue-sheet limit: recomputing the limit from this run's packets would describe a file that was not written.""" | ||
| 113 | try: | ||
| 114 | with open(path, "rb") as f: | ||
| 115 | data = f.read() | ||
| 116 | except OSError: | ||
| 117 | return None | ||
| 118 | at = data.rfind(b"OggS") | ||
| 119 | if at < 0 or at + 14 > len(data): | ||
| 120 | return None | ||
| 121 | return struct.unpack_from("<q", data, at + 6)[0] | ||
| 122 | |||
| 123 | |||
| 108 | def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, | 124 | def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0, |
| 109 | pre_skip: int = OPUS_PRE_SKIP) -> int: | 125 | pre_skip: int = OPUS_PRE_SKIP) -> int: |
| 110 | """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is | 126 | """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is |
| @@ -469,10 +485,11 @@ def write_cue_sheet(sheet, rows): | |||
| 469 | write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8")) | 485 | write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8")) |
| 470 | 486 | ||
| 471 | 487 | ||
| 472 | def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False): | 488 | def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False, |
| 489 | skip_existing: bool = False): | ||
| 473 | od = bank_output_dir(path, out_dir) | 490 | od = bank_output_dir(path, out_dir) |
| 474 | if cue_sheet: | 491 | sheet = os.path.join(od, "cue_regions.json") |
| 475 | sheet = os.path.join(od, "cue_regions.json") | 492 | if cue_sheet and not skip_existing: |
| 476 | if os.path.exists(sheet): | 493 | if os.path.exists(sheet): |
| 477 | # A skipped bank or interrupted channel write must not leave last run's regions current. | 494 | # A skipped bank or interrupted channel write must not leave last run's regions current. |
| 478 | write_cue_sheet(sheet, []) | 495 | write_cue_sheet(sheet, []) |
| @@ -491,8 +508,21 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee | |||
| 491 | if cue_sheet: | 508 | if cue_sheet: |
| 492 | channel_counts[cid] += 1 | 509 | channel_counts[cid] += 1 |
| 493 | if pk: | 510 | if pk: |
| 511 | # The write below uses the de-duplicated stem, so the skip has to look at the same name: a bank | ||
| 512 | # whose streams share an id exports XXXXXXXX.ogg and XXXXXXXX~2.ogg, and only the first would have | ||
| 513 | # been seen under the raw id. | ||
| 514 | target = os.path.join(od, stem + ".ogg") | ||
| 515 | # Kept from an earlier run: its own EOS granule is the only authority for the cue-sheet | ||
| 516 | # limit. Recomputing it from this run's packets would describe a file that was not written. | ||
| 517 | if skip_existing and os.path.exists(target): | ||
| 518 | counts["music"] += 1 | ||
| 519 | if cue_sheet and rate == 48000 and samples > 0: | ||
| 520 | kept = ogg_last_granule(target) | ||
| 521 | if kept is not None: | ||
| 522 | frame_limits[cid] = min(samples, max(0, kept - pre_skip)) | ||
| 523 | continue | ||
| 494 | n48 = samples * 48000 // rate if rate else 0 | 524 | n48 = samples * 48000 // rate if rate else 0 |
| 495 | granule = write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, packet_channels, cid, n48, | 525 | granule = write_ogg_opus(target, pk, packet_channels, cid, n48, |
| 496 | pre_skip=pre_skip) | 526 | pre_skip=pre_skip) |
| 497 | if cue_sheet and rate == 48000 and samples > 0: | 527 | if cue_sheet and rate == 48000 and samples > 0: |
| 498 | frame_limits[cid] = min(samples, max(0, granule - pre_skip)) | 528 | frame_limits[cid] = min(samples, max(0, granule - pre_skip)) |
| @@ -500,6 +530,10 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee | |||
| 500 | for s, stem in zip(streams, export_stems([s["id"] for s in streams])): | 530 | for s, stem in zip(streams, export_stems([s["id"] for s in streams])): |
| 501 | at, size = s["data"] | 531 | at, size = s["data"] |
| 502 | if s["codec"] == 0x0B and size % 2048 == 0 and s["channels"] in (1, 2): | 532 | if s["codec"] == 0x0B and size % 2048 == 0 and s["channels"] in (1, 2): |
| 533 | ogg = os.path.join(od, stem + ".ogg") | ||
| 534 | if skip_existing and os.path.exists(ogg): | ||
| 535 | counts["opus"] += 1 | ||
| 536 | continue | ||
| 503 | pk = opus_packets(d, at, size) | 537 | pk = opus_packets(d, at, size) |
| 504 | if pk: | 538 | if pk: |
| 505 | # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and | 539 | # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and |
| @@ -509,17 +543,25 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee | |||
| 509 | frames = s["frames"] | 543 | frames = s["frames"] |
| 510 | if not frames or frames * s["channels"] != s["samples"]: | 544 | if not frames or frames * s["channels"] != s["samples"]: |
| 511 | frames = s["samples"] // max(1, s["channels"]) | 545 | frames = s["samples"] // max(1, s["channels"]) |
| 512 | write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, | 546 | write_ogg_opus(ogg, pk, s["channels"], s["id"], frames, |
| 513 | pre_skip=pre_skip) | 547 | pre_skip=pre_skip) |
| 514 | counts["opus"] += 1 | 548 | counts["opus"] += 1 |
| 515 | continue | 549 | continue |
| 516 | if s["codec"] == 2 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 4: | 550 | if s["codec"] == 2 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 4: |
| 517 | # codec 2: 32-bit float PCM (4 bytes per sample; values can exceed +-1, e.g. impulse responses) | 551 | # codec 2: 32-bit float PCM (4 bytes per sample; values can exceed +-1, e.g. impulse responses) |
| 518 | write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"], True) | 552 | wav = os.path.join(od, stem + ".wav") |
| 553 | if skip_existing and os.path.exists(wav): | ||
| 554 | counts["pcm"] += 1 | ||
| 555 | continue | ||
| 556 | write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"], True) | ||
| 519 | counts["pcm"] += 1 | 557 | counts["pcm"] += 1 |
| 520 | continue | 558 | continue |
| 521 | if s["codec"] == 0 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 2: | 559 | if s["codec"] == 0 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 2: |
| 522 | write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"]) | 560 | wav = os.path.join(od, stem + ".wav") |
| 561 | if skip_existing and os.path.exists(wav): | ||
| 562 | counts["pcm"] += 1 | ||
| 563 | continue | ||
| 564 | write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"]) | ||
| 523 | counts["pcm"] += 1 | 565 | counts["pcm"] += 1 |
| 524 | continue | 566 | continue |
| 525 | counts["other"] += 1 | 567 | counts["other"] += 1 |
| @@ -538,6 +580,9 @@ def main(argv=None) -> int: | |||
| 538 | ap.add_argument("src") | 580 | ap.add_argument("src") |
| 539 | ap.add_argument("out") | 581 | ap.add_argument("out") |
| 540 | ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files") | 582 | ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files") |
| 583 | ap.add_argument("--skip-existing", action="store_true", | ||
| 584 | help="leave outputs that already exist alone, so a stopped export resumes instead of " | ||
| 585 | "rewriting every file") | ||
| 541 | ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)") | 586 | ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)") |
| 542 | ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), | 587 | ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), |
| 543 | help="banks to export at once (default: half the CPU count)") | 588 | help="banks to export at once (default: half the CPU count)") |
| @@ -601,7 +646,7 @@ def main(argv=None) -> int: | |||
| 601 | if jobs == 1: | 646 | if jobs == 1: |
| 602 | for i, (b, output_parent) in enumerate(banks): | 647 | for i, (b, output_parent) in enumerate(banks): |
| 603 | try: | 648 | try: |
| 604 | add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet)) | 649 | add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing)) |
| 605 | except (ValueError, struct.error, IndexError, OSError) as e: | 650 | except (ValueError, struct.error, IndexError, OSError) as e: |
| 606 | skipped(b, e) | 651 | skipped(b, e) |
| 607 | continue | 652 | continue |
| @@ -609,7 +654,7 @@ def main(argv=None) -> int: | |||
| 609 | print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True) | 654 | print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True) |
| 610 | else: | 655 | else: |
| 611 | with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex: | 656 | with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex: |
| 612 | futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet): b for b, output_parent in banks} | 657 | futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing): b for b, output_parent in banks} |
| 613 | for i, fut in enumerate(as_completed(futures), 1): | 658 | for i, fut in enumerate(as_completed(futures), 1): |
| 614 | b = futures[fut] | 659 | b = futures[fut] |
| 615 | try: | 660 | try: |
diff --git a/tools/chain_check.py b/tools/chain_check.py new file mode 100644 index 000000000..5405e8f50 --- /dev/null +++ b/tools/chain_check.py | |||
| @@ -0,0 +1,776 @@ | |||
| 1 | """One page of counts for the whole shader chain of a work folder: tools, disassembly and translation per family, the | ||
| 2 | contract with the runtime and, from a run's log, what the runtime made of it. One block per link, each with a verdict | ||
| 3 | (OK / WARN / FAIL) and its most likely cause, then the weakest link. | ||
| 4 | |||
| 5 | python -I tools/chain_check.py <work folder> [--log RUN.log] [--no-probe] [--json] [--strict] [--show-paths] | ||
| 6 | |||
| 7 | The links fail quietly one by one: an llvm-mc whose gfx1013 decoder rejects words leaves programs untranslated | ||
| 8 | without a warning (#1923), a translation made by older translator sources keeps loading after main changed the | ||
| 9 | contract (#2098, "descriptor_table": "tagged"), and the runtime's slot-67 refusals and failed CreatePipelineState | ||
| 10 | calls sit in a log of a million lines. This page puts the counts side by side. | ||
| 11 | |||
| 12 | Reads, in the work folder (make_game.py's layout): | ||
| 13 | |||
| 14 | * shaders/<family>/index.json (and dxbc/fssm_index.json): what was unpacked, with `invalid_words` where the | ||
| 15 | unpacker records them; shaders/<family>/disasm/*.s: the listings; | ||
| 16 | * shaders/spirv[/<family>]/index.json and the .spv beside it: what was translated, with each module's | ||
| 17 | `descriptor_table`; translation_sources.sha256 and <family>_build.json: the llvm-mc and the translator sources | ||
| 18 | the translation was made with; shaders/dxbc/disasm.done: the llvm-mc of the game's disassembly; | ||
| 19 | * logs/shaders.log: the translator's own refusal reasons of the latest run per family (optional); | ||
| 20 | * --log: a gta6rt stderr log (scripts/windows-boot/boot.ps1's <Name>.log), with <Name>.stdout.log and | ||
| 21 | <Name>.digest.txt beside it when they are there. | ||
| 22 | |||
| 23 | Verdicts (also in --help): | ||
| 24 | |||
| 25 | * tools: FAIL with no llvm-mc record or one without the AMDGPU (amdgcn) target; WARN for an llvm-mc older than | ||
| 26 | GOOD_LLVM_MAJOR (23, the version #1923 measured reading the library), for families made with different llvm-mc | ||
| 27 | versions or with another one than LLVM_MC names now, for a translation made by other translator sources than this | ||
| 28 | checkout's (make_game.py's translation_sources_digest()), and for no spirv-val on PATH. | ||
| 29 | * a family: OK when every unpacked program has a module; WARN when at most FAIL_FRACTION (1 %) of them have none | ||
| 30 | (99 of 100 is WARN, 197 of 200 is FAIL) or when there are more modules than programs; FAIL above that, with no | ||
| 31 | readable index, or with no translated index (named "in progress or interrupted" when shard files are there); n/a | ||
| 32 | when the work folder does not hold that family. An index entry whose .spv is missing does not count as translated. | ||
| 33 | * contract: WARN for mixed tagged and plain modules, for only plain modules when the translator's default is tagged | ||
| 34 | (#2098), and for no fspx_compute/ while library programs are untranslated. | ||
| 35 | * runtime: FAIL for a device loss or fault, a failed device slot call, no translated-shaders line or a non-zero exit | ||
| 36 | code; WARN for "device-fault: submitted dispatch" lines alone (a stall prints them too), for failed or unsupported | ||
| 37 | D3D12 calls and for a loaded module count other than the work folder's. The log may be UTF-8 or UTF-16 with or | ||
| 38 | without a BOM (detected from its zero bytes). | ||
| 39 | |||
| 40 | The weakest link is the first block, in chain order, with the worst verdict. The exit code is 0 whatever the | ||
| 41 | verdicts (this is a report); --strict exits 1 when a block is FAIL. Bad arguments exit 2. | ||
| 42 | |||
| 43 | It prints counts, verdicts, versions, short digests and the translator's and runtime's own fixed words, never a | ||
| 44 | program name, a path or a log line (AGENTS.md, "No game data"). Each free-text field is closed against the sources: | ||
| 45 | a refusal reason is printed only when it matches one of the messages rdna2spirv.py raises (read from its source), | ||
| 46 | each variable part kept only when it is an instruction of rdna2_isa_tables.py (encoding suffix _dpp, _sdwa, _e32 or | ||
| 47 | _e64 removed) or a built-in exception name and printed as "#" otherwise, and the whole reason is "other" when it | ||
| 48 | matches no message; a D3D12 trace method is printed only when it is a string literal of runtime/shims or | ||
| 49 | runtime/src (or Interface::Method built from them), else "(other)"; boot.ps1's ending only in its three forms, else | ||
| 50 | "other". The work folder and log paths appear only with --show-paths. | ||
| 51 | Standard library only. It runs nothing heavy: with probing on (the default) it asks llvm-mc and spirv-val for | ||
| 52 | --version, and git for the current commit; --no-probe runs nothing. A partial or empty work folder gives n/a blocks. | ||
| 53 | """ | ||
| 54 | from __future__ import annotations | ||
| 55 | |||
| 56 | import argparse | ||
| 57 | import ast | ||
| 58 | import builtins | ||
| 59 | import functools | ||
| 60 | import hashlib | ||
| 61 | import json | ||
| 62 | import os | ||
| 63 | import re | ||
| 64 | import shutil | ||
| 65 | import subprocess | ||
| 66 | import sys | ||
| 67 | from collections import Counter | ||
| 68 | |||
| 69 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 70 | ROOT = os.path.dirname(HERE) | ||
| 71 | |||
| 72 | OK, WARN, FAIL, NA = "OK", "WARN", "FAIL", "n/a" | ||
| 73 | RANK = {NA: -1, OK: 0, WARN: 1, FAIL: 2} | ||
| 74 | # The llvm-mc major whose gfx1013 decoder reads the pipeline library (#1923 measured 21.1.8 against 23.1.5). | ||
| 75 | GOOD_LLVM_MAJOR = 23 | ||
| 76 | # A family with untranslated programs is WARN up to this fraction of its programs, FAIL above it. | ||
| 77 | FAIL_FRACTION = 0.01 | ||
| 78 | VERDICTS = (f"Verdicts: a family is OK when every program has a module, WARN up to {FAIL_FRACTION:.0%} untranslated, " | ||
| 79 | f"FAIL above; tools are WARN for llvm-mc older than {GOOD_LLVM_MAJOR} or a stale translator digest, FAIL " | ||
| 80 | "with no llvm-mc record or no AMDGPU target; the runtime is FAIL for a failed device slot call, a device " | ||
| 81 | "loss or a non-zero exit. Exit code 0 (a report), 1 with --strict when a block is FAIL, 2 for bad " | ||
| 82 | "arguments.") | ||
| 83 | # (key, label, folder under shaders/, folder under shaders/spirv/, build settings file) | ||
| 84 | FAMILIES = ( | ||
| 85 | ("game", "game programs (shaders.rpf)", "dxbc", "", None), | ||
| 86 | ("library", "pipeline library compute", "library", "library", "library_build.json"), | ||
| 87 | ("fspx", "FidelityFX FSPX", "fspx", "fspx", "fspx_build.json"), | ||
| 88 | ("bvh", "BVH builder", "bvh", "bvh", "bvh_build.json"), | ||
| 89 | ("exe", "executable", "exe", "exe", "exe_build.json"), | ||
| 90 | ) | ||
| 91 | # The sub-folders the runtime's ShaderLibrary::load() reads (runtime/src/shader_library.h). | ||
| 92 | RUNTIME_FOLDERS = ("fspx", "fspx_compute", "fspx_gfx", "bvh", "exe", "library") | ||
| 93 | |||
| 94 | CMD = re.compile(r"rdna2spirv\.py\s+(\S+)") | ||
| 95 | SUMMARY = re.compile(r"^\s*(\d+) shaders: (\d+) translated, (\d+) ") | ||
| 96 | REASON = re.compile(r"^\s*(\d+)\s{2,}(\S.{0,300}?)\s*$") # free text here: normalize_reason() closes it | ||
| 97 | LLVM_VERSION = re.compile(r"LLVM version (\d+)(?:\.(\d+))?(?:\.(\d+))?") | ||
| 98 | SPIRV_VAL_VERSION = re.compile(r"(v\d{4}\.\d+)") | ||
| 99 | DEFAULT_TABLE = re.compile(r'"--descriptor-table",\s*choices=DESCRIPTOR_TABLES,\s*default="(\w+)"') | ||
| 100 | |||
| 101 | LOADED = re.compile(r"\[rt\] d3d12: (\d+) translated shaders \((\d+) fspx, (\d+) fspx_compute, (\d+) fspx_gfx, " | ||
| 102 | r"(\d+) bvh, (\d+) exe\)") | ||
| 103 | TABLE_ALL = re.compile(r"\[rt\] d3d12: descriptor table: (plain|tagged) \(all (\d+) modules\)") | ||
| 104 | TABLE_MIX = re.compile(r"\[rt\] d3d12: descriptor table: (\d+) tagged / (\d+) plain modules; using (plain|tagged)") | ||
| 105 | TABLE_FORCED = re.compile(r"\[rt\] d3d12: descriptor table: (plain|tagged) \(LEONIDA_DESCRIPTOR_TABLE; (\d+) tagged / " | ||
| 106 | r"(\d+) plain modules\)") | ||
| 107 | SLOT_FAIL = re.compile(r"\[rt\] d3d12_xs: slot (\d+) call \d+ failed with (0x[0-9a-fA-F]{8})") | ||
| 108 | NO_COMPUTE = re.compile(r"\[rt\] d3d12: no translated compute shader for ") | ||
| 109 | BUILD_START = re.compile(r"\[rt\] d3d12: compute pipeline \S+ \(\d+ B SPIR-V, [^)]*\) build starts") | ||
| 110 | # "to build" is the line of older logs. The line now names where the pipeline came from, and only a compile is a build. | ||
| 111 | BUILD_SLOW = re.compile(r"\[rt\] d3d12: compute pipeline \S+ took [0-9.]+ s to (?:build|obtain from a compile) ") | ||
| 112 | TRACE = re.compile(r"\[d3d12-trace\] #\d+ (.+) (failed|unsupported|refused|partial)\s*$") | ||
| 113 | GATE = re.compile(r"\[rt\] submit-lock: thread \d+ is waiting at the compile gate") | ||
| 114 | STALL = re.compile(r"\[rt\] device-fault: submitted dispatch ") # also printed for a plain stall | ||
| 115 | FAULT = re.compile(r"\[rt\] device-fault: (?!enabled|submitted dispatch )") | ||
| 116 | LOST = re.compile(r"VK_ERROR_DEVICE_LOST") | ||
| 117 | EXITED = re.compile(r"game exited with code (-?\d+)") | ||
| 118 | # A trace method is printed only when it is a string literal of the runtime's sources, or Interface::Method / | ||
| 119 | # Interface::Slot<N> built from one (d3d12_xs_device.cpp, child_trace_name()); anything else is "(other)". | ||
| 120 | COMPOSED_METHOD = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)::([A-Za-z_][A-Za-z0-9_]*)$") | ||
| 121 | C_STRING = re.compile(r'"((?:[^"\\\n]|\\.){1,120})"') | ||
| 122 | RUNTIME_SOURCE_DIRS = ("runtime/shims", "runtime/src") | ||
| 123 | # A variable part of a refusal reason is kept only when it is an instruction of tools/rdna2_isa_tables.py (with a | ||
| 124 | # _dpp, _sdwa, _e32 or _e64 encoding suffix removed first) or a built-in exception name; else it is "#". | ||
| 125 | MNEMONIC = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$") | ||
| 126 | ISA_NAME = re.compile(r"'([a-z][a-z0-9]*(?:_[a-z0-9]+)+)'") | ||
| 127 | ISA_SUFFIX = re.compile(r"_(?:dpp|sdwa|e32|e64)$") | ||
| 128 | UNSUPPORTED_CALL = re.compile(r"(?<![\w.])Unsupported\(") | ||
| 129 | # The three verdicts scripts/windows-boot/boot.ps1 writes on its digest's first line; anything else is "other". | ||
| 130 | ENDINGS = (re.compile(r"^ran its full time limit \(\d+ s\), stopped$"), | ||
| 131 | re.compile(r"^exited by itself after \d+ s, exit code (?:unknown|(-?\d+) \(0x[0-9a-f]{8}\))$"), | ||
| 132 | re.compile(r"^digest of an earlier run \(-DigestOnly\)$")) | ||
| 133 | |||
| 134 | |||
| 135 | # ------------------------------------------------------------------------------------------------ reading helpers | ||
| 136 | def load_json(path: str): | ||
| 137 | try: | ||
| 138 | with open(path, encoding="utf-8-sig") as f: | ||
| 139 | return json.load(f) | ||
| 140 | except (OSError, ValueError): | ||
| 141 | return None | ||
| 142 | |||
| 143 | |||
| 144 | def read_utf8(path: str) -> str | None: | ||
| 145 | try: | ||
| 146 | with open(path, encoding="utf-8-sig", errors="replace") as f: | ||
| 147 | return f.read().strip() | ||
| 148 | except OSError: | ||
| 149 | return None | ||
| 150 | |||
| 151 | |||
| 152 | def log_encoding(path: str) -> str: | ||
| 153 | """UTF-8, or UTF-16 with a BOM (PowerShell 5.1 redirection) or without one: ASCII text in UTF-16 has a zero in | ||
| 154 | every other byte, little-endian at the odd offsets.""" | ||
| 155 | with open(path, "rb") as f: | ||
| 156 | head = f.read(4096) | ||
| 157 | if head[:2] in (b"\xff\xfe", b"\xfe\xff"): | ||
| 158 | return "utf-16" | ||
| 159 | if head.count(0) * 4 >= len(head) > 0: | ||
| 160 | return "utf-16-le" if head[1::2].count(0) >= head[0::2].count(0) else "utf-16-be" | ||
| 161 | return "utf-8" | ||
| 162 | |||
| 163 | |||
| 164 | def log_lines(path: str): | ||
| 165 | """The lines of a log in the encoding log_encoding() finds.""" | ||
| 166 | with open(path, encoding=log_encoding(path), errors="replace") as f: | ||
| 167 | yield from f | ||
| 168 | |||
| 169 | |||
| 170 | def _safe_lines(path: str): | ||
| 171 | """log_lines(), ending quietly at an unreadable file instead of raising.""" | ||
| 172 | try: | ||
| 173 | yield from log_lines(path) | ||
| 174 | except (OSError, UnicodeError): | ||
| 175 | return | ||
| 176 | |||
| 177 | |||
| 178 | def listing_count(folder: str) -> int | None: | ||
| 179 | try: | ||
| 180 | with os.scandir(folder) as entries: | ||
| 181 | return sum(1 for e in entries if e.name.endswith(".s") and e.is_file() and e.stat().st_size > 0) | ||
| 182 | except OSError: | ||
| 183 | return None | ||
| 184 | |||
| 185 | |||
| 186 | def shard_parts(spirv: str) -> int: | ||
| 187 | """The shard plans and index parts make_game.py's translate() leaves while a translation runs or once it stopped.""" | ||
| 188 | try: | ||
| 189 | with os.scandir(spirv) as entries: | ||
| 190 | return sum(1 for e in entries if re.fullmatch(r"(?:shard\d+|index\.part\d+)\.json", e.name)) | ||
| 191 | except OSError: | ||
| 192 | return 0 | ||
| 193 | |||
| 194 | |||
| 195 | def pct(part: int, whole: int) -> str: | ||
| 196 | return f"{100.0 * part / whole:.1f}%" if whole else "-" | ||
| 197 | |||
| 198 | |||
| 199 | def short(digest: str | None) -> str: | ||
| 200 | return digest[:12] if isinstance(digest, str) and digest else "none" | ||
| 201 | |||
| 202 | |||
| 203 | # ------------------------------------------------------------------------------------------------ repository side | ||
| 204 | def repo_translation_digest(root: str = ROOT) -> str | None: | ||
| 205 | """make_game.py's translation_sources_digest(), computed without importing make_game.py: the TRANSLATION_SOURCES | ||
| 206 | tuple is read from its source, then SHA-256 over each file's name, length and bytes (sources_digest()).""" | ||
| 207 | try: | ||
| 208 | with open(os.path.join(root, "make_game.py"), encoding="utf-8") as f: | ||
| 209 | tree = ast.parse(f.read()) | ||
| 210 | except (OSError, SyntaxError): | ||
| 211 | return None | ||
| 212 | names = None | ||
| 213 | for node in tree.body: | ||
| 214 | if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == "TRANSLATION_SOURCES" for t in node.targets): | ||
| 215 | names = ast.literal_eval(node.value) | ||
| 216 | if not names: | ||
| 217 | return None | ||
| 218 | h = hashlib.sha256(b"") | ||
| 219 | try: | ||
| 220 | for name in names: | ||
| 221 | with open(os.path.join(root, "tools", name), "rb") as f: | ||
| 222 | data = f.read() | ||
| 223 | h.update(f"{name}\0{len(data)}\0".encode()) | ||
| 224 | h.update(data) | ||
| 225 | except OSError: | ||
| 226 | return None | ||
| 227 | return h.hexdigest() | ||
| 228 | |||
| 229 | |||
| 230 | def translator_default_table(root: str = ROOT) -> str | None: | ||
| 231 | text = read_utf8(os.path.join(root, "tools", "rdna2spirv.py")) or "" | ||
| 232 | m = DEFAULT_TABLE.search(text) | ||
| 233 | return m.group(1) if m else None | ||
| 234 | |||
| 235 | |||
| 236 | def run_quiet(command: list[str], timeout: int = 20) -> str | None: | ||
| 237 | try: | ||
| 238 | r = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=timeout) | ||
| 239 | except (OSError, subprocess.SubprocessError): | ||
| 240 | return None | ||
| 241 | return (r.stdout + r.stderr).strip() if r.returncode == 0 else None | ||
| 242 | |||
| 243 | |||
| 244 | def parse_llvm(text: str | None) -> dict: | ||
| 245 | """Version and AMDGPU target from an llvm-mc --version text, or from make_game.py's signature (a JSON pair).""" | ||
| 246 | command = None | ||
| 247 | if text and text.startswith("["): | ||
| 248 | try: | ||
| 249 | command, text = json.loads(text) | ||
| 250 | except (ValueError, TypeError): | ||
| 251 | pass | ||
| 252 | m = LLVM_VERSION.search(text or "") | ||
| 253 | program = os.path.basename(str(command[-1])) if isinstance(command, list) and command else None | ||
| 254 | via = "wsl" if isinstance(command, list) and any("wsl" in str(c).lower() for c in command[:1]) else None | ||
| 255 | return {"version": ".".join(g for g in m.groups() if g) if m else None, | ||
| 256 | "major": int(m.group(1)) if m else None, | ||
| 257 | "amdgpu": ("amdgcn" in text) if text else None, | ||
| 258 | "program": program, "via": via} | ||
| 259 | |||
| 260 | |||
| 261 | # ------------------------------------------------------------------------------------------------ refusal reasons | ||
| 262 | def _pattern(node) -> list: | ||
| 263 | """An Unsupported(...) message as a list of literal strings, with None for each variable part.""" | ||
| 264 | if isinstance(node, ast.Constant) and isinstance(node.value, str): | ||
| 265 | return [node.value] | ||
| 266 | if isinstance(node, ast.JoinedStr): | ||
| 267 | return [v.value if isinstance(v, ast.Constant) else None for v in node.values] | ||
| 268 | if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): | ||
| 269 | return _pattern(node.left) + _pattern(node.right) | ||
| 270 | return [None] | ||
| 271 | |||
| 272 | |||
| 273 | def _unsupported_args(source: str): | ||
| 274 | """The first argument of each Unsupported(...) call in source. Each call is parsed on its own (the shortest text | ||
| 275 | up to a closing parenthesis that parses), since parsing the whole 20,000-line translator takes seconds.""" | ||
| 276 | for m in UNSUPPORTED_CALL.finditer(source): | ||
| 277 | start = m.end() | ||
| 278 | end = start | ||
| 279 | while (end := source.find(")", end + 1 if end > start else start)) != -1 and end - start < 2000: | ||
| 280 | try: | ||
| 281 | call = ast.parse("f(" + source[start:end] + ")", mode="eval").body | ||
| 282 | except SyntaxError: | ||
| 283 | continue | ||
| 284 | if isinstance(call, ast.Call) and call.args: | ||
| 285 | yield call.args[0] | ||
| 286 | break | ||
| 287 | |||
| 288 | |||
| 289 | @functools.lru_cache(maxsize=4) | ||
| 290 | def reason_templates(root: str = ROOT) -> tuple: | ||
| 291 | """The refusal messages rdna2spirv.py counts, as (regex, parts) pairs with the most literal text first, plus its | ||
| 292 | "translator error <exception>" count. Empty when the translator's source cannot be read.""" | ||
| 293 | try: | ||
| 294 | with open(os.path.join(root, "tools", "rdna2spirv.py"), encoding="utf-8") as f: | ||
| 295 | source = f.read() | ||
| 296 | except (OSError, ValueError): | ||
| 297 | return () | ||
| 298 | found = {("translator error ", None)} | ||
| 299 | for arg in _unsupported_args(source): | ||
| 300 | merged = [] | ||
| 301 | for part in _pattern(arg): # adjacent variable parts are one | ||
| 302 | if not (part is None and merged and merged[-1] is None): | ||
| 303 | merged.append(part) | ||
| 304 | found.add(tuple(merged)) | ||
| 305 | templates = [(re.compile("^" + "".join("(.+?)" if p is None else re.escape(p) for p in parts) + "$"), parts) | ||
| 306 | for parts in found] | ||
| 307 | templates.sort(key=lambda t: (-sum(len(p) for p in t[1] if p), t[0].pattern)) | ||
| 308 | return tuple(templates) | ||
| 309 | |||
| 310 | |||
| 311 | @functools.lru_cache(maxsize=4) | ||
| 312 | def isa_names(root: str = ROOT) -> frozenset: | ||
| 313 | """The instruction names of tools/rdna2_isa_tables.py (empty when it cannot be read).""" | ||
| 314 | try: | ||
| 315 | with open(os.path.join(root, "tools", "rdna2_isa_tables.py"), encoding="utf-8") as f: | ||
| 316 | return frozenset(ISA_NAME.findall(f.read())) | ||
| 317 | except (OSError, ValueError): | ||
| 318 | return frozenset() | ||
| 319 | |||
| 320 | |||
| 321 | def known_value(value: str) -> bool: | ||
| 322 | """A variable part that may be printed: an ISA instruction of the decoder's tables or a built-in exception.""" | ||
| 323 | if MNEMONIC.match(value) and ISA_SUFFIX.sub("", value) in isa_names(): | ||
| 324 | return True | ||
| 325 | builtin = getattr(builtins, value, None) | ||
| 326 | return isinstance(builtin, type) and issubclass(builtin, BaseException) | ||
| 327 | |||
| 328 | |||
| 329 | @functools.lru_cache(maxsize=4) | ||
| 330 | def runtime_literals(root: str = ROOT) -> frozenset: | ||
| 331 | """Every short C string literal in the runtime's sources: the closed set a trace method name must come from.""" | ||
| 332 | found = set() | ||
| 333 | for folder in RUNTIME_SOURCE_DIRS: | ||
| 334 | for dirpath, _, files in os.walk(os.path.join(root, folder)): | ||
| 335 | for name in files: | ||
| 336 | if name.endswith((".cpp", ".h", ".hpp", ".inl")): | ||
| 337 | try: | ||
| 338 | with open(os.path.join(dirpath, name), encoding="utf-8", errors="replace") as f: | ||
| 339 | found.update(C_STRING.findall(f.read())) | ||
| 340 | except OSError: | ||
| 341 | continue | ||
| 342 | return frozenset(found) | ||
| 343 | |||
| 344 | |||
| 345 | def trace_method(method: str) -> str: | ||
| 346 | """The method of a [d3d12-trace] line when the runtime's sources name it, else "(other)".""" | ||
| 347 | literals = runtime_literals() | ||
| 348 | if method in literals: | ||
| 349 | return method | ||
| 350 | m = COMPOSED_METHOD.match(method) | ||
| 351 | if m and m.group(1) in literals and (m.group(2) in literals or re.fullmatch(r"Slot\d{1,3}", m.group(2))): | ||
| 352 | return method | ||
| 353 | return "(other)" | ||
| 354 | |||
| 355 | |||
| 356 | def normalize_reason(reason: str, templates: list) -> str: | ||
| 357 | """The reason when it is one of the translator's messages, each variable part kept only when known_value() (else | ||
| 358 | "#"); "other" for anything else.""" | ||
| 359 | for regex, parts in templates: | ||
| 360 | m = regex.match(reason) | ||
| 361 | if not m: | ||
| 362 | continue | ||
| 363 | values = iter(m.groups()) | ||
| 364 | out = [] | ||
| 365 | for part in parts: | ||
| 366 | if part is None: | ||
| 367 | value = next(values) | ||
| 368 | part = value if known_value(value) else "#" | ||
| 369 | out.append(part) | ||
| 370 | text = "".join(out) | ||
| 371 | # A message that is only a variable part (Unsupported(op)) says nothing once that part is masked. | ||
| 372 | return "other" if not text.strip("# ") else text | ||
| 373 | return "other" | ||
| 374 | |||
| 375 | |||
| 376 | # ------------------------------------------------------------------------------------------------ the build log | ||
| 377 | def family_of(disasm_path: str) -> str | None: | ||
| 378 | parts = [p for p in re.split(r"[\\/]+", disasm_path.lower()) if p] | ||
| 379 | parent = parts[-2] if len(parts) >= 2 else "" | ||
| 380 | return {"dxbc": "game", "library": "library", "fspx": "fspx", "bvh": "bvh", "exe": "exe"}.get(parent) | ||
| 381 | |||
| 382 | |||
| 383 | def parse_build_log(path: str, templates: list | None = None) -> dict: | ||
| 384 | """The latest translator run of each family in logs/shaders.log: programs, translated, and refusals by reason. | ||
| 385 | A run starts at an rdna2spirv.py command line (not --merge) and its shards' summaries follow it.""" | ||
| 386 | runs: dict = {} | ||
| 387 | current = None | ||
| 388 | in_reasons = False | ||
| 389 | try: | ||
| 390 | lines = log_lines(path) | ||
| 391 | for line in lines: | ||
| 392 | m = CMD.search(line) | ||
| 393 | if m and "--merge" not in line: | ||
| 394 | current = family_of(m.group(1)) | ||
| 395 | if current: | ||
| 396 | runs[current] = {"programs": 0, "translated": 0, "valid": 0, "reasons": Counter()} | ||
| 397 | in_reasons = False | ||
| 398 | continue | ||
| 399 | m = SUMMARY.match(line) | ||
| 400 | if m and current: | ||
| 401 | run = runs[current] | ||
| 402 | run["programs"] += int(m.group(1)) | ||
| 403 | run["translated"] += int(m.group(2)) | ||
| 404 | run["valid"] += int(m.group(3)) | ||
| 405 | in_reasons = True | ||
| 406 | continue | ||
| 407 | if in_reasons and current: | ||
| 408 | m = REASON.match(line) | ||
| 409 | if m: | ||
| 410 | reason = normalize_reason(m.group(2), templates or []) | ||
| 411 | runs[current]["reasons"][reason] += int(m.group(1)) | ||
| 412 | continue | ||
| 413 | in_reasons = False | ||
| 414 | except (OSError, UnicodeError): | ||
| 415 | return {} | ||
| 416 | return runs | ||
| 417 | |||
| 418 | |||
| 419 | # ------------------------------------------------------------------------------------------------ the blocks | ||
| 420 | def tools_block(work: str, probe: bool) -> dict: | ||
| 421 | sh = os.path.join(work, "shaders") | ||
| 422 | records = {} | ||
| 423 | done = load_json(os.path.join(sh, "dxbc", "disasm.done")) | ||
| 424 | if isinstance(done, dict) and isinstance(done.get("llvm"), str): | ||
| 425 | records["game"] = parse_llvm(done["llvm"]) | ||
| 426 | translator = {"game": read_utf8(os.path.join(sh, "spirv", "translation_sources.sha256"))} | ||
| 427 | for key, _, _, spirv_sub, settings in FAMILIES: | ||
| 428 | if not settings: | ||
| 429 | continue | ||
| 430 | s = load_json(os.path.join(sh, "spirv", spirv_sub, settings)) | ||
| 431 | if isinstance(s, dict): | ||
| 432 | if isinstance(s.get("llvm_mc"), str): | ||
| 433 | records[key] = parse_llvm(s["llvm_mc"]) | ||
| 434 | translator[key] = s.get("translator") | ||
| 435 | versions = Counter(r["version"] or "?" for r in records.values()) | ||
| 436 | repo = repo_translation_digest() | ||
| 437 | translator = {k: v for k, v in translator.items() if isinstance(v, str) and v} | ||
| 438 | local = Counter(short(v) for v in translator.values()) | ||
| 439 | stale = sorted(k for k, v in translator.items() if repo and v != repo) | ||
| 440 | current = spirv_val = head = None | ||
| 441 | if probe: | ||
| 442 | sys.path.insert(0, HERE) | ||
| 443 | try: | ||
| 444 | from mc_command import mc_command | ||
| 445 | command = mc_command() | ||
| 446 | command[0] = shutil.which(command[0]) or command[0] | ||
| 447 | text = run_quiet([*command, "--version"]) | ||
| 448 | current = parse_llvm(text) if text else {"version": None} | ||
| 449 | except (Exception, SystemExit): # noqa: BLE001 - a broken LLVM_MC is reported, not raised | ||
| 450 | current = {"version": None} | ||
| 451 | exe = shutil.which("spirv-val") | ||
| 452 | text = run_quiet([exe, "--version"]) if exe else None | ||
| 453 | m = SPIRV_VAL_VERSION.search(text or "") | ||
| 454 | spirv_val = (m.group(1) if m else "found, version unread") if exe else "not found" | ||
| 455 | head = run_quiet(["git", "-C", ROOT, "rev-parse", "--short", "HEAD"]) | ||
| 456 | verdict, causes = OK, [] | ||
| 457 | majors = {r["major"] for r in records.values()} | ||
| 458 | if not records and not translator: | ||
| 459 | verdict, causes = NA, ["nothing disassembled or translated in this work folder"] | ||
| 460 | elif not records: | ||
| 461 | verdict, causes = FAIL, ["no llvm-mc record in the work folder (disassembly never finished)"] | ||
| 462 | elif any(r["amdgpu"] is False for r in records.values()): | ||
| 463 | verdict, causes = FAIL, ["a recorded llvm-mc has no AMDGPU (amdgcn) target"] | ||
| 464 | else: | ||
| 465 | old = {k: r["version"] for k, r in records.items() if r["major"] is not None and r["major"] < GOOD_LLVM_MAJOR} | ||
| 466 | if old: | ||
| 467 | verdict = WARN | ||
| 468 | causes.append(f"llvm-mc {'/'.join(sorted(set(old.values())))} (used for {', '.join(sorted(old))}) " | ||
| 469 | f"predates {GOOD_LLVM_MAJOR}: its gfx1013 decoder rejects words the library needs (#1923)") | ||
| 470 | if len(versions) > 1: | ||
| 471 | verdict = WARN | ||
| 472 | causes.append("families were disassembled with different llvm-mc versions") | ||
| 473 | if current and current.get("version") and current["version"] not in versions: | ||
| 474 | verdict = WARN | ||
| 475 | causes.append(f"llvm-mc now on LLVM_MC is {current['version']}: the folder was made with another") | ||
| 476 | if stale and verdict != NA: | ||
| 477 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 478 | causes.append(f"translation of {', '.join(stale)} made by other translator sources than this checkout's " | ||
| 479 | "(make_game.py shaders translates again)") | ||
| 480 | if spirv_val == "not found" and verdict != NA: | ||
| 481 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 482 | causes.append("spirv-val not on PATH") | ||
| 483 | return {"name": "tools", "verdict": verdict, "cause": "; ".join(causes) or "-", | ||
| 484 | "_majors": {k: r["major"] for k, r in records.items()}, | ||
| 485 | "llvm_mc_recorded": dict(versions), "llvm_mc_records": len(records), | ||
| 486 | "llvm_mc_amdgpu": (False if any(r["amdgpu"] is False for r in records.values()) else | ||
| 487 | True if records and all(r["amdgpu"] for r in records.values()) else None), | ||
| 488 | "llvm_mc_via": sorted({r["via"] or "native" for r in records.values()}), | ||
| 489 | "llvm_mc_current": (current or {}).get("version") if probe else NA, | ||
| 490 | "spirv_val": spirv_val if probe else NA, | ||
| 491 | "translator_local": dict(local), "translator_repo": short(repo), "repo_head": head, | ||
| 492 | "translator_stale": stale} | ||
| 493 | |||
| 494 | |||
| 495 | def family_block(work: str, key: str, label: str, folder: str, spirv_sub: str, build: dict, llvm_major) -> dict: | ||
| 496 | sh = os.path.join(work, "shaders") | ||
| 497 | unpacked = os.path.join(sh, folder) | ||
| 498 | block = {"name": key, "label": label} | ||
| 499 | if not os.path.isdir(unpacked): | ||
| 500 | block.update(verdict=NA, cause="not unpacked in this work folder") | ||
| 501 | return block | ||
| 502 | index = load_json(os.path.join(unpacked, "fssm_index.json" if key == "game" else "index.json")) | ||
| 503 | expected = len(index) if isinstance(index, (list, dict)) else None | ||
| 504 | rejected = None | ||
| 505 | if isinstance(index, list) and index and isinstance(index[0], dict) and "invalid_words" in index[0]: | ||
| 506 | rejected = sum(1 for e in index if isinstance(e, dict) and isinstance(e.get("invalid_words"), int) | ||
| 507 | and e["invalid_words"] > 0) | ||
| 508 | listings = listing_count(os.path.join(unpacked, "disasm")) | ||
| 509 | spirv = os.path.join(sh, "spirv", spirv_sub) if spirv_sub else os.path.join(sh, "spirv") | ||
| 510 | translated_index = load_json(os.path.join(spirv, "index.json")) | ||
| 511 | translated = no_module = None | ||
| 512 | tables = Counter() | ||
| 513 | if isinstance(translated_index, dict): | ||
| 514 | present = [n for n in translated_index if n and os.path.isfile(os.path.join(spirv, n + ".spv"))] | ||
| 515 | translated, no_module = len(present), len(translated_index) - len(present) | ||
| 516 | tables = Counter(m["descriptor_table"] if isinstance(m, dict) and m.get("descriptor_table") == "tagged" | ||
| 517 | else "plain" for m in translated_index.values()) | ||
| 518 | run = build.get(key) | ||
| 519 | reasons = run["reasons"].most_common(5) if run else [] | ||
| 520 | block.update(expected=expected, listings=listings, listings_with_rejected_words=rejected, | ||
| 521 | translated=translated, modules_missing=no_module, tables=dict(tables), | ||
| 522 | reasons=[[n, r] for r, n in reasons], | ||
| 523 | log_run=({"programs": run["programs"], "translated": run["translated"]} if run else None)) | ||
| 524 | if expected is None: | ||
| 525 | block.update(verdict=FAIL, cause="no readable unpack index") | ||
| 526 | elif translated is None: | ||
| 527 | parts = shard_parts(spirv) | ||
| 528 | block.update(verdict=FAIL, cause=f"no translated index: translation in progress or interrupted ({parts} shard " | ||
| 529 | "files)" if parts else "no translated index (translation never finished)") | ||
| 530 | else: | ||
| 531 | failed = max(expected - translated, 0) | ||
| 532 | block.update(failed=failed, percent=pct(translated, expected)) | ||
| 533 | if translated > expected: | ||
| 534 | block.update(verdict=WARN, cause=f"{translated - expected} more modules than unpacked programs " | ||
| 535 | "(a translation from another unpack?)") | ||
| 536 | elif failed == 0 and not no_module: | ||
| 537 | block.update(verdict=OK, cause="-") | ||
| 538 | else: | ||
| 539 | block["verdict"] = WARN if failed <= expected * FAIL_FRACTION and not no_module else FAIL | ||
| 540 | top = reasons[0][0] if reasons else None | ||
| 541 | if top and "undecodable" in top and llvm_major is not None and llvm_major < GOOD_LLVM_MAJOR: | ||
| 542 | cause = f"llvm-mc {llvm_major}.x leaves undecodable words ({reasons[0][1]} refusals; #1923)" | ||
| 543 | elif top: | ||
| 544 | cause = f"translator refusal: {top} ({reasons[0][1]})" | ||
| 545 | elif no_module: | ||
| 546 | cause = f"{no_module} index entries without their .spv" | ||
| 547 | else: | ||
| 548 | cause = "untranslated, no reason in logs/shaders.log" | ||
| 549 | block["cause"] = cause | ||
| 550 | return block | ||
| 551 | |||
| 552 | |||
| 553 | def contract_block(work: str, families: list[dict]) -> dict: | ||
| 554 | spirv = os.path.join(work, "shaders", "spirv") | ||
| 555 | default = translator_default_table() | ||
| 556 | tables = Counter() | ||
| 557 | for f in families: | ||
| 558 | tables.update(f.get("tables") or {}) | ||
| 559 | folders = {name: os.path.isfile(os.path.join(spirv, name, "index.json")) for name in RUNTIME_FOLDERS} | ||
| 560 | library_failed = next((f.get("failed") or 0 for f in families if f["name"] == "library"), 0) | ||
| 561 | verdict, causes = (OK, []) if tables else (NA, ["no translated modules"]) | ||
| 562 | if tables.get("tagged") and tables.get("plain"): | ||
| 563 | verdict = WARN | ||
| 564 | causes.append("mixed tagged and plain modules: the runtime picks one table for all") | ||
| 565 | elif default == "tagged" and tables and not tables.get("tagged"): | ||
| 566 | verdict = WARN | ||
| 567 | causes.append("every module is plain while this checkout's translator writes tagged (#2098): " | ||
| 568 | "the runtime falls back to the plain table without a word") | ||
| 569 | if tables and not folders["fspx_compute"] and library_failed: | ||
| 570 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 571 | causes.append(f"no fspx_compute/ to cover the {library_failed} untranslated library programs") | ||
| 572 | return {"name": "contract", "verdict": verdict, "cause": "; ".join(causes) or "-", | ||
| 573 | "translator_default_table": default, "modules": dict(tables), | ||
| 574 | "folders_present": [n for n, ok in folders.items() if ok], | ||
| 575 | "folders_absent": [n for n, ok in folders.items() if not ok]} | ||
| 576 | |||
| 577 | |||
| 578 | def runtime_block(path: str, families: list[dict]) -> dict: | ||
| 579 | loaded = table = None | ||
| 580 | slots, trace = Counter(), Counter() | ||
| 581 | counts = Counter() | ||
| 582 | exit_code = None | ||
| 583 | try: | ||
| 584 | encoding = log_encoding(path) | ||
| 585 | except OSError: | ||
| 586 | encoding = None | ||
| 587 | for line in _safe_lines(path): | ||
| 588 | if "[rt]" not in line and "[d3d12-trace]" not in line and "VK_ERROR" not in line and "exited" not in line: | ||
| 589 | continue | ||
| 590 | m = TRACE.search(line) | ||
| 591 | if m: | ||
| 592 | trace[f"{trace_method(m.group(1))} {m.group(2)}"] += 1 | ||
| 593 | continue | ||
| 594 | if loaded is None and (m := LOADED.search(line)): | ||
| 595 | loaded = dict(zip(("total", "fspx", "fspx_compute", "fspx_gfx", "bvh", "exe"), map(int, m.groups()))) | ||
| 596 | elif m := SLOT_FAIL.search(line): | ||
| 597 | slots[f"slot {m.group(1)} {m.group(2).lower()}"] += 1 | ||
| 598 | elif NO_COMPUTE.search(line): | ||
| 599 | counts["no_translated_compute"] += 1 | ||
| 600 | elif BUILD_START.search(line): | ||
| 601 | counts["compute_builds"] += 1 | ||
| 602 | elif BUILD_SLOW.search(line): | ||
| 603 | counts["slow_compute_builds"] += 1 | ||
| 604 | elif GATE.search(line): | ||
| 605 | counts["compile_gate_waits"] += 1 | ||
| 606 | elif STALL.search(line): | ||
| 607 | counts["stalled_dispatch_lines"] += 1 | ||
| 608 | elif FAULT.search(line): | ||
| 609 | counts["device_fault_lines"] += 1 | ||
| 610 | elif m := TABLE_ALL.search(line): | ||
| 611 | table = m.group(1) | ||
| 612 | elif m := TABLE_MIX.search(line): | ||
| 613 | table = f"{m.group(3)} ({m.group(1)} tagged / {m.group(2)} plain)" | ||
| 614 | elif m := TABLE_FORCED.search(line): | ||
| 615 | table = f"{m.group(1)} forced by LEONIDA_DESCRIPTOR_TABLE ({m.group(2)} tagged / {m.group(3)} plain)" | ||
| 616 | if LOST.search(line): | ||
| 617 | counts["device_lost_lines"] += 1 | ||
| 618 | if m := EXITED.search(line): | ||
| 619 | exit_code = int(m.group(1)) | ||
| 620 | stem = path[:-4] if path.lower().endswith(".log") else path | ||
| 621 | if exit_code is None and os.path.isfile(stem + ".stdout.log"): | ||
| 622 | for line in _safe_lines(stem + ".stdout.log"): | ||
| 623 | if m := EXITED.search(line): | ||
| 624 | exit_code = int(m.group(1)) | ||
| 625 | digest = read_utf8(stem + ".digest.txt") | ||
| 626 | ending = None | ||
| 627 | if digest: | ||
| 628 | first = digest.splitlines()[0] | ||
| 629 | ending = first.split(":", 1)[1].strip() if first.startswith("== boot") and ":" in first else None | ||
| 630 | if ending: | ||
| 631 | matched = next((m for m in (e.match(ending) for e in ENDINGS) if m), None) | ||
| 632 | if not matched: | ||
| 633 | ending = "other" | ||
| 634 | elif exit_code is None and matched.groups() and matched.group(1) is not None: | ||
| 635 | exit_code = int(matched.group(1)) | ||
| 636 | local = sum(f.get("translated") or 0 for f in families) | ||
| 637 | library = next((f for f in families if f["name"] == "library"), {}) | ||
| 638 | verdict, causes = OK, [] | ||
| 639 | if counts["device_lost_lines"] or counts["device_fault_lines"]: | ||
| 640 | verdict = FAIL | ||
| 641 | if counts["device_lost_lines"] or counts["device_fault_lines"] or counts["stalled_dispatch_lines"]: | ||
| 642 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 643 | causes.append(f"device lost, faulted or stalled (lost {counts['device_lost_lines']}, fault " | ||
| 644 | f"{counts['device_fault_lines']}, stalled dispatch {counts['stalled_dispatch_lines']} lines)") | ||
| 645 | if slots: | ||
| 646 | verdict = FAIL | ||
| 647 | worst, n = slots.most_common(1)[0] | ||
| 648 | hint = "" | ||
| 649 | if worst.startswith("slot 67") and library.get("failed"): | ||
| 650 | hint = f", against {library['failed']} untranslated library programs" | ||
| 651 | causes.append(f"{sum(slots.values())} device slot calls failed ({worst}: {n}{hint})") | ||
| 652 | failed_pso = sum(n for k, n in trace.items() if k.endswith((" failed", " unsupported", " refused"))) | ||
| 653 | if failed_pso: | ||
| 654 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 655 | causes.append(f"{failed_pso} D3D12 calls failed or unsupported") | ||
| 656 | if loaded is None: | ||
| 657 | verdict = FAIL | ||
| 658 | causes.append("no translated-shaders line (Vulkan device not reached?)" if encoding else | ||
| 659 | "the log could not be read") | ||
| 660 | elif loaded["total"] != local: | ||
| 661 | verdict = max(verdict, WARN, key=RANK.get) | ||
| 662 | causes.append(f"loaded {loaded['total']} modules, the work folder holds {local} (another folder or build?)") | ||
| 663 | if exit_code not in (None, 0): | ||
| 664 | verdict = FAIL | ||
| 665 | causes.append(f"exit code {exit_code}") | ||
| 666 | return {"name": "runtime", "verdict": verdict, "cause": "; ".join(causes) or "-", "loaded": loaded, | ||
| 667 | "descriptor_table": table, "slot_failures": dict(slots.most_common(5)), | ||
| 668 | "d3d12_problems": dict(trace.most_common(5)), "exit_code": exit_code, "ending": ending, | ||
| 669 | "log_encoding": encoding, | ||
| 670 | **{k: counts[k] for k in ("no_translated_compute", "compute_builds", "slow_compute_builds", | ||
| 671 | "compile_gate_waits", "device_fault_lines", "device_lost_lines", | ||
| 672 | "stalled_dispatch_lines")}} | ||
| 673 | |||
| 674 | |||
| 675 | def check(work: str, log: str | None = None, probe: bool = True, show_paths: bool = False) -> dict: | ||
| 676 | tools = tools_block(work, probe) | ||
| 677 | majors = tools.pop("_majors") # the llvm-mc major each family was disassembled with | ||
| 678 | build = parse_build_log(os.path.join(work, "logs", "shaders.log"), reason_templates()) | ||
| 679 | families = [family_block(work, key, label, folder, sub, build, majors.get(key)) | ||
| 680 | for key, label, folder, sub, _ in FAMILIES] | ||
| 681 | blocks = [tools, *families, contract_block(work, families)] | ||
| 682 | if log: | ||
| 683 | blocks.append(runtime_block(log, families)) | ||
| 684 | worst = max(RANK[b["verdict"]] for b in blocks) | ||
| 685 | weakest = next(b for b in blocks if RANK[b["verdict"]] == worst) | ||
| 686 | report = {"blocks": blocks, | ||
| 687 | "weakest": ({"name": weakest["name"], "verdict": weakest["verdict"], "cause": weakest["cause"]} | ||
| 688 | if worst >= 0 else {"name": "none", "verdict": NA, "cause": "nothing to check"})} | ||
| 689 | if show_paths: | ||
| 690 | report.update(work=work, log=log) | ||
| 691 | return report | ||
| 692 | |||
| 693 | |||
| 694 | # ------------------------------------------------------------------------------------------------ text output | ||
| 695 | def fmt_counter(d: dict, joiner: str = "") -> str: | ||
| 696 | sep = f" {joiner} " if joiner else " " | ||
| 697 | return ", ".join(f"{k}{sep}{v}" for k, v in d.items()) or "none" | ||
| 698 | |||
| 699 | |||
| 700 | def render(report: dict) -> str: | ||
| 701 | out = ["chain check" + (f" of {report['work']}" if report.get("work") else "") | ||
| 702 | + (f" with log {report['log']}" if report.get("log") else "")] | ||
| 703 | for b in report["blocks"]: | ||
| 704 | out.append(f"[{b['verdict']}] {b['name']}" + (f" {b['label']}" if b.get("label") else "")) | ||
| 705 | if b["verdict"] == NA: | ||
| 706 | pass | ||
| 707 | elif b["name"] == "tools": | ||
| 708 | recorded = fmt_counter(b["llvm_mc_recorded"], "in") | ||
| 709 | amdgcn = {True: "yes", False: "NO", None: "n/a"}[b["llvm_mc_amdgpu"]] | ||
| 710 | out.append(f" llvm-mc recorded {recorded} ({b['llvm_mc_records']} records, " | ||
| 711 | f"amdgcn {amdgcn}, via {'/'.join(b['llvm_mc_via']) or 'n/a'}); " | ||
| 712 | f"LLVM_MC now {b['llvm_mc_current'] or 'unreadable'}") | ||
| 713 | out.append(f" spirv-val {b['spirv_val']}") | ||
| 714 | local = fmt_counter(b["translator_local"], "in") | ||
| 715 | out.append(f" translator local {local}; checkout {b['translator_repo']}" | ||
| 716 | f"{' at ' + b['repo_head'] if b['repo_head'] else ''}; stale: " | ||
| 717 | f"{', '.join(b['translator_stale']) or 'none'}") | ||
| 718 | elif b["name"] == "contract": | ||
| 719 | out.append(f" modules {fmt_counter(b['modules'])}; translator default {b['translator_default_table']}") | ||
| 720 | out.append(f" folders present {', '.join(b['folders_present']) or 'none'}; absent " | ||
| 721 | f"{', '.join(b['folders_absent']) or 'none'}") | ||
| 722 | elif b["name"] == "runtime": | ||
| 723 | ld = b["loaded"] | ||
| 724 | out.append(" loaded " + (fmt_counter(ld) if ld else "no translated-shaders line") | ||
| 725 | + f"; descriptor table {b['descriptor_table'] or '?'}") | ||
| 726 | out.append(f" slot fails {fmt_counter(b['slot_failures'])}; no translated compute shader " | ||
| 727 | f"{b['no_translated_compute']}") | ||
| 728 | out.append(f" d3d12 {fmt_counter(b['d3d12_problems'])}") | ||
| 729 | out.append(f" pipelines compute builds {b['compute_builds']} (slow {b['slow_compute_builds']}); " | ||
| 730 | f"compile gate waits {b['compile_gate_waits']}") | ||
| 731 | out.append(f" device fault lines {b['device_fault_lines']}, device lost lines " | ||
| 732 | f"{b['device_lost_lines']}, stalled dispatch lines {b['stalled_dispatch_lines']}; exit code " | ||
| 733 | f"{'none logged' if b['exit_code'] is None else b['exit_code']}" | ||
| 734 | + (f"; boot.ps1: {b['ending']}" if b['ending'] else "")) | ||
| 735 | else: | ||
| 736 | def n(key): | ||
| 737 | return "none" if b.get(key) is None else b[key] | ||
| 738 | rej = b.get("listings_with_rejected_words") | ||
| 739 | out.append(f" expected {n('expected')} listings {n('listings')}" | ||
| 740 | + (f" ({rej} with rejected words)" if rej is not None else "") | ||
| 741 | + f" translated {n('translated')} ({b.get('percent', '-')}) failed {b.get('failed', '-')}" | ||
| 742 | + (f" index without .spv {b['modules_missing']}" if b.get("modules_missing") else "")) | ||
| 743 | if b.get("reasons"): | ||
| 744 | out.append(" reasons " + "; ".join(f"{n} {r}" for n, r in b["reasons"])) | ||
| 745 | out.append(f" cause: {b['cause']}") | ||
| 746 | w = report["weakest"] | ||
| 747 | out.append(f"weakest link: {w['name']} [{w['verdict']}]: {w['cause']}") | ||
| 748 | return "\n".join(out) | ||
| 749 | |||
| 750 | |||
| 751 | def main(argv=None) -> int: | ||
| 752 | ap = argparse.ArgumentParser(description="One page of counts for the shader chain of a work folder.", | ||
| 753 | epilog=VERDICTS) | ||
| 754 | ap.add_argument("work", help="make_game.py's work folder (holds shaders/ and logs/)") | ||
| 755 | ap.add_argument("--log", help="a gta6rt stderr log of one run (scripts/windows-boot/boot.ps1's <Name>.log)") | ||
| 756 | ap.add_argument("--no-probe", action="store_true", help="run nothing: no llvm-mc, spirv-val or git --version") | ||
| 757 | ap.add_argument("--json", action="store_true", help="print the report as JSON") | ||
| 758 | ap.add_argument("--strict", action="store_true", help="exit 1 when a block is FAIL (default: 0, a report)") | ||
| 759 | ap.add_argument("--show-paths", action="store_true", | ||
| 760 | help="name the work folder and the log in the report (not for publishing)") | ||
| 761 | a = ap.parse_args(argv) | ||
| 762 | if not os.path.isdir(a.work): | ||
| 763 | ap.error(f"no work folder at {a.work}") | ||
| 764 | if a.log and not os.path.isfile(a.log): | ||
| 765 | ap.error(f"no log at {a.log}") | ||
| 766 | report = check(a.work, a.log, probe=not a.no_probe, show_paths=a.show_paths) | ||
| 767 | print(json.dumps(report, indent=1) if a.json else render(report)) | ||
| 768 | return 1 if a.strict and any(b["verdict"] == FAIL for b in report["blocks"]) else 0 | ||
| 769 | |||
| 770 | |||
| 771 | if __name__ == "__main__": | ||
| 772 | try: | ||
| 773 | sys.stdout.reconfigure(errors="replace") | ||
| 774 | except AttributeError: | ||
| 775 | pass | ||
| 776 | sys.exit(main()) | ||
diff --git a/tools/fmisc_diff.py b/tools/fmisc_diff.py index b5196ae62..c674cd60a 100644 --- a/tools/fmisc_diff.py +++ b/tools/fmisc_diff.py | |||
| @@ -33,9 +33,12 @@ Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows d | |||
| 33 | 33 | ||
| 34 | Not judged (the program is skipped with the reason, counted): a denormal operand or result (whether f32 denormals | 34 | Not judged (the program is skipped with the reason, counted): a denormal operand or result (whether f32 denormals |
| 35 | are flushed is the MODE question, SHADER-35), a NaN whose payload is later read as an integer (payloads are not | 35 | are flushed is the MODE question, SHADER-35), a NaN whose payload is later read as an integer (payloads are not |
| 36 | modelled), the clamp of a NaN and an output modifier whose result is a zero (tools/f32_fuzz.py measures both), and | 36 | modelled), the clamp of a NaN and an output modifier whose result is a zero (tools/f32_fuzz.py measures both), an |
| 37 | an output modifier on a signalling-NaN result (the translator's multiply quiets it, which a later v_cmp_class sees; | 37 | output modifier on a signalling-NaN result (the translator's multiply quiets it, which a later v_cmp_class sees; |
| 38 | whether the hardware does is not measured). | 38 | whether the hardware does is not measured), and the class bits of a NaN that a float op computed (v_fmamk_f32 & co.: |
| 39 | whether the hardware quiets a signalling NaN operand is payload-level and only partly measured - on gfx1036 under | ||
| 40 | the game's MODE it mostly passes the NaN source through unchanged but sometimes quiets or flips its sign, so a | ||
| 41 | v_cmp_class_f32 on the result cannot be judged). | ||
| 39 | 42 | ||
| 40 | Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to | 43 | Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to |
| 41 | differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always | 44 | differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always |
| @@ -450,12 +453,39 @@ def raw(tok, st): | |||
| 450 | return int(tok, 0) & M32 | 453 | return int(tok, 0) & M32 |
| 451 | 454 | ||
| 452 | 455 | ||
| 456 | def _vreg(tok): | ||
| 457 | """The VGPR a source token reads, ignoring neg/abs modifiers; None for anything else.""" | ||
| 458 | if tok.startswith("-") and not tok[1:2].isdigit(): | ||
| 459 | tok = tok[1:] | ||
| 460 | tok = tok.strip("|") | ||
| 461 | m = re.fullmatch(r"v(\d+)", tok) | ||
| 462 | return int(m.group(1)) if m else None | ||
| 463 | |||
| 464 | |||
| 453 | def ivalue(tok, st): | 465 | def ivalue(tok, st): |
| 454 | if re.fullmatch(r"v\d+", tok) and int(tok[1:]) in st["nan"]: | 466 | if re.fullmatch(r"v\d+", tok) and int(tok[1:]) in st["nan"]: |
| 455 | raise Uncertain("a computed NaN read as an integer") | 467 | raise Uncertain("a computed NaN read as an integer") |
| 456 | return raw(tok, st) | 468 | return raw(tok, st) |
| 457 | 469 | ||
| 458 | 470 | ||
| 471 | # Ops whose NaN output is the NaN input's word, unchanged (a pass-through or a bit move): the quiet bit a | ||
| 472 | # v_cmp_class_f32 later reads is the input's, modelled exactly when the input's is (st["nanf"] does not propagate | ||
| 473 | # through them, it only survives). v_fmamk_f32 is the one op here that makes a NaN from its operands: on gfx1036 | ||
| 474 | # under the game's MODE (IEEE off) the hardware mostly returns the NaN source's word but sometimes quiets a | ||
| 475 | # signalling one, so a signalling-NaN operand - or an operand whose NaN quiet bit is already unmodelled - makes | ||
| 476 | # the result's class bits unmodelled too. | ||
| 477 | NAN_PASSTHROUGH = {"v_fract_f32", "v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"} | ||
| 478 | |||
| 479 | |||
| 480 | def _nan_fuzzy(tok, w, st): | ||
| 481 | """Whether a NaN input to v_fmamk_f32 leaves the result's quiet bit unmodelled: the input is signalling, or | ||
| 482 | it is a register whose NaN quiet bit already is.""" | ||
| 483 | if not is_nan(w): | ||
| 484 | return False | ||
| 485 | r = _vreg(tok) | ||
| 486 | return (r is not None and r in st["nanf"]) or not w & 0x400000 | ||
| 487 | |||
| 488 | |||
| 459 | def fvalue(tok, st): | 489 | def fvalue(tok, st): |
| 460 | neg = tok.startswith("-") and not tok[1:2].isdigit() | 490 | neg = tok.startswith("-") and not tok[1:2].isdigit() |
| 461 | if neg: | 491 | if neg: |
| @@ -489,7 +519,9 @@ def out_mods(w, mods): | |||
| 489 | 519 | ||
| 490 | def reference(lines): | 520 | def reference(lines): |
| 491 | """Run the program; returns the four exported words. Raises Uncertain for what it does not judge.""" | 521 | """Run the program; returns the four exported words. Raises Uncertain for what it does not judge.""" |
| 492 | st = {"v": {}, "s": {}, "nan": set()} # nan: VGPRs holding a computed NaN (payload not modelled) | 522 | st = {"v": {}, "s": {}, "nan": set(), "nanf": set()} # nan: VGPRs holding a computed NaN (payload not |
| 523 | # modelled); nanf: of those, the ones whose quiet bit is not modelled either (a v_fmamk_f32 NaN, or a | ||
| 524 | # pass-through of one): a later v_cmp_class_f32 on them is Uncertain, everything else still judges them. | ||
| 493 | for line in lines: | 525 | for line in lines: |
| 494 | op, _, rest = line.partition(" ") | 526 | op, _, rest = line.partition(" ") |
| 495 | args, mods = parse(rest) | 527 | args, mods = parse(rest) |
| @@ -499,6 +531,9 @@ def reference(lines): | |||
| 499 | if op.startswith("v_cmp_"): | 531 | if op.startswith("v_cmp_"): |
| 500 | a = fvalue(args[1], st) | 532 | a = fvalue(args[1], st) |
| 501 | if op.startswith("v_cmp_class_f32"): | 533 | if op.startswith("v_cmp_class_f32"): |
| 534 | r = _vreg(args[1]) | ||
| 535 | if r is not None and r in st["nanf"]: | ||
| 536 | raise Uncertain("the class bits of a NaN whose quiet bit is not modelled") | ||
| 502 | bit = class_bits(a) & ivalue(args[2], st) | 537 | bit = class_bits(a) & ivalue(args[2], st) |
| 503 | else: | 538 | else: |
| 504 | bit = fcmp(op[len("v_cmp_"):].split("_f32")[0], a, fvalue(args[2], st)) | 539 | bit = fcmp(op[len("v_cmp_"):].split("_f32")[0], a, fvalue(args[2], st)) |
| @@ -508,8 +543,11 @@ def reference(lines): | |||
| 508 | if op in ("v_mov_b32_e32", "v_cndmask_b32_e64"): | 543 | if op in ("v_mov_b32_e32", "v_cndmask_b32_e64"): |
| 509 | src = args[1] if op == "v_mov_b32_e32" else args[2 if raw(args[3], st) & 1 else 1] | 544 | src = args[1] if op == "v_mov_b32_e32" else args[2 if raw(args[3], st) & 1 else 1] |
| 510 | st["v"][d] = raw(src, st) | 545 | st["v"][d] = raw(src, st) |
| 511 | nan = re.fullmatch(r"v\d+", src) and int(src[1:]) in st["nan"] | 546 | r = _vreg(src) |
| 547 | nan = r is not None and r in st["nan"] | ||
| 512 | (st["nan"].add if nan else st["nan"].discard)(d) | 548 | (st["nan"].add if nan else st["nan"].discard)(d) |
| 549 | fuzzy = r is not None and r in st["nanf"] | ||
| 550 | (st["nanf"].add if fuzzy else st["nanf"].discard)(d) | ||
| 513 | continue | 551 | continue |
| 514 | base = op[:-4] if op.endswith(("_e32", "_e64")) else op | 552 | base = op[:-4] if op.endswith(("_e32", "_e64")) else op |
| 515 | if base not in OPS: | 553 | if base not in OPS: |
| @@ -524,7 +562,18 @@ def reference(lines): | |||
| 524 | if is_denorm(w): | 562 | if is_denorm(w): |
| 525 | raise Uncertain("denormal result") | 563 | raise Uncertain("denormal result") |
| 526 | w = out_mods(w, mods) | 564 | w = out_mods(w, mods) |
| 527 | (st["nan"].add if fout and is_nan(w) else st["nan"].discard)(d) | 565 | nan_out = fout and is_nan(w) |
| 566 | # Read the sources' nanf before d's own entry is replaced (d may alias a source). | ||
| 567 | if not nan_out: | ||
| 568 | fuzzy = False | ||
| 569 | elif base == "v_fmamk_f32": | ||
| 570 | fuzzy = any(_nan_fuzzy(t, v, st) for t, v in zip(args[1:4], vals)) | ||
| 571 | elif base in NAN_PASSTHROUGH: | ||
| 572 | fuzzy = any(_vreg(t) in st["nanf"] for t, f in zip(args[1:], fin) if f) | ||
| 573 | else: | ||
| 574 | fuzzy = False | ||
| 575 | (st["nan"].add if nan_out else st["nan"].discard)(d) | ||
| 576 | (st["nanf"].add if fuzzy else st["nanf"].discard)(d) | ||
| 528 | st["v"][d] = w | 577 | st["v"][d] = w |
| 529 | return [st["v"].get(8 + i, 0) for i in range(4)] | 578 | return [st["v"].get(8 + i, 0) for i in range(4)] |
| 530 | 579 | ||
diff --git a/tools/lod_bias_probe.py b/tools/lod_bias_probe.py new file mode 100644 index 000000000..ac5421a2c --- /dev/null +++ b/tools/lod_bias_probe.py | |||
| @@ -0,0 +1,128 @@ | |||
| 1 | """Measure whether the Vulkan driver applies VkSamplerCreateInfo::mipLodBias, for rdna2spirv.py --explicit-lod-bias. | ||
| 2 | |||
| 3 | python -I tools/lod_bias_probe.py [--build <folder with vk_sampler_test>] | ||
| 4 | |||
| 5 | The answer is measured, not looked up: MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 (ps_ssharp fails on | ||
| 6 | main) but applies it on an Apple M5 Pro (ps_ssharp passes on main), so a driver ID can't decide. | ||
| 7 | |||
| 8 | First it asks tools/vk_subgroup_info.py --lod-bias, which measures it with one compute dispatch from Python | ||
| 9 | (tools/vk_lod_bias.py) and needs no built test programs, llvm-mc or SPIR-V tools. Only when that has no answer and | ||
| 10 | --build names the test programs does it fall back to the draw below. The draw translates runtime/test/shaders/vs_ids and ps_ssharp *without* the flag into a temporary folder (build.py with | ||
| 11 | LEONIDA_EXPLICIT_LOD_BIAS=0), then draws them with vk_sampler_test three times: no bias, LOD_BIAS +1 and -1 (S# words | ||
| 12 | from check.py's ssharp_words). ps_ssharp's mrt0 is (lz.r, lz.g, implicit.r, implicit.g): the explicit sample at LOD | ||
| 13 | 0 and the derivative one at LOD 1, on a two-level texture. | ||
| 14 | |||
| 15 | * no-bias draw wrong -> None (the probe can't judge this device) | ||
| 16 | * +1 and -1 both as check.py expects -> False: the driver applies the bias, the flag would count it twice | ||
| 17 | * +1 and -1 both read the no-bias levels -> True: the driver drops it, translate with --explicit-lod-bias | ||
| 18 | * anything else -> None | ||
| 19 | |||
| 20 | The last line printed is {"explicit_lod_bias": true|false|null, "reason": "..."}; the exit status is 0 either way | ||
| 21 | (2 on a usage error). It honours the environment the tests run under (VK_DRIVER_FILES, LEONIDA_VULKAN_LOADER, ...). | ||
| 22 | Standard library only; needs llvm-mc and the SPIR-V tools build.py needs, no game files. | ||
| 23 | """ | ||
| 24 | import argparse | ||
| 25 | import json | ||
| 26 | import os | ||
| 27 | import subprocess | ||
| 28 | import sys | ||
| 29 | import tempfile | ||
| 30 | from pathlib import Path | ||
| 31 | |||
| 32 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 33 | ROOT = os.path.dirname(HERE) | ||
| 34 | SHADERS = os.path.join(ROOT, "runtime", "test", "shaders") | ||
| 35 | EXE = ".exe" if os.name == "nt" else "" | ||
| 36 | sys.path.insert(0, SHADERS) | ||
| 37 | import check # noqa: E402 (ssharp_words, sampler_mismatch, the SAMPLER_SIZE readback layout) | ||
| 38 | |||
| 39 | |||
| 40 | def subgroup_info_answer(timeout: int = 120): | ||
| 41 | """(True | False | None, reason) from tools/vk_subgroup_info.py --lod-bias.""" | ||
| 42 | try: | ||
| 43 | r = subprocess.run([sys.executable, "-I", os.path.join(HERE, "vk_subgroup_info.py"), "--lod-bias"], | ||
| 44 | capture_output=True, text=True, timeout=timeout) | ||
| 45 | answer = json.loads(r.stdout.strip().splitlines()[-1]) | ||
| 46 | except (OSError, ValueError, IndexError, subprocess.SubprocessError) as e: | ||
| 47 | return None, f"vk_subgroup_info.py --lod-bias: {e}" | ||
| 48 | if "error" in answer: | ||
| 49 | return None, f"vk_subgroup_info.py --lod-bias: {answer['error']}" | ||
| 50 | return answer.get("explicit_lod_bias"), answer.get("explicit_lod_bias_reason", "") | ||
| 51 | |||
| 52 | |||
| 53 | def probe(build: str | None = None, timeout: int = 120): | ||
| 54 | """(True | False | None, reason): vk_subgroup_info.py's measurement, else the vk_sampler_test draw.""" | ||
| 55 | answer, reason = subgroup_info_answer(timeout) | ||
| 56 | if answer is not None or not build: | ||
| 57 | return answer, reason | ||
| 58 | drawn, why = draw_probe(build, timeout) | ||
| 59 | return drawn, why if drawn is not None else f"{reason}; {why}" | ||
| 60 | |||
| 61 | |||
| 62 | def draw_probe(build: str, timeout: int = 120): | ||
| 63 | """(True | False | None, reason) from three vk_sampler_test draws of ps_ssharp.""" | ||
| 64 | tool = os.path.join(build, "vk_sampler_test" + EXE) | ||
| 65 | if not os.path.isfile(tool): | ||
| 66 | return None, f"no vk_sampler_test{EXE} in {build}" | ||
| 67 | with tempfile.TemporaryDirectory(prefix="leonida-lod-bias-") as tmp: | ||
| 68 | env = dict(os.environ, LEONIDA_EXPLICIT_LOD_BIAS="0") | ||
| 69 | try: | ||
| 70 | r = subprocess.run([sys.executable, "-I", os.path.join(SHADERS, "build.py"), tmp, "vs_ids", "ps_ssharp"], | ||
| 71 | capture_output=True, text=True, env=env, timeout=timeout) | ||
| 72 | except (OSError, subprocess.SubprocessError) as e: | ||
| 73 | return None, f"build.py: {e}" | ||
| 74 | shaders = [os.path.join(tmp, "spirv", n + ".spv") for n in ("vs_ids", "ps_ssharp")] | ||
| 75 | if r.returncode or not all(os.path.isfile(s) for s in shaders): | ||
| 76 | out = (r.stdout + r.stderr).strip() | ||
| 77 | if "llvm-mc" in out and "could not be started" in out: | ||
| 78 | # Homebrew's llvm is keg-only: say what to set instead of a bare "could not be started". | ||
| 79 | sys.path.insert(0, HERE) | ||
| 80 | import mc_command # noqa: E402 | ||
| 81 | return None, "the draw needs llvm-mc to translate ps_ssharp: " + mc_command.install_hint() | ||
| 82 | return None, "build.py could not translate vs_ids and ps_ssharp: " + out[-300:] | ||
| 83 | view = (0, 1) | ||
| 84 | |||
| 85 | def draw(bias): | ||
| 86 | words = check.ssharp_words(1, bias=bias) | ||
| 87 | raw = Path(tmp) / f"bias{bias:+}.raw" | ||
| 88 | try: | ||
| 89 | d = subprocess.run([tool, *shaders, str(raw), *(f"{w:x}" for w in words), *(str(v) for v in view)], | ||
| 90 | capture_output=True, text=True, timeout=timeout) | ||
| 91 | except (OSError, subprocess.SubprocessError) as e: | ||
| 92 | return None, f"vk_sampler_test: {e}" | ||
| 93 | if d.returncode or not raw.is_file(): | ||
| 94 | return None, f"vk_sampler_test exited {d.returncode}: " + (d.stdout + d.stderr).strip()[-200:] | ||
| 95 | data = raw.read_bytes() | ||
| 96 | return check.sampler_mismatch(data, words, view), data | ||
| 97 | |||
| 98 | base = draw(0) | ||
| 99 | if base[0] is None: | ||
| 100 | return None, base[1] | ||
| 101 | if base[0]: | ||
| 102 | return None, f"the no-bias draw is already wrong ({base[0]})" | ||
| 103 | results = {} | ||
| 104 | for bias in (1, -1): | ||
| 105 | problem, data = draw(bias) | ||
| 106 | if problem is None: | ||
| 107 | return None, data | ||
| 108 | results[bias] = (problem, data) | ||
| 109 | if not any(p for p, _ in results.values()): | ||
| 110 | return False, "the sampler applies LOD_BIAS +1 and -1" | ||
| 111 | if all(p and data == base[1] for p, data in results.values()): | ||
| 112 | return True, "the sampler drops LOD_BIAS: +1 and -1 read the no-bias levels" | ||
| 113 | return None, "; ".join(f"bias {b:+}: {p or 'ok'}" for b, (p, _) in results.items()) | ||
| 114 | |||
| 115 | |||
| 116 | def main(argv=None): | ||
| 117 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 118 | ap.add_argument("--build", help="the folder with vk_sampler_test, for the draw fallback (the GPU test programs)") | ||
| 119 | a = ap.parse_args(argv) | ||
| 120 | answer, reason = probe(a.build) | ||
| 121 | print(json.dumps({"explicit_lod_bias": answer, "reason": reason})) | ||
| 122 | return 0 | ||
| 123 | |||
| 124 | |||
| 125 | if __name__ == "__main__": | ||
| 126 | if hasattr(sys.stdout, "reconfigure"): | ||
| 127 | sys.stdout.reconfigure(errors="replace") | ||
| 128 | sys.exit(main()) | ||
diff --git a/tools/mc_command.py b/tools/mc_command.py index 762008d7a..17fde8437 100644 --- a/tools/mc_command.py +++ b/tools/mc_command.py | |||
| @@ -4,7 +4,7 @@ LLVM_MC may be one executable (a path, spaces and all, with or without its .exe) | |||
| 4 | needs the command-line form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU | 4 | needs the command-line form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU |
| 5 | target: | 5 | target: |
| 6 | 6 | ||
| 7 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc | 7 | set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc |
| 8 | 8 | ||
| 9 | On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted | 9 | On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted |
| 10 | argument before the closing quote. | 10 | argument before the closing quote. |
| @@ -116,7 +116,7 @@ def default_command() -> str: | |||
| 116 | 116 | ||
| 117 | 117 | ||
| 118 | def mc_command(raw: str | None = None) -> list: | 118 | def mc_command(raw: str | None = None) -> list: |
| 119 | """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'. Unset or empty, | 119 | """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc'. Unset or empty, |
| 120 | default_command().""" | 120 | default_command().""" |
| 121 | if raw is None: | 121 | if raw is None: |
| 122 | raw = os.environ.get("LLVM_MC", "") | 122 | raw = os.environ.get("LLVM_MC", "") |
| @@ -127,14 +127,14 @@ def install_hint() -> str: | |||
| 127 | """Where to get an llvm-mc with the AMDGPU target on this OS, for the messages that report a missing one.""" | 127 | """Where to get an llvm-mc with the AMDGPU target on this OS, for the messages that report a missing one.""" |
| 128 | if os.name == "nt": | 128 | if os.name == "nt": |
| 129 | return ("The official Windows LLVM build has no AMDGPU target: build a native one with " | 129 | return ("The official Windows LLVM build has no AMDGPU target: build a native one with " |
| 130 | "scripts\\build_llvm_mc.ps1 (it sets LLVM_MC), or install llvm-21 in WSL and set LLVM_MC to the " | 130 | "scripts\\build_llvm_mc.ps1 (it sets LLVM_MC), or install llvm-23 in WSL and set LLVM_MC to the " |
| 131 | "whole command, e.g.\n LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") | 131 | "whole command, e.g.\n LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-23/bin/llvm-mc") |
| 132 | if sys.platform == "darwin": | 132 | if sys.platform == "darwin": |
| 133 | return ("Homebrew's llvm has the AMDGPU target but is keg-only (not on PATH): brew install llvm, then\n" | 133 | return ("Homebrew's llvm has the AMDGPU target but is keg-only (not on PATH): brew install llvm, then\n" |
| 134 | " LLVM_MC=\"$(brew --prefix llvm)/bin/llvm-mc\"") | 134 | " LLVM_MC=\"$(brew --prefix llvm)/bin/llvm-mc\"") |
| 135 | return ("Distribution LLVM packages include the AMDGPU target: on Debian or Ubuntu, sudo apt install llvm-21\n" | 135 | return ("Distribution LLVM packages include the AMDGPU target: on Debian or Ubuntu, sudo apt install llvm-23\n" |
| 136 | "(found as /usr/lib/llvm-21/bin/llvm-mc without further setup); elsewhere install your distribution's\n" | 136 | "(found as /usr/lib/llvm-23/bin/llvm-mc without further setup); elsewhere install your distribution's\n" |
| 137 | "LLVM 21+ package and put llvm-mc on PATH, or set LLVM_MC=/path/to/llvm-mc") | 137 | "LLVM 23+ package and put llvm-mc on PATH, or set LLVM_MC=/path/to/llvm-mc") |
| 138 | 138 | ||
| 139 | 139 | ||
| 140 | def not_found(exe: str, error: OSError, flag: str | None = None) -> str: | 140 | def not_found(exe: str, error: OSError, flag: str | None = None) -> str: |
diff --git a/tools/picture_metrics.py b/tools/picture_metrics.py new file mode 100644 index 000000000..d12d588d7 --- /dev/null +++ b/tools/picture_metrics.py | |||
| @@ -0,0 +1,583 @@ | |||
| 1 | """Numbers about a frame on your disk, for the PICTURE block of docs/agent_collaboration.md. | ||
| 2 | |||
| 3 | python -I tools/picture_metrics.py <frame.png|.ppm> [<reference.png|.ppm>] [--json] [--class CLASS] | ||
| 4 | [--region X,Y,W,H] [--tolerance N] | ||
| 5 | |||
| 6 | From one frame the tool prints its size, luma statistics, the dark share of each of a fixed 4 x 4 grid of regions, | ||
| 7 | a lattice detector (dark marks in square tiles along one diagonal in N: tile, period, phase, diagonal, corner of | ||
| 8 | the tile), a block-grid detector (rectangular blocks cut off from the picture around them: block size and share) | ||
| 9 | and a measured defect class. With a second frame, the reference, it adds the per-8x8 diff of the two (count, | ||
| 10 | share, bounding box and position of the changed tiles) and the reference's luma, and can measure FLASH. | ||
| 11 | |||
| 12 | Luma is BT.601 in integers, ``(299 R + 587 G + 114 B + 500) // 1000``; a pixel is dark at luma 24 or less. | ||
| 13 | |||
| 14 | Measured classes, first match: ``BLACK-NEAR`` (95% or more of the frame dark), ``FLASH`` (the two luma means | ||
| 15 | differ by 64 or more), ``LATTICE``, ``BLOCKS``, else ``OK``. ``CHAR-BLACK``, ``CHAR-MISSING``, ``2D-MISSING``, | ||
| 16 | ``STRAY-GEO`` and ``SMEAR`` need to know what the scene should show, so the tool has no detector for them: a human | ||
| 17 | gives one with ``--class`` and it is printed as ``given``, next to the measured class, never in its place. | ||
| 18 | ``--region`` adds the luma statistics of a rectangle the human picked (a character, a HUD element) so a given | ||
| 19 | class comes with numbers. ``--tolerance`` lets a diff ignore channel changes up to N; it is 0 (exact) by default. | ||
| 20 | |||
| 21 | Reads PNG (8-bit grey, grey + alpha, RGB or RGBA, not interlaced, all five filters; alpha is ignored) and binary | ||
| 22 | PPM/PGM (P6/P5, maxval 255). Anything else (palette, 16-bit, interlaced PNG, other formats) is refused with one | ||
| 23 | ``error:`` line and exit 2. | ||
| 24 | |||
| 25 | What it does not do: it does not look at what the scene contains, it does not write any file, and its output holds | ||
| 26 | numbers and classes only: no pixel values beyond statistics, no image path (the path stays a local argument). | ||
| 27 | The detectors are tuned on synthetic frames; on a real frame a scene edge on the grid or a dark texture on a | ||
| 28 | diagonal can hide or fake them, so a class is a hint for a human to confirm. A lattice needs 8 marked tiles on 3 | ||
| 29 | half-marked diagonals of its class, so a lattice cropped to fewer repeats is not reported. BLOCKS refuses one | ||
| 30 | sharp rectangle and a checkerboard, but several sharp rectangles (HUD panels, window frames) can still read as | ||
| 31 | BLOCKS, and blocks off the frame's origin are given at the divisor of their edges (16-pixel blocks shifted by 4 | ||
| 32 | read as 4x4): see ``find_blocks``. | ||
| 33 | """ | ||
| 34 | from __future__ import annotations | ||
| 35 | |||
| 36 | import argparse | ||
| 37 | import json | ||
| 38 | import math | ||
| 39 | import struct | ||
| 40 | import sys | ||
| 41 | import zlib | ||
| 42 | from typing import NamedTuple, Optional | ||
| 43 | |||
| 44 | DARK = 24 # a pixel at this luma or below is dark | ||
| 45 | BLACK_NEAR_SHARE = 0.95 # dark share of the frame for BLACK-NEAR | ||
| 46 | FLASH_DELTA = 64 # luma mean difference between the two frames for FLASH | ||
| 47 | REGIONS = 4 # the dark-share grid is REGIONS x REGIONS | ||
| 48 | DIFF_TILE = 8 | ||
| 49 | LATTICE_TILES = (4, 8, 16, 32) | ||
| 50 | LATTICE_MAX_PERIOD = 32 | ||
| 51 | LATTICE_MIN_SCORE = 0.5 # cover of the diagonal minus the rate of marks off it | ||
| 52 | LATTICE_MIN_TILES = 8 # marked tiles in the winning class, not in the whole frame | ||
| 53 | LATTICE_MAX_OUTSIDE = 0.25 # the rate of marks off the diagonal stays under this share of its cover | ||
| 54 | LATTICE_MIN_REPEATS = 3 # half-marked diagonals in the winning class: the pattern repeats at least this often | ||
| 55 | NEAR_BEST = 0.9 # the smallest tile and period within this share of the best score win | ||
| 56 | EDGE_JUMP = 8 # a step across a block edge: at least this many luma levels ... | ||
| 57 | EDGE_RATIO = 3 # ... and this many times the steps beside it | ||
| 58 | MIN_LINE_ROWS = 4 # pixels on one grid line that must step for it to count | ||
| 59 | MIN_BLOCK = 4 | ||
| 60 | MIN_EDGE_LINES = 3 # edge columns, and edge rows, a block grid needs | ||
| 61 | MAX_BLOCK_SHARE = 0.5 # cut-off blocks are a minority: past this there is no picture around them | ||
| 62 | TEXT_TILES = 16 # changed tiles listed in the text block (all of them in --json) | ||
| 63 | |||
| 64 | MEASURED = ("BLACK-NEAR", "FLASH", "LATTICE", "BLOCKS", "OK") | ||
| 65 | GIVEN_ONLY = ("CHAR-BLACK", "CHAR-MISSING", "2D-MISSING", "STRAY-GEO", "SMEAR") | ||
| 66 | CLASSES = ("LATTICE", "BLACK-NEAR", "BLOCKS", "FLASH") + GIVEN_ONLY + ("OK",) | ||
| 67 | |||
| 68 | PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" | ||
| 69 | |||
| 70 | |||
| 71 | class Frame(NamedTuple): | ||
| 72 | """A decoded frame: row-major RGB, 3 bytes a pixel.""" | ||
| 73 | width: int | ||
| 74 | height: int | ||
| 75 | rgb: bytes | ||
| 76 | |||
| 77 | |||
| 78 | # ---- reading --------------------------------------------------------------------------------------------------- | ||
| 79 | |||
| 80 | def _paeth(a: int, b: int, c: int) -> int: | ||
| 81 | p = a + b - c | ||
| 82 | pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) | ||
| 83 | if pa <= pb and pa <= pc: | ||
| 84 | return a | ||
| 85 | return b if pb <= pc else c | ||
| 86 | |||
| 87 | |||
| 88 | def _unfilter(raw: bytes, height: int, stride: int, bpp: int) -> bytearray: | ||
| 89 | if len(raw) < height * (stride + 1): | ||
| 90 | raise ValueError("PNG image data is shorter than the image") | ||
| 91 | out = bytearray(height * stride) | ||
| 92 | prev = bytearray(stride) | ||
| 93 | for y in range(height): | ||
| 94 | kind = raw[y * (stride + 1)] | ||
| 95 | row = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) | ||
| 96 | if kind == 1: | ||
| 97 | for i in range(bpp, stride): | ||
| 98 | row[i] = (row[i] + row[i - bpp]) & 0xFF | ||
| 99 | elif kind == 2: | ||
| 100 | for i in range(stride): | ||
| 101 | row[i] = (row[i] + prev[i]) & 0xFF | ||
| 102 | elif kind == 3: | ||
| 103 | for i in range(stride): | ||
| 104 | left = row[i - bpp] if i >= bpp else 0 | ||
| 105 | row[i] = (row[i] + ((left + prev[i]) >> 1)) & 0xFF | ||
| 106 | elif kind == 4: | ||
| 107 | for i in range(stride): | ||
| 108 | if i >= bpp: | ||
| 109 | row[i] = (row[i] + _paeth(row[i - bpp], prev[i], prev[i - bpp])) & 0xFF | ||
| 110 | else: | ||
| 111 | row[i] = (row[i] + prev[i]) & 0xFF | ||
| 112 | elif kind != 0: | ||
| 113 | raise ValueError(f"PNG filter type {kind} is not one of the five") | ||
| 114 | out[y * stride:(y + 1) * stride] = row | ||
| 115 | prev = row | ||
| 116 | return out | ||
| 117 | |||
| 118 | |||
| 119 | def decode_png(data: bytes) -> Frame: | ||
| 120 | """An 8-bit, non-interlaced grey, grey + alpha, RGB or RGBA PNG as a Frame; ValueError for anything else.""" | ||
| 121 | if not data.startswith(PNG_SIGNATURE): | ||
| 122 | raise ValueError("not a PNG") | ||
| 123 | pos, header, idat = len(PNG_SIGNATURE), None, [] | ||
| 124 | while True: | ||
| 125 | if pos + 8 > len(data): | ||
| 126 | raise ValueError("PNG is truncated") | ||
| 127 | length, kind = struct.unpack(">I4s", data[pos:pos + 8]) | ||
| 128 | body = data[pos + 8:pos + 8 + length] | ||
| 129 | if len(body) != length or pos + 12 + length > len(data): | ||
| 130 | raise ValueError("PNG is truncated") | ||
| 131 | (crc,) = struct.unpack(">I", data[pos + 8 + length:pos + 12 + length]) | ||
| 132 | if zlib.crc32(kind + body) & 0xFFFFFFFF != crc: | ||
| 133 | raise ValueError(f"PNG chunk {kind.decode('latin-1')!r} has a bad CRC") | ||
| 134 | pos += 12 + length | ||
| 135 | if kind == b"IHDR": | ||
| 136 | if length != 13: | ||
| 137 | raise ValueError("PNG IHDR is not 13 bytes") | ||
| 138 | header = struct.unpack(">IIBBBBB", body) | ||
| 139 | elif kind == b"IDAT": | ||
| 140 | idat.append(body) | ||
| 141 | elif kind == b"IEND": | ||
| 142 | break | ||
| 143 | if header is None: | ||
| 144 | raise ValueError("PNG has no IHDR") | ||
| 145 | width, height, depth, color, _compression, _filter, interlace = header | ||
| 146 | channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(color) | ||
| 147 | if channels is None: | ||
| 148 | raise ValueError(f"PNG colour type {color} is not read (grey, grey + alpha, RGB or RGBA only)") | ||
| 149 | if depth != 8: | ||
| 150 | raise ValueError(f"PNG bit depth {depth} is not read (8 only)") | ||
| 151 | if interlace: | ||
| 152 | raise ValueError("interlaced PNG is not read") | ||
| 153 | if not width or not height: | ||
| 154 | raise ValueError("PNG has no pixels") | ||
| 155 | try: | ||
| 156 | raw = zlib.decompress(b"".join(idat)) | ||
| 157 | except zlib.error as e: | ||
| 158 | raise ValueError(f"PNG image data does not inflate: {e}") from None | ||
| 159 | px = _unfilter(raw, height, width * channels, channels) | ||
| 160 | return Frame(width, height, _to_rgb(px, channels)) | ||
| 161 | |||
| 162 | |||
| 163 | def _to_rgb(px: bytes, channels: int) -> bytes: | ||
| 164 | if channels == 3: | ||
| 165 | return bytes(px) | ||
| 166 | out = bytearray(len(px) // channels * 3) | ||
| 167 | if channels in (1, 2): | ||
| 168 | grey = px[0::channels] | ||
| 169 | out[0::3] = out[1::3] = out[2::3] = grey | ||
| 170 | else: | ||
| 171 | for c in range(3): | ||
| 172 | out[c::3] = px[c::4] | ||
| 173 | return bytes(out) | ||
| 174 | |||
| 175 | |||
| 176 | def decode_ppm(data: bytes) -> Frame: | ||
| 177 | """A binary PPM (P6) or PGM (P5) with maxval 255 as a Frame; ValueError for anything else.""" | ||
| 178 | fields, pos = [], 2 | ||
| 179 | while len(fields) < 3: | ||
| 180 | while pos < len(data) and data[pos:pos + 1].isspace(): | ||
| 181 | pos += 1 | ||
| 182 | if data[pos:pos + 1] == b"#": | ||
| 183 | while pos < len(data) and data[pos:pos + 1] not in (b"\n", b"\r"): | ||
| 184 | pos += 1 | ||
| 185 | continue | ||
| 186 | start = pos | ||
| 187 | while pos < len(data) and data[pos:pos + 1].isdigit(): | ||
| 188 | pos += 1 | ||
| 189 | if start == pos: | ||
| 190 | raise ValueError("PPM header is not three numbers") | ||
| 191 | fields.append(int(data[start:pos])) | ||
| 192 | width, height, maxval = fields | ||
| 193 | if maxval != 255: | ||
| 194 | raise ValueError(f"PPM maxval {maxval} is not read (255 only)") | ||
| 195 | if not width or not height: | ||
| 196 | raise ValueError("PPM has no pixels") | ||
| 197 | channels = 3 if data[:2] == b"P6" else 1 | ||
| 198 | px = data[pos + 1:pos + 1 + width * height * channels] | ||
| 199 | if len(px) != width * height * channels: | ||
| 200 | raise ValueError("PPM is truncated") | ||
| 201 | return Frame(width, height, _to_rgb(px, channels)) | ||
| 202 | |||
| 203 | |||
| 204 | def decode_image(data: bytes) -> Frame: | ||
| 205 | """A PNG or a binary PPM/PGM, told apart by their first bytes.""" | ||
| 206 | if data.startswith(PNG_SIGNATURE): | ||
| 207 | return decode_png(data) | ||
| 208 | if data[:2] in (b"P6", b"P5"): | ||
| 209 | return decode_ppm(data) | ||
| 210 | raise ValueError("neither a PNG nor a binary PPM/PGM") | ||
| 211 | |||
| 212 | |||
| 213 | # ---- one frame ------------------------------------------------------------------------------------------------- | ||
| 214 | |||
| 215 | def luma(frame: Frame) -> bytes: | ||
| 216 | """BT.601 integer luma of every pixel, row-major.""" | ||
| 217 | rgb = frame.rgb | ||
| 218 | return bytes((299 * r + 587 * g + 114 * b + 500) // 1000 for r, g, b in zip(rgb[0::3], rgb[1::3], rgb[2::3])) | ||
| 219 | |||
| 220 | |||
| 221 | def luma_stats(lumas: bytes) -> dict: | ||
| 222 | """Mean, minimum, maximum, population standard deviation and dark share of a list of luma values.""" | ||
| 223 | n = len(lumas) | ||
| 224 | total = sum(lumas) | ||
| 225 | squares = sum(v * v for v in lumas) | ||
| 226 | mean = total / n | ||
| 227 | sd = math.sqrt(max(squares / n - mean * mean, 0.0)) | ||
| 228 | dark = sum(1 for v in lumas if v <= DARK) | ||
| 229 | return {"mean": round(mean, 2), "min": min(lumas), "max": max(lumas), "sd": round(sd, 2), | ||
| 230 | "dark": round(dark / n, 4)} | ||
| 231 | |||
| 232 | |||
| 233 | def dark_regions(lumas: bytes, width: int, height: int) -> list[list[float]]: | ||
| 234 | """Dark share of each region of a REGIONS x REGIONS grid, rows top to bottom; region edges at ``i * size // 4``.""" | ||
| 235 | xs = [i * width // REGIONS for i in range(REGIONS + 1)] | ||
| 236 | ys = [i * height // REGIONS for i in range(REGIONS + 1)] | ||
| 237 | grid = [] | ||
| 238 | for r in range(REGIONS): | ||
| 239 | row = [] | ||
| 240 | for c in range(REGIONS): | ||
| 241 | dark = sum(1 for y in range(ys[r], ys[r + 1]) for v in lumas[y * width + xs[c]:y * width + xs[c + 1]] | ||
| 242 | if v <= DARK) | ||
| 243 | area = (xs[c + 1] - xs[c]) * (ys[r + 1] - ys[r]) | ||
| 244 | row.append(round(dark / area, 4) if area else 0.0) | ||
| 245 | grid.append(row) | ||
| 246 | return grid | ||
| 247 | |||
| 248 | |||
| 249 | def region_stats(lumas: bytes, width: int, rect: tuple[int, int, int, int]) -> dict: | ||
| 250 | x, y, w, h = rect | ||
| 251 | values = b"".join(lumas[(y + j) * width + x:(y + j) * width + x + w] for j in range(h)) | ||
| 252 | return {"width": w, "height": h, **luma_stats(values)} | ||
| 253 | |||
| 254 | |||
| 255 | def _diagonal_sizes(nx: int, ny: int) -> list[int]: | ||
| 256 | """Number of tiles on each '+' diagonal ``tx + ty = s``, s = 0 .. nx + ny - 2.""" | ||
| 257 | return [min(s, nx - 1, ny - 1, nx + ny - 2 - s) + 1 for s in range(nx + ny - 1)] | ||
| 258 | |||
| 259 | |||
| 260 | def find_lattice(lumas: bytes, width: int, height: int) -> Optional[dict]: | ||
| 261 | """Dark marks in square tiles along one diagonal in N, or None. | ||
| 262 | |||
| 263 | A tile is marked when it holds dark pixels but fewer than half. For each tile size, diagonal direction | ||
| 264 | (``+``: ``tx + ty``, ``-``: ``tx - ty``) and period P, the tiles fall into P classes by diagonal index mod P; | ||
| 265 | the score of the best class is its cover (marked share) minus the rate of marked tiles outside it. The | ||
| 266 | smallest tile, then the smallest period, scoring within NEAR_BEST of the best wins: a lattice of period 16 also | ||
| 267 | covers fully at 32, and one in 8-pixel tiles at 16-pixel tiles for some phases. | ||
| 268 | """ | ||
| 269 | nx4, ny4 = width // 4, height // 4 | ||
| 270 | if nx4 < 2 or ny4 < 2: | ||
| 271 | return None | ||
| 272 | counts = [0] * (nx4 * ny4) | ||
| 273 | for y in range(ny4 * 4): | ||
| 274 | base = (y // 4) * nx4 | ||
| 275 | row = lumas[y * width:y * width + nx4 * 4] | ||
| 276 | for x, v in enumerate(row): | ||
| 277 | if v <= DARK: | ||
| 278 | counts[base + x // 4] += 1 | ||
| 279 | grids = {4: (nx4, ny4, counts)} | ||
| 280 | for tile in LATTICE_TILES[1:]: | ||
| 281 | cnx, cny, prev = grids[tile // 2] | ||
| 282 | nx, ny = cnx // 2, cny // 2 | ||
| 283 | grids[tile] = (nx, ny, [prev[(2 * ty) * cnx + 2 * tx] + prev[(2 * ty) * cnx + 2 * tx + 1] | ||
| 284 | + prev[(2 * ty + 1) * cnx + 2 * tx] + prev[(2 * ty + 1) * cnx + 2 * tx + 1] | ||
| 285 | for ty in range(ny) for tx in range(nx)]) | ||
| 286 | candidates = [] | ||
| 287 | for tile in LATTICE_TILES: | ||
| 288 | nx, ny, grid = grids[tile] | ||
| 289 | if nx < 2 or ny < 2: | ||
| 290 | continue | ||
| 291 | marked = [(tx, ty) for ty in range(ny) for tx in range(nx) if 0 < grid[ty * nx + tx] < tile * tile / 2] | ||
| 292 | if len(marked) < LATTICE_MIN_TILES: | ||
| 293 | continue | ||
| 294 | sizes = _diagonal_sizes(nx, ny) | ||
| 295 | total = nx * ny | ||
| 296 | for diagonal in "+-": | ||
| 297 | offset = 0 if diagonal == "+" else ny - 1 # tx - ty + ny - 1 indexes the same sizes | ||
| 298 | hist = [0] * len(sizes) | ||
| 299 | for tx, ty in marked: | ||
| 300 | hist[(tx + ty) if diagonal == "+" else (tx - ty + offset)] += 1 | ||
| 301 | for period in range(2, min(LATTICE_MAX_PERIOD, len(sizes)) + 1): | ||
| 302 | n_c, m_c, repeats = [0] * period, [0] * period, [0] * period | ||
| 303 | for s, size in enumerate(sizes): | ||
| 304 | c = (s - offset) % period | ||
| 305 | n_c[c] += size | ||
| 306 | m_c[c] += hist[s] | ||
| 307 | if hist[s] * 2 >= size: # this diagonal is a repeat of the pattern | ||
| 308 | repeats[c] += 1 | ||
| 309 | # A class counts only with LATTICE_MIN_TILES marked tiles on LATTICE_MIN_REPEATS diagonals that | ||
| 310 | # are each half marked or more: one or two corner diagonals cover fully at a large period by | ||
| 311 | # chance, which is no repetition. | ||
| 312 | supported = [c for c in range(period) if n_c[c] and m_c[c] >= LATTICE_MIN_TILES | ||
| 313 | and repeats[c] >= LATTICE_MIN_REPEATS] | ||
| 314 | if not supported: | ||
| 315 | continue | ||
| 316 | best = max(supported, key=lambda c: (m_c[c] / n_c[c], -c)) | ||
| 317 | if n_c[best] == total: | ||
| 318 | continue | ||
| 319 | cover = m_c[best] / n_c[best] | ||
| 320 | outside = (len(marked) - m_c[best]) / (total - n_c[best]) | ||
| 321 | if outside > LATTICE_MAX_OUTSIDE * cover: # marks everywhere: dark texture, not a lattice | ||
| 322 | continue | ||
| 323 | candidates.append((cover - outside, tile, period, diagonal, best, m_c[best], cover)) | ||
| 324 | if not candidates: | ||
| 325 | return None | ||
| 326 | top = max(c[0] for c in candidates) | ||
| 327 | if top < LATTICE_MIN_SCORE: | ||
| 328 | return None | ||
| 329 | score, tile, period, diagonal, phase, tiles, cover = min( | ||
| 330 | (c for c in candidates if c[0] >= NEAR_BEST * top), key=lambda c: (c[1], c[2], c[3] != "+")) | ||
| 331 | return {"tile": tile, "period": period, "phase": phase, "diagonal": diagonal, | ||
| 332 | "corner": _corner(lumas, width, height, tile, period, diagonal, phase), | ||
| 333 | "tiles": tiles, "cover": round(cover, 4), "score": round(score, 4)} | ||
| 334 | |||
| 335 | |||
| 336 | def _corner(lumas: bytes, width: int, height: int, tile: int, period: int, diagonal: str, phase: int) -> str: | ||
| 337 | """Which corner of its tile the dark pixels of the lattice sit in: TL, TR, BL, BR, or C when centred.""" | ||
| 338 | sx = sy = n = 0 | ||
| 339 | for ty in range(height // tile): | ||
| 340 | for tx in range(width // tile): | ||
| 341 | if ((tx + ty) if diagonal == "+" else (tx - ty)) % period != phase: | ||
| 342 | continue | ||
| 343 | for ly in range(tile): | ||
| 344 | start = (ty * tile + ly) * width + tx * tile | ||
| 345 | for lx, v in enumerate(lumas[start:start + tile]): | ||
| 346 | if v <= DARK: | ||
| 347 | sx, sy, n = sx + lx, sy + ly, n + 1 | ||
| 348 | if not n: | ||
| 349 | return "C" | ||
| 350 | mid = (tile - 1) / 2 | ||
| 351 | dx, dy = sx / n - mid, sy / n - mid | ||
| 352 | if abs(dx) < 0.5 or abs(dy) < 0.5: | ||
| 353 | return "C" | ||
| 354 | return ("T" if dy < 0 else "B") + ("L" if dx < 0 else "R") | ||
| 355 | |||
| 356 | |||
| 357 | def _steps(lumas: bytes, width: int, height: int, vertical: bool) -> list[list[bool]]: | ||
| 358 | """For each grid line (column x, or row y when ``vertical`` is False) whether each pixel along it steps. | ||
| 359 | |||
| 360 | A pixel steps when it differs from the one before it across the line by EDGE_JUMP or more and by EDGE_RATIO | ||
| 361 | times the larger of the steps just before and just after. | ||
| 362 | """ | ||
| 363 | def at(i: int, j: int) -> int: # i across the line, j along it | ||
| 364 | return lumas[j * width + i] if vertical else lumas[i * width + j] | ||
| 365 | |||
| 366 | across, along = (width, height) if vertical else (height, width) | ||
| 367 | lines: list[list[bool]] = [[] for _ in range(across)] | ||
| 368 | for i in range(1, across): | ||
| 369 | for j in range(along): | ||
| 370 | jump = abs(at(i, j) - at(i - 1, j)) | ||
| 371 | before = abs(at(i - 1, j) - at(i - 2, j)) if i >= 2 else 0 | ||
| 372 | after = abs(at(i + 1, j) - at(i, j)) if i + 1 < across else 0 | ||
| 373 | lines[i].append(jump >= EDGE_JUMP and jump >= EDGE_RATIO * max(before, after)) | ||
| 374 | return lines | ||
| 375 | |||
| 376 | |||
| 377 | def find_blocks(lumas: bytes, width: int, height: int) -> Optional[dict]: | ||
| 378 | """Rectangular blocks cut off from the picture around them, or None. | ||
| 379 | |||
| 380 | A grid line is an edge line when MIN_LINE_ROWS or more of its pixels step (see ``_steps``); the block width is | ||
| 381 | the greatest common divisor of the edge columns and the height that of the edge rows (both at least | ||
| 382 | MIN_BLOCK). On that grid a block edge is cut when half its pixels or more step; the blocks outside the largest | ||
| 383 | region joined by uncut edges are the blocks counted. | ||
| 384 | |||
| 385 | Refused: fewer than MIN_EDGE_LINES edge lines on either axis (one sharp rectangle, such as a HUD panel, has two | ||
| 386 | a side, and the divisor of two positions is no grid), and a share over MAX_BLOCK_SHARE (a checkerboard texture: | ||
| 387 | no picture around the blocks). Still misread: a grid that only ever shows multiples of the true size (every | ||
| 388 | cut block on even positions) reads as the larger size; blocks off the frame's origin (a grid shifted by 4) | ||
| 389 | read at the divisor of their edges (4x4); several sharp rectangles on a few common divisors (HUD panels, | ||
| 390 | window frames) can read as BLOCKS. | ||
| 391 | """ | ||
| 392 | cols = _steps(lumas, width, height, True) | ||
| 393 | rows = _steps(lumas, width, height, False) | ||
| 394 | edge_cols = [x for x, line in enumerate(cols) if sum(line) >= MIN_LINE_ROWS] | ||
| 395 | edge_rows = [y for y, line in enumerate(rows) if sum(line) >= MIN_LINE_ROWS] | ||
| 396 | if len(edge_cols) < MIN_EDGE_LINES or len(edge_rows) < MIN_EDGE_LINES: | ||
| 397 | return None | ||
| 398 | bw, bh = math.gcd(*edge_cols), math.gcd(*edge_rows) | ||
| 399 | if bw < MIN_BLOCK or bh < MIN_BLOCK: | ||
| 400 | return None | ||
| 401 | nx, ny = width // bw, height // bh | ||
| 402 | if nx < 2 or ny < 2: | ||
| 403 | return None | ||
| 404 | parent = list(range(nx * ny)) | ||
| 405 | |||
| 406 | def root(i: int) -> int: | ||
| 407 | while parent[i] != i: | ||
| 408 | parent[i] = parent[parent[i]] | ||
| 409 | i = parent[i] | ||
| 410 | return i | ||
| 411 | |||
| 412 | for by in range(ny): | ||
| 413 | for bx in range(nx): | ||
| 414 | if bx + 1 < nx and sum(cols[(bx + 1) * bw][by * bh:(by + 1) * bh]) * 2 < bh: | ||
| 415 | parent[root(by * nx + bx)] = root(by * nx + bx + 1) | ||
| 416 | if by + 1 < ny and sum(rows[(by + 1) * bh][bx * bw:(bx + 1) * bw]) * 2 < bw: | ||
| 417 | parent[root(by * nx + bx)] = root((by + 1) * nx + bx) | ||
| 418 | sizes: dict[int, int] = {} | ||
| 419 | for i in range(nx * ny): | ||
| 420 | r = root(i) | ||
| 421 | sizes[r] = sizes.get(r, 0) + 1 | ||
| 422 | cut = nx * ny - max(sizes.values()) | ||
| 423 | if not cut or cut > MAX_BLOCK_SHARE * nx * ny: | ||
| 424 | return None | ||
| 425 | return {"width": bw, "height": bh, "blocks": cut, "of": nx * ny, "share": round(cut / (nx * ny), 4)} | ||
| 426 | |||
| 427 | |||
| 428 | # ---- two frames ------------------------------------------------------------------------------------------------ | ||
| 429 | |||
| 430 | def tile_diff(frame: Frame, reference: Frame, tolerance: int = 0) -> dict: | ||
| 431 | """The 8x8 tiles where a channel of ``frame`` differs from ``reference`` by more than ``tolerance``. | ||
| 432 | |||
| 433 | Tiles are listed as ``[tx, ty]`` in row order; partial tiles at the right and bottom edges count. | ||
| 434 | """ | ||
| 435 | if (frame.width, frame.height) != (reference.width, reference.height): | ||
| 436 | raise ValueError(f"the frames differ in size: {frame.width}x{frame.height} and " | ||
| 437 | f"{reference.width}x{reference.height}") | ||
| 438 | width, height = frame.width, frame.height | ||
| 439 | nx, ny = -(-width // DIFF_TILE), -(-height // DIFF_TILE) | ||
| 440 | changed = set() | ||
| 441 | a, b = frame.rgb, reference.rgb | ||
| 442 | for y in range(height): | ||
| 443 | start, end = y * width * 3, (y + 1) * width * 3 | ||
| 444 | if a[start:end] == b[start:end]: | ||
| 445 | continue | ||
| 446 | ty = y // DIFF_TILE | ||
| 447 | for i in range(start, end): | ||
| 448 | if abs(a[i] - b[i]) > tolerance: | ||
| 449 | changed.add((ty, (i - start) // 3 // DIFF_TILE)) | ||
| 450 | tiles = [[tx, ty] for ty, tx in sorted(changed)] | ||
| 451 | box = None | ||
| 452 | if tiles: | ||
| 453 | box = [min(t[0] for t in tiles), min(t[1] for t in tiles), max(t[0] for t in tiles), | ||
| 454 | max(t[1] for t in tiles)] | ||
| 455 | return {"tile": DIFF_TILE, "changed": len(tiles), "of": nx * ny, "share": round(len(tiles) / (nx * ny), 4), | ||
| 456 | "box": box, "tiles": tiles} | ||
| 457 | |||
| 458 | |||
| 459 | # ---- the block ------------------------------------------------------------------------------------------------- | ||
| 460 | |||
| 461 | def measure(frame: Frame, reference: Optional[Frame] = None, given: Optional[str] = None, | ||
| 462 | region: Optional[tuple[int, int, int, int]] = None, tolerance: int = 0) -> dict: | ||
| 463 | """Every number of the PICTURE block, as a dict (the ``--json`` output).""" | ||
| 464 | lumas = luma(frame) | ||
| 465 | out: dict = {"picture": 1, "frame": {"width": frame.width, "height": frame.height}, | ||
| 466 | "luma": luma_stats(lumas), "dark_regions": dark_regions(lumas, frame.width, frame.height), | ||
| 467 | "lattice": find_lattice(lumas, frame.width, frame.height), | ||
| 468 | "blocks": find_blocks(lumas, frame.width, frame.height), | ||
| 469 | "reference": None, "diff": None, "region": None} | ||
| 470 | if reference is not None: | ||
| 471 | out["diff"] = tile_diff(frame, reference, tolerance) | ||
| 472 | out["reference"] = {"width": reference.width, "height": reference.height, | ||
| 473 | "luma": luma_stats(luma(reference))} | ||
| 474 | if region is not None: | ||
| 475 | out["region"] = region_stats(lumas, frame.width, region) | ||
| 476 | if out["luma"]["dark"] >= BLACK_NEAR_SHARE: | ||
| 477 | measured = "BLACK-NEAR" | ||
| 478 | elif out["reference"] and abs(out["luma"]["mean"] - out["reference"]["luma"]["mean"]) >= FLASH_DELTA: | ||
| 479 | measured = "FLASH" | ||
| 480 | elif out["lattice"]: | ||
| 481 | measured = "LATTICE" | ||
| 482 | elif out["blocks"]: | ||
| 483 | measured = "BLOCKS" | ||
| 484 | else: | ||
| 485 | measured = "OK" | ||
| 486 | out["class"] = {"measured": measured, "given": given} | ||
| 487 | return out | ||
| 488 | |||
| 489 | |||
| 490 | def _luma_text(s: dict) -> str: | ||
| 491 | return f"mean {s['mean']} | min {s['min']} | max {s['max']} | sd {s['sd']} | dark {s['dark']}" | ||
| 492 | |||
| 493 | |||
| 494 | def render(m: dict) -> str: | ||
| 495 | """The PICTURE block as text: numbers and classes only.""" | ||
| 496 | f = m["frame"] | ||
| 497 | lines = ["PICTURE | <date UTC> | <GitHub handle> | AI-assisted: <tool>"] | ||
| 498 | frame = f"{f['width']}x{f['height']}" | ||
| 499 | if m["reference"]: | ||
| 500 | frame += f" | reference {m['reference']['width']}x{m['reference']['height']}" | ||
| 501 | lines.append(f"FRAME: {frame}") | ||
| 502 | lines.append(f"LUMA: {_luma_text(m['luma'])}") | ||
| 503 | lines.append("DARK 4x4: " + " / ".join(" ".join(f"{v:.2f}" for v in row) for row in m["dark_regions"])) | ||
| 504 | lat = m["lattice"] | ||
| 505 | lines.append("LATTICE: " + ("none" if not lat else | ||
| 506 | f"tile {lat['tile']} | period {lat['period']} | phase {lat['phase']} | " | ||
| 507 | f"diagonal {lat['diagonal']} | corner {lat['corner']} | tiles {lat['tiles']} | " | ||
| 508 | f"cover {lat['cover']}")) | ||
| 509 | blk = m["blocks"] | ||
| 510 | lines.append("BLOCKS: " + ("none" if not blk else | ||
| 511 | f"block {blk['width']}x{blk['height']} | blocks {blk['blocks']} of {blk['of']} | " | ||
| 512 | f"share {blk['share']}")) | ||
| 513 | d = m["diff"] | ||
| 514 | if d is None: | ||
| 515 | lines.append("DIFF: none (one frame)") | ||
| 516 | else: | ||
| 517 | text = f"changed {d['changed']} of {d['of']} {d['tile']}x{d['tile']} tiles | share {d['share']}" | ||
| 518 | if d["box"]: | ||
| 519 | text += " | box {},{}-{},{}".format(*d["box"]) | ||
| 520 | listed = " ".join(f"{tx},{ty}" for tx, ty in d["tiles"][:TEXT_TILES]) | ||
| 521 | more = len(d["tiles"]) - TEXT_TILES | ||
| 522 | text += f" | tiles {listed}" + (f" (+{more})" if more > 0 else "") | ||
| 523 | text += f" | reference luma mean {m['reference']['luma']['mean']}" | ||
| 524 | lines.append(f"DIFF: {text}") | ||
| 525 | if m["region"]: | ||
| 526 | r = m["region"] | ||
| 527 | lines.append(f"REGION: {r['width']}x{r['height']} | {_luma_text(r)}") | ||
| 528 | lines.append(f"CLASS: {m['class']['measured']} (measured) | given: {m['class']['given'] or 'none'}") | ||
| 529 | lines.append("EVIDENCE: MEASURED (tools/picture_metrics.py, 1 frame)" if d is None | ||
| 530 | else "EVIDENCE: MEASURED (tools/picture_metrics.py, 2 frames)") | ||
| 531 | return "\n".join(lines) + "\n" | ||
| 532 | |||
| 533 | |||
| 534 | def _read(path: str, what: str) -> Frame: | ||
| 535 | try: | ||
| 536 | with open(path, "rb") as fh: | ||
| 537 | return decode_image(fh.read()) | ||
| 538 | except OSError as e: | ||
| 539 | raise ValueError(f"{what}: cannot read it: {e.strerror or e}") from None | ||
| 540 | except ValueError as e: | ||
| 541 | raise ValueError(f"{what}: {e}") from None | ||
| 542 | |||
| 543 | |||
| 544 | def main(argv=None) -> int: | ||
| 545 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | ||
| 546 | ap.add_argument("frame", help="the frame to measure (PNG or binary PPM/PGM)") | ||
| 547 | ap.add_argument("reference", nargs="?", help="a second frame: adds the per-8x8 diff and FLASH") | ||
| 548 | ap.add_argument("--json", action="store_true", help="print the numbers as JSON instead of the text block") | ||
| 549 | ap.add_argument("--class", dest="given", choices=CLASSES, metavar="CLASS", | ||
| 550 | help="a class a human saw, printed as given next to the measured one: " + ", ".join(CLASSES)) | ||
| 551 | ap.add_argument("--region", help="X,Y,W,H: also print the luma statistics of this rectangle of the frame") | ||
| 552 | ap.add_argument("--tolerance", type=int, default=0, | ||
| 553 | help="diff: ignore channel changes up to N (default 0: any change counts)") | ||
| 554 | a = ap.parse_args(argv) | ||
| 555 | if not 0 <= a.tolerance <= 255: | ||
| 556 | ap.error("--tolerance must be within 0..255") | ||
| 557 | region = None | ||
| 558 | if a.region is not None: | ||
| 559 | try: | ||
| 560 | region = tuple(int(v) for v in a.region.split(",")) | ||
| 561 | except ValueError: | ||
| 562 | ap.error("--region takes four integers X,Y,W,H") | ||
| 563 | if len(region) != 4 or min(region) < 0 or not region[2] or not region[3]: | ||
| 564 | ap.error("--region takes four integers X,Y,W,H with W and H above 0") | ||
| 565 | try: | ||
| 566 | frame = _read(a.frame, "frame") | ||
| 567 | reference = _read(a.reference, "reference") if a.reference else None | ||
| 568 | if region and (region[0] + region[2] > frame.width or region[1] + region[3] > frame.height): | ||
| 569 | raise ValueError(f"--region goes past the {frame.width}x{frame.height} frame") | ||
| 570 | m = measure(frame, reference, a.given, region, a.tolerance) | ||
| 571 | except ValueError as e: | ||
| 572 | print(f"error: {e}", file=sys.stderr) | ||
| 573 | return 2 | ||
| 574 | sys.stdout.write(json.dumps(m, indent=2) + "\n" if a.json else render(m)) | ||
| 575 | return 0 | ||
| 576 | |||
| 577 | |||
| 578 | if __name__ == "__main__": | ||
| 579 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 580 | sys.stdout.reconfigure(errors="replace") | ||
| 581 | except (AttributeError, ValueError, OSError): | ||
| 582 | pass | ||
| 583 | sys.exit(main()) | ||
diff --git a/tools/rdna2_decode.py b/tools/rdna2_decode.py index d66c1de2d..14195cfac 100644 --- a/tools/rdna2_decode.py +++ b/tools/rdna2_decode.py | |||
| @@ -374,7 +374,15 @@ def _format_dpp16_ctrl(ctrl: int) -> str: | |||
| 374 | return f"dpp_ctrl:0x{ctrl:x}" | 374 | return f"dpp_ctrl:0x{ctrl:x}" |
| 375 | 375 | ||
| 376 | 376 | ||
| 377 | def _format_ds_swizzle(offset16: int) -> str: | 377 | def _format_ds_swizzle(offset16: int) -> str | None: |
| 378 | if offset16 == 0: | ||
| 379 | return None | ||
| 380 | if offset16 >= 0xE000: | ||
| 381 | return f"offset:swizzle(FFT,{offset16 & 0x1F})" | ||
| 382 | if offset16 >= 0xC000: | ||
| 383 | direction = (offset16 >> 10) & 1 | ||
| 384 | size = (offset16 >> 5) & 0x1F | ||
| 385 | return f"offset:swizzle(ROTATE,{direction},{size})" | ||
| 378 | if (offset16 & 0x8000) == 0: | 386 | if (offset16 & 0x8000) == 0: |
| 379 | # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask. | 387 | # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask. |
| 380 | # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM. | 388 | # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM. |
| @@ -1107,9 +1115,11 @@ def _decode_one(code: bytes, pc: int, wave32: bool, mcpu: str) -> tuple[dict | N | |||
| 1107 | elif fn == "DATA1": | 1115 | elif fn == "DATA1": |
| 1108 | args.append(_vreg(data1, w)) | 1116 | args.append(_vreg(data1, w)) |
| 1109 | mods = [] | 1117 | mods = [] |
| 1110 | is_2addr = ("2_" in name or "2st64_" in name) | 1118 | is_2addr = name.startswith(("ds_read2", "ds_write2", "ds_wrxchg2")) |
| 1111 | if name == "ds_swizzle_b32": | 1119 | if name == "ds_swizzle_b32": |
| 1112 | mods.append(_format_ds_swizzle(offset0 | (offset1 << 8))) | 1120 | swz = _format_ds_swizzle(offset0 | (offset1 << 8)) |
| 1121 | if swz: | ||
| 1122 | mods.append(swz) | ||
| 1113 | elif is_2addr: | 1123 | elif is_2addr: |
| 1114 | if offset0: | 1124 | if offset0: |
| 1115 | mods.append(f"offset0:{offset0}") | 1125 | mods.append(f"offset0:{offset0}") |
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 7e4529e75..80b641633 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py | |||
| @@ -111,6 +111,14 @@ FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from si | |||
| 111 | # maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original | 111 | # maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original |
| 112 | # coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). | 112 | # coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). |
| 113 | TEXEL_OFFSET_FALLBACK = False | 113 | TEXEL_OFFSET_FALLBACK = False |
| 114 | # --explicit-lod-bias: MoltenVK 1.4.2 on an Apple M3 drops VkSamplerCreateInfo::mipLodBias (ps_ssharp: neither | ||
| 115 | # image_sample_lz with a +1 S# LOD_BIAS nor the derivative-LOD image_sample with -1 moves a level); on an Apple M5 Pro | ||
| 116 | # the same MoltenVK applies it, so tools/lod_bias_probe.py measures it per device. With this flag the shader applies the | ||
| 117 | # S#'s signed 5.8 LOD_BIAS (word 2 [13:0]) itself: added to the Lod of explicit-LOD samples and to the bias of | ||
| 118 | # _b / _c_b, as a Bias operand on implicit samples, and as a 2^bias scale of Grad derivatives (lambda = log2 of | ||
| 119 | # their length). The sampler still clamps the result to MIN_LOD..MAX_LOD. Only for a driver that drops the | ||
| 120 | # sampler's bias: elsewhere it would count twice. | ||
| 121 | EXPLICIT_LOD_BIAS = False | ||
| 114 | FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property | 122 | FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property |
| 115 | FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32 | 123 | FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32 |
| 116 | LDS_BOUNDS = True # False (--no-lds-bounds): restore wrapped power-of-two LDS array when constant offsets stay in range | 124 | LDS_BOUNDS = True # False (--no-lds-bounds): restore wrapped power-of-two LDS array when constant offsets stay in range |
| @@ -454,6 +462,23 @@ SOPC_SRC32_SPECIALS = frozenset({ | |||
| 454 | }) | 462 | }) |
| 455 | SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) | 463 | SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) |
| 456 | 464 | ||
| 465 | # Ops that read a lane-mask operand as a plain number even though the destination is not a VGPR | ||
| 466 | # (the scalar ALU set; the v_* entries already qualify through their VGPR destinations). Ported from | ||
| 467 | # PR #1043's lane_masks.NUMBER_READERS so scalar readers (s_add_u32 s20, s10, K after v_cmp wrote s10) | ||
| 468 | # see the wave's mask word, not this lane's 0 / ~0 bit. Mask-preserving ops (s_mov_b32, the MASK_SOP2 | ||
| 469 | # logic ops, saveexec/wrexec) are deliberately absent: a mask moving or combining as a mask keeps the | ||
| 470 | # per-lane bit mask_src readers rely on. _sdwa / _dpp / _dpp8 forms are excluded at the check site. | ||
| 471 | MASK_NUMBER_READERS = frozenset(( | ||
| 472 | "s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32", "s_mul_i32", | ||
| 473 | "s_mul_hi_u32", "s_mul_hi_i32", "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_bfe_u32", "s_bfe_i32", | ||
| 474 | "s_min_u32", "s_min_i32", "s_max_u32", "s_max_i32", "s_brev_b32", | ||
| 475 | "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32", | ||
| 476 | "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_lshlrev_b32", "v_lshrrev_b32", | ||
| 477 | "v_ashrrev_i32", "v_mul_lo_u32", "v_mul_hi_u32", "v_min_u32", "v_max_u32", "v_min_i32", | ||
| 478 | "v_max_i32", "v_bfe_u32", "v_bfe_i32", "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", | ||
| 479 | "v_bcnt_u32_b32", | ||
| 480 | )) | ||
| 481 | |||
| 457 | # Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). | 482 | # Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). |
| 458 | # VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or | 483 | # VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or |
| 459 | # other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). | 484 | # other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). |
| @@ -747,7 +772,21 @@ class Gen: | |||
| 747 | 772 | ||
| 748 | def src_u(self, a): | 773 | def src_u(self, a): |
| 749 | k = a["k"] | 774 | k = a["k"] |
| 750 | if k in ("vgpr", "sgpr"): | 775 | if ((k == "sgpr" and a.get("n", 1) == 1) or |
| 776 | (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \ | ||
| 777 | and self.holds_lane_mask(a) and self.mask_read_is_data(): | ||
| 778 | # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's | ||
| 779 | # mask word (the same in every lane), as the SOP ops that read a mask as a number already do | ||
| 780 | # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each | ||
| 781 | # lane its own bit where hardware gives the mask itself (found by tools/crosslane_fuzz.py). | ||
| 782 | # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this | ||
| 783 | # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too — | ||
| 784 | # mask_src extracts this lane's bit back out when a mask consumer reads one. | ||
| 785 | # The gather itself is eager (wave_mask): EXEC narrowing is a per-lane value in this | ||
| 786 | # model, not SPIR-V control flow, and mask-data readers are kept out of lane-local | ||
| 787 | # `if (active)` runs, so lanes off in EXEC still contribute their mask bits. | ||
| 788 | v = self.lane_mask_word(a) | ||
| 789 | elif k in ("vgpr", "sgpr"): | ||
| 751 | if a.get("n", 1) != 1: | 790 | if a.get("n", 1) != 1: |
| 752 | raise Unsupported("64-bit operand") | 791 | raise Unsupported("64-bit operand") |
| 753 | v = self.load_reg(k, a["r"]) | 792 | v = self.load_reg(k, a["r"]) |
| @@ -788,6 +827,33 @@ class Gen: | |||
| 788 | v = self.sdwa_src(v, a) | 827 | v = self.sdwa_src(v, a) |
| 789 | return self.modify(v, a) | 828 | return self.modify(v, a) |
| 790 | 829 | ||
| 830 | def mask_read_is_data(self, ins=None): | ||
| 831 | """Whether the instruction being translated (self.cur_ins, or `ins`) consumes a lane mask as plain data. | ||
| 832 | A VGPR destination means the mask operand is read as a 32-bit value — the whole wave's mask word, | ||
| 833 | which is what hardware holds and what the VGPR then stores (a mask that stays in a VGPR keeps the | ||
| 834 | word too; mask_src extracts this lane's bit back out for mask consumers). Anything else — an SGPR, | ||
| 835 | EXEC or VCC destination — keeps this lane's 0 / ~0 bit, which mask_src readers rely on.""" | ||
| 836 | ins = self.cur_ins if ins is None else ins | ||
| 837 | if ins is None: | ||
| 838 | return False | ||
| 839 | a = ins["args"] | ||
| 840 | if not a: | ||
| 841 | return False | ||
| 842 | if base_op(ins["op"]) in MASK_NUMBER_READERS and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")): | ||
| 843 | # A scalar (or plain vector) number op reads the mask operand as data even with an SGPR | ||
| 844 | # destination: s_add_u32 s20, s10, K wants the wave's mask word in s20 (#1043's | ||
| 845 | # NUMBER_READERS). Mask moves and mask logic ops are not listed, so they keep the bit. | ||
| 846 | return True | ||
| 847 | if a[0]["k"] != "vgpr": | ||
| 848 | return False | ||
| 849 | if base_op(ins["op"]) == "v_writelane_b32": | ||
| 850 | # A mask parked in one lane of a VGPR comes back through v_readlane as this lane's bit: the | ||
| 851 | # parked SGPR slot keeps the per-lane value. | ||
| 852 | slot = lane_masks.lane_slot(a[0], a[2], wave64=self.wave64) | ||
| 853 | if slot and slot[1:] in self.parked: | ||
| 854 | return False | ||
| 855 | return True | ||
| 856 | |||
| 791 | def src_u_sign_mods(self, a): | 857 | def src_u_sign_mods(self, a): |
| 792 | """A 32-bit source with its VOP3 abs/neg applied as sign-bit moves on the raw bits (abs clears bit 31, neg | 858 | """A 32-bit source with its VOP3 abs/neg applied as sign-bit moves on the raw bits (abs clears bit 31, neg |
| 793 | flips it), for an op that only moves bits: SPIR-V FAbs/OpFNegate may quiet a signalling NaN or flush a | 859 | flips it), for an op that only moves bits: SPIR-V FAbs/OpFNegate may quiet a signalling NaN or flush a |
| @@ -2073,13 +2139,43 @@ class Gen: | |||
| 2073 | """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only | 2139 | """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only |
| 2074 | ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as | 2140 | ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as |
| 2075 | keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as | 2141 | keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as |
| 2076 | data is this lane's bit (only s_bcnt1, s_ff1 and v_mbcnt gather the whole wave's); a mask on its way | 2142 | data gathers the whole wave's mask word (mask_data_src keeps such instructions out of |
| 2143 | the run, since the subgroup op can't sit inside `if (active)`); a mask on its way | ||
| 2077 | through a VGPR (mask_writes) is written in every lane, so it stays out.""" | 2144 | through a VGPR (mask_writes) is written in every lane, so it stays out.""" |
| 2078 | op = base_op(ins["op"]) | 2145 | op = base_op(ins["op"]) |
| 2079 | a = ins["args"] | 2146 | a = ins["args"] |
| 2080 | return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op | 2147 | return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op |
| 2081 | and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) | 2148 | and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) |
| 2082 | and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes) | 2149 | and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes |
| 2150 | and not self.mask_data_src(ins)) | ||
| 2151 | |||
| 2152 | def mask_data_src(self, ins): | ||
| 2153 | """Whether ins reads a lane mask as data through src_u (a mask-holding SGPR, or EXEC/VCC), which | ||
| 2154 | materializes the whole wave's mask word with a subgroup op. That can't happen inside an active run | ||
| 2155 | (RUN_FORBIDDEN bars OpGroup there, and inactive lanes wouldn't vote), so lane_local keeps the | ||
| 2156 | instruction out; dst()'s per-write EXEC select gates the VGPR write instead. A mask-holding VGPR is | ||
| 2157 | not listed: it already stores the wave's mask word, so reading it is a plain register load. The mask | ||
| 2158 | state is the one lane_masks.py precomputed for this instruction (self.lane_masks), since lane_local | ||
| 2159 | runs before the instruction is translated.""" | ||
| 2160 | masks = self.lane_masks.get(id(ins)) or {} | ||
| 2161 | return any(self._mask_data_operand(x, masks, ins) for x in ins["args"][1:]) | ||
| 2162 | |||
| 2163 | def _mask_data_operand(self, x, masks, ins): | ||
| 2164 | """Whether src_u will materialize operand `x`'s lane mask as the wave's mask word for `ins` | ||
| 2165 | (a subgroup op or, under --wave64-emulate, an exchange round): `masks` is the lane_masks state | ||
| 2166 | for ins — self.lane_masks[id(ins)], the same dict self.cur_masks holds while translating.""" | ||
| 2167 | if x["k"] == "sgpr": | ||
| 2168 | if x.get("n", 1) != 1 or x["r"] not in masks: | ||
| 2169 | return False | ||
| 2170 | elif x["k"] == "special": | ||
| 2171 | t = x.get("t", "") | ||
| 2172 | if not (t in ("exec_lo", "exec_hi") or | ||
| 2173 | (t in ("vcc", "vcc_lo") and "vcc" in masks) or | ||
| 2174 | (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks)): | ||
| 2175 | return False | ||
| 2176 | else: | ||
| 2177 | return False | ||
| 2178 | return self.mask_read_is_data(ins) | ||
| 2083 | 2179 | ||
| 2084 | def insns(self, seq): | 2180 | def insns(self, seq): |
| 2085 | """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN | 2181 | """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN |
| @@ -7032,6 +7128,16 @@ class Gen: | |||
| 7032 | ) | 7128 | ) |
| 7033 | all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots)) | 7129 | all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots)) |
| 7034 | self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)} | 7130 | self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)} |
| 7131 | # Instructions whose lane-mask data read will gather the wave's mask word (src_u's | ||
| 7132 | # lane_mask_word path) are cross-lane exchanges for the | ||
| 7133 | # wave64-emulation planner: it must not fold them into a lane-local region or schedule | ||
| 7134 | # a barrier beside them (wave64_emulate_opt checks ins["mask_words"]). | ||
| 7135 | for blk in blocks[0]: | ||
| 7136 | for ins in blk: | ||
| 7137 | words = tuple(i for i, x in enumerate(ins["args"]) | ||
| 7138 | if i and self._mask_data_operand(x, self.lane_masks.get(id(ins), {}), ins)) | ||
| 7139 | if words: | ||
| 7140 | ins["mask_words"] = words | ||
| 7035 | 7141 | ||
| 7036 | def mask_half(self, a): | 7142 | def mask_half(self, a): |
| 7037 | """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" | 7143 | """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" |
| @@ -7050,6 +7156,12 @@ class Gen: | |||
| 7050 | return "lo" | 7156 | return "lo" |
| 7051 | if k == lane_masks.MASK_HI: | 7157 | if k == lane_masks.MASK_HI: |
| 7052 | return "hi" | 7158 | return "hi" |
| 7159 | if a["k"] == "vgpr" and a.get("n", 1) == 1: | ||
| 7160 | k = self.cur_masks.get(("v", a["r"])) | ||
| 7161 | if k == lane_masks.MASK_LO: | ||
| 7162 | return "lo" | ||
| 7163 | if k == lane_masks.MASK_HI: | ||
| 7164 | return "hi" | ||
| 7053 | return None | 7165 | return None |
| 7054 | 7166 | ||
| 7055 | def lane_mask_word(self, a): | 7167 | def lane_mask_word(self, a): |
| @@ -7380,6 +7492,23 @@ class Gen: | |||
| 7380 | self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") | 7492 | self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") |
| 7381 | return r | 7493 | return r |
| 7382 | 7494 | ||
| 7495 | def _vgpr_mask_lane_bit(self, word, a): | ||
| 7496 | """This lane's 0 / ~0 bit of the lane-mask word `word` held by mask VGPR operand `a`: its own position | ||
| 7497 | of the word — and only when the lane is in the half the register covers (a MASK_LO/MASK_HI word means | ||
| 7498 | nothing to the other half).""" | ||
| 7499 | half = self.mask_half(a) | ||
| 7500 | if half is None: | ||
| 7501 | return self._scalar_word_lane_bit(word) | ||
| 7502 | lane = self.wave_lane() | ||
| 7503 | in_half = self.tmp() | ||
| 7504 | self.emit(f"{in_half} = OpULessThan %bool {lane} {self.cu(32)}" | ||
| 7505 | if half == "lo" else | ||
| 7506 | f"{in_half} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") | ||
| 7507 | bit = self._scalar_word_lane_bit(word, lane) | ||
| 7508 | r = self.tmp() | ||
| 7509 | self.emit(f"{r} = OpSelect %uint {in_half} {bit} {self.cu(0)}") | ||
| 7510 | return r | ||
| 7511 | |||
| 7383 | def mask_src(self, a, wide=True): | 7512 | def mask_src(self, a, wide=True): |
| 7384 | """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one | 7513 | """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one |
| 7385 | bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or | 7514 | bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or |
| @@ -7410,6 +7539,8 @@ class Gen: | |||
| 7410 | return self._scalar_word_lane_bit(word, lane) | 7539 | return self._scalar_word_lane_bit(word, lane) |
| 7411 | if a["k"] == "special" and a["t"] == "null": | 7540 | if a["k"] == "special" and a["t"] == "null": |
| 7412 | return self.cu(0) | 7541 | return self.cu(0) |
| 7542 | if a["k"] == "vgpr" and a.get("n", 1) == 1 and ("v", a["r"]) in self.cur_masks: | ||
| 7543 | return self._vgpr_mask_lane_bit(self.load_reg("vgpr", a["r"]), a) | ||
| 7413 | if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: | 7544 | if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: |
| 7414 | v = self.tmp() | 7545 | v = self.tmp() |
| 7415 | self.emit(f"{v} = OpLoad %uint %vcc_hi") | 7546 | self.emit(f"{v} = OpLoad %uint %vcc_hi") |
| @@ -8800,11 +8931,15 @@ class Gen: | |||
| 8800 | # lane took its own value. That is the same thing only when all lanes hold the value, and after a | 8931 | # lane took its own value. That is the same thing only when all lanes hold the value, and after a |
| 8801 | # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group | 8932 | # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group |
| 8802 | # of lanes), they loaded from wherever their stale register pointed. | 8933 | # of lanes), they loaded from wherever their stale register pointed. |
| 8803 | if a[1]["k"] == "vgpr" and ("v", a[1]["r"]) in self.cur_masks: | 8934 | # A VGPR that holds a lane mask keeps the whole wave's mask word, but only in the lanes a write |
| 8804 | # A lane mask that went through the vector unit (three SGPRs ORed with v_or3_b32, say). The | 8935 | # reached: an EXEC-gated v_mov_b32 leaves the other lanes' old word behind (SHADER-21 part 2), so |
| 8805 | # hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit. | 8936 | # this lane's own copy can be a stale half's word. Hardware reads the first active lane's copy — |
| 8806 | self.dst(a[0], self.src_u(a[1])) | 8937 | # the broadcast below. A VGPR destination is never mask-tracked (lane_masks.put ignores VGPR |
| 8807 | return | 8938 | # writes), so it gets the broadcast word itself, as hardware leaves it; a mask-tracked SGPR or |
| 8939 | # special destination gets this lane's bit of that word (_vgpr_mask_lane_bit, half-aware in | ||
| 8940 | # wave64), the per-lane value mask_src readers rely on. | ||
| 8941 | mask_vgpr = (a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1 | ||
| 8942 | and ("v", a[1]["r"]) in self.cur_masks) | ||
| 8808 | if self.x_one_lane: | 8943 | if self.x_one_lane: |
| 8809 | # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC. | 8944 | # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC. |
| 8810 | self.dst(a[0], self.src_u(a[1])) | 8945 | self.dst(a[0], self.src_u(a[1])) |
| @@ -8819,7 +8954,8 @@ class Gen: | |||
| 8819 | self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") | 8954 | self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") |
| 8820 | self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") | 8955 | self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") |
| 8821 | self.g_shuffle(r, v, first) | 8956 | self.g_shuffle(r, v, first) |
| 8822 | self.dst(a[0], r) | 8957 | res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) |
| 8958 | self.dst(a[0], res) | ||
| 8823 | return | 8959 | return |
| 8824 | if self.emulate: | 8960 | if self.emulate: |
| 8825 | # The wave's active lanes as two mask words and every lane's value, in one round. | 8961 | # The wave's active lanes as two mask words and every lane's value, in one round. |
| @@ -8834,7 +8970,9 @@ class Gen: | |||
| 8834 | self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") | 8970 | self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") |
| 8835 | self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") | 8971 | self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") |
| 8836 | self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") | 8972 | self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") |
| 8837 | self.dst(a[0], read(first)) | 8973 | w = read(first) |
| 8974 | res = w if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(w, a[1]) | ||
| 8975 | self.dst(a[0], res) | ||
| 8838 | return | 8976 | return |
| 8839 | self.uses_subgroup = self.uses_ballot = True | 8977 | self.uses_subgroup = self.uses_ballot = True |
| 8840 | v, act = self.src_u(a[1]), self.active_b() | 8978 | v, act = self.src_u(a[1]), self.active_b() |
| @@ -8850,7 +8988,8 @@ class Gen: | |||
| 8850 | fallback = self.subgroup_first_running_lane() | 8988 | fallback = self.subgroup_first_running_lane() |
| 8851 | self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}") | 8989 | self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}") |
| 8852 | self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") | 8990 | self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") |
| 8853 | self.dst(a[0], r) | 8991 | res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) |
| 8992 | self.dst(a[0], res) | ||
| 8854 | elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): | 8993 | elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): |
| 8855 | self.image_op(op, a, mods) | 8994 | self.image_op(op, a, mods) |
| 8856 | elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", | 8995 | elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", |
| @@ -10404,7 +10543,12 @@ class Gen: | |||
| 10404 | self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}") | 10543 | self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}") |
| 10405 | r = sat | 10544 | r = sat |
| 10406 | lo = self.tmp() | 10545 | lo = self.tmp() |
| 10407 | self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") | 10546 | # BitFieldUExtract, not OpBitwiseAnd & 0xFFFF: on NVIDIA's shader compiler an And of a value that |
| 10547 | # passed through %int ops (the signed i16 add/sub/min/max and ashr paths below) feeding the | ||
| 10548 | # preserve-high-half merge miscompiles the KEPT high half (measured on an RTX 4070 SUPER, wave32: | ||
| 10549 | # v_add_nc_i16 ... op_sel:[1,1,0] clamp wrote 0x1113AAA8 for 0x0002AAA8). Extract reads the same | ||
| 10550 | # low 16 bits and dodges that peephole; AMD and the interpreter are unaffected. | ||
| 10551 | self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") | ||
| 10408 | if e64 and sb[2]: | 10552 | if e64 and sb[2]: |
| 10409 | # op_sel destination bit: the result goes to the high half, the low half is kept. | 10553 | # op_sel destination bit: the result goes to the high half, the low half is kept. |
| 10410 | if a[0]["k"] != "vgpr": | 10554 | if a[0]["k"] != "vgpr": |
| @@ -10446,7 +10590,7 @@ class Gen: | |||
| 10446 | self.emit(f"{sat} = OpBitcast %uint {hi_c}") | 10590 | self.emit(f"{sat} = OpBitcast %uint {hi_c}") |
| 10447 | r = sat | 10591 | r = sat |
| 10448 | lo = self.tmp() | 10592 | lo = self.tmp() |
| 10449 | self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") | 10593 | self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # see the nc_i16 note above: And & 0xFFFF miscompiles on NVIDIA |
| 10450 | if dhi: | 10594 | if dhi: |
| 10451 | old, keep, sh16, v = (self.tmp() for _ in range(4)) | 10595 | old, keep, sh16, v = (self.tmp() for _ in range(4)) |
| 10452 | self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") | 10596 | self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") |
| @@ -10486,7 +10630,7 @@ class Gen: | |||
| 10486 | else: | 10630 | else: |
| 10487 | r = m | 10631 | r = m |
| 10488 | lo = self.tmp() | 10632 | lo = self.tmp() |
| 10489 | self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") | 10633 | self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # same NVIDIA And-&-0xFFFF workaround as above |
| 10490 | self.write_half16(a[0], lo, dhi) | 10634 | self.write_half16(a[0], lo, dhi) |
| 10491 | elif op == "v_bcnt_u32_b32": | 10635 | elif op == "v_bcnt_u32_b32": |
| 10492 | self._check_int32_valu(op, ins["op"], a, mods) | 10636 | self._check_int32_valu(op, ins["op"], a, mods) |
| @@ -11981,7 +12125,10 @@ class Gen: | |||
| 11981 | self.emit(f"{conv} = OpBitcast %uint {ci}") | 12125 | self.emit(f"{conv} = OpBitcast %uint {ci}") |
| 11982 | else: | 12126 | else: |
| 11983 | self.emit(f"{conv} = OpConvertFToU %uint {cl}") | 12127 | self.emit(f"{conv} = OpConvertFToU %uint {cl}") |
| 11984 | self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") | 12128 | # BitFieldUExtract, not And & 0xFFFF: the signed form's conv is a Bitcast of an %int |
| 12129 | # ConvertFToS, and NVIDIA's shader compiler miscompiles that And feeding the | ||
| 12130 | # preserve-high-half merge (same workaround as the VOP3 16-bit integer ops). | ||
| 12131 | self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}") | ||
| 11985 | if not dhi: | 12132 | if not dhi: |
| 11986 | self.write_lo16(a[0], lo) | 12133 | self.write_lo16(a[0], lo) |
| 11987 | else: | 12134 | else: |
| @@ -12041,7 +12188,8 @@ class Gen: | |||
| 12041 | self.emit(f"{conv} = OpBitcast %uint {ci}") | 12188 | self.emit(f"{conv} = OpBitcast %uint {ci}") |
| 12042 | else: | 12189 | else: |
| 12043 | self.emit(f"{conv} = OpConvertFToU %uint {rn}") | 12190 | self.emit(f"{conv} = OpConvertFToU %uint {rn}") |
| 12044 | self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") | 12191 | # Same NVIDIA And-&-0xFFFF workaround as v_cvt_i16_f16 above. |
| 12192 | self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}") | ||
| 12045 | if not dhi: | 12193 | if not dhi: |
| 12046 | self.write_lo16(a[0], lo) | 12194 | self.write_lo16(a[0], lo) |
| 12047 | else: | 12195 | else: |
| @@ -14467,6 +14615,47 @@ class Gen: | |||
| 14467 | self.emit(f"{one} = OpLogicalOr %bool {white} {black}") | 14615 | self.emit(f"{one} = OpLogicalOr %bool {white} {black}") |
| 14468 | return one | 14616 | return one |
| 14469 | 14617 | ||
| 14618 | def ssharp_lod_bias(self, word_reg: int): | ||
| 14619 | """--explicit-lod-bias: the S#'s LOD_BIAS (word 2 [13:0], signed 5.8 fixed point, -32..31 in steps of 1/256) | ||
| 14620 | as a float id, or None when a literal S# has a zero bias.""" | ||
| 14621 | literal = self.sgpr_imm.get(word_reg) | ||
| 14622 | if literal is not None: | ||
| 14623 | bias = ((literal & 0x3fff) ^ 0x2000) - 0x2000 | ||
| 14624 | return self.fconst(bias / 256.0) if bias else None | ||
| 14625 | word = self.load_reg("sgpr", word_reg) | ||
| 14626 | raw, signed, value, scaled = (self.tmp() for _ in range(4)) | ||
| 14627 | self.emit(f"{raw} = OpBitFieldSExtract %uint {word} {self.cu(0)} {self.cu(14)}") | ||
| 14628 | self.emit(f"{signed} = OpBitcast %int {raw}") | ||
| 14629 | self.emit(f"{value} = OpConvertSToF %float {signed}") | ||
| 14630 | self.emit(f"{scaled} = OpFMul %float {value} {self.fconst(1.0 / 256.0)}") | ||
| 14631 | return scaled | ||
| 14632 | |||
| 14633 | def add_ssharp_lod_bias(self, lod: str, word_reg: int) -> str: | ||
| 14634 | """--explicit-lod-bias: lod + the S#'s LOD_BIAS.""" | ||
| 14635 | b = self.ssharp_lod_bias(word_reg) | ||
| 14636 | if b is None: | ||
| 14637 | return lod | ||
| 14638 | out = self.tmp() | ||
| 14639 | self.emit(f"{out} = OpFAdd %float {lod} {b}") | ||
| 14640 | return out | ||
| 14641 | |||
| 14642 | def scale_grads_by_ssharp_bias(self, grads, width: int, word_reg: int): | ||
| 14643 | """--explicit-lod-bias: (dx, dy) * 2^LOD_BIAS, which adds the bias to the LOD the derivatives give.""" | ||
| 14644 | b = self.ssharp_lod_bias(word_reg) | ||
| 14645 | if b is None: | ||
| 14646 | return grads | ||
| 14647 | k = self.tmp() | ||
| 14648 | self.emit(f"{k} = OpExtInst %float %glsl Exp2 {b}") | ||
| 14649 | out = [] | ||
| 14650 | for g in grads: | ||
| 14651 | t = self.tmp() | ||
| 14652 | if width == 1: | ||
| 14653 | self.emit(f"{t} = OpFMul %float {g} {k}") | ||
| 14654 | else: | ||
| 14655 | self.emit(f"{t} = OpVectorTimesScalar %v{width}float {g} {k}") | ||
| 14656 | out.append(t) | ||
| 14657 | return tuple(out) | ||
| 14658 | |||
| 14470 | def clamp_gather_lod(self, lod: str, word_reg: int) -> str: | 14659 | def clamp_gather_lod(self, lod: str, word_reg: int) -> str: |
| 14471 | """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. | 14660 | """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. |
| 14472 | 14661 | ||
| @@ -15449,6 +15638,8 @@ class Gen: | |||
| 15449 | bias = None | 15638 | bias = None |
| 15450 | if kind in ("_b", "_c_b"): | 15639 | if kind in ("_b", "_c_b"): |
| 15451 | bias, f = f[0], f[1:] | 15640 | bias, f = f[0], f[1:] |
| 15641 | if EXPLICIT_LOD_BIAS: | ||
| 15642 | bias = self.add_ssharp_lod_bias(bias, a[3]["r"] + 2) | ||
| 15452 | ref = None | 15643 | ref = None |
| 15453 | if kind.startswith("_c"): | 15644 | if kind.startswith("_c"): |
| 15454 | ref, f = f[0], f[1:] | 15645 | ref, f = f[0], f[1:] |
| @@ -15464,6 +15655,8 @@ class Gen: | |||
| 15464 | self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") | 15655 | self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") |
| 15465 | self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") | 15656 | self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") |
| 15466 | grads = (gx, gy) | 15657 | grads = (gx, gy) |
| 15658 | if EXPLICIT_LOD_BIAS: | ||
| 15659 | grads = self.scale_grads_by_ssharp_bias(grads, grad_width, a[3]["r"] + 2) | ||
| 15467 | f = f[2 * grad_width:] | 15660 | f = f[2 * grad_width:] |
| 15468 | if clamp: | 15661 | if clamp: |
| 15469 | # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so | 15662 | # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so |
| @@ -15485,12 +15678,15 @@ class Gen: | |||
| 15485 | uv = self.tmp() | 15678 | uv = self.tmp() |
| 15486 | self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") | 15679 | self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") |
| 15487 | lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" | 15680 | lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" |
| 15681 | if EXPLICIT_LOD_BIAS and kind in ("_lz", "_l"): | ||
| 15682 | lod = self.add_ssharp_lod_bias(lod, a[3]["r"] + 2) | ||
| 15488 | if typed_sample: | 15683 | if typed_sample: |
| 15489 | float_only = self._is_float_only_image_op(op, a, mods) | 15684 | float_only = self._is_float_only_image_op(op, a, mods) |
| 15490 | # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its | 15685 | # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its |
| 15491 | # 6-layer 2D-array view, which is what `img` was loaded from above. | 15686 | # 6-layer 2D-array view, which is what `img` was loaded from above. |
| 15492 | di = self.STORE_DIMS[view_dim][0] | 15687 | di = self.STORE_DIMS[view_dim][0] |
| 15493 | if typed_implicit and float_only: | 15688 | if typed_implicit and float_only and not EXPLICIT_LOD_BIAS: |
| 15689 | # With --explicit-lod-bias the Grad path below scales the derivatives by the S# bias. | ||
| 15494 | def sample(image, cls, ty): | 15690 | def sample(image, cls, ty): |
| 15495 | sampled = sampled_image(image, cls, di) | 15691 | sampled = sampled_image(image, cls, di) |
| 15496 | result = self.tmp() | 15692 | result = self.tmp() |
| @@ -15503,6 +15699,8 @@ class Gen: | |||
| 15503 | dx, dy = self.tmp(), self.tmp() | 15699 | dx, dy = self.tmp(), self.tmp() |
| 15504 | self.emit(f"{dx} = OpDPdx %v2float {uv}") | 15700 | self.emit(f"{dx} = OpDPdx %v2float {uv}") |
| 15505 | self.emit(f"{dy} = OpDPdy %v2float {uv}") | 15701 | self.emit(f"{dy} = OpDPdy %v2float {uv}") |
| 15702 | if EXPLICIT_LOD_BIAS: | ||
| 15703 | dx, dy = self.scale_grads_by_ssharp_bias((dx, dy), 2, a[3]["r"] + 2) | ||
| 15506 | operands = f"Grad {dx} {dy}" | 15704 | operands = f"Grad {dx} {dy}" |
| 15507 | 15705 | ||
| 15508 | def sample(image, cls, ty): | 15706 | def sample(image, cls, ty): |
| @@ -15525,19 +15723,31 @@ class Gen: | |||
| 15525 | # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is | 15723 | # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is |
| 15526 | # max(base, clamp) and no MinLod operand. | 15724 | # max(base, clamp) and no MinLod operand. |
| 15527 | lod_zero = "%f0" | 15725 | lod_zero = "%f0" |
| 15726 | if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"): | ||
| 15727 | # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias). | ||
| 15728 | # The bias goes in before the _cl clamp below: Vulkan clamps the biased LOD, max(bias, minlod). | ||
| 15729 | lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2) | ||
| 15528 | if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): | 15730 | if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): |
| 15731 | base = lod_zero | ||
| 15529 | lod_zero = self.tmp() | 15732 | lod_zero = self.tmp() |
| 15530 | self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax %f0 {minlod}") | 15733 | self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax {base} {minlod}") |
| 15531 | bias_lod = bias | 15734 | bias_lod = bias |
| 15532 | if kind in ("_b", "_c_b") and not implicit and minlod is not None: | 15735 | if kind in ("_b", "_c_b") and not implicit and minlod is not None: |
| 15533 | bias_lod = self.tmp() | 15736 | bias_lod = self.tmp() |
| 15534 | self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") | 15737 | self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") |
| 15738 | # Implicit samples without a bias of their own take the S# bias as a Bias operand. | ||
| 15739 | sbias = (self.ssharp_lod_bias(a[3]["r"] + 2) | ||
| 15740 | if EXPLICIT_LOD_BIAS and implicit and kind in ("", "_c") else None) | ||
| 15535 | grads_fb = None | 15741 | grads_fb = None |
| 15536 | if off is not None and TEXEL_OFFSET_FALLBACK: | 15742 | if off is not None and TEXEL_OFFSET_FALLBACK: |
| 15537 | fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod | 15743 | fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod |
| 15538 | uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, | 15744 | uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, |
| 15539 | a[3]) | 15745 | a[3]) |
| 15540 | off = None | 15746 | off = None |
| 15747 | if grads_fb is not None and sbias is not None: | ||
| 15748 | # Grad, not Bias, carries these samples now: scale the derivatives instead. | ||
| 15749 | grads_fb = self.scale_grads_by_ssharp_bias(grads_fb, 3 if is3d else ncoord, a[3]["r"] + 2) | ||
| 15750 | sbias = None | ||
| 15541 | 15751 | ||
| 15542 | def opnd(mask, args): | 15752 | def opnd(mask, args): |
| 15543 | """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" | 15753 | """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" |
| @@ -15558,7 +15768,7 @@ class Gen: | |||
| 15558 | self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " | 15768 | self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " |
| 15559 | f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") | 15769 | f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") |
| 15560 | elif kind == "": | 15770 | elif kind == "": |
| 15561 | self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else | 15771 | self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', sbias) if sbias else opnd('', '')}" if self.stage == "ps" else |
| 15562 | f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") | 15772 | f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") |
| 15563 | elif kind in ("_lz", "_l"): | 15773 | elif kind in ("_lz", "_l"): |
| 15564 | self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") | 15774 | self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") |
| @@ -15570,6 +15780,8 @@ class Gen: | |||
| 15570 | if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): | 15780 | if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): |
| 15571 | # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) | 15781 | # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) |
| 15572 | d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) | 15782 | d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) |
| 15783 | if EXPLICIT_LOD_BIAS and kind == "_c_l": | ||
| 15784 | d_lod = self.add_ssharp_lod_bias(d_lod, a[3]["r"] + 2) | ||
| 15573 | self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") | 15785 | self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") |
| 15574 | elif grads_fb is not None: | 15786 | elif grads_fb is not None: |
| 15575 | self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " | 15787 | self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " |
| @@ -15577,7 +15789,7 @@ class Gen: | |||
| 15577 | elif kind == "_c_b": | 15789 | elif kind == "_c_b": |
| 15578 | self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") | 15790 | self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") |
| 15579 | else: | 15791 | else: |
| 15580 | self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('', '')}") | 15792 | self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', sbias) if sbias else opnd('', '')}") |
| 15581 | if d16: | 15793 | if d16: |
| 15582 | # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until | 15794 | # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until |
| 15583 | # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). | 15795 | # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). |
| @@ -15700,7 +15912,9 @@ class Gen: | |||
| 15700 | self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} " | 15912 | self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} " |
| 15701 | f"{self.as_int(self.cu(0x7FFF))}") | 15913 | f"{self.as_int(self.cu(0x7FFF))}") |
| 15702 | self.emit(f"{raw} = OpBitcast %uint {clamped}") | 15914 | self.emit(f"{raw} = OpBitcast %uint {clamped}") |
| 15703 | self.emit(f"{half} = OpBitwiseAnd %uint {raw} {self.cu(0xFFFF)}") | 15915 | # BitFieldUExtract, not And & 0xFFFF: raw is a Bitcast of an %int SClamp and the result |
| 15916 | # reaches preserve-high-half merges (d16 image/buffer stores); NVIDIA miscompiles the And. | ||
| 15917 | self.emit(f"{half} = OpBitFieldUExtract %uint {raw} {self.cu(0)} {self.cu(16)}") | ||
| 15704 | else: | 15918 | else: |
| 15705 | self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") | 15919 | self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") |
| 15706 | return half | 15920 | return half |
| @@ -23817,6 +24031,9 @@ def main(): | |||
| 23817 | ap.add_argument("--texel-offset-fallback", action="store_true", | 24031 | ap.add_argument("--texel-offset-fallback", action="store_true", |
| 23818 | help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " | 24032 | help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " |
| 23819 | "the coordinate instead of the Offset operand") | 24033 | "the coordinate instead of the Offset operand") |
| 24034 | ap.add_argument("--explicit-lod-bias", action="store_true", | ||
| 24035 | help="apply the S# LOD_BIAS in the shader, for a driver whose sampler drops mipLodBias (measured by " | ||
| 24036 | "tools/lod_bias_probe.py); elsewhere the bias would count twice") | ||
| 23820 | ap.add_argument("--mesh-compute", action="store_true", | 24037 | ap.add_argument("--mesh-compute", action="store_true", |
| 23821 | help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " | 24038 | help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " |
| 23822 | "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " | 24039 | "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " |
| @@ -23898,7 +24115,7 @@ def main(): | |||
| 23898 | LOOP_LIMIT = a.loop_limit | 24115 | LOOP_LIMIT = a.loop_limit |
| 23899 | MAX_STRUCTURED_DEPTH = a.max_structured_depth | 24116 | MAX_STRUCTURED_DEPTH = a.max_structured_depth |
| 23900 | global INTEGER_DOT_FALLBACK | 24117 | global INTEGER_DOT_FALLBACK |
| 23901 | global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV | 24118 | global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, EXPLICIT_LOD_BIAS, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV |
| 23902 | global MESH_SERIAL_WAVES | 24119 | global MESH_SERIAL_WAVES |
| 23903 | global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD | 24120 | global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD |
| 23904 | PC_TAIL_UBO = a.pc_tail_ubo | 24121 | PC_TAIL_UBO = a.pc_tail_ubo |
| @@ -23919,6 +24136,7 @@ def main(): | |||
| 23919 | INTEGER_DOT_FALLBACK = a.integer_dot_fallback | 24136 | INTEGER_DOT_FALLBACK = a.integer_dot_fallback |
| 23920 | ADDR_PAIR = not a.int64_addresses | 24137 | ADDR_PAIR = not a.int64_addresses |
| 23921 | TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback | 24138 | TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback |
| 24139 | EXPLICIT_LOD_BIAS = a.explicit_lod_bias | ||
| 23922 | MESH_COMPUTE = a.mesh_compute | 24140 | MESH_COMPUTE = a.mesh_compute |
| 23923 | MESH_SERIAL_WAVES = a.mesh_serial_waves | 24141 | MESH_SERIAL_WAVES = a.mesh_serial_waves |
| 23924 | F16_HALVES = a.f16_interp_fallback | 24142 | F16_HALVES = a.f16_interp_fallback |
diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs index 911ab8183..c89f08e0e 100644 --- a/tools/rpf9dump/Program.cs +++ b/tools/rpf9dump/Program.cs | |||
| @@ -12,7 +12,7 @@ for (int i = 0; i < argv.Count; ) | |||
| 12 | { | 12 | { |
| 13 | if (argv[i] == "--jobs") | 13 | if (argv[i] == "--jobs") |
| 14 | { | 14 | { |
| 15 | if (i + 1 >= argv.Count || !int.TryParse(argv[i + 1], out jobs) || jobs < 1) | 15 | if (i + 1 >= argv.Count || !int.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out jobs) || jobs < 1) |
| 16 | { | 16 | { |
| 17 | Console.Error.WriteLine("--jobs must be at least 1"); | 17 | Console.Error.WriteLine("--jobs must be at least 1"); |
| 18 | return 2; | 18 | return 2; |
| @@ -36,14 +36,18 @@ string mode = argv[0], src = Path.GetFullPath(argv[1]), outRoot = Path.GetFullPa | |||
| 36 | long scanStart = 0; long? scanLength = null; | 36 | long scanStart = 0; long? scanLength = null; |
| 37 | for (int i = 3; i < argv.Count; i += 2) | 37 | for (int i = 3; i < argv.Count; i += 2) |
| 38 | { | 38 | { |
| 39 | if (argv[i] is not ("--start" or "--length")) | ||
| 40 | { | ||
| 41 | Console.Error.WriteLine($"Unknown option {argv[i]}."); | ||
| 42 | return 2; | ||
| 43 | } | ||
| 39 | if (i + 1 >= argv.Count || !long.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out long bytes) || bytes < 0) | 44 | if (i + 1 >= argv.Count || !long.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out long bytes) || bytes < 0) |
| 40 | { | 45 | { |
| 41 | Console.WriteLine($"{argv[i]} needs a non-negative byte count."); | 46 | Console.Error.WriteLine($"{argv[i]} needs a non-negative byte count."); |
| 42 | return 2; | 47 | return 2; |
| 43 | } | 48 | } |
| 44 | if (argv[i] == "--start") scanStart = bytes; | 49 | if (argv[i] == "--start") scanStart = bytes; |
| 45 | else if (argv[i] == "--length") scanLength = bytes; | 50 | else scanLength = bytes; |
| 46 | else { Console.WriteLine($"Unknown option {argv[i]}."); return 2; } | ||
| 47 | } | 51 | } |
| 48 | bool window = scanStart != 0 || scanLength is not null; | 52 | bool window = scanStart != 0 || scanLength is not null; |
| 49 | if (window && mode is not ("models" or "textures")) | 53 | if (window && mode is not ("models" or "textures")) |
diff --git a/tools/rpf9dump/Segments.cs b/tools/rpf9dump/Segments.cs index 206b8d5f3..69366a7fd 100644 --- a/tools/rpf9dump/Segments.cs +++ b/tools/rpf9dump/Segments.cs | |||
| @@ -24,8 +24,11 @@ public static class RecoveredResource | |||
| 24 | int written = 0; | 24 | int written = 0; |
| 25 | foreach (var block in segments) | 25 | foreach (var block in segments) |
| 26 | { | 26 | { |
| 27 | if (block.Offset < 0 || block.StoredSize < 6 || block.Size < 0 || block.Offset + block.StoredSize > file.Length) | 27 | if (block.Offset < 0 || block.StoredSize < 6 || block.Size < 0 |
| 28 | || block.Offset > file.Length || block.StoredSize > file.Length - block.Offset) | ||
| 28 | throw new InvalidDataException("A recovered block runs past the file."); | 29 | throw new InvalidDataException("A recovered block runs past the file."); |
| 30 | if (block.IsRaw && block.StoredSize != block.Size) | ||
| 31 | throw new InvalidDataException("A raw recovered block's stored and uncompressed sizes disagree."); | ||
| 29 | if (block.Size > data.Length - written) | 32 | if (block.Size > data.Length - written) |
| 30 | throw new InvalidDataException("The recovered blocks exceed the resource size."); | 33 | throw new InvalidDataException("The recovered blocks exceed the resource size."); |
| 31 | file.Position = block.Offset; | 34 | file.Position = block.Offset; |
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index f1d4d4dda..0e4a83239 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py | |||
| @@ -85,7 +85,7 @@ def probe(mcpu: str) -> None: | |||
| 85 | if p.returncode != 0 or "s_endpgm" not in p.stdout: | 85 | if p.returncode != 0 or "s_endpgm" not in p.stdout: |
| 86 | why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] | 86 | why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] |
| 87 | fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" | 87 | fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" |
| 88 | f"The disassembler needs LLVM 21+ with the AMDGPU target (docs/design.md, 'Disassembling shaders').\n" | 88 | f"The disassembler needs LLVM 23+ with the AMDGPU target (LLVM 21 cannot decode some pipeline-library compute programs; docs/design.md, 'Disassembling shaders').\n" |
| 89 | f"{install_hint()}") | 89 | f"{install_hint()}") |
| 90 | 90 | ||
| 91 | 91 | ||
diff --git a/tools/vk_fuzz_run.py b/tools/vk_fuzz_run.py index d56b59d24..0357d359b 100644 --- a/tools/vk_fuzz_run.py +++ b/tools/vk_fuzz_run.py | |||
| @@ -18,6 +18,11 @@ wave64_text() rewrites the wave32 spellings of lane masks (vcc_lo, s20, s21) as | |||
| 18 | cf_diff), bypassing llvm-mc while keeping the same translation and per-lane Vulkan execution path. | 18 | cf_diff), bypassing llvm-mc while keeping the same translation and per-lane Vulkan execution path. |
| 19 | For wave64 on a 32-wide GPU, LEONIDA_W64_EMULATE=1 passes --wave64-emulate to the translator. | 19 | For wave64 on a 32-wide GPU, LEONIDA_W64_EMULATE=1 passes --wave64-emulate to the translator. |
| 20 | 20 | ||
| 21 | LEONIDA_PC_TAIL_UBO=1 translates with rdna2spirv.py --pc-tail-ubo and passes the same variable to vk_compute_test | ||
| 22 | for 128-byte push-constant devices. VK_FUZZ_SKIP_CRASH=1 records any vk_compute_test exit other than 0, 1, 2 or 77 | ||
| 23 | as a skip, including signal deaths (which Python reports as negative return codes); exits 1 and 2 stay fatal because | ||
| 24 | they are harness/check failures, not driver crashes. | ||
| 25 | |||
| 21 | opaque=True (the default of run_programs) keeps the driver from folding the program: a `v_mov_b32 vN, K` seed becomes | 26 | opaque=True (the default of run_programs) keeps the driver from folding the program: a `v_mov_b32 vN, K` seed becomes |
| 22 | `v_xor_b32 vN, K ^ FILL, vF`, where vF is read from the output buffer, which vk_compute_test fills with 0xEEEEEEEE. | 27 | `v_xor_b32 vN, K ^ FILL, vF`, where vF is read from the output buffer, which vk_compute_test fills with 0xEEEEEEEE. |
| 23 | The program computes the same values at run time, but a compiler that sees literal operands folds them itself, and | 28 | The program computes the same values at run time, but a compiler that sees literal operands folds them itself, and |
| @@ -148,6 +153,11 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries= | |||
| 148 | emulate = wave == 64 and os.environ.get("LEONIDA_W64_EMULATE") == "1" | 153 | emulate = wave == 64 and os.environ.get("LEONIDA_W64_EMULATE") == "1" |
| 149 | if emulate: | 154 | if emulate: |
| 150 | cmd.append("--wave64-emulate") | 155 | cmd.append("--wave64-emulate") |
| 156 | # LEONIDA_PC_TAIL_UBO=1 (the convention the other fuzzers' --pc-tail-ubo flag sets): translate with | ||
| 157 | # rdna2spirv.py --pc-tail-ubo so the modules fit a device's 128-byte push-constant range; vk_compute_test | ||
| 158 | # reads the same variable for its own range. | ||
| 159 | if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): | ||
| 160 | cmd.append("--pc-tail-ubo") | ||
| 151 | translation = subprocess.run(cmd, capture_output=True, text=True) | 161 | translation = subprocess.run(cmd, capture_output=True, text=True) |
| 152 | index = {} | 162 | index = {} |
| 153 | index_path = os.path.join(spirv, "index.json") | 163 | index_path = os.path.join(spirv, "index.json") |
| @@ -176,6 +186,13 @@ def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries= | |||
| 176 | if r.returncode in (0, 77): | 186 | if r.returncode in (0, 77): |
| 177 | break | 187 | break |
| 178 | msg = (r.stdout + r.stderr).strip() | 188 | msg = (r.stdout + r.stderr).strip() |
| 189 | # VK_FUZZ_SKIP_CRASH=1: a vk_compute_test that dies (the AMD Windows shader compiler's access | ||
| 190 | # violation, exit 3221225477, or any other crash code) is recorded as a skip instead of aborting the | ||
| 191 | # whole batch — the crash is a driver/harness finding, not a result for this program. | ||
| 192 | skip_crash = (os.environ.get("VK_FUZZ_SKIP_CRASH") or "").strip().lower() in ("1", "true", "yes", "on") | ||
| 193 | if r.returncode not in (0, 77) and skip_crash and r.returncode not in (1, 2): | ||
| 194 | results[i] = f"vk_compute_test: crashed (exit {r.returncode})" | ||
| 195 | continue | ||
| 179 | if r.returncode not in (0, 77): | 196 | if r.returncode not in (0, 77): |
| 180 | detail = f": {msg[-400:]}" if msg else "" | 197 | detail = f": {msg[-400:]}" if msg else "" |
| 181 | raise RuntimeError(f"{name}: vk_compute_test exit {r.returncode}{detail}") | 198 | raise RuntimeError(f"{name}: vk_compute_test exit {r.returncode}{detail}") |
diff --git a/tools/vk_lod_bias.py b/tools/vk_lod_bias.py new file mode 100644 index 000000000..642e1aadc --- /dev/null +++ b/tools/vk_lod_bias.py | |||
| @@ -0,0 +1,351 @@ | |||
| 1 | """Measure whether a Vulkan device applies VkSamplerCreateInfo::mipLodBias, with no built test programs. | ||
| 2 | |||
| 3 | tools/vk_subgroup_info.py --lod-bias calls measure() for the device it picks and reports the answer as | ||
| 4 | "explicit_lod_bias". The same MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 and applies it on an Apple M5 | ||
| 5 | Pro (#1774), so the answer is measured, not looked up: a 4x4 R32_SFLOAT image gets 0.0 in level 0 and 1.0 in level 1 | ||
| 6 | (vkCmdClearColorImage), and one compute invocation samples it at explicit LOD 0 through a sampler with mipLodBias 0 | ||
| 7 | and one with +1 (nearest filters and mips, clamp to edge), plus once at explicit LOD 1 with no bias, writing the three | ||
| 8 | texels to a host-visible buffer. The LOD 1 read is the control: it must return 1.0, or level 1 was never cleared (or | ||
| 9 | mip selection is broken) and a biased 0.0 would not mean the bias was dropped. | ||
| 10 | |||
| 11 | * plain 0.0, biased 1.0, level 1 1.0 -> False: the sampler applies the bias (--explicit-lod-bias would count it twice) | ||
| 12 | * plain 0.0, biased 0.0, level 1 1.0 -> True: the sampler drops it (translate with rdna2spirv.py --explicit-lod-bias) | ||
| 13 | * anything else, or any Vulkan error -> None, with the reason | ||
| 14 | |||
| 15 | The shader is SHADER_WORDS, compiled from this GLSL with glslangValidator -V -g0 --target-env vulkan1.0: | ||
| 16 | |||
| 17 | #version 450 | ||
| 18 | layout(local_size_x = 1) in; | ||
| 19 | layout(set = 0, binding = 0) uniform sampler2D plain; | ||
| 20 | layout(set = 0, binding = 1) uniform sampler2D biased; | ||
| 21 | layout(set = 0, binding = 2) buffer Out { float r[3]; }; | ||
| 22 | void main() { | ||
| 23 | r[0] = textureLod(plain, vec2(0.5), 0.0).r; | ||
| 24 | r[1] = textureLod(biased, vec2(0.5), 0.0).r; | ||
| 25 | r[2] = textureLod(plain, vec2(0.5), 1.0).r; | ||
| 26 | } | ||
| 27 | |||
| 28 | Standard library only (ctypes); 64-bit struct layouts, as vk_subgroup_info.py. No game files. | ||
| 29 | """ | ||
| 30 | import ctypes | ||
| 31 | import struct | ||
| 32 | |||
| 33 | SHADER_WORDS = ( | ||
| 34 | 0x07230203, 0x00010000, 0x0008000b, 0x0000002d, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, | ||
| 35 | 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0005000f, 0x00000005, | ||
| 36 | 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, 0x00000001, 0x00000001, 0x00000001, | ||
| 37 | 0x00040047, 0x00000009, 0x00000006, 0x00000004, 0x00030047, 0x0000000a, 0x00000003, 0x00050048, 0x0000000a, | ||
| 38 | 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x0000000c, 0x00000021, 0x00000002, 0x00040047, 0x0000000c, | ||
| 39 | 0x00000022, 0x00000000, 0x00040047, 0x00000012, 0x00000021, 0x00000000, 0x00040047, 0x00000012, 0x00000022, | ||
| 40 | 0x00000000, 0x00040047, 0x0000001f, 0x00000021, 0x00000001, 0x00040047, 0x0000001f, 0x00000022, 0x00000000, | ||
| 41 | 0x00040047, 0x0000002c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, | ||
| 42 | 0x00030016, 0x00000006, 0x00000020, 0x00040015, 0x00000007, 0x00000020, 0x00000000, 0x0004002b, 0x00000007, | ||
| 43 | 0x00000008, 0x00000003, 0x0004001c, 0x00000009, 0x00000006, 0x00000008, 0x0003001e, 0x0000000a, 0x00000009, | ||
| 44 | 0x00040020, 0x0000000b, 0x00000002, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000002, 0x00040015, | ||
| 45 | 0x0000000d, 0x00000020, 0x00000001, 0x0004002b, 0x0000000d, 0x0000000e, 0x00000000, 0x00090019, 0x0000000f, | ||
| 46 | 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000010, | ||
| 47 | 0x0000000f, 0x00040020, 0x00000011, 0x00000000, 0x00000010, 0x0004003b, 0x00000011, 0x00000012, 0x00000000, | ||
| 48 | 0x00040017, 0x00000014, 0x00000006, 0x00000002, 0x0004002b, 0x00000006, 0x00000015, 0x3f000000, 0x0005002c, | ||
| 49 | 0x00000014, 0x00000016, 0x00000015, 0x00000015, 0x0004002b, 0x00000006, 0x00000017, 0x00000000, 0x00040017, | ||
| 50 | 0x00000018, 0x00000006, 0x00000004, 0x0004002b, 0x00000007, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c, | ||
| 51 | 0x00000002, 0x00000006, 0x0004002b, 0x0000000d, 0x0000001e, 0x00000001, 0x0004003b, 0x00000011, 0x0000001f, | ||
| 52 | 0x00000000, 0x0004002b, 0x0000000d, 0x00000024, 0x00000002, 0x0004002b, 0x00000006, 0x00000026, 0x3f800000, | ||
| 53 | 0x00040017, 0x0000002a, 0x00000007, 0x00000003, 0x0004002b, 0x00000007, 0x0000002b, 0x00000001, 0x0006002c, | ||
| 54 | 0x0000002a, 0x0000002c, 0x0000002b, 0x0000002b, 0x0000002b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, | ||
| 55 | 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000010, 0x00000013, 0x00000012, 0x00070058, 0x00000018, | ||
| 56 | 0x00000019, 0x00000013, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x0000001b, 0x00000019, | ||
| 57 | 0x00000000, 0x00060041, 0x0000001c, 0x0000001d, 0x0000000c, 0x0000000e, 0x0000000e, 0x0003003e, 0x0000001d, | ||
| 58 | 0x0000001b, 0x0004003d, 0x00000010, 0x00000020, 0x0000001f, 0x00070058, 0x00000018, 0x00000021, 0x00000020, | ||
| 59 | 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x00000022, 0x00000021, 0x00000000, 0x00060041, | ||
| 60 | 0x0000001c, 0x00000023, 0x0000000c, 0x0000000e, 0x0000001e, 0x0003003e, 0x00000023, 0x00000022, 0x0004003d, | ||
| 61 | 0x00000010, 0x00000025, 0x00000012, 0x00070058, 0x00000018, 0x00000027, 0x00000025, 0x00000016, 0x00000002, | ||
| 62 | 0x00000026, 0x00050051, 0x00000006, 0x00000028, 0x00000027, 0x00000000, 0x00060041, 0x0000001c, 0x00000029, | ||
| 63 | 0x0000000c, 0x0000000e, 0x00000024, 0x0003003e, 0x00000029, 0x00000028, 0x000100fd, 0x00010038 | ||
| 64 | ) | ||
| 65 | |||
| 66 | u32, u64, f32, vp = ctypes.c_uint32, ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p | ||
| 67 | |||
| 68 | |||
| 69 | def _s(name, fields): | ||
| 70 | return type(name, (ctypes.Structure,), {"_fields_": fields}) | ||
| 71 | |||
| 72 | |||
| 73 | QueueCreateInfo = _s("QueueCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueFamilyIndex", u32), | ||
| 74 | ("queueCount", u32), ("pQueuePriorities", ctypes.POINTER(f32))]) | ||
| 75 | DeviceCreateInfo = _s("DeviceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueCreateInfoCount", u32), | ||
| 76 | ("pQueueCreateInfos", ctypes.POINTER(QueueCreateInfo)), | ||
| 77 | ("enabledLayerCount", u32), ("ppEnabledLayerNames", vp), | ||
| 78 | ("enabledExtensionCount", u32), | ||
| 79 | ("ppEnabledExtensionNames", ctypes.POINTER(ctypes.c_char_p)), | ||
| 80 | ("pEnabledFeatures", vp)]) | ||
| 81 | QueueFamily = _s("QueueFamily", [("queueFlags", u32), ("queueCount", u32), ("timestampValidBits", u32), | ||
| 82 | ("granularity", u32 * 3)]) | ||
| 83 | Extent3D = _s("Extent3D", [("width", u32), ("height", u32), ("depth", u32)]) | ||
| 84 | ImageCreateInfo = _s("ImageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("imageType", u32), | ||
| 85 | ("format", u32), ("extent", Extent3D), ("mipLevels", u32), | ||
| 86 | ("arrayLayers", u32), ("samples", u32), ("tiling", u32), ("usage", u32), | ||
| 87 | ("sharingMode", u32), ("queueFamilyIndexCount", u32), | ||
| 88 | ("pQueueFamilyIndices", vp), ("initialLayout", u32)]) | ||
| 89 | MemoryRequirements = _s("MemoryRequirements", [("size", u64), ("alignment", u64), ("memoryTypeBits", u32)]) | ||
| 90 | MemoryType = _s("MemoryType", [("propertyFlags", u32), ("heapIndex", u32)]) | ||
| 91 | MemoryHeap = _s("MemoryHeap", [("size", u64), ("flags", u32)]) | ||
| 92 | MemoryProperties = _s("MemoryProperties", [("memoryTypeCount", u32), ("memoryTypes", MemoryType * 32), | ||
| 93 | ("memoryHeapCount", u32), ("memoryHeaps", MemoryHeap * 16)]) | ||
| 94 | MemoryAllocateInfo = _s("MemoryAllocateInfo", [("sType", u32), ("pNext", vp), ("allocationSize", u64), | ||
| 95 | ("memoryTypeIndex", u32)]) | ||
| 96 | SubresourceRange = _s("SubresourceRange", [("aspectMask", u32), ("baseMipLevel", u32), ("levelCount", u32), | ||
| 97 | ("baseArrayLayer", u32), ("layerCount", u32)]) | ||
| 98 | ImageViewCreateInfo = _s("ImageViewCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("image", u64), | ||
| 99 | ("viewType", u32), ("format", u32), ("components", u32 * 4), | ||
| 100 | ("subresourceRange", SubresourceRange)]) | ||
| 101 | SamplerCreateInfo = _s("SamplerCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("magFilter", u32), | ||
| 102 | ("minFilter", u32), ("mipmapMode", u32), ("addressModeU", u32), | ||
| 103 | ("addressModeV", u32), ("addressModeW", u32), ("mipLodBias", f32), | ||
| 104 | ("anisotropyEnable", u32), ("maxAnisotropy", f32), | ||
| 105 | ("compareEnable", u32), ("compareOp", u32), ("minLod", f32), | ||
| 106 | ("maxLod", f32), ("borderColor", u32), | ||
| 107 | ("unnormalizedCoordinates", u32)]) | ||
| 108 | BufferCreateInfo = _s("BufferCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("size", u64), | ||
| 109 | ("usage", u32), ("sharingMode", u32), ("queueFamilyIndexCount", u32), | ||
| 110 | ("pQueueFamilyIndices", vp)]) | ||
| 111 | LayoutBinding = _s("LayoutBinding", [("binding", u32), ("descriptorType", u32), ("descriptorCount", u32), | ||
| 112 | ("stageFlags", u32), ("pImmutableSamplers", vp)]) | ||
| 113 | SetLayoutCreateInfo = _s("SetLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("bindingCount", u32), | ||
| 114 | ("pBindings", ctypes.POINTER(LayoutBinding))]) | ||
| 115 | PoolSize = _s("PoolSize", [("type", u32), ("descriptorCount", u32)]) | ||
| 116 | PoolCreateInfo = _s("PoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("maxSets", u32), | ||
| 117 | ("poolSizeCount", u32), ("pPoolSizes", ctypes.POINTER(PoolSize))]) | ||
| 118 | SetAllocateInfo = _s("SetAllocateInfo", [("sType", u32), ("pNext", vp), ("descriptorPool", u64), | ||
| 119 | ("descriptorSetCount", u32), ("pSetLayouts", ctypes.POINTER(u64))]) | ||
| 120 | DescriptorImageInfo = _s("DescriptorImageInfo", [("sampler", u64), ("imageView", u64), ("imageLayout", u32)]) | ||
| 121 | DescriptorBufferInfo = _s("DescriptorBufferInfo", [("buffer", u64), ("offset", u64), ("range", u64)]) | ||
| 122 | WriteDescriptorSet = _s("WriteDescriptorSet", [("sType", u32), ("pNext", vp), ("dstSet", u64), ("dstBinding", u32), | ||
| 123 | ("dstArrayElement", u32), ("descriptorCount", u32), | ||
| 124 | ("descriptorType", u32), | ||
| 125 | ("pImageInfo", ctypes.POINTER(DescriptorImageInfo)), | ||
| 126 | ("pBufferInfo", ctypes.POINTER(DescriptorBufferInfo)), | ||
| 127 | ("pTexelBufferView", vp)]) | ||
| 128 | ShaderModuleCreateInfo = _s("ShaderModuleCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), | ||
| 129 | ("codeSize", ctypes.c_size_t), ("pCode", ctypes.POINTER(u32))]) | ||
| 130 | PipelineLayoutCreateInfo = _s("PipelineLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), | ||
| 131 | ("setLayoutCount", u32), | ||
| 132 | ("pSetLayouts", ctypes.POINTER(u64)), | ||
| 133 | ("pushConstantRangeCount", u32), | ||
| 134 | ("pPushConstantRanges", vp)]) | ||
| 135 | StageCreateInfo = _s("StageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("stage", u32), | ||
| 136 | ("module", u64), ("pName", ctypes.c_char_p), ("pSpecializationInfo", vp)]) | ||
| 137 | ComputePipelineCreateInfo = _s("ComputePipelineCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), | ||
| 138 | ("stage", StageCreateInfo), ("layout", u64), | ||
| 139 | ("basePipelineHandle", u64), | ||
| 140 | ("basePipelineIndex", ctypes.c_int32)]) | ||
| 141 | CommandPoolCreateInfo = _s("CommandPoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), | ||
| 142 | ("queueFamilyIndex", u32)]) | ||
| 143 | CommandBufferAllocateInfo = _s("CommandBufferAllocateInfo", [("sType", u32), ("pNext", vp), ("commandPool", u64), | ||
| 144 | ("level", u32), ("commandBufferCount", u32)]) | ||
| 145 | CommandBufferBeginInfo = _s("CommandBufferBeginInfo", [("sType", u32), ("pNext", vp), ("flags", u32), | ||
| 146 | ("pInheritanceInfo", vp)]) | ||
| 147 | ImageMemoryBarrier = _s("ImageMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32), | ||
| 148 | ("dstAccessMask", u32), ("oldLayout", u32), ("newLayout", u32), | ||
| 149 | ("srcQueueFamilyIndex", u32), ("dstQueueFamilyIndex", u32), | ||
| 150 | ("image", u64), ("subresourceRange", SubresourceRange)]) | ||
| 151 | BufferMemoryBarrier = _s("BufferMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32), | ||
| 152 | ("dstAccessMask", u32), ("srcQueueFamilyIndex", u32), | ||
| 153 | ("dstQueueFamilyIndex", u32), ("buffer", u64), ("offset", u64), | ||
| 154 | ("size", u64)]) | ||
| 155 | SubmitInfo = _s("SubmitInfo", [("sType", u32), ("pNext", vp), ("waitSemaphoreCount", u32), ("pWaitSemaphores", vp), | ||
| 156 | ("pWaitDstStageMask", vp), ("commandBufferCount", u32), | ||
| 157 | ("pCommandBuffers", ctypes.POINTER(vp)), ("signalSemaphoreCount", u32), | ||
| 158 | ("pSignalSemaphores", vp)]) | ||
| 159 | FenceCreateInfo = _s("FenceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32)]) | ||
| 160 | |||
| 161 | R32_SFLOAT, LEVELS, SIZE = 100, 2, 4 | ||
| 162 | QUEUE_COMPUTE = 0x2 | ||
| 163 | IGNORED = 0xFFFFFFFF | ||
| 164 | WHOLE = 0xFFFFFFFFFFFFFFFF | ||
| 165 | |||
| 166 | |||
| 167 | class VkFailure(RuntimeError): | ||
| 168 | pass | ||
| 169 | |||
| 170 | |||
| 171 | def _check(name, result): | ||
| 172 | if result != 0: | ||
| 173 | raise VkFailure(f"{name} failed ({result})") | ||
| 174 | |||
| 175 | |||
| 176 | def _proto(vk): | ||
| 177 | """argtypes for every call measure() makes (all pointers and 64-bit handles).""" | ||
| 178 | names = { | ||
| 179 | "vkGetPhysicalDeviceQueueFamilyProperties": [vp, vp, vp], | ||
| 180 | "vkGetPhysicalDeviceMemoryProperties": [vp, vp], | ||
| 181 | "vkCreateDevice": [vp, vp, vp, vp], "vkDestroyDevice": [vp, vp], "vkGetDeviceQueue": [vp, u32, u32, vp], | ||
| 182 | "vkCreateImage": [vp, vp, vp, vp], "vkDestroyImage": [vp, u64, vp], | ||
| 183 | "vkGetImageMemoryRequirements": [vp, u64, vp], "vkGetBufferMemoryRequirements": [vp, u64, vp], | ||
| 184 | "vkAllocateMemory": [vp, vp, vp, vp], "vkFreeMemory": [vp, u64, vp], | ||
| 185 | "vkBindImageMemory": [vp, u64, u64, u64], "vkBindBufferMemory": [vp, u64, u64, u64], | ||
| 186 | "vkMapMemory": [vp, u64, u64, u64, u32, vp], "vkUnmapMemory": [vp, u64], | ||
| 187 | "vkCreateImageView": [vp, vp, vp, vp], "vkDestroyImageView": [vp, u64, vp], | ||
| 188 | "vkCreateSampler": [vp, vp, vp, vp], "vkDestroySampler": [vp, u64, vp], | ||
| 189 | "vkCreateBuffer": [vp, vp, vp, vp], "vkDestroyBuffer": [vp, u64, vp], | ||
| 190 | "vkCreateDescriptorSetLayout": [vp, vp, vp, vp], "vkDestroyDescriptorSetLayout": [vp, u64, vp], | ||
| 191 | "vkCreateDescriptorPool": [vp, vp, vp, vp], "vkDestroyDescriptorPool": [vp, u64, vp], | ||
| 192 | "vkAllocateDescriptorSets": [vp, vp, vp], "vkUpdateDescriptorSets": [vp, u32, vp, u32, vp], | ||
| 193 | "vkCreateShaderModule": [vp, vp, vp, vp], "vkDestroyShaderModule": [vp, u64, vp], | ||
| 194 | "vkCreatePipelineLayout": [vp, vp, vp, vp], "vkDestroyPipelineLayout": [vp, u64, vp], | ||
| 195 | "vkCreateComputePipelines": [vp, u64, u32, vp, vp, vp], "vkDestroyPipeline": [vp, u64, vp], | ||
| 196 | "vkCreateCommandPool": [vp, vp, vp, vp], "vkDestroyCommandPool": [vp, u64, vp], | ||
| 197 | "vkAllocateCommandBuffers": [vp, vp, vp], "vkBeginCommandBuffer": [vp, vp], "vkEndCommandBuffer": [vp], | ||
| 198 | "vkCmdPipelineBarrier": [vp, u32, u32, u32, u32, vp, u32, vp, u32, vp], | ||
| 199 | "vkCmdClearColorImage": [vp, u64, u32, vp, u32, vp], | ||
| 200 | "vkCmdBindPipeline": [vp, u32, u64], "vkCmdBindDescriptorSets": [vp, u32, u64, u32, u32, vp, u32, vp], | ||
| 201 | "vkCmdDispatch": [vp, u32, u32, u32], | ||
| 202 | "vkCreateFence": [vp, vp, vp, vp], "vkDestroyFence": [vp, u64, vp], | ||
| 203 | "vkQueueSubmit": [vp, u32, vp, u64], "vkWaitForFences": [vp, u32, vp, u32, u64], | ||
| 204 | } | ||
| 205 | for name, args in names.items(): | ||
| 206 | getattr(vk, name).argtypes = args | ||
| 207 | |||
| 208 | |||
| 209 | def _memory_type(props, bits, wanted): | ||
| 210 | for i in range(props.memoryTypeCount): | ||
| 211 | if bits >> i & 1 and props.memoryTypes[i].propertyFlags & wanted == wanted: | ||
| 212 | return i | ||
| 213 | raise VkFailure(f"no memory type with flags {wanted:#x}") | ||
| 214 | |||
| 215 | |||
| 216 | def measure(vk, physical_device, extensions=()): | ||
| 217 | """(True | False | None, reason) for one physical device; `extensions` are its extension names (bytes).""" | ||
| 218 | try: | ||
| 219 | _proto(vk) | ||
| 220 | except AttributeError as e: | ||
| 221 | return None, f"the Vulkan library lacks a call: {e}" | ||
| 222 | pd = ctypes.c_void_p(physical_device) if not isinstance(physical_device, ctypes.c_void_p) else physical_device | ||
| 223 | count = u32() | ||
| 224 | vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), None) | ||
| 225 | families = (QueueFamily * count.value)() | ||
| 226 | vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), families) | ||
| 227 | family = next((i for i, f in enumerate(families) if f.queueFlags & QUEUE_COMPUTE), None) | ||
| 228 | if family is None: | ||
| 229 | return None, "no compute queue" | ||
| 230 | destroy = [] # (call, handle) in creation order, destroyed backwards | ||
| 231 | dev = ctypes.c_void_p() | ||
| 232 | try: | ||
| 233 | prio = f32(1.0) | ||
| 234 | qinfo = QueueCreateInfo(2, None, 0, family, 1, ctypes.pointer(prio)) | ||
| 235 | ext = [b"VK_KHR_portability_subset"] if b"VK_KHR_portability_subset" in extensions else [] | ||
| 236 | ext_arr = (ctypes.c_char_p * max(len(ext), 1))(*ext) | ||
| 237 | dinfo = DeviceCreateInfo(3, None, 0, 1, ctypes.pointer(qinfo), 0, None, len(ext), ext_arr, None) | ||
| 238 | _check("vkCreateDevice", vk.vkCreateDevice(pd, ctypes.byref(dinfo), None, ctypes.byref(dev))) | ||
| 239 | queue = ctypes.c_void_p() | ||
| 240 | vk.vkGetDeviceQueue(dev, family, 0, ctypes.byref(queue)) | ||
| 241 | mem_props = MemoryProperties() | ||
| 242 | vk.vkGetPhysicalDeviceMemoryProperties(pd, ctypes.byref(mem_props)) | ||
| 243 | |||
| 244 | def make(call, info, kind): | ||
| 245 | handle = u64() | ||
| 246 | _check(call, getattr(vk, call)(dev, ctypes.byref(info), None, ctypes.byref(handle))) | ||
| 247 | destroy.append((kind, handle.value)) | ||
| 248 | return handle.value | ||
| 249 | |||
| 250 | image = make("vkCreateImage", ImageCreateInfo(14, None, 0, 1, R32_SFLOAT, Extent3D(SIZE, SIZE, 1), LEVELS, 1, 1, | ||
| 251 | 0, 0x2 | 0x4, 0, 0, None, 0), "vkDestroyImage") | ||
| 252 | req = MemoryRequirements() | ||
| 253 | vk.vkGetImageMemoryRequirements(dev, image, ctypes.byref(req)) | ||
| 254 | image_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, req.size, | ||
| 255 | _memory_type(mem_props, req.memoryTypeBits, 0x1)), | ||
| 256 | "vkFreeMemory") | ||
| 257 | _check("vkBindImageMemory", vk.vkBindImageMemory(dev, image, image_mem, 0)) | ||
| 258 | whole = SubresourceRange(1, 0, LEVELS, 0, 1) | ||
| 259 | view = make("vkCreateImageView", ImageViewCreateInfo(15, None, 0, image, 1, R32_SFLOAT, (u32 * 4)(0, 0, 0, 0), | ||
| 260 | whole), "vkDestroyImageView") | ||
| 261 | samplers = [make("vkCreateSampler", SamplerCreateInfo(31, None, 0, 0, 0, 0, 2, 2, 2, bias, 0, 1.0, 0, 0, 0.0, | ||
| 262 | 1000.0, 0, 0), "vkDestroySampler") for bias in (0.0, 1.0)] | ||
| 263 | buffer = make("vkCreateBuffer", BufferCreateInfo(12, None, 0, 12, 0x20, 0, 0, None), "vkDestroyBuffer") | ||
| 264 | breq = MemoryRequirements() | ||
| 265 | vk.vkGetBufferMemoryRequirements(dev, buffer, ctypes.byref(breq)) | ||
| 266 | buffer_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, breq.size, | ||
| 267 | _memory_type(mem_props, breq.memoryTypeBits, 0x6)), | ||
| 268 | "vkFreeMemory") | ||
| 269 | _check("vkBindBufferMemory", vk.vkBindBufferMemory(dev, buffer, buffer_mem, 0)) | ||
| 270 | bindings = (LayoutBinding * 3)(LayoutBinding(0, 1, 1, 0x20, None), LayoutBinding(1, 1, 1, 0x20, None), | ||
| 271 | LayoutBinding(2, 7, 1, 0x20, None)) | ||
| 272 | set_layout = make("vkCreateDescriptorSetLayout", SetLayoutCreateInfo(32, None, 0, 3, bindings), | ||
| 273 | "vkDestroyDescriptorSetLayout") | ||
| 274 | sizes = (PoolSize * 2)(PoolSize(1, 2), PoolSize(7, 1)) | ||
| 275 | pool = make("vkCreateDescriptorPool", PoolCreateInfo(33, None, 0, 1, 2, sizes), "vkDestroyDescriptorPool") | ||
| 276 | layouts = (u64 * 1)(set_layout) | ||
| 277 | dset = u64() | ||
| 278 | _check("vkAllocateDescriptorSets", vk.vkAllocateDescriptorSets(dev, ctypes.byref( | ||
| 279 | SetAllocateInfo(34, None, pool, 1, layouts)), ctypes.byref(dset))) | ||
| 280 | images = [DescriptorImageInfo(s, view, 5) for s in samplers] | ||
| 281 | binfo = DescriptorBufferInfo(buffer, 0, WHOLE) | ||
| 282 | writes = (WriteDescriptorSet * 3)( | ||
| 283 | WriteDescriptorSet(35, None, dset.value, 0, 0, 1, 1, ctypes.pointer(images[0]), None, None), | ||
| 284 | WriteDescriptorSet(35, None, dset.value, 1, 0, 1, 1, ctypes.pointer(images[1]), None, None), | ||
| 285 | WriteDescriptorSet(35, None, dset.value, 2, 0, 1, 7, None, ctypes.pointer(binfo), None)) | ||
| 286 | vk.vkUpdateDescriptorSets(dev, 3, writes, 0, None) | ||
| 287 | code = (u32 * len(SHADER_WORDS))(*SHADER_WORDS) | ||
| 288 | module = make("vkCreateShaderModule", ShaderModuleCreateInfo(16, None, 0, 4 * len(SHADER_WORDS), code), | ||
| 289 | "vkDestroyShaderModule") | ||
| 290 | playout = make("vkCreatePipelineLayout", PipelineLayoutCreateInfo(30, None, 0, 1, layouts, 0, None), | ||
| 291 | "vkDestroyPipelineLayout") | ||
| 292 | cinfo = ComputePipelineCreateInfo(29, None, 0, StageCreateInfo(18, None, 0, 0x20, module, b"main", None), | ||
| 293 | playout, 0, -1) | ||
| 294 | pipeline = u64() | ||
| 295 | _check("vkCreateComputePipelines", vk.vkCreateComputePipelines(dev, 0, 1, ctypes.byref(cinfo), None, | ||
| 296 | ctypes.byref(pipeline))) | ||
| 297 | destroy.append(("vkDestroyPipeline", pipeline.value)) | ||
| 298 | cpool = make("vkCreateCommandPool", CommandPoolCreateInfo(39, None, 0, family), "vkDestroyCommandPool") | ||
| 299 | cmd = ctypes.c_void_p() | ||
| 300 | _check("vkAllocateCommandBuffers", vk.vkAllocateCommandBuffers(dev, ctypes.byref( | ||
| 301 | CommandBufferAllocateInfo(40, None, cpool, 0, 1)), ctypes.byref(cmd))) | ||
| 302 | _check("vkBeginCommandBuffer", vk.vkBeginCommandBuffer(cmd, ctypes.byref(CommandBufferBeginInfo(42, None, 1, | ||
| 303 | None)))) | ||
| 304 | to_dst = ImageMemoryBarrier(45, None, 0, 0x1000, 0, 7, IGNORED, IGNORED, image, whole) | ||
| 305 | vk.vkCmdPipelineBarrier(cmd, 0x1, 0x1000, 0, 0, None, 0, None, 1, ctypes.byref(to_dst)) | ||
| 306 | for level, value in ((0, 0.0), (1, 1.0)): | ||
| 307 | color = (f32 * 4)(value, value, value, value) | ||
| 308 | rng = SubresourceRange(1, level, 1, 0, 1) | ||
| 309 | vk.vkCmdClearColorImage(cmd, image, 7, ctypes.byref(color), 1, ctypes.byref(rng)) | ||
| 310 | to_read = ImageMemoryBarrier(45, None, 0x1000, 0x20, 7, 5, IGNORED, IGNORED, image, whole) | ||
| 311 | vk.vkCmdPipelineBarrier(cmd, 0x1000, 0x800, 0, 0, None, 0, None, 1, ctypes.byref(to_read)) | ||
| 312 | vk.vkCmdBindPipeline(cmd, 1, pipeline.value) | ||
| 313 | sets = (u64 * 1)(dset.value) | ||
| 314 | vk.vkCmdBindDescriptorSets(cmd, 1, playout, 0, 1, sets, 0, None) | ||
| 315 | vk.vkCmdDispatch(cmd, 1, 1, 1) | ||
| 316 | to_host = BufferMemoryBarrier(44, None, 0x40, 0x2000, IGNORED, IGNORED, buffer, 0, WHOLE) | ||
| 317 | vk.vkCmdPipelineBarrier(cmd, 0x800, 0x4000, 0, 0, None, 1, ctypes.byref(to_host), 0, None) | ||
| 318 | _check("vkEndCommandBuffer", vk.vkEndCommandBuffer(cmd)) | ||
| 319 | fence = make("vkCreateFence", FenceCreateInfo(8, None, 0), "vkDestroyFence") | ||
| 320 | cmds = (ctypes.c_void_p * 1)(cmd.value) | ||
| 321 | submit = SubmitInfo(4, None, 0, None, None, 1, cmds, 0, None) | ||
| 322 | _check("vkQueueSubmit", vk.vkQueueSubmit(queue, 1, ctypes.byref(submit), fence)) | ||
| 323 | fences = (u64 * 1)(fence) | ||
| 324 | _check("vkWaitForFences", vk.vkWaitForFences(dev, 1, fences, 1, 10_000_000_000)) | ||
| 325 | mapped = ctypes.c_void_p() | ||
| 326 | _check("vkMapMemory", vk.vkMapMemory(dev, buffer_mem, 0, 12, 0, ctypes.byref(mapped))) | ||
| 327 | plain, biased, level1 = struct.unpack("<3f", ctypes.string_at(mapped, 12)) | ||
| 328 | vk.vkUnmapMemory(dev, buffer_mem) | ||
| 329 | except VkFailure as e: | ||
| 330 | return None, str(e) | ||
| 331 | finally: | ||
| 332 | if dev.value: | ||
| 333 | for call, handle in reversed(destroy): | ||
| 334 | getattr(vk, call)(dev, handle, None) | ||
| 335 | vk.vkDestroyDevice(dev, None) | ||
| 336 | return verdict(plain, biased, level1) | ||
| 337 | |||
| 338 | |||
| 339 | def verdict(plain: float, biased: float, level1: float): | ||
| 340 | """The answer from the three texels: level 0 holds 0.0 and level 1 holds 1.0. | ||
| 341 | |||
| 342 | `level1` is the control read at explicit LOD 1: unless it is 1.0, a biased 0.0 could come from a level 1 that was | ||
| 343 | never cleared rather than from a dropped bias, so there is no answer. | ||
| 344 | """ | ||
| 345 | if level1 != 1.0: | ||
| 346 | return None, f"control read at LOD 1 gave {level1}, not 1.0 (level 1 not cleared or not selected)" | ||
| 347 | if plain == 0.0 and biased == 1.0: | ||
| 348 | return False, "the sampler applies mipLodBias (+1 reads level 1)" | ||
| 349 | if plain == 0.0 and biased == 0.0: | ||
| 350 | return True, "the sampler drops mipLodBias (+1 still reads level 0)" | ||
| 351 | return None, f"unexpected texels: plain {plain}, biased {biased}" | ||
diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index 9844739c2..4e9f0948b 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py | |||
| @@ -272,8 +272,10 @@ def device_rank(device_type: int, vendor_id: int) -> int: | |||
| 272 | return (0 if vendor_id == MICROSOFT_VENDOR_ID else 10) + type_rank | 272 | return (0 if vendor_id == MICROSOFT_VENDOR_ID else 10) + type_rank |
| 273 | 273 | ||
| 274 | 274 | ||
| 275 | def query(*, stage_caps=False) -> dict: | 275 | def query(*, stage_caps=False, lod_bias=False) -> dict: |
| 276 | """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none.""" | 276 | """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none. |
| 277 | lod_bias adds "explicit_lod_bias" (and its reason), which tools/vk_lod_bias.py measures on that device with one | ||
| 278 | small compute dispatch: True where the sampler drops mipLodBias, False where it applies it, None when unknown.""" | ||
| 277 | if sys.maxsize <= 2**32: | 279 | if sys.maxsize <= 2**32: |
| 278 | # the struct sizes below are the 64-bit ones, and 32-bit Windows Vulkan is stdcall, not CDLL's cdecl | 280 | # the struct sizes below are the 64-bit ones, and 32-bit Windows Vulkan is stdcall, not CDLL's cdecl |
| 279 | raise RuntimeError("needs a 64-bit Python") | 281 | raise RuntimeError("needs a 64-bit Python") |
| @@ -431,14 +433,25 @@ def query(*, stage_caps=False) -> dict: | |||
| 431 | result.update(supported_subgroup_stages=supported_stages, | 433 | result.update(supported_subgroup_stages=supported_stages, |
| 432 | required_subgroup_size_stages=required_stages, | 434 | required_subgroup_size_stages=required_stages, |
| 433 | max_compute_workgroup_subgroups=max_workgroup_subgroups) | 435 | max_compute_workgroup_subgroups=max_workgroup_subgroups) |
| 436 | if lod_bias: | ||
| 437 | try: | ||
| 438 | here = os.path.dirname(os.path.abspath(__file__)) | ||
| 439 | if here not in sys.path: # python -I leaves the script's folder off sys.path | ||
| 440 | sys.path.insert(0, here) | ||
| 441 | import vk_lod_bias # noqa: E402 | ||
| 442 | answer, reason = vk_lod_bias.measure( | ||
| 443 | vk, chosen_d, device_extensions(vk, chosen_d) if chosen_extensions is None else chosen_extensions) | ||
| 444 | except Exception as e: # a measurement that can't run is "unknown", never a guess | ||
| 445 | answer, reason = None, f"{type(e).__name__}: {e}" | ||
| 446 | result.update(explicit_lod_bias=answer, explicit_lod_bias_reason=reason) | ||
| 434 | return result | 447 | return result |
| 435 | finally: | 448 | finally: |
| 436 | vk.vkDestroyInstance(inst, None) | 449 | vk.vkDestroyInstance(inst, None) |
| 437 | 450 | ||
| 438 | 451 | ||
| 439 | def main(*, stage_caps=False) -> int: | 452 | def main(*, stage_caps=False, lod_bias=False) -> int: |
| 440 | try: | 453 | try: |
| 441 | print(json.dumps(query(stage_caps=stage_caps))) | 454 | print(json.dumps(query(stage_caps=stage_caps, lod_bias=lod_bias))) |
| 442 | return 0 | 455 | return 0 |
| 443 | except Exception as e: # any failure means "unknown": the caller falls back to emulation | 456 | except Exception as e: # any failure means "unknown": the caller falls back to emulation |
| 444 | print(json.dumps({"error": f"{type(e).__name__}: {e}"})) | 457 | print(json.dumps({"error": f"{type(e).__name__}: {e}"})) |
| @@ -452,4 +465,7 @@ if __name__ == "__main__": | |||
| 452 | pass | 465 | pass |
| 453 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | 466 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 454 | parser.add_argument("--stage-caps", action="store_true", help="include raw subgroup stage masks and limits") | 467 | parser.add_argument("--stage-caps", action="store_true", help="include raw subgroup stage masks and limits") |
| 455 | sys.exit(main(stage_caps=parser.parse_args().stage_caps)) | 468 | parser.add_argument("--lod-bias", action="store_true", |
| 469 | help="measure whether the sampler applies mipLodBias (one compute dispatch; explicit_lod_bias)") | ||
| 470 | args = parser.parse_args() | ||
| 471 | sys.exit(main(stage_caps=args.stage_caps, lod_bias=args.lod_bias)) | ||
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index f92b1ad2b..f28b2461f 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py | |||
| @@ -924,6 +924,9 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes): | |||
| 924 | if sacc[1]: | 924 | if sacc[1]: |
| 925 | mem_w = True | 925 | mem_w = True |
| 926 | 926 | ||
| 927 | if ins.get("mask_words"): # a lane mask read as a number (rdna2spirv._mask_data_operand) | ||
| 928 | return False, _EMPTY_MEM_STATS, 0, (), () | ||
| 929 | |||
| 927 | # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). | 930 | # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). |
| 928 | a = ins["args"] | 931 | a = ins["args"] |
| 929 | mask_chk = m[11] | 932 | mask_chk = m[11] |
| @@ -1330,6 +1333,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 1330 | if sacc[1]: | 1333 | if sacc[1]: |
| 1331 | mem_w = True | 1334 | mem_w = True |
| 1332 | 1335 | ||
| 1336 | if ins.get("mask_words"): | ||
| 1337 | clean = False | ||
| 1338 | continue | ||
| 1333 | a = ins["args"] | 1339 | a = ins["args"] |
| 1334 | mask_chk = m[11] | 1340 | mask_chk = m[11] |
| 1335 | if mask_chk: | 1341 | if mask_chk: |
| @@ -1581,7 +1587,7 @@ def _insn_may_barrier_with_meta(ins, meta, lane_masks, scc_live): | |||
| 1581 | if meta[1]: | 1587 | if meta[1]: |
| 1582 | return False | 1588 | return False |
| 1583 | flags = meta[8] | 1589 | flags = meta[8] |
| 1584 | if flags & _FLAG_ALWAYS_BARRIER or _vcc_pair_collects_mask(ins, lane_masks): | 1590 | if flags & _FLAG_ALWAYS_BARRIER or ins.get("mask_words") or _vcc_pair_collects_mask(ins, lane_masks): |
| 1585 | return True | 1591 | return True |
| 1586 | mask_chk = meta[11] | 1592 | mask_chk = meta[11] |
| 1587 | if not mask_chk: | 1593 | if not mask_chk: |