From ae7524fa96f6d64c150c8b9a3fa9e388bcb008dd Mon Sep 17 00:00:00 2001 From: 0b101010 <362234467+0b101010-lab@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:59:22 +0700 Subject: [PATCH] fix(macos): integrate shader and runtime prerequisites with main Preserve upstream mesh layout, SCC analysis, descriptor batching and CrossOver release handling while integrating the guarded shader, resource synchronization, diagnostics and toolkit recovery changes. Cover multiple bounded relative moves, recomputed publication facts, caller-relative toolkit paths and diagnostic output destinations. --- README.md | 38 + apps/victory/src/run.rs | 6 +- apps/victory/src/translate.rs | 447 +++++--- apps/victory/tests/translate.rs | 414 +++++++ crates/victory-gpu/src/ambient.rs | 12 +- crates/victory-gpu/src/ambient_estimate.rs | 9 +- crates/victory-gpu/src/ambient_set.rs | 8 +- crates/victory-gpu/src/descriptor.rs | 165 ++- crates/victory-gpu/src/descriptor/host.rs | 160 ++- crates/victory-gpu/src/draw.rs | 2 +- .../src/draw/tests/tracked_rows.rs | 38 +- crates/victory-gpu/src/host.rs | 7 +- crates/victory-gpu/src/lib.rs | 6 +- crates/victory-gpu/src/pipeline/builder.rs | 44 +- crates/victory-gpu/src/ranges.rs | 78 ++ crates/victory-gpu/src/ray_settings.rs | 100 ++ crates/victory-gpu/src/ray_skip.rs | 52 +- crates/victory-gpu/src/shader_cache.rs | 111 +- crates/victory-gpu/src/texture.rs | 171 ++- crates/victory-gpu/src/texture_rows.rs | 56 + crates/victory-loader/src/crash.rs | 16 + crates/victory-loader/src/lib.rs | 4 + crates/victory-loader/src/pool.rs | 206 ++++ crates/victory-loader/src/pool/residents.rs | 605 ++++++++++ .../src/pool/residents/owner.rs | 745 ++++++++++++ .../src/pool/residents/primary.rs | 416 +++++++ .../src/pool/residents/request.rs | 168 +++ crates/victory-loader/src/pool/windows.rs | 763 +++++++++++++ crates/victory-loader/src/windows.rs | 4 + crates/victory-shader/src/emit/bitcode.rs | 197 +++- .../src/emit/bitcode/lds_tests.rs | 59 + .../victory-shader/src/emit/halves_tests.rs | 1001 ++++++++++++++++- .../src/emit/halves_tests/indexed.rs | 595 ++++++++++ .../src/emit/halves_tests/literal_lds.rs | 209 ++++ .../src/emit/halves_tests/literal_publish.rs | 554 +++++++++ .../emit/halves_tests/literal_publish/wide.rs | 193 ++++ .../emit/halves_tests/normal_publication.rs | 375 ++++++ .../normal_publication/saved_exec.rs | 85 ++ .../src/emit/halves_tests/terminal_owner.rs | 338 ++++++ crates/victory-shader/src/emit/host.rs | 25 +- crates/victory-shader/src/emit/lower.rs | 245 ++-- .../victory-shader/src/emit/lower/barriers.rs | 166 ++- .../src/emit/lower/first_lane.rs | 46 +- .../victory-shader/src/emit/lower/halves.rs | 217 +++- .../src/emit/lower/literal_lds.rs | 210 ++++ .../src/emit/lower/literal_lds/tests.rs | 154 +++ .../src/emit/lower/literal_publish.rs | 772 +++++++++++++ .../src/emit/lower/literal_publish/tests.rs | 276 +++++ .../src/emit/lower/predicate.rs | 511 ++++++++- crates/victory-shader/src/emit/lower/retry.rs | 56 +- .../src/emit/lower/retry/immutable.rs | 480 ++++++++ .../src/emit/lower/retry/immutable/paired.rs | 345 ++++++ .../src/emit/lower/retry/tests.rs | 852 ++++++++++++++ .../src/emit/lower/terminal_owner.rs | 472 ++++++++ crates/victory-shader/src/emit/mod.rs | 236 +++- crates/victory-shader/src/ir.rs | 101 +- crates/victory-shader/src/range.rs | 303 ++++- crates/victory-shader/src/resource.rs | 15 +- crates/victory-shader/src/resource/indexed.rs | 180 +++ docs/backend.md | 2 + docs/macos.md | 39 +- .../plans/2026-11-27-direct-metal.md | 187 +++ .../specs/2026-11-27-direct-metal-design.md | 109 ++ setup.sh | 168 ++- tools/macos/build-crossover-wine.sh | 67 +- tools/macos/gptk-version.sh | 22 + tools/macos/tests/gptk-setup.sh | 342 ++++++ tools/macos/tests/gptk-version.sh | 17 + tools/macos/victory.sh | 17 +- 69 files changed, 14231 insertions(+), 858 deletions(-) create mode 100644 crates/victory-gpu/src/ray_settings.rs create mode 100644 crates/victory-gpu/src/texture_rows.rs create mode 100644 crates/victory-loader/src/pool.rs create mode 100644 crates/victory-loader/src/pool/residents.rs create mode 100644 crates/victory-loader/src/pool/residents/owner.rs create mode 100644 crates/victory-loader/src/pool/residents/primary.rs create mode 100644 crates/victory-loader/src/pool/residents/request.rs create mode 100644 crates/victory-loader/src/pool/windows.rs create mode 100644 crates/victory-shader/src/emit/bitcode/lds_tests.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/indexed.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/literal_lds.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/literal_publish.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/literal_publish/wide.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/normal_publication.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/normal_publication/saved_exec.rs create mode 100644 crates/victory-shader/src/emit/halves_tests/terminal_owner.rs create mode 100644 crates/victory-shader/src/emit/lower/literal_lds.rs create mode 100644 crates/victory-shader/src/emit/lower/literal_lds/tests.rs create mode 100644 crates/victory-shader/src/emit/lower/literal_publish.rs create mode 100644 crates/victory-shader/src/emit/lower/literal_publish/tests.rs create mode 100644 crates/victory-shader/src/emit/lower/retry/immutable.rs create mode 100644 crates/victory-shader/src/emit/lower/retry/immutable/paired.rs create mode 100644 crates/victory-shader/src/emit/lower/retry/tests.rs create mode 100644 crates/victory-shader/src/emit/lower/terminal_owner.rs create mode 100644 crates/victory-shader/src/resource/indexed.rs create mode 100644 docs/superpowers/plans/2026-11-27-direct-metal.md create mode 100644 docs/superpowers/specs/2026-11-27-direct-metal-design.md create mode 100644 tools/macos/gptk-version.sh create mode 100644 tools/macos/tests/gptk-setup.sh create mode 100644 tools/macos/tests/gptk-version.sh diff --git a/README.md b/README.md index d6b6bf3b8..95bbf0dd2 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_KEYS_FILE=` | one key name per line, each pressed 0.2 s once its line is newline-terminated, in order (`Add-Content Enter`) | | `VICTORY_FRAME_HZ=60` | tests a 60 Hz frame interval for the runtime's flip events | | `VICTORY_CRASH_BREAKPOINTS=1` | appends first-chance breakpoints to `crashes.log`, including ones a handler may recover from | +| `VICTORY_POOL_OBSERVE=1` | on the identified Series 1.0.2.1 main executable, records the first pool breakpoint in `crashes.log` and the most recent 1,200 periodic activity samples in `pool-observation.log`, and BUILDING slot and retirement observations in `pool-residents.bin` | | `VICTORY_CRASH_SAVE=:,...` | saves title memory to the cache folder on a crash | | `VICTORY_CAPTURE=` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=`) | | `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | @@ -197,6 +198,43 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | +The external `pool-residents.bin` retains the latest 64 samples and the first +validated active sample at each of four occupancy thresholds (any, 50%, 80%, +95%). Each little-endian v2 frame is 968,152 bytes and begins with `BRES0002`. +Older `BRES0001` files have 901,736-byte frames. Require the matching size, +the sample sequence at byte 8, and its bitwise complement in +the final eight bytes. For the regular ring also require `sequence % 64` to +equal the frame index. Join to the aggregate log by sequence. + +The 68,144-byte v2 frame header records pool identity, queue, clock and budget +fields, plus up to eight distinct IDs in slot order and eight rotating IDs from +the remaining eligible population. Header offset 114 holds its u16 population +size. Each cohort can retain the matched 28-byte stream entry, checked upstream +fields and the two owner output-array reads bracketing the lookup. + +The primary request table at byte 2,528 has an 80-byte header and 2,048 entries +of 32 bytes. It is sampled independently of BUILDING availability, before and +after the cohort reads. Table status byte 0 equals 1 for matching storage; +entry status is free (1), matched allocated observations (2), changed or inconsistent (3), or +stable allocated with invalid primary identity (4). For an owner/request +association require the stream ID and saved owner to match, unchanged header +sequence and tagged head, and complete coverage. A repeated tuple, a changing +table, or incomplete coverage needs separate treatment. A raw request state +records an observed value; several game paths write state 4. + +Each subsequent +40-byte record corresponds to one slot index. Interpret records only when the +u32 at header offset 24 equals 1, and only up to the capacity at offset 56. +Slot byte 0 identifies changed/unavailable (0), free metadata (1), a matched +BUILDING handle/type/generation/vtable (2), or stable allocated metadata with +a mismatched identity (3). For matched slots, bytes 12 and 14 record observed +type-1 and mixed queue membership (0 unavailable, 1 absent, 2 unique, 3 +duplicate). Byte 3 is the entity's pending bit. The sampler checks repeated +protected copies without locking title data. Events between reads, same-address +reuse and generation wrap can escape detection. A queue membership or an +output-array match describes an observation within that sample window. + + `VICTORY_KEYS` and `VICTORY_KEYS_FILE` work in ordinary Windows builds, no diagnostics needed: they press keys on the keyboard device and, through it, on the keyboard's stand-in pad. Injecting them into a connected XInput pad instead requires a diagnostics build. ## Where things are diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index e69665b39..4279de690 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -278,6 +278,10 @@ pub fn run( victory_hle::runtime::use_console_timers(); #[cfg(feature = "diagnostics")] diagnostics(&image, &cfg); + let image = Arc::new(image); + #[cfg(feature = "diagnostics")] + let _pool_observer = + victory_loader::start_pool_observation(&image, &temp.with_file_name("pool-observation.log")); let late = LateDlls { host: resolver.host.clone(), title_dir: title_dir.to_owned(), @@ -290,7 +294,7 @@ pub fn run( late.load(file, show).map_err(|e| format!("{e:#}")) })); // SAFETY: imports are bound; from here on we run title code. - let main = unsafe { Arc::new(image).spawn_main(dlls)? }; + let main = unsafe { image.clone().spawn_main(dlls)? }; let code = main .join() .map_err(|_| anyhow::anyhow!("title main thread panicked"))??; diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 9a779d9f7..d97c8b56a 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -7,6 +7,7 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::{Context, Result}; +use victory_gpu::shader_cache::translation_options; use victory_shader::emit::host::{self, Host}; use victory_shader::emit::{self, validator::Validator}; use victory_shader::structure::{self, Atom, LaneExit}; @@ -22,7 +23,9 @@ struct Tally { containers: usize, duplicates: usize, programs: usize, - translated: usize, + extra_programs: usize, + ir_built: usize, + runtime_emitted: usize, instructions: usize, structured: usize, vector: usize, @@ -84,17 +87,45 @@ impl Tally { self.failed.entry(reason).or_insert((0, e)).0 += 1; return; } + self.note_failure(reason, example); + } + + fn note_failure(&mut self, reason: String, example: impl FnOnce() -> String) { self.failed .entry(reason) .or_insert_with(|| (0, example())) .0 += 1; } + fn runtime_outcome( + &mut self, + hash: blake3::Hash, + selected: Option<(HwStage, usize)>, + result: Result<&emit::HostShader, &ShaderError>, + example: impl FnOnce() -> String, + ) { + self.runtime_emitted += usize::from(result.is_ok()); + if self.list { + let stage = selected.map_or_else( + || "-".into(), + |(stage, index)| format!("{stage:?} #{index}"), + ); + let outcome = match result { + Ok(shader) => format!("emitted {}", blake3::hash(&shader.dxil)), + Err(error) => format!("refused {error}"), + }; + self.lines + .push(format!("runtime {hash} {stage} {outcome} {}", example())); + } + } + fn merge(&mut self, other: Tally) { self.containers += other.containers; self.duplicates += other.duplicates; self.programs += other.programs; - self.translated += other.translated; + self.extra_programs += other.extra_programs; + self.ir_built += other.ir_built; + self.runtime_emitted += other.runtime_emitted; self.instructions += other.instructions; self.structured += other.structured; self.vector += other.vector; @@ -164,8 +195,10 @@ pub fn run( wave32: bool, ) -> Result<()> { // Dumped shaders and validator reports are game-derived (rule #1). - if let Some(dir) = std::env::var_os("VICTORY_EMIT_DUMP") { - victory_core::ensure_outside_repo(Path::new(&dir))?; + for name in ["VICTORY_EMIT_DUMP", "VICTORY_FAIL_DUMP"] { + if let Some(dir) = std::env::var_os(name) { + victory_core::ensure_outside_repo(Path::new(&dir))?; + } } let paths = crate::default_paths(paths)?; let dll = validate.then(Validator::default_path).flatten(); @@ -250,18 +283,24 @@ pub fn run( } let t = total.into_inner().unwrap_or_else(|e| e.into_inner()); println!( - "containers {} ({} duplicates skipped)", + "containers {} distinct ({} duplicates skipped)", t.containers, t.duplicates ); println!( - "programs {} translated of {} ({} IR instructions)", - t.translated, t.programs, t.instructions + "runtime {} emitted of {} distinct containers; {} refused", + t.runtime_emitted, + t.containers, + t.containers - t.runtime_emitted + ); + println!( + "programs {} IR builds of {} native programs ({} extra diagnostic programs; {} IR instructions)", + t.ir_built, t.programs, t.extra_programs, t.instructions ); println!( "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \ branches {} per lane, {} uniform)", t.structured, - t.translated, + t.ir_built, t.vector, t.guarded, t.opaque, @@ -271,7 +310,7 @@ pub fn run( println!( "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \ {} scalar accesses; {} with a computed term)", - t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic + t.tracked, t.ir_built, t.loaded, t.built, t.constant, t.scalar, t.dynamic ); println!( " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed", @@ -376,12 +415,7 @@ pub fn warm( s.spawn(|| { while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { let Some(bytes) = job.bytes() else { continue }; - // As the title passes it: the container's own size - // (a raw source runs on to the end of the file). - let size = bytes.get(0x18..0x1c).map_or(0, |b| { - u32::from_le_bytes(b.try_into().expect("4")) as usize - }); - let container = &bytes[..size.min(bytes.len())]; + let container = declared_container(&bytes); let hash = blake3::hash(container); if !lock(&seen).insert(hash) { continue; @@ -398,7 +432,10 @@ pub fn warm( }; counts[k].fetch_add(1, Ordering::Relaxed); tracing::debug!( - hash = %&hash.to_hex()[..16], + hash = %hash, + stage = ?done.as_ref().ok().map(|shader| shader.stage), + dxil_hash = ?done.as_ref().ok().map(|shader| blake3::hash(&shader.dxil)), + reason = done.as_ref().err().map(String::as_str), ms = one.elapsed().as_millis() as u64, cached, ok = done.is_ok(), @@ -513,11 +550,10 @@ fn translate( let Some(bytes) = source.bytes() else { return t.fail("corrupt record".into(), example); }; - // The hash a run's log names the shader by (`hash=` in "shader - // translated", "shader does not translate"), as `VICTORY_SHADER_SAVE` - // names its files. - let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); - // `VICTORY_TRANSLATE_ONLY=,...`: those containers alone. + let bytes = declared_container(&bytes); + let hash = blake3::hash(bytes); + let short_hash = hash.to_hex()[..16].to_owned(); + // Match the runtime's container identity, including when scanning a larger file. static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); let only = ONLY.get_or_init(|| { std::env::var("VICTORY_TRANSLATE_ONLY") @@ -527,36 +563,88 @@ fn translate( .filter(|h| !h.is_empty()) .collect() }); - if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { + if !only.is_empty() && !only.iter().any(|o| short_hash.starts_with(o.as_str())) { return; } - let example = || format!("{}{} #{hash}", path.display(), source.label()); - t.containers += 1; - let Ok(container) = Container::parse(&bytes) else { - return t.fail("no DXIL part (SM5 or older)".into(), example); - }; - let Some(dxil) = container - .part(FourCC::DXIL) - .or(container.part(FourCC::ACCC)) - .map(|p| p.data) - else { - return t.fail("no DXIL part (SM5 or older)".into(), example); - }; - if !lock(seen).insert(blake3::hash(dxil)) { + let example = || format!("{}{} #{short_hash}", path.display(), source.label()); + if !lock(seen).insert(hash) { t.duplicates += 1; return; } - let programs = match native_programs(dxil) { - Ok(p) => p, - Err(e) => return t.fail(e.to_string(), example), + t.containers += 1; + + let container = Container::parse(bytes).and_then(|container| { + let part = container + .part(FourCC::DXIL) + .or(container.part(FourCC::ACCC)) + .ok_or(ShaderError::Malformed("no DXIL part"))?; + let programs = native_programs(part.data)?; + Ok((container, programs)) + }); + let (container, programs) = match container { + Ok(ready) => ready, + Err(error) => { + t.runtime_outcome(hash, None, Err(&error), example); + return t.note_failure(error.to_string(), example); + } }; - // `VICTORY_FAIL_DUMP=`: the first 3 containers of each failure - // reason, as the title has them (`.cdxil`), to work on a translator gap - // offline (`VICTORY_REF_PS`, `VICTORY_TRANSLATE_ONLY`). let dump = std::env::var_os("VICTORY_FAIL_DUMP"); - let before: Option> = - dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); - translate_programs(&container, programs, &example, t, checks); + let before: Option> = dump + .as_ref() + .map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); + let selected = match emit::runtime_program_index(&programs) { + Ok(index) => Some(index), + Err(error) => { + t.runtime_outcome(hash, None, Err(&error), example); + t.note_failure(error.to_string(), example); + None + } + }; + t.programs += programs.len(); + t.extra_programs += programs.len() - usize::from(selected.is_some()); + let options = translation_options(bytes, checks.wave32); + for (index, p) in programs.iter().enumerate() { + let label = || format!("{} {:?} #{index}", example(), p.stage); + let is_runtime = Some(index) == selected; + match diagnose_program(&container, p, options, t) { + Ok(Some(shader)) => { + if is_runtime { + t.runtime_outcome(hash, Some((p.stage, index)), Ok(&shader), example); + } else if t.list { + t.lines.push(format!("{} extra program emitted", label())); + } + check(shader, t, checks, label); + } + Ok(None) => { + if t.list { + t.lines.push(format!("{} extra program analysed", label())); + } + } + Err((step, error)) => { + if is_runtime { + t.runtime_outcome(hash, Some((p.stage, index)), Err(&error), example); + } + let (reason, offset) = match error { + ShaderError::Unsupported { offset, what } => { + (format!("{step}{what}"), Some(offset)) + } + ShaderError::Isa { offset, reason } if step == "structure: " => { + (format!("{step}{reason}"), Some(offset)) + } + _ => (format!("{step}{error}"), None), + }; + let where_ = || match offset { + Some(offset) => format!("{} at {offset:#x}", label()), + None => label(), + }; + if is_runtime { + t.note_failure(reason, where_); + } else { + t.fail(reason, where_); + } + } + } + } if let (Some(dir), Some(before)) = (dump, before) { for (reason, (n, _)) in &t.failed { let was = before.get(reason).copied().unwrap_or(0); @@ -568,120 +656,69 @@ fn translate( .collect(); let dir = Path::new(&dir); let _ = std::fs::create_dir_all(dir); - let _ = std::fs::write(dir.join(format!("{stem}_{was}.{hash}.cdxil")), &bytes[..]); + let _ = std::fs::write(dir.join(format!("{stem}_{was}.{short_hash}.cdxil")), bytes); } } } } -fn translate_programs( - container: &Container, - programs: Vec, - example: &dyn Fn() -> String, +/// Counts the intermediate results independently, then returns the first +/// blocking error in the order used by the runtime's emitter. +fn diagnose_program( + container: &Container<'_>, + p: &NativeProgram, + options: emit::Options, t: &mut Tally, - checks: &mut Checks, -) { - for p in programs { - t.programs += 1; - match victory_shader::range::build(&p.patched_code(), p.wave64, p.vgprs) { - Ok((program, structured)) => { - t.translated += 1; - t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); - // Per-lane descriptors are traced on the per-lane form; its - // failure is listed after the resources' and I/O's. - let lanes = structured.as_ref().ok(); - let res = match resource::track(&program, &p.layout, p.stage, lanes) { - Ok(r) => { - tally_resources(&p, &r, t); - Some(r) - } - Err(ShaderError::Unsupported { offset, what }) => { - t.fail(format!("resources: {what}"), || { - format!("{} {:?} at {offset:#x}", example(), p.stage) - }); - None - } - Err(e) => { - t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)); - None - } - }; - let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); - let compute = p.stage == HwStage::Cs; - let mut raised = None; - if graphics || compute || p.stage == HwStage::Ms { - t.io_programs += usize::from(graphics); - match io::raise(&program, &p) { - Ok(r) => { - if graphics { - tally_io(&r, t); - } - raised = Some(r); - } - Err(ShaderError::Unsupported { offset, what }) => t - .fail(format!("I/O: {what}"), || { - format!("{} {:?} at {offset:#x}", example(), p.stage) - }), - Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), - } - } - let structured = match structured { - Ok(s) => { - tally_structured(&program, &s, t); - Some(s) - } - Err(e) => { - let reason = match e { - ShaderError::Unsupported { what, .. } => format!("structure: {what}"), - ShaderError::Isa { reason, .. } => format!("structure: {reason}"), - e => e.to_string(), - }; - t.fail(reason, || format!("{} {:?}", example(), p.stage)); - None - } - }; - if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { - let label = || format!("{} {:?}", example(), p.stage); - *counter(t, p.stage, 0) += 1; - let marks = - emit_options(checks.wave32, victory_gpu::shader_cache::narrow_waves()); - match emit::emit_with(container, &p, &program, &s, &i, &r, marks) { - Ok(shader) => { - *counter(t, p.stage, 1) += 1; - check(shader, t, checks, label); - } - Err(ShaderError::Unsupported { offset, what }) => t - .fail(format!("emit: {what}"), || { - format!("{} at {offset:#x}", label()) - }), - Err(e) => t.fail(format!("emit: {e}"), label), - } - } - } - Err(e) => { - let reason = match e { - ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"), - e => e.to_string(), - }; - t.fail(reason, || format!("{} {:?}", example(), p.stage)); - } +) -> Result, (&'static str, ShaderError)> { + let (program, structured) = victory_shader::range::build(&p.patched_code(), p.wave64, p.vgprs) + .map_err(|e| { + ( + if matches!(e, ShaderError::Unsupported { .. }) { + "unsupported: " + } else { + "" + }, + e, + ) + })?; + t.ir_built += 1; + t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); + let res = resource::track(&program, &p.layout, p.stage, structured.as_ref().ok()); + if let Ok(r) = &res { + tally_resources(p, r, t); + } + + let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); + let io = emit::supports_stage(p.stage).then(|| io::raise(&program, p)); + if graphics { + t.io_programs += 1; + if let Some(Ok(io)) = &io { + tally_io(io, t); } } + if let Ok(s) = &structured { + tally_structured(&program, s, t); + } + + let res = res.map_err(|error| ("resources: ", error))?; + let io = io.transpose().map_err(|error| ("I/O: ", error))?; + let st = structured.map_err(|error| ("structure: ", error))?; + let Some(io) = io else { + return Ok(None); + }; + *counter(t, p.stage, 0) += 1; + let shader = emit::emit_with(container, p, &program, &st, &io, &res, options) + .map_err(|error| ("emit: ", error))?; + *counter(t, p.stage, 1) += 1; + Ok(Some(shader)) } -/// The emit options for one program. For 32-lane waves (`wave32`), as -/// `run` translates where its host narrows the waves (`narrow`: under Wine, -/// D3DMetal runs wave64 programs in 32-lane waves whatever `WaveSize` says; -/// `VICTORY_NARROW_WAVES` overrides): a group that is one console wave64 -/// with LDS then gets barriers between its halves instead of being refused. -/// Without them the offline check refuses programs `run` translates. -fn emit_options(wave32: bool, narrow: bool) -> emit::Options { - emit::Options { - view_marks: true, - host_wave32: wave32, - narrow_waves: wave32 && narrow, - ..Default::default() - } +/// As the title passes it: a raw source runs on to the end of its file. +fn declared_container(bytes: &[u8]) -> &[u8] { + let size = bytes.get(0x18..0x1c).map_or(0, |size| { + u32::from_le_bytes(size.try_into().expect("four bytes")) as usize + }); + &bytes[..size.min(bytes.len())] } /// Validates an emitted shader if asked to. @@ -725,9 +762,6 @@ fn check( } } let Some(v) = checks.validator.as_mut() else { - if t.list && checks.host.is_none() { - t.lines.push(format!("{} emitted", label())); - } return; }; match v.validate(&mut shader.dxil) { @@ -950,32 +984,28 @@ pub(crate) fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { #[cfg(test)] mod tests { - /// `--wave32` translates as `run` does on a host that narrows the waves - /// (D3DMetal under Wine), and only then; without `--wave32` the waves are - /// never narrowed, as on a host whose waves hold a whole wave64. - #[test] - fn narrow_waves_follow_wave32_and_the_host() { - let o = super::emit_options(true, true); - assert!(o.host_wave32 && o.narrow_waves); - let o = super::emit_options(true, false); - assert!( - o.host_wave32 && !o.narrow_waves, - "NVIDIA, Intel: halves only" - ); - let o = super::emit_options(false, true); - assert!(!o.host_wave32 && !o.narrow_waves); - assert!(super::emit_options(false, false).view_marks); - } - /// Shader dumps are game-derived, so a dump directory in the repo is refused. #[test] fn emit_dump_inside_repo_is_refused() { - // SAFETY: no other test in this binary touches the environment. - unsafe { std::env::set_var("VICTORY_EMIT_DUMP", env!("CARGO_MANIFEST_DIR")) }; + let repo = env!("CARGO_MANIFEST_DIR"); + if std::env::var("VICTORY_EMIT_DUMP").as_deref() != Ok(repo) { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "translate::tests::emit_dump_inside_repo_is_refused", + ]) + .env("VICTORY_EMIT_DUMP", repo) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + return; + } let missing = std::env::temp_dir().join("victory-translate-no-such-dir"); let err = super::run(vec![missing], false, false, false, Some(1), false).unwrap_err(); - // SAFETY: as above; unset so a later test's `run` is not refused. - unsafe { std::env::remove_var("VICTORY_EMIT_DUMP") }; assert!( matches!( err.downcast_ref(), @@ -984,4 +1014,77 @@ mod tests { "{err}" ); } + + /// Each child gets its own process-wide translation switches. + #[test] + fn diagnostic_options_match_runtime_translation() { + use std::process::Command; + use victory_shader::emit::Options; + + let container = b"an original synthetic container"; + let hash = blake3::hash(container).to_hex(); + if let Ok(case) = std::env::var("VICTORY_TEST_TRANSLATION_OPTIONS") { + let (wide, configured) = match case.as_str() { + "configured" => (false, true), + "wide" => (true, true), + "disabled" => (true, false), + other => panic!("unexpected test case {other}"), + }; + let expected = Options { + view_marks: true, + atomic_locks: configured, + atomic_lock_rounds: configured, + atomic_umax: configured, + bias_as_gradients: configured, + host_wave32: !wide, + narrow_waves: configured, + disable_literal_halves: configured, + per_vertex_center: false, + uav_size_level0: configured, + halves_rendezvous: configured, + thread_limits: false, + }; + assert_eq!(super::translation_options(container, !wide), expected); + assert_eq!( + super::translation_options(b"another container", !wide), + Options { + uav_size_level0: false, + ..expected + }, + ); + return; + } + + for (case, value, size) in [ + ("configured", "1", &hash[..16]), + ("wide", "1", &hash[..16]), + ("disabled", "0", "0"), + ] { + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "translate::tests::diagnostic_options_match_runtime_translation", + ]) + .env("VICTORY_TEST_TRANSLATION_OPTIONS", case) + .env("VICTORY_ATOMIC_LOCKS", value) + .env("VICTORY_ATOMIC_LOCK_ROUNDS", value) + .env("VICTORY_ATOMIC_UMAX", value) + .env("VICTORY_BIAS_AS_GRADIENTS", value) + .env("VICTORY_NARROW_WAVES", value) + .env("VICTORY_HALVES_RENDEZVOUS", value) + .env( + "VICTORY_LITERAL_HALVES", + if value == "1" { "0" } else { "1" }, + ) + .env("VICTORY_UAV_SIZE_LEVEL0", size) + .output() + .unwrap(); + assert!( + output.status.success(), + "{case}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + } } diff --git a/apps/victory/tests/translate.rs b/apps/victory/tests/translate.rs index 644bbdc09..dc3dbdb52 100644 --- a/apps/victory/tests/translate.rs +++ b/apps/victory/tests/translate.rs @@ -1,6 +1,9 @@ use std::path::Path; use std::process::Command; +use victory_shader::HwStage; +use victory_shader::emit::{self, Options}; + #[test] fn translate_rejects_zero_workers() { let input = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"); @@ -18,3 +21,414 @@ fn translate_rejects_zero_workers() { assert!(stderr.contains("--jobs"), "{extra_args:?}: {stderr}"); } } + +const END: u32 = 0xBF81_0000; + +fn container(tag: &[u8; 4], payload: &[u8], digest_byte: u8) -> Vec { + let mut bytes = b"DXBC".to_vec(); + bytes.extend_from_slice(&[digest_byte; 16]); + for word in [1, (44 + payload.len()) as u32, 1, 36] { + bytes.extend_from_slice(&word.to_le_bytes()); + } + bytes.extend_from_slice(tag); + bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + bytes.extend_from_slice(payload); + bytes +} + +fn accc(words: &[u32], threads: u16, lds: bool, descriptor: Option<(u32, u32, u8)>) -> Vec { + let mut packet = [0u8; 28]; + for (at, n) in [(12, threads), (14, 1), (16, 1)] { + packet[at..at + 2].copy_from_slice(&n.to_le_bytes()); + } + packet[20] = 7; // 32 VGPRs in wave64 mode. + // One user-data SGPR for the descriptor table, and one 512-byte LDS block. + let rsrc2 = (u32::from(descriptor.is_some()) << 1) | (u32::from(lds) << 15); + packet[24..28].copy_from_slice(&rsrc2.to_le_bytes()); + let code: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let mut metadata = vec![0u8; 24]; + metadata[8..12].copy_from_slice(&(words.len() as u32).to_le_bytes()); + if let Some((offset, dimension, dwords)) = descriptor { + let mut uav = [0u8; 32]; + uav[..8].copy_from_slice(&[0x41, 0, 0, 0, 3, 3, 0, 0]); + uav[8..12].copy_from_slice(&offset.to_le_bytes()); + uav[16..20].copy_from_slice(&dimension.to_le_bytes()); + uav[20] = dwords; + metadata.extend_from_slice(&uav); + } + let entries = [(0u32, &packet[..]), (6, &code[..]), (7, &metadata[..])]; + let mut at = 16 + 16 * entries.len(); + let size = at + entries.iter().map(|(_, data)| data.len()).sum::(); + let mut payload = b"FSPX".to_vec(); + for word in [1, entries.len() as u32, size as u32] { + payload.extend_from_slice(&word.to_le_bytes()); + } + for (kind, data) in entries { + for word in [kind, at as u32, data.len() as u32, 0] { + payload.extend_from_slice(&word.to_le_bytes()); + } + at += data.len(); + } + for (_, data) in entries { + payload.extend_from_slice(data); + } + payload +} + +fn divergent_wave() -> Vec { + let payload = accc( + &[ + 0xBE84_0300, + 0xBE85_0380, + 0xF408_0A02, + 0xFA00_0040, + 0xBF8C_C07F, + 0x3420_0085, + 0x7E06_0280, // v16 = v0 * 32; v3 = 0 + 0x3404_0082, + 0x3A08_00A0, + 0x3408_0882, // v2 = v0 * 4; v4 = (v0 ^ 32) * 4 + 0x3602_009F, + 0x7D86_0290, // Active lanes in both halves have (v0 & 31) >= 16. + 0xBE94_246A, + 0xBF88_0006, // Save EXEC and skip the body if empty. + 0xD834_0000, + 0x0000_0002, + 0xBF8C_C07F, // Write lane ID to LDS at v2. + 0xD8D8_0000, + 0x0300_0004, + 0xBF8C_C07F, // Read the other half's ID from v4. + 0xBEFE_0414, // Restore EXEC before writing each lane's result. + 0xE070_1000, + 0x800A_0310, + END, + ], + 64, + true, + Some((16, 1, 4)), + ); + container(b"ACCC", &payload, 0) +} + +#[test] +fn divergent_wave_translation_depends_on_the_literal_halves_retry() { + let input = divergent_wave(); + let options = Options { + host_wave32: true, + ..Options::default() + }; + assert_eq!( + emit::translate_with(&input, options).unwrap().stage, + HwStage::Cs + ); + let without_retry = emit::translate_with( + &input, + Options { + disable_literal_halves: true, + ..options + }, + ) + .unwrap_err(); + assert!( + without_retry + .to_string() + .contains("LDS one console wave64 shares without barriers"), + "{without_retry}" + ); +} + +fn uav_size_payload() -> Vec { + accc( + &[ + 0xBE81_0380, + 0xF40C_0400, + 0xFA00_0000, + 0xBF8C_C07F, // Load the image UAV into s[16:23]. + 0x7E00_0280, + 0x7E02_0280, // v0 = v1 = 0 (texel coordinates and query level). + 0xF038_1108, + 0x0004_0200, // image_get_resinfo v2, v0, s[16:23], width only. + 0xF020_1108, + 0x0004_0200, // Write that width to the UAV. + END, + ], + 1, + false, + Some((0, 4, 8)), + ) +} + +fn dxil(include_runtime_stages: bool) -> Vec { + let mut fssm = b"FSSM".to_vec(); + fssm.extend_from_slice(&0x101u32.to_le_bytes()); + fssm.extend_from_slice(&[0; 8]); + let mut payload = vec![0; 0x68]; + payload[..8].copy_from_slice(&6u64.to_le_bytes()); + for at in [0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x48, 0x60] { + payload[at..at + 8].copy_from_slice(&0xDEAD_BEEF_DEAD_BEEFu64.to_le_bytes()); + } + // A merged GS precedes the supported VS, then an extra CS. + for (at, info_size) in [(0x20, 0), (0x28, 0x18c), (0x60, 0x34)] + .into_iter() + .take(if include_runtime_stages { 3 } else { 1 }) + { + let record = payload.len(); + payload[at..at + 8].copy_from_slice(&(record as u64).to_le_bytes()); + let code = record + 0x54 + info_size; + payload.extend_from_slice(&(code as u64).to_le_bytes()); + payload.extend_from_slice(&4u64.to_le_bytes()); + payload.resize(code, 0); + if at == 0x60 { + for axis in 0..3 { + payload[record + 0x54 + 0x28 + 4 * axis] = 1; + } + } + payload.extend_from_slice(&END.to_le_bytes()); + } + fssm[8..16].copy_from_slice(&(payload.len() as u64).to_le_bytes()); + fssm.extend_from_slice(&payload); + // The synthetic XBCH contains one uncompressed deflate block in a zlib stream. + let size = fssm.len() as u16; + let (mut a, mut b) = (1u32, 0u32); + for &byte in &fssm { + a = (a + u32::from(byte)) % 65521; + b = (b + a) % 65521; + } + let mut stream = vec![0x78, 0x01, 0x01]; + stream.extend_from_slice(&size.to_le_bytes()); + stream.extend_from_slice(&(!size).to_le_bytes()); + stream.extend_from_slice(&fssm); + stream.extend_from_slice(&(b << 16 | a).to_be_bytes()); + let mut part = vec![0; 0x18]; + part.extend_from_slice(b"XDAT"); + for word in [1u32, 0x24, 0x0d, 0x30, (0x18 + stream.len()) as u32] { + part.extend_from_slice(&word.to_le_bytes()); + } + part.extend_from_slice(b"XBCH"); + part.extend_from_slice(&3u32.to_le_bytes()); + part.extend_from_slice(&(stream.len() as u64).to_le_bytes()); + part.extend_from_slice(&u64::from(size).to_le_bytes()); + part.extend_from_slice(&stream); + part +} + +#[test] +fn synthetic_containers_exercise_size_queries_and_runtime_stage_selection() { + let size = container(b"ACCC", &uav_size_payload(), 0); + let plain = emit::translate_with(&size, Options::default()).expect("default size query"); + let level0 = emit::translate_with( + &size, + Options { + uav_size_level0: true, + ..Options::default() + }, + ) + .expect("level-0 size query"); + assert_ne!(blake3::hash(&plain.dxil), blake3::hash(&level0.dxil)); + + let multi = container(b"DXIL", &dxil(true), 0); + assert_eq!(emit::translate(&multi).unwrap().stage, HwStage::Vs); + let merged_only = container(b"DXIL", &dxil(false), 0); + let refusal = emit::translate(&merged_only).unwrap_err(); + assert!( + refusal + .to_string() + .contains("a container without a vertex, pixel, compute or mesh program") + ); +} + +#[cfg(windows)] +fn diagnostic_command(input: &Path) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_victory")); + cmd.args(["translate", "--wave32", "--list"]) + .arg(input) + .env("VICTORY_WARP", "1") + .env("VICTORY_ATOMIC_LOCKS", "0") + .env("VICTORY_BIAS_AS_GRADIENTS", "0") + .env("VICTORY_HALVES_RENDEZVOUS", "0") + .env("VICTORY_NARROW_WAVES", "0") + .env_remove("VICTORY_EMIT_DUMP") + .env_remove("VICTORY_FAIL_DUMP") + .env_remove("VICTORY_TRANSLATE_ONLY") + .env_remove("VICTORY_PAIRS") + .env_remove("VICTORY_UAV_SIZE_LEVEL0"); + cmd +} + +#[cfg(windows)] +fn stdout(cmd: &mut Command) -> String { + let out = cmd.output().expect("run offline diagnostics"); + let stdout = String::from_utf8(out.stdout).unwrap(); + assert!( + out.status.success(), + "{stdout}\n{}", + String::from_utf8_lossy(&out.stderr) + ); + stdout +} + +#[cfg(windows)] +#[test] +fn diagnostic_filter_uses_the_declared_container_hash() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("synthetic.bin"); + let payload = uav_size_payload(); + let selected = container(b"ACCC", &payload, 1); + let other = container(b"ACCC", &payload, 2); + std::fs::write(&file, [&selected[..], &other, b"trailing bytes"].concat()).unwrap(); + let hash = blake3::hash(&selected); + let output = stdout(diagnostic_command(&file).env( + "VICTORY_TRANSLATE_ONLY", + format!(" , {}, ", hash.to_hex()[..16].to_uppercase()), + )); + assert!( + output.contains("1 distinct (0 duplicates skipped)"), + "{output}" + ); + assert!( + output.contains(&format!("runtime {hash} Cs #0 emitted")), + "{output}" + ); + assert!( + !output.contains(&format!("runtime {}", blake3::hash(&other))), + "{output}" + ); +} + +#[cfg(windows)] +#[test] +fn failed_container_dumps_keep_the_declared_bytes_and_bound_the_samples() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("synthetic.bin"); + let dumps = dir.path().join("failures"); + let payload = dxil(false); + let inputs: Vec<_> = (0..5) + .map(|digest| container(b"DXIL", &payload, digest)) + .collect(); + std::fs::write(&file, inputs.concat()).unwrap(); + let mut command = diagnostic_command(&file); + // One worker makes the per-worker diagnostic sample limit deterministic. + command + .args(["--jobs", "1"]) + .env("VICTORY_FAIL_DUMP", &dumps); + let output = stdout(&mut command); + assert!(output.contains("5 distinct"), "{output}"); + let files: Vec<_> = std::fs::read_dir(&dumps) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(files.len(), 3, "{files:?}"); + for path in files { + let bytes = std::fs::read(&path).unwrap(); + assert!( + inputs.contains(&bytes), + "dump includes bytes outside its container" + ); + let name = path.file_name().unwrap().to_str().unwrap(); + assert!( + name.contains(&blake3::hash(&bytes).to_hex()[..16]), + "{name}" + ); + } +} + +#[cfg(windows)] +#[test] +fn failed_container_dump_refuses_a_source_tree_destination() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(".victory-root"), "").unwrap(); + let input = dir.path().join("synthetic.bin"); + std::fs::write(&input, container(b"DXIL", &dxil(false), 0)).unwrap(); + let dumps = dir.path().join("failures"); + let output = diagnostic_command(&input) + .env("VICTORY_FAIL_DUMP", &dumps) + .output() + .unwrap(); + assert!( + !output.status.success(), + "source-tree output must be refused" + ); + assert!(String::from_utf8_lossy(&output.stderr).contains("inside the VIctory source tree")); + assert!(!dumps.exists()); +} + +#[cfg(windows)] +#[test] +fn wave32_offline_analysis_uses_the_runtime_literal_halves_switch() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("divergent-wave.bin"); + std::fs::write(&file, divergent_wave()).unwrap(); + let on = stdout(diagnostic_command(&file).env("VICTORY_LITERAL_HALVES", "1")); + assert!(on.contains("Cs") && on.contains("emitted"), "{on}"); + let off = stdout(diagnostic_command(&file).env("VICTORY_LITERAL_HALVES", "0")); + assert!( + off.contains("LDS one console wave64 shares without barriers"), + "{off}" + ); +} + +#[cfg(windows)] +#[test] +fn same_payload_containers_keep_distinct_overrides() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("synthetic.bin"); + let payload = uav_size_payload(); + let selected = container(b"ACCC", &payload, 1); + let default = container(b"ACCC", &payload, 2); + let multi = container(b"DXIL", &dxil(true), 0); + let merged_only = container(b"DXIL", &dxil(false), 0); + let selected_hash = blake3::hash(&selected).to_hex(); + std::fs::write( + &file, + [ + &selected[..], + &default, + &selected, + &multi, + &merged_only, + b"trailing bytes", + ] + .concat(), + ) + .unwrap(); + let output = stdout( + diagnostic_command(&file) + .env("VICTORY_LITERAL_HALVES", "1") + .env("VICTORY_UAV_SIZE_LEVEL0", &selected_hash[..16]), + ); + assert!( + output.contains("4 distinct (1 duplicates skipped)"), + "{output}" + ); + assert!( + output.contains("6 native programs") && output.contains("3 extra diagnostic programs"), + "{output}" + ); + for (bytes, level0, stage, index) in [ + (&selected, true, HwStage::Cs, 0), + (&default, false, HwStage::Cs, 0), + (&multi, false, HwStage::Vs, 1), + ] { + let expected = emit::translate_with( + bytes, + Options { + view_marks: true, + host_wave32: true, + uav_size_level0: level0, + ..Options::default() + }, + ) + .unwrap(); + assert_eq!(expected.stage, stage); + let hash = blake3::hash(bytes); + let dxil = blake3::hash(&expected.dxil); + assert!( + output.contains(&format!("runtime {hash} {stage:?} #{index} emitted {dxil}")), + "{output}" + ); + } + assert!(output.contains(&format!( + "runtime {} - refused GFX10 code at 0x0: a container without a vertex, pixel, compute or mesh program is not supported", + blake3::hash(&merged_only) + )), "{output}"); +} diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index 2d4be9327..6d8d1a9a5 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -18,9 +18,9 @@ //! //! What differs from the fork's file, for this line (Wine's HLSL compiler //! and D3DMetal; one host texture per texture memory): -//! - Off by default, behind `VICTORY_AMBIENT=1`; the level is -//! `VICTORY_AMBIENT_LEVEL` (0.6 by default). Off, nothing here runs: the -//! title's containers are not searched for names and no pass is made. +//! - `VICTORY_AMBIENT=1` selects the constant stand-in. Its level is +//! `VICTORY_AMBIENT_LEVEL` (0.6 by default). With both stand-ins off, +//! the title's containers are not searched for names and no pass is made. //! - The pass's root signature is built in code and its shader keeps to //! what Wine's compiler takes (`crate::ambient_set::SOURCE`). //! - Programs are known per title pipeline (`crate::pipeline::ambient_role`, @@ -47,11 +47,9 @@ use crate::resource::HostTexture; pub(crate) use set::{DEPTH, DRAWS_SKY, ENDS_REFLECTIONS, LIGHT, REFLECTIONS, RESOLVES}; -/// Whether the stand-in is on: `VICTORY_AMBIENT=1` (off when unset, empty, -/// `0` or `off`). Read once. +/// Whether either ambient stand-in is on. pub(crate) fn on() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| set::is_on(var("VICTORY_AMBIENT").as_deref())) + crate::ray_settings::ambient().enabled } fn var(name: &str) -> Option { diff --git a/crates/victory-gpu/src/ambient_estimate.rs b/crates/victory-gpu/src/ambient_estimate.rs index 9e3139f77..a38a633c8 100644 --- a/crates/victory-gpu/src/ambient_estimate.rs +++ b/crates/victory-gpu/src/ambient_estimate.rs @@ -3,7 +3,7 @@ //! VIctory-7900XTX at 9576c45f, after beloooo's constant). On with //! `VICTORY_AMBIENT=estimate` (or `estimate:`), beside the constant //! stand-in of `crate::ambient` (`VICTORY_AMBIENT=1`), which it leaves as it -//! is; off, nothing here runs. +//! is. The estimate is also the default when the BVH builder is disabled. //! //! The constant stand-in gives every point of the picture one light: far //! too little outdoors by day, flat grey indoors. This one works the light @@ -46,8 +46,8 @@ //! //! What differs from the fork's file, for this line (as `crate::ambient` //! differs from Belobug's): -//! - The mode is chosen by `VICTORY_AMBIENT=estimate[:]`; in the -//! fork a number alone is the share and `constant:` the constant. +//! - `VICTORY_AMBIENT=estimate[:]` selects the estimate explicitly. +//! In the fork a number alone is the share and `constant:` the constant. //! - The root signatures are built in code, and the shader keeps to what //! Wine's compiler takes (`crate::ambient_estimate_set::SOURCE`). //! - The passes have a view heap of their own, made with other threads' @@ -99,8 +99,7 @@ fn var(name: &str) -> Option { /// The share of the estimate asked for (`VICTORY_AMBIENT=estimate` or /// `estimate:`), if the estimate is. Read once. fn share() -> Option { - static SHARE: OnceLock> = OnceLock::new(); - *SHARE.get_or_init(|| set::share(var("VICTORY_AMBIENT").as_deref())) + crate::ray_settings::ambient().estimate_share } /// Whether the stand-in is the estimate. diff --git a/crates/victory-gpu/src/ambient_set.rs b/crates/victory-gpu/src/ambient_set.rs index 66845bdcc..ad4888f54 100644 --- a/crates/victory-gpu/src/ambient_set.rs +++ b/crates/victory-gpu/src/ambient_set.rs @@ -6,9 +6,9 @@ // Used by `crate::ambient`, which is only built for Windows. #![cfg_attr(not(windows), allow(dead_code))] -/// Whether `VICTORY_AMBIENT`'s value turns the stand-in on: it is set, and -/// is not empty, `0` or `off`. Off by default on this line. (In Belobug's -/// fork the variable is the light's level and the stand-in is on unless it +/// Whether the effective `VICTORY_AMBIENT` value enables a stand-in: it is +/// set and is not empty, `0` or `off`. (In Belobug's fork the variable is +/// the light's level and the stand-in is on unless it /// says `off`; the level is `VICTORY_AMBIENT_LEVEL` here.) pub(crate) fn is_on(value: Option<&str>) -> bool { value @@ -382,7 +382,7 @@ mod tests { /// Off unless set to something other than nothing, `0` or `off`. #[test] - fn off_by_default() { + fn the_value_selects_whether_a_stand_in_runs() { for off in [None, Some(""), Some(" "), Some("0"), Some(" 0 "), Some("off"), Some("OFF")] { assert!(!is_on(off), "{off:?}"); } diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 75b4cd890..bb5c1b556 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -349,33 +349,43 @@ pub(crate) fn seen_before(keys: &[u64]) -> u64 { /// Mirrors what the title wrote into its shader-visible heaps without a /// call: Grand Theft Auto VI copies descriptors (our records) into its heap -/// as bytes, so only a change of its memory shows them. Each slot of a page -/// written since the last sync is made again if its record changed (in the -/// world 1,300-14,400 slots a frame, against a few hundred views made by -/// calls). Called before each submission: shaders take descriptors from the -/// heap at indices in their data, where a slot never mirrored reads nothing. +/// as bytes, so only a change of its memory shows them. Before submission, +/// check the pages written since the last sync and any bytes that cannot be +/// tracked. Shaders select slots by index, including slots only written by copy. #[cfg(windows)] pub(crate) fn sync_heaps() { - /// A heap's start, its address, and the ranges written since the last sync. - type Written = (u64, usize, Vec<(usize, usize)>); - // The written ranges of every heap, taken in one short hold of the lock. + /// A heap's start, its address, and the byte ranges to examine. + type HeapRanges = (u64, usize, Vec<(usize, usize)>); + // The ranges of every placed heap, taken in one short hold of the lock. let taking = std::time::Instant::now(); sync_stat(SyncStat::Syncs, 1); - let work: Vec = { + let work: Vec = { let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); heaps .iter() - .filter_map(|&(start, _, at)| { + .filter_map(|&(start, end, at)| { // SAFETY: registered heaps are live (removed when dropped). let heap = unsafe { &*(at as *const Heap) }; - // As before: ranges are taken only once the heap has its - // host heap, so writes before that are not lost. - let (Some(Some(_)), Some(written), Some(_)) = - (heap.host.get(), &heap.written, increment(heap.desc.kind)) - else { + if heap.memory.is_some() { + return None; + } + // Preserve writes until the host heap has been made. + let host = heap.made_host()?; + let count = heap.desc.count.min(host.count()); + let bytes = u64::from(count) * u64::from(increment(heap.desc.kind)?); + let end = end.min(start.saturating_add(bytes)); + let (from, to) = (start as usize, end as usize); + if from >= to { return None; + } + let ranges = if let Some(written) = &heap.written { + let mut ranges = written.take(from, to); + ranges.extend(written.untracked(from, to)); + ranges + } else { + vec![(from, to)] }; - Some((start, at, written.take(start as usize, usize::MAX))) + (!ranges.is_empty()).then_some((start, at, ranges)) }) .collect() }; @@ -440,10 +450,11 @@ pub(crate) fn sync_heaps() { break; }; let step = u64::from(step); - let heap_end = start.saturating_add(u64::from(heap.desc.count).saturating_mul(step)); + let count = heap.desc.count.min(host.count()); + let heap_end = start.saturating_add(u64::from(count).saturating_mul(step)); let (page, end) = ( page.max(from), - (page + page_size).min(to).min(heap_end as usize), + page.saturating_add(page_size).min(to).min(heap_end as usize), ); if page >= end { continue; @@ -457,15 +468,15 @@ pub(crate) fn sync_heaps() { let read = crate::host::read_into(page as *const u8, &mut page_buf[..len]); sync_stat(SyncStat::ReadUs, reading.elapsed().as_micros() as u64); if read { - sync_range(host, heap.desc.count, start, step, page, end, &page_buf[..len]); + sync_range(host, count, start, step, page, end, &page_buf[..len]); } else { for sub in (page & !(SUB_PAGE - 1)..end).step_by(SUB_PAGE) { - let (sub_from, sub_to) = (sub.max(page), (sub + SUB_PAGE).min(end)); + let (sub_from, sub_to) = (sub.max(page), sub.saturating_add(SUB_PAGE).min(end)); let sub_len = sub_to - sub_from; if crate::host::read_into(sub_from as *const u8, &mut page_buf[..sub_len]) { sync_range( host, - heap.desc.count, + count, start, step, sub_from, @@ -522,7 +533,7 @@ pub(crate) fn make_read(slots: &[u32]) { // SAFETY: registered heaps are live under `SHADER_HEAPS`. let heap = unsafe { &*(at as *const Heap) }; if let (Some(host), Some(handle)) = (heap.made_host(), heap.handle(i)) { - host.mirror(i, handle, true); + host.mirror_shader_read(i, handle); host.stamp_read(i); } } @@ -569,7 +580,7 @@ pub(crate) fn make_read(slots: &[u32]) { continue; } for &i in slots.iter().filter(|&&i| i < heap.desc.count) { - host.mirror(i, start + u64::from(i) * u64::from(step), true); + host.mirror_shader_read(i, start + u64::from(i) * u64::from(step)); host.stamp_read(i); } } @@ -1451,32 +1462,35 @@ pub(crate) fn view(handle: u64) -> Option { (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten() } +/// A placement page can be unmapped between reading a slot and making its view. +#[cfg(windows)] +fn read_sync_record(handle: u64) -> Option<[u32; 3]> { + let mut raw = [0u8; 12]; + (handle != 0 && crate::host::read_into(handle as *const u8, &mut raw)) + .then(|| sync_record(&raw)) +} + +#[cfg(windows)] +fn sync_record(raw: &[u8]) -> [u32; 3] { + [ + u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]), + u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]), + u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]), + ] +} + /// Like [`view`], but reads the title descriptor slot through /// [`crate::host::read_into`] so unmapped heap pages never fault. #[cfg(windows)] pub(crate) fn view_safe(handle: u64) -> Option { - if handle == 0 { - return None; - } - let mut raw = [0u8; 12]; - if !crate::host::read_into(handle as *const u8, &mut raw) { - return None; - } - let tag = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]); - let i = u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]); - let generation = u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]); + let [tag, i, generation] = read_sync_record(handle)?; (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten() } -/// The view recorded at `handle` and the `(generation << 32) | index` key that -/// identifies that specific record (`host::HostHeap::publish`). -#[cfg(any(windows, test))] +/// The view and its key for background work that can outlive the mapping. +#[cfg(windows)] pub(crate) fn view_and_key(handle: u64) -> Option<(ViewPin, u64)> { - if handle == 0 { - return None; - } - // SAFETY: as in `view`. - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let [tag, i, generation] = read_sync_record(handle)?; if tag != VIEW_TAG { return None; } @@ -2097,6 +2111,75 @@ pub(crate) mod tests { crate::watch::tests::free(memory); } + #[cfg(windows)] + fn placed_sampler_heap(address: usize) -> HeapOwner { + let desc = HeapDesc { kind: SAMPLERS, count: 8, flags: SHADER_VISIBLE, nodes: 1 }; + owner(desc, Placement { address: address as u64, size: 8 * 16 }) + } + + #[cfg(windows)] + fn check_raw_sampler_updates(heap: &Heap) { + let host = heap.host().expect("the test requires a real D3D12 heap"); + let slot = heap.handle(5).unwrap(); + let mut records = [[0_u64; 2]; 2]; + for (record, filter) in records.iter_mut().zip([21, 0]) { + let desc = [filter, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + create_sampler(std::ptr::null(), &desc, record.as_mut_ptr() as u64); + } + assert_ne!(records[0], records[1]); + assert!(!host.made(5)); + for record in records { + // SAFETY: the fixture owns this aligned, committed 16-byte sampler slot. + unsafe { (slot as *mut [u64; 2]).write(record) }; + sync_heaps(); + assert!(host.texture_slot_made_from(5, slot), "raw record must reach the host slot"); + } + // SAFETY: the same slot belongs to the fixture until the heap drops. + unsafe { (slot as *mut [u64; 2]).write([0; 2]) }; + sync_heaps(); + assert!(!host.made(5), "raw clear must remove the previous record"); + } + + #[cfg(windows)] + #[test] + #[ignore = "requires a real D3D12 host heap"] + fn untracked_placed_heap_syncs_raw_record_creation_replacement_and_clear() { + let mut slots = [[0_u64; 2]; 8]; + let h = placed_sampler_heap(slots.as_mut_ptr() as usize); + let heap = heap(h.0); + assert!(heap.written.is_none(), "these private bytes have no write tracker"); + check_raw_sampler_updates(heap); + } + + #[cfg(windows)] + #[test] + #[ignore = "requires a real D3D12 host heap and fault tracking"] + fn partially_tracked_placed_heap_syncs_the_untracked_slots() { + use crate::watch::PAGE; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: a fresh reservation, with only the second page committed as private memory. + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_READWRITE) }; + assert!(!base.is_null()); + let plain = base as usize + PAGE; + assert_eq!( + // SAFETY: this page lies inside the fixture's fresh reservation. + unsafe { VirtualAlloc(plain as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) } as usize, + plain + ); + { + // The first two slots are reserved, the remaining six are writable and untracked. + let h = placed_sampler_heap(plain - 32); + let heap = heap(h.0); + let tracker = heap.written.as_ref().expect("the reserved page is tracked"); + assert_eq!(tracker.untracked(plain - 32, plain + 96), [(plain, plain + 96)]); + check_raw_sampler_updates(heap); + } + // SAFETY: the heap and its tracker dropped before freeing the reservation. + assert_ne!(unsafe { VirtualFree(base, 0, MEM_RELEASE) }, 0); + } + #[cfg(windows)] #[test] fn sync_heaps_reads_partial_64k_pages_and_small_heaps() { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index ac79d42fe..8aa8aa503 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -14,8 +14,8 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::paged::Paged; use super::{ - VIEW_TAG, View, ViewPin, view_at, view_gen_current, views_at_batch, views_current_into, - views_forgot, + VIEW_TAG, View, ViewPin, read_sync_record, sync_record, view_at, view_gen_current, views_at_batch, + views_current_into, views_forgot, }; use crate::backend::{HostGpu, HostMemory}; use crate::host::host; @@ -31,6 +31,12 @@ thread_local! { static PUBLISHING: std::cell::Cell = const { std::cell::Cell::new(false) }; } +fn read_matching_record(handle: u64, key: u64) -> Option<[u32; 3]> { + read_sync_record(handle).filter(|&[tag, i, generation]| { + tag == VIEW_TAG && (u64::from(generation) << 32 | u64::from(i)) == key + }) +} + struct PublishingGuard(bool); impl Drop for PublishingGuard { @@ -1595,16 +1601,11 @@ impl HostHeap { buf.as_ptr().add(off).cast::<[u32; 3]>().read_unaligned() } } else if !buf.is_empty() { - let mut raw = [0u8; 12]; - if !crate::host::read_into(addr as *const u8, &mut raw) { + let Some(record) = read_sync_record(addr) else { i += 1; continue; - } - [ - u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]), - u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]), - u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]), - ] + }; + record } else { // SAFETY: direct test path (`sync_slots`) in committed memory. unsafe { (addr as *const [u32; 3]).read_unaligned() } @@ -1658,15 +1659,10 @@ impl HostHeap { // SAFETY: `off + 12 <= buf.len()`, unaligned copy of 12 bytes. unsafe { buf.as_ptr().add(off).cast::<[u32; 3]>().read_unaligned() } } else if !buf.is_empty() { - let mut raw = [0u8; 12]; - if !crate::host::read_into(addr as *const u8, &mut raw) { + let Some(record) = read_sync_record(addr) else { continue; - } - [ - u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]), - u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]), - u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]), - ] + }; + record } else { // SAFETY: direct test path (`sync_slots`) in committed memory. unsafe { (addr as *const [u32; 3]).read_unaligned() } @@ -1705,7 +1701,7 @@ impl HostHeap { } for i in stale { - self.mirror(i, at(i), false); + self.mirror_synced_slot(i, at(i)); } legacy_verify = legacy_fast; } @@ -1846,20 +1842,15 @@ impl HostHeap { let addr = at(index); // Re-read live title memory under `self.made`: if a title // thread overwrote the slot since the page snapshot (including - // during `prepare`), defer to `mirror` after dropping locks. - // SAFETY: the caller holds the heap alive until the sync completes. - let mut raw = [0u8; 12]; - if span_read { + // during `prepare`), retry the live record after dropping locks. + let live = if span_read { let off = (addr - span.0) as usize; - raw.copy_from_slice(&live_span[off..off + 12]); - } else if !crate::host::read_into(addr as *const u8, &mut raw) { + sync_record(&live_span[off..off + 12]) + } else if let Some(live) = read_sync_record(addr) { + live + } else { continue; - } - let live = [ - u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]), - u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]), - u32::from_le_bytes([raw[8], raw[9], raw[10], raw[11]]), - ]; + }; if live != snapshot { again.push(index); continue; @@ -2094,7 +2085,7 @@ impl HostHeap { crate::host::retire_all(retired); drop(pins); for index in again { - self.mirror(index, at(index), false); + self.mirror_synced_slot(index, at(index)); } } @@ -2156,6 +2147,31 @@ impl HostHeap { } pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { + self.mirror_read(index, handle, for_draw, || { + // SAFETY: the descriptor API caller supplies a live slot. + Some(unsafe { (handle as *const [u32; 3]).read_unaligned() }) + }) + } + + /// A shader-read index can name a placed slot whose backing page is gone. + pub(crate) fn mirror_shader_read(&self, index: u32, handle: u64) { + self.mirror_read(index, handle, true, || read_sync_record(handle)); + } + + fn mirror_synced_slot(&self, index: u32, handle: u64) { + let left = stale_left(); + self.mirror_read(index, handle, false, || { + read_sync_record(handle).filter(|record| !left || record[0] == VIEW_TAG) + }); + } + + fn mirror_read( + &self, + index: u32, + handle: u64, + for_draw: bool, + read_record: impl Fn() -> Option<[u32; 3]>, + ) -> Option { if index >= self.count { // Diagnostic (NVIDIA heap cap): the highest title slot past the // host heap seen so far. @@ -2170,8 +2186,7 @@ impl HostHeap { } return None; } - // SAFETY: the handle is a descriptor slot in title memory. - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let [tag, i, generation] = read_record()?; // Generations start at 1, so a made slot's key is never 0. let key = u64::from(generation) << 32 | u64::from(i); // Made from this record already and readable as it is (what the @@ -2186,8 +2201,7 @@ impl HostHeap { } let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); // A second recorder may have replaced the slot while this thread waited. - // SAFETY: the caller holds the heap alive until the update completes. - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let [tag, i, generation] = read_record()?; let key = u64::from(generation) << 32 | u64::from(i); let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { @@ -2247,11 +2261,11 @@ impl HostHeap { made = self.made.lock().unwrap_or_else(|e| e.into_inner()); // The title may have written another record there meanwhile (and // another thread made it): that one is the slot's. - // SAFETY: as above. - if unsafe { (handle as *const [u32; 3]).read_unaligned() } != [tag, i, generation] { + let live = read_record(); + if live != Some([tag, i, generation]) { drop(made); drop(view); - return self.mirror(index, handle, for_draw); + return live.and_then(|_| self.mirror_read(index, handle, for_draw, read_record)); } if made[index as usize] == key && !needs_remake() { return Some(view); @@ -2315,16 +2329,12 @@ impl HostHeap { /// record `key`. Called inside `Host::execute` once the texture's upload is /// recorded in the submission's upload list (`crate::heap_worker`). pub(crate) fn publish(&self, index: u32, handle: u64, key: u64) -> bool { - if handle == 0 || index >= self.count { - return false; - } - // SAFETY: the handle is a descriptor slot in title memory. - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; - if tag != VIEW_TAG || (u64::from(generation) << 32 | u64::from(i)) != key { + if index >= self.count { return false; } let _guard = PublishingGuard(PUBLISHING.replace(true)); - self.mirror(index, handle, true).is_some() + self.mirror_read(index, handle, true, || read_matching_record(handle, key)) + .is_some() } /// Leaves slot `index` showing what it showed, to be made from the @@ -2361,15 +2371,13 @@ impl HostHeap { }; let mut shown = 0; for (index, (handle, key)) in held { - // SAFETY: a descriptor slot in the live title heap the caller - // holds (`SHADER_HEAPS`). - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; - if tag != VIEW_TAG || (u64::from(generation) << 32 | u64::from(i)) != key { + let read = || read_matching_record(handle, key); + if read().is_none() { // Written again since: that write made (or held) the slot. SHOWN_AFTER[2].fetch_add(1, Ordering::Relaxed); continue; } - if self.mirror(index, handle, true).is_some() { + if self.mirror_read(index, handle, true, read).is_some() { shown += 1; } } @@ -2401,8 +2409,9 @@ impl HostHeap { if handle == 0 || index >= self.count { return false; } - // SAFETY: descriptor slot in title memory. - let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let Some([tag, i, generation]) = read_sync_record(handle) else { + return false; + }; if tag != VIEW_TAG { return false; } @@ -2545,7 +2554,7 @@ impl HostHeap { made[index as usize] = 0; self.set_made_nonzero(index, false); } - self.mirror(index, start + u64::from(index) * step, true); + self.mirror_shader_read(index, start + u64::from(index) * step); } slots.len() } @@ -5388,6 +5397,49 @@ mod tests { let _ = mem.as_ptr(); } + #[test] + #[ignore = "requires a real D3D12 host heap"] + fn sync_keeps_the_previous_slot_if_placement_is_decommitted_during_prepare() { + use windows_sys::Win32::System::Memory::{MEM_DECOMMIT, VirtualFree}; + for fast in [false, true] { + let heap = HostHeap::new(true, 1).expect("the test requires a real D3D12 heap"); + let page = crate::watch::tests::pool(1); + let sampler = |handle, filter| { + let desc = [filter, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + crate::descriptor::create_sampler(std::ptr::null(), &desc, handle); + }; + sampler(page as u64, 0); + assert!(heap.mirror(0, page as u64, false).is_some()); + let previous = heap.ready[0].load(Ordering::Acquire); + assert_ne!(previous, 0); + + let mut snapshot = [0u8; 16]; + sampler(snapshot.as_mut_ptr() as u64, 21); + sampler(page as u64, 1); + let decommit = move || { + // SAFETY: this fixture owns the committed allocation until after the sync. + assert_ne!(unsafe { VirtualFree(page as *mut _, 4096, MEM_DECOMMIT) }, 0); + }; + if fast { + // The batch prepares the snapshot first. The mismatched live record + // then enters the single-slot retry, where its prepare decommits the page. + when_preparing(move || when_preparing(decommit)); + } else { + when_preparing(decommit); + } + heap.sync_slots_bytes_with(0..1, page as u64, 16, page as u64, &snapshot, fast); + assert!(prepared()); + assert!(!crate::host::read_into(page as *const _, &mut [0u8; 12])); + assert_eq!(heap.ready[0].load(Ordering::Acquire), previous); + assert!(!heap.publish(0, page as u64, previous)); + heap.hold(0, page as u64, previous); + assert_eq!(heap.show_held(), 0); + heap.mirror_shader_read(0, page as u64); + assert_eq!(heap.ready[0].load(Ordering::Acquire), previous); + crate::watch::tests::free(page); + } + } + #[test] fn fast_heap_sync_handles_placed_null_duplicates_forget_and_concurrent_rewrite() { let Some(host) = HostHeap::new(false, 512) else { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 5d49aa204..ed6628aa2 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1570,7 +1570,7 @@ impl State { // The acceleration-structure builder runs whole or not at all // (`pipeline::builder`). if crate::pipeline::held_back(self.pipeline as This) { - once!("a dispatch of the BVH builder held back"); + once!("a dispatch of the BVH builder was held back"); DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] dropped(list, self.pipeline, "dispatch"); diff --git a/crates/victory-gpu/src/draw/tests/tracked_rows.rs b/crates/victory-gpu/src/draw/tests/tracked_rows.rs index d7b189a7d..50480d1c5 100644 --- a/crates/victory-gpu/src/draw/tests/tracked_rows.rs +++ b/crates/victory-gpu/src/draw/tests/tracked_rows.rs @@ -144,7 +144,7 @@ fn decoded(color: u16) -> [f32; 4] { /// A block-compressed texture whose block rows span the page boundaries: a /// write into one page copies only the 4x4 block rows it covers, and the /// other pages keep what they had. -fn check_block_rows(address: usize, mixed: bool) { +fn check_block_rows(address: usize, mixed: bool, skip_block_rows: usize) { let host = crate::host::host().unwrap(); const WIDTH: usize = 64; let words = |height: usize| texture_words(WIDTH as u32, height as u32, 71, 0x100, 0); @@ -164,7 +164,9 @@ fn check_block_rows(address: usize, mixed: bool) { "block row pitch {pitch}" ); let rows_per_page = PAGE / pitch * 4; - let height = 3 * rows_per_page; + let first_page_rows = rows_per_page - skip_block_rows * 4; + let height = first_page_rows + 2 * rows_per_page; + let offset = skip_block_rows * pitch; let fill = |page: usize, color: u16| { let at = address + page * PAGE; let block = [color.to_le_bytes(), color.to_le_bytes(), [0; 2], [0; 2]].concat(); @@ -174,12 +176,12 @@ fn check_block_rows(address: usize, mixed: bool) { unsafe { std::ptr::copy_nonoverlapping(block.as_ptr(), (at + offset) as *mut u8, 8) }; } }; - let object = texture_at_address(address as u64, &words(height)); + let object = texture_at_address((address + offset) as u64, &words(height)); let (_, desc) = crate::resource::texture_memory(object).unwrap(); let layout = crate::resource::texture_layout(&desc).unwrap(); let layout = &layout.planes[0].layout; - assert_eq!(layout.offset(0, 0, rows_per_page as u32 / 4, 0).unwrap(), PAGE as u64); - assert_eq!(layout.size, (3 * PAGE) as u64); + assert_eq!(layout.offset(0, 0, first_page_rows as u32 / 4, 0).unwrap(), (PAGE - offset) as u64); + assert_eq!(layout.size, (3 * PAGE - offset) as u64); let copy = crate::resource::host_copy(object).unwrap(); let staging = crate::texture::staging(object, ©.texture).unwrap(); let ordinary = crate::texture::tests::untracked_bytes(&staging); @@ -197,17 +199,20 @@ fn check_block_rows(address: usize, mixed: bool) { srv[..6].copy_from_slice(&[71, 4, 0x1688, 0, 0, 1]); let view = View::Shader(object as usize, Some(srv)); slots.make(0, &view); - let (output, mapped) = host.shared_buffer((WIDTH * height * 16) as u64).unwrap(); + let groups = height.div_ceil(8); + let (output, mapped) = host.shared_buffer((WIDTH * groups * 8 * 16) as u64).unwrap(); let submit = |expected: [u16; 3], copies| { let list = host.new_list().unwrap(); readable(&list, &used(ResourceType::Srv), &view, false); - run(&list, &slots, &read, 0, Some(&output), (8, height as u32 / 8)); + run(&list, &slots, &read, 0, Some(&output), (8, groups as u32)); list.close(); let before = crate::texture::copied(object); host.execute(&[&list]); // SAFETY: the completed dispatch wrote WIDTH * height float4s. let pixels = unsafe { std::slice::from_raw_parts(mapped.cast::<[f32; 4]>(), WIDTH * height) }; - for (page, group) in pixels.chunks(WIDTH * rows_per_page).enumerate() { + let boundaries = [0, first_page_rows, first_page_rows + rows_per_page, height]; + for (page, rows) in boundaries.windows(2).enumerate() { + let group = &pixels[WIDTH * rows[0]..WIDTH * rows[1]]; let want = decoded(expected[page]); let wrong = group .iter() @@ -224,6 +229,10 @@ fn check_block_rows(address: usize, mixed: bool) { submit([YELLOW, GREEN, BLUE], 0); } else { fill(1, YELLOW); + if skip_block_rows != 0 { + // Page 1 starts at an odd block row and cannot be rebased. + assert_eq!(crate::texture::tests::defer_one_upload(&staging), 3 * PAGE - offset); + } submit([RED, YELLOW, BLUE], 1); fill(2, WHITE); crate::texture::tests::defer_one_upload(&staging); @@ -244,6 +253,15 @@ fn block_compressed_rows_keep_their_block_alignment_across_pages() { // The pools stay allocated, as in the test above. let mixed = mixed_pages(); let tracked = crate::watch::tests::pool(3); - check_block_rows(mixed, true); - check_block_rows(tracked, false); + check_block_rows(mixed, true, 0); + check_block_rows(tracked, false, 0); +} + +#[test] +fn block_compressed_odd_row_placement_reloads_the_whole_subresource() { + if crate::host::host().is_none() { + return; + } + let tracked = crate::watch::tests::pool(3); + check_block_rows(tracked, false, 1); } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d35468c7d..d779a3b77 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5417,7 +5417,7 @@ impl HostList { } /// A submission's refreshes not done yet, as the ranges of each buffer copy -/// asked for (ranges less than [`JOIN`] apart are done as one): done before +/// asked for (nearby ranges may join across a gap of up to [`JOIN`]): done before /// a step that writes title memory or gives a range to shaders, and before /// the lists run. /// @@ -5583,7 +5583,8 @@ impl Batch { // a title copy took a few bytes of it. let empty = crate::ranges::Ranges::default(); let have = self.current.get(&key).map_or(&empty, |(_, have)| have); - let mut todo = have.missing(address, end).peekable(); + let (missing, join) = have.plan_refresh(address, end, JOIN, crate::watch::fault_tracking()); + let mut todo = missing.peekable(); if todo.peek().is_none() { // Already current: what a later list asked again, and what // #259 keeps current across its moves. @@ -5607,7 +5608,7 @@ impl Batch { } }; for (from, to) in todo { - self.refreshes[i].1.insert(from, to, JOIN); + self.refreshes[i].1.insert(from, to, join); } } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d02823f31..82242d63f 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -85,7 +85,9 @@ pub mod queue; // Plain std, so its tests run everywhere. #[cfg(any(windows, test))] mod ranges; -// Plain std, so its tests run everywhere. +// Plain std, so these policies' tests run everywhere. +#[cfg(any(windows, test))] +mod ray_settings; #[cfg(any(windows, test))] mod ray_skip; #[cfg(any(windows, test))] @@ -108,6 +110,8 @@ mod tdr; mod texback; #[cfg(windows)] mod texture; +#[cfg(any(windows, test))] +mod texture_rows; // Plain std, so its tests run everywhere. #[cfg(any(windows, test))] mod timing_cuts; diff --git a/crates/victory-gpu/src/pipeline/builder.rs b/crates/victory-gpu/src/pipeline/builder.rs index bc5c3f4be..50ea95cdc 100644 --- a/crates/victory-gpu/src/pipeline/builder.rs +++ b/crates/victory-gpu/src/pipeline/builder.rs @@ -10,7 +10,8 @@ //! into title memory: on fxceless/victory-fork, garbage bounds that crashed //! the title. So the builder's dispatches run only in frames where every //! pipeline it has created has its host pipeline; otherwise none of them -//! run (the structures keep what they held). +//! run (the structures keep what they held). Its host pipelines are made +//! whether or not the builder is asked to run. //! //! With every pipeline made it still runs only when asked to //! (`VICTORY_BVH_BUILDER=1`): its lists address title memory that no host @@ -30,6 +31,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use super::make::{self, Pending}; +use crate::ray_settings; /// The builder's image, `[start, end)`, once mapped. static IMAGE: Mutex> = Mutex::new(None); @@ -101,22 +103,10 @@ pub(crate) fn note(p: &Arc) { make::begin(p); } -/// The frame [`runs`] last decided for, and its decision. +/// The frame [`runs`] last decided for, and its pipeline readiness. static DECIDED: Mutex<(u64, bool)> = Mutex::new((u64::MAX, true)); -/// Whether the builder is asked to run (`VICTORY_BVH_BUILDER=1`); read -/// once. -fn asked() -> bool { - static ASKED: std::sync::OnceLock = std::sync::OnceLock::new(); - *ASKED.get_or_init(|| asked_value(std::env::var_os("VICTORY_BVH_BUILDER").as_deref())) -} - -fn asked_value(value: Option<&std::ffi::OsStr>) -> bool { - value == Some(std::ffi::OsStr::new("1")) -} - -/// Why the builder is held back, if it is: `made` (every pipeline has its -/// host pipeline) and `asked` ([`asked`]). +/// Why the builder is held back given its pipeline readiness and opt-in. fn held(made: bool, asked: bool) -> Option<&'static str> { if !made { Some("not all its pipelines are made") @@ -131,10 +121,11 @@ fn held(made: bool, asked: bool) -> Option<&'static str> { /// per frame, so that a frame never runs part of the builder. pub(crate) fn runs() -> bool { static SAID: AtomicBool = AtomicBool::new(false); + let enabled = ray_settings::builder_enabled(); let frame = crate::frame::current(); let mut decided = DECIDED.lock().unwrap_or_else(|e| e.into_inner()); if decided.0 == frame { - return decided.1; + return ray_settings::builder_runs(enabled, decided.1); } let states: Vec> = { let mut pipelines = PIPELINES.lock().unwrap_or_else(|e| e.into_inner()); @@ -145,9 +136,8 @@ pub(crate) fn runs() -> bool { .map(|p| make::state(&p)) .collect() }; - let why = held(all_made(&states), asked()); - let open = why.is_none(); - if open != decided.1 || !SAID.swap(true, Ordering::Relaxed) { + let ready = all_made(&states); + if ready != decided.1 || !SAID.swap(true, Ordering::Relaxed) { let (made, refused) = ( states.iter().filter(|s| **s == Some(true)).count(), states.iter().filter(|s| **s == Some(false)).count(), @@ -158,14 +148,14 @@ pub(crate) fn runs() -> bool { made, refused, "BVH builder {}", - match why { + match held(ready, enabled) { None => "runs".to_owned(), Some(why) => format!("held back: {why}"), } ); } - *decided = (frame, open); - open + *decided = (frame, ready); + ray_settings::builder_runs(enabled, ready) } /// Whether every pipeline is made (`Some(true)`); refused ones are @@ -198,16 +188,8 @@ mod tests { assert!(!all_made(&[Some(true), None]), "one still being made"); } - /// With every pipeline made the builder still runs only when asked to: - /// `VICTORY_BVH_BUILDER=1`, nothing else. #[test] - fn the_builder_runs_only_when_asked_to() { - let os = std::ffi::OsStr::new; - assert!(!asked_value(None)); - assert!(asked_value(Some(os("1")))); - for other in ["", "0", "on", "true", " 1"] { - assert!(!asked_value(Some(os(other))), "{other:?}"); - } + fn the_builder_reports_why_it_is_held_back() { assert_eq!(held(true, true), None); assert!(held(true, false).unwrap().contains("no host copy")); assert!(held(false, true).unwrap().contains("not all its pipelines")); diff --git a/crates/victory-gpu/src/ranges.rs b/crates/victory-gpu/src/ranges.rs index da5715603..d2bda9a7c 100644 --- a/crates/victory-gpu/src/ranges.rs +++ b/crates/victory-gpu/src/ranges.rs @@ -73,6 +73,22 @@ impl Ranges { self.0.drain(kept..last); } + /// Plans missing refreshes without joining back across current untracked bytes. + pub(crate) fn plan_refresh( + &self, + from: usize, + to: usize, + join: usize, + tracked: bool, + ) -> (impl Iterator + '_, usize) { + let join = if !tracked && !self.0.is_empty() { + 0 + } else { + join + }; + (self.missing(from, to), join) + } + /// The parts of `[from, to)` not in the set, in order. pub(crate) fn missing( &self, @@ -309,6 +325,68 @@ mod tests { ); } + fn planned_refreshes( + current: &Ranges, + requests: &[(usize, usize)], + tracked: bool, + ) -> Vec<(usize, usize)> { + let mut pending = Ranges::default(); + for &(from, to) in requests { + let (missing, join) = current.plan_refresh(from, to, 0x10000, tracked); + for (from, to) in missing { + pending.insert(from, to, join); + } + } + all(&pending) + } + + #[test] + fn untracked_refresh_keeps_current_bytes_out_of_the_pending_plan() { + let current = set(&[(0x1000, 0x9000)]); + let expected = [(0, 0x1000), (0x9000, 0xa000)]; + assert_eq!(planned_refreshes(¤t, &[(0, 0xa000)], false), expected); + assert_eq!( + planned_refreshes(¤t, &[(0, 0x3000), (0x2000, 0xa000)], false), + expected + ); + assert_eq!( + planned_refreshes( + ¤t, + &[ + (0, 0x800), + (0x600, 0xc00), + (0xc00, 0x1000), + (0x9000, 0xa000) + ], + false, + ), + expected, + "overlapping and adjacent pending ranges still merge" + ); + + let mut current = set(&[(0, 0xa000)]); + current.remove(0x1000, 0x1008); + current.remove(0x9000, 0x9008); + assert_eq!( + planned_refreshes(¤t, &[(0, 0xa000)], false), + [(0x1000, 0x1008), (0x9000, 0x9008)], + "only the two invalidated title-write intervals are due again" + ); + } + + #[test] + fn initial_and_tracked_refreshes_keep_the_gap_join() { + let requests = [(0, 0x1000), (0x9000, 0xa000)]; + assert_eq!( + planned_refreshes(&Ranges::default(), &requests, false), + [(0, 0xa000)] + ); + assert_eq!( + planned_refreshes(&set(&[(0x1000, 0x9000)]), &requests, true), + [(0, 0xa000)] + ); + } + /// Every operation against a bitmap, on a long run of random ones. #[test] fn ranges_match_a_bitmap() { diff --git a/crates/victory-gpu/src/ray_settings.rs b/crates/victory-gpu/src/ray_settings.rs new file mode 100644 index 000000000..632f5fbf8 --- /dev/null +++ b/crates/victory-gpu/src/ray_settings.rs @@ -0,0 +1,100 @@ +//! Startup policy for the BVH builder and indirect lighting. + +use std::ffi::OsStr; +use std::sync::OnceLock; + +fn builder_opted_in(value: Option<&OsStr>) -> bool { + value == Some(OsStr::new("1")) +} + +// On native hosts only the policy tests use this module. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) fn builder_enabled() -> bool { + static ENABLED: OnceLock = OnceLock::new(); + *ENABLED.get_or_init(|| builder_opted_in(std::env::var_os("VICTORY_BVH_BUILDER").as_deref())) +} + +pub(crate) fn builder_runs(enabled: bool, ready: bool) -> bool { + enabled && ready +} + +pub(crate) struct Ambient { + pub(crate) enabled: bool, + pub(crate) estimate_share: Option, +} + +fn ambient_settings(value: Option<&str>, builder_enabled: bool) -> Ambient { + let value = value.or(if builder_enabled { + None + } else { + Some("estimate") + }); + Ambient { + enabled: crate::ambient_set::is_on(value), + estimate_share: crate::ambient_estimate_set::share(value), + } +} + +#[cfg(windows)] +pub(crate) fn ambient() -> &'static Ambient { + static AMBIENT: OnceLock = OnceLock::new(); + AMBIENT.get_or_init(|| { + let value = std::env::var_os("VICTORY_AMBIENT"); + let value = value.as_deref().map(|v| v.to_str().unwrap_or_default()); + ambient_settings(value, builder_enabled()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_builder_requires_an_exact_opt_in() { + assert!(!builder_opted_in(None)); + for value in ["", "0", "off", "on", "yes", " 1", "1 ", "01"] { + assert!(!builder_opted_in(Some(OsStr::new(value))), "{value:?}"); + } + assert!(builder_opted_in(Some(OsStr::new("1")))); + } + + #[test] + fn the_builder_needs_both_opt_in_and_ready_pipelines() { + assert!(!builder_runs(false, true)); + assert!(!builder_runs(false, false)); + assert!(!builder_runs(true, false)); + assert!(builder_runs(true, true)); + } + + #[test] + fn unset_ambient_uses_the_estimate_only_with_the_builder_disabled() { + let fallback = ambient_settings(None, false); + assert!(fallback.enabled); + assert_eq!(fallback.estimate_share, Some(1.0)); + + let title = ambient_settings(None, true); + assert!(!title.enabled); + assert_eq!(title.estimate_share, None); + } + + #[test] + fn explicit_ambient_keeps_its_meaning() { + for builder_enabled in [false, true] { + for (value, enabled, share) in [ + ("", false, None), + ("0", false, None), + ("off", false, None), + ("1", true, None), + ("estimate", true, Some(1.0)), + ("estimate:0.25", true, Some(0.25)), + ] { + let settings = ambient_settings(Some(value), builder_enabled); + assert_eq!( + (settings.enabled, settings.estimate_share), + (enabled, share), + "{value:?}" + ); + } + } + } +} diff --git a/crates/victory-gpu/src/ray_skip.rs b/crates/victory-gpu/src/ray_skip.rs index 09d7f1c5d..45d927fac 100644 --- a/crates/victory-gpu/src/ray_skip.rs +++ b/crates/victory-gpu/src/ray_skip.rs @@ -1,15 +1,14 @@ //! Ray passes left out while nothing builds the ray-tracing structures -//! (`VICTORY_RAY_SKIP`, off by default). The idea is cool_fox's +//! (`VICTORY_RAY_SKIP`). The idea is cool_fox's //! (codec-d/cool_fox 8cc31ab3, `pipeline/make.rs` `left_out`); the code is //! this line's own. Plain std, so its tests run everywhere. //! //! The title traces its reflections and the rays of its screen probes //! against structures that its builder (`XboxBvhBuilder.dll`) makes every -//! frame. This line holds the builder back in every frame where it cannot -//! run whole (`crate::pipeline::held_back`, upstream #2118), and always -//! with `VICTORY_HALVES_LOCAL=1` or `VICTORY_HALVES_SHARED_LDS=1`. Then the -//! traces run against structures that were never built, and two kinds of -//! programs work on what they find: +//! frame. This line holds the builder back by default and in every frame +//! where it cannot run whole (`crate::pipeline::held_back`, upstream #2118). +//! Traces can then run against structures that were never built, and two +//! kinds of programs work on what they find: //! //! - `CS_RaytracingResolve_*` (technique `raytracingresolve_dispatch`, one //! program per material effect; 1,000 in the title's shader file): each @@ -57,8 +56,8 @@ //! //! `VICTORY_RAY_SKIP=1` (or `on`, `all`): both; `resolve`: the resolves //! only; `activate`: the activation only (`resolve,activate` is both). -//! Unset, empty, `0` or `off`: nothing is left out and nothing here runs -//! but one check of a stored value per container and per pipeline. +//! Unset: skip only the resolves if the builder is disabled, or skip +//! nothing if it is opted in. Empty, `0` or `off`: skip nothing. // Used by `crate::pipeline` and `crate::draw`, which are only built for // Windows. @@ -100,15 +99,23 @@ fn parts(value: Option<&str>) -> (u8, bool) { (parts, true) } +fn configured_parts(value: Option<&str>, builder_enabled: bool) -> (u8, bool) { + if value.is_none() && !builder_enabled { + return (RESOLVE, true); + } + parts(value) +} + /// The parts that are on, read once. pub(crate) fn on() -> u8 { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { - let value = std::env::var("VICTORY_RAY_SKIP").ok(); - let (on, understood) = parts(value.as_deref()); + let value = std::env::var_os("VICTORY_RAY_SKIP"); + let value = value.as_deref().map(|v| v.to_str().unwrap_or_default()); + let (on, understood) = configured_parts(value, crate::ray_settings::builder_enabled()); if !understood { tracing::warn!( - value = value.as_deref().unwrap_or_default(), + value = value.unwrap_or_default(), "VICTORY_RAY_SKIP takes 1, resolve or activate: nothing is left out" ); } @@ -245,6 +252,29 @@ pub(crate) fn log(frames: f64) { mod tests { use super::*; + #[test] + fn unset_skips_only_resolves_with_the_builder_disabled() { + assert_eq!(configured_parts(None, false), (RESOLVE, true)); + assert_eq!(configured_parts(None, true), (0, true)); + } + + #[test] + fn explicit_skip_parts_override_either_default() { + for builder_enabled in [false, true] { + for (value, mask, understood) in [ + ("", 0, true), + ("0", 0, true), + ("off", 0, true), + ("resolve", RESOLVE, true), + ("activate", ACTIVATE, true), + ("all", RESOLVE | ACTIVATE, true), + ("yes", 0, false), + ] { + assert_eq!(configured_parts(Some(value), builder_enabled), (mask, understood), "{value:?}"); + } + } + } + #[test] fn the_switch_names_its_parts() { assert_eq!(parts(None), (0, true)); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index fb818fef1..b81151b49 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -159,9 +159,8 @@ fn bias_as_gradients() -> bool { /// Whether translations take wave64 programs to run in 32-lane host waves: /// under Wine, whose D3DMetal reports 32 lanes and ignores `WaveSize(64)`. -/// `VICTORY_NARROW_WAVES=0` or `1` overrides. Also what the offline -/// `translate --wave32` follows, so its results match `run`'s. -pub fn narrow_waves() -> bool { +/// `VICTORY_NARROW_WAVES=0` or `1` overrides. +fn narrow_waves() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| match std::env::var("VICTORY_NARROW_WAVES").as_deref() { Ok("0") => false, @@ -339,6 +338,16 @@ pub(crate) fn translation_build(options: victory_shader::emit::Options) -> &'sta } pub(crate) fn runtime_options() -> victory_shader::emit::Options { + base_options(host_wave32(), uav_size_level0()) +} + +/// Runtime translation settings for a container and a known host wave width. +/// Offline diagnostics can supply the wave width without opening a GPU device. +pub fn translation_options(container: &[u8], host_wave32: bool) -> victory_shader::emit::Options { + base_options(host_wave32, uav_size_level0_for(container)) +} + +fn base_options(host_wave32: bool, uav_size_level0: bool) -> victory_shader::emit::Options { // Writes through views mark their pages: copy-backs compare only those // (`crate::shadow::copy_back_marks`). // Under Wine (D3DMetal), 64-bit image atomics run under locks: its own @@ -350,11 +359,11 @@ pub(crate) fn runtime_options() -> victory_shader::emit::Options { atomic_lock_rounds: atomic_lock_rounds(), atomic_umax: atomic_umax(), bias_as_gradients: bias_as_gradients(), - host_wave32: host_wave32(), + host_wave32, narrow_waves: narrow_waves(), disable_literal_halves: literal_halves_disabled(), per_vertex_center: false, - uav_size_level0: uav_size_level0(), + uav_size_level0, halves_rendezvous: halves_rendezvous(), // Only for the pipelines a dispatch counted in threads needs it // for (`crate::pipeline::thread_limited`). @@ -371,9 +380,8 @@ pub fn host_shader(container: &[u8]) -> (Result, bool) { /// [`host_shader`] made as `options` say (cached under their own key). pub(crate) fn host_shader_with( container: &[u8], - options: victory_shader::emit::Options, + mut options: victory_shader::emit::Options, ) -> (Result, bool) { - let mut options = options; // One program at a time, if the switch lists hashes. options.uav_size_level0 = uav_size_level0_for(container); let translate = @@ -864,20 +872,85 @@ mod tests { } #[test] - fn disabling_literal_halves_changes_the_translation_key() { - let options = victory_shader::emit::Options { + fn translation_settings_invalidate_cached_shaders() { + use victory_shader::emit::Options; + + let base = Options { host_wave32: true, - ..runtime_options() + halves_rendezvous: true, + ..Options::default() }; - let on = translation_build(victory_shader::emit::Options { - disable_literal_halves: false, - ..options - }); - let off = translation_build(victory_shader::emit::Options { - disable_literal_halves: true, - ..options - }); - assert_ne!(on, off); + for (name, options) in [ + ( + "atomic locks", + Options { + atomic_locks: true, + ..base + }, + ), + ( + "bias as gradients", + Options { + bias_as_gradients: true, + ..base + }, + ), + ( + "narrow waves", + Options { + narrow_waves: true, + ..base + }, + ), + ( + "literal halves", + Options { + disable_literal_halves: true, + ..base + }, + ), + ( + "UAV size level 0", + Options { + uav_size_level0: true, + ..base + }, + ), + ( + "halves rendezvous", + Options { + halves_rendezvous: false, + ..base + }, + ), + ( + "thread limits", + Options { + thread_limits: true, + ..base + }, + ), + ] { + assert_ne!( + translation_build(base), + translation_build(options), + "{name}" + ); + } + let locks = Options { + atomic_locks: true, + ..base + }; + let rounds = Options { + atomic_lock_rounds: true, + ..locks + }; + let umax = Options { + atomic_umax: true, + ..rounds + }; + assert_ne!(translation_build(locks), translation_build(rounds)); + assert_ne!(translation_build(rounds), translation_build(umax)); } fn shader() -> HostShader { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 04bb9d724..8d141f3ee 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -56,6 +56,8 @@ pub(crate) struct Staging { size: u64, footprints: Vec, rows: Vec, + #[cfg(feature = "diagnostics")] + row_sizes: Vec, layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, @@ -530,21 +532,52 @@ fn copies( (buffer, at): (&ID3D12Resource, u64), subresources: &[Sub], ) { + let block = staging.layout.desc.block.max(1); for (i, band) in subresources { let i = *i as usize; let mut footprint = staging.footprints[i]; footprint.Offset += at; - let footprint = &footprint; + let f = footprint.Footprint; + let (top, source_box) = match band { + Some(r) if *r != (0..staging.rows[i]) => { + // Other rows in the staging allocation may still contain old data. + if block > 1 { + // D3DMetal 4.0 beta 1 copies the wrong rows from a nonzero BC source box. + let (offset, texels) = staging + .compact_rows(i, at, r) + .expect("compressed row band selected before detiling"); + footprint.Offset = offset; + footprint.Footprint.Height = texels.end - texels.start; + (texels.start, None) + } else { + let (top, bottom) = (r.start, r.end.min(f.Height)); + if top >= bottom { + continue; + } + let rows = D3D12_BOX { + left: 0, + top, + front: 0, + right: f.Width, + bottom, + back: f.Depth, + }; + (top, Some(rows)) + } + } + _ => (0, None), + }; #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; // SAFETY: live resources. let (gpu, d) = unsafe { (buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; - let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + let (first, end) = source_box.as_ref().map_or((0, f.Height), |b| (b.top, b.bottom)); + let (first_byte, len) = staging.copy_read_span(i, footprint, first..end); list.note_read( || { format!( - "texture upload ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + "texture upload ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {first_byte:#x} {}x{}x{} pitch {} to y={top}", d.Width, d.Height, d.DepthOrArraySize, @@ -552,14 +585,13 @@ fn copies( d.MipLevels, staging.footprints.len(), staging.size, - footprint.Offset, f.Width, - f.Height, + end - first, f.Depth, f.RowPitch ) }, - (gpu + footprint.Offset, len), + (gpu + first_byte, len), ); } let to = D3D12_TEXTURE_COPY_LOCATION { @@ -575,33 +607,12 @@ fn copies( pResource: unsafe { std::mem::transmute_copy(buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: *footprint, + PlacedFootprint: footprint, }, }; - // Only the rows detiled: the staging buffer's other rows hold whatever - // its last user left. - let f = footprint.Footprint; - let block = staging.layout.desc.block.max(1); - match band { - Some(r) if *r != (0..staging.rows[i]) => { - let (top, bottom) = (r.start * block, (r.end * block).min(f.Height)); - if top >= bottom { - continue; - } - let rows = D3D12_BOX { - left: 0, - top, - front: 0, - right: f.Width, - bottom, - back: f.Depth, - }; - // SAFETY: an open list; both locations name live resources, - // and the box lies inside the footprint. - unsafe { list.list.CopyTextureRegion(&to, 0, top, 0, &from, Some(&rows)) }; - } - // SAFETY: an open list; both locations name live resources. - _ => unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }, + // SAFETY: an open list; both locations name live resources. + unsafe { + list.list.CopyTextureRegion(&to, 0, top, 0, &from, source_box.as_ref().map(std::ptr::from_ref)); } } } @@ -900,6 +911,44 @@ impl Staging { WorkerRefresh::Uploaded((b, at, fresh)) } + #[cfg(feature = "diagnostics")] + fn copy_read_span( + &self, + i: usize, + footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + texels: std::ops::Range, + ) -> (u64, u64) { + let f = footprint.Footprint; + let block = self.layout.desc.block.max(1); + let pitch = u64::from(f.RowPitch); + let first = texels.start / block; + let rows = texels.end.div_ceil(block) - first; + let first_byte = footprint.Offset + pitch * u64::from(first); + let slice_rows = u64::from(self.rows[i]); + let len = pitch * ((u64::from(f.Depth) - 1) * slice_rows + u64::from(rows) - 1) + + self.row_sizes[i]; + (first_byte, len) + } + + fn compact_rows( + &self, + i: usize, + at: u64, + rows: &std::ops::Range, + ) -> Option<(u64, std::ops::Range)> { + let footprint = self.footprints[i]; + let f = footprint.Footprint; + crate::texture_rows::compact( + at, + footprint.Offset, + f.RowPitch, + f.Height, + f.Depth, + self.layout.desc.block, + rows, + ) + } + /// Returns the bytes of title memory read, and the buffer it detiled /// into with the subresources detiled. fn refresh_now( @@ -1024,6 +1073,14 @@ impl Staging { let band = if use_rows && own(i) { self.layout .touched_rows(s % self.mips, s / self.mips, &changed) + .filter(|(rows, _)| { + // Select the whole read and detile before touching scratch. + // Staging allocation bases are 512-byte aligned. + self.layout.desc.block <= 1 + || rows.is_empty() + || *rows == (0..self.rows[i]) + || self.compact_rows(i, 0, rows).is_some() + }) } else { None }; @@ -1627,6 +1684,12 @@ pub(crate) fn staging(resource: This, texture: &ID3D12Resource) -> Option Option Option usize { let mut attempted = false; let (read, upload) = staging.refresh_now(|_, _, _| { attempted = true; None }); assert!(attempted && read > 0 && upload.is_none()); + read } #[test] @@ -2366,11 +2432,13 @@ pub(crate) mod tests { } } - fn linear_rgba8_staging( + fn linear_staging( address: usize, width: u32, height: u32, slices: u32, + format: u32, + flags: u32, ) -> Option<(This, Arc)> { let _host = host()?; let words: [u32; 14] = [ @@ -2382,11 +2450,11 @@ pub(crate) mod tests { 0, height, slices | (1 << 16), - 28, // DXGI_FORMAT_R8G8B8A8_UNORM + format, 1, 0, 0x100, // linear - 0, + flags, 0, ]; let iid = crate::object::guid( @@ -2411,6 +2479,33 @@ pub(crate) mod tests { Some((out, s)) } + #[cfg(feature = "diagnostics")] + #[test] + fn partial_upload_marker_covers_the_unpadded_host_row() { + let address = crate::watch::tests::pool(1); + // The width leaves padding in the host pitch for either format. + let Some((obj, s)) = linear_staging(address, 2559, 5, 1, 115, 4) else { + return; + }; + let mut footprint = s.footprints[0]; + let format = footprint.Footprint.Format.0; + eprintln!("upload marker fixture host format {format}"); + let (pitch, last_row) = match format { + 28 => (10_240, 10_236), // RGBA8 after packed-color promotion + 115 => (5120, 5118), // native packed color on a capable device + _ => panic!("unexpected host format {format}"), + }; + assert_eq!(s.layout.desc.element_bytes, 2); + assert_eq!(u64::from(footprint.Footprint.RowPitch), pitch); + footprint.Offset += 1024; + assert_eq!( + s.copy_read_span(0, footprint, 2..5), + (1024 + 2 * pitch, 2 * pitch + last_row) + ); + release_staging(obj, s); + crate::object::release(obj); + } + fn release_staging(object: This, s: Arc) { if let Some(copy) = crate::resource::host_copy(object) { copy.staging.lock().unwrap_or_else(|e| e.into_inner()).take(); @@ -2441,7 +2536,7 @@ pub(crate) mod tests { let page = crate::watch::PAGE; let mut mem = PlaceholderPages::new(2); mem.map(0, 0x42); - let Some((obj, s)) = linear_rgba8_staging(mem.base, 128, 128, 2) else { + let Some((obj, s)) = linear_staging(mem.base, 128, 128, 2, 28, 0) else { return; // no host GPU here }; assert!(s.tracked.is_some(), "placeholder views must be tracked"); @@ -2503,7 +2598,7 @@ pub(crate) mod tests { let page = crate::watch::PAGE; let mut mem = PlaceholderPages::new(2); mem.map(0, 0x33); - let Some((obj, s)) = linear_rgba8_staging(mem.base, 128, 256, 1) else { + let Some((obj, s)) = linear_staging(mem.base, 128, 256, 1, 28, 0) else { return; // no host GPU here }; assert!(s.tracked.is_some()); diff --git a/crates/victory-gpu/src/texture_rows.rs b/crates/victory-gpu/src/texture_rows.rs new file mode 100644 index 000000000..8553456ab --- /dev/null +++ b/crates/victory-gpu/src/texture_rows.rs @@ -0,0 +1,56 @@ +use std::ops::Range; + +/// Rebase a compressed band onto its first staged row. Reducing the height +/// would change the distance between depth slices. +pub(super) fn compact( + base: u64, + offset: u64, + pitch: u32, + height: u32, + depth: u32, + block: u32, + rows: &Range, +) -> Option<(u64, Range)> { + let texels = rows.start.saturating_mul(block)..rows.end.saturating_mul(block).min(height); + let offset = base + .checked_add(offset)? + .checked_add(u64::from(rows.start) * u64::from(pitch))?; + (depth == 1 && !texels.is_empty() && offset.is_multiple_of(512)).then_some((offset, texels)) +} + +#[cfg(test)] +mod tests { + use super::compact; + + #[test] + fn compact_band_reads_the_staged_rows_at_a_nonzero_base() { + // The allocation starts at 1024 and this subresource starts 512 bytes in. + let mut staging = [0xFF; 3080]; + staging[2560..2568].fill(0x45); + staging[2816..2824].fill(0x56); + let (source, texels) = compact(1024, 512, 256, 25, 1, 4, &(4..6)).unwrap(); + let source = source as usize; + assert_eq!(texels, 16..24); + assert_eq!(staging[source..source + 8], [0x45; 8]); + assert_eq!(staging[source + 256..source + 264], [0x56; 8]); + } + + #[test] + fn an_unaligned_offset_or_multiple_depth_slices_preclude_rebasing() { + assert_eq!(compact(1024, 512, 256, 25, 1, 4, &(3..5)), None); + assert_eq!(compact(1024, 512, 256, 25, 2, 4, &(4..6)), None); + } + + #[test] + fn compact_band_clips_the_final_block_row() { + assert_eq!( + compact(1024, 512, 256, 25, 1, 4, &(6..7)), + Some((3072, 24..25)) + ); + assert_eq!(compact(1024, 512, 256, 25, 1, 4, &(7..7)), None); + assert_eq!( + compact(1024, 512, 256, 25, 1, 4, &(0..7)), + Some((1536, 0..25)) + ); + } +} diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index ad60bf018..6b8860777 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -936,6 +936,12 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) }; let code = record.ExceptionCode; let at = record.ExceptionAddress as usize; + #[cfg(feature = "diagnostics")] + let pool = (what == "first-chance exception" && code == EXCEPTION_BREAKPOINT) + .then(|| crate::pool::windows::first_fault(at, context)) + .flatten(); + #[cfg(feature = "diagnostics")] + let to_file = to_file || pool.is_some(); let p = record.ExceptionInformation; let detail = if code == EXCEPTION_ACCESS_VIOLATION { let kind = match p[0] { @@ -966,6 +972,10 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { code as u32, locate(at) )); + #[cfg(feature = "diagnostics")] + if let Some(pool) = pool { + line(format!(" {pool}")); + } line(format!( " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}", context.Rax, @@ -1300,6 +1310,12 @@ unsafe fn dump_title_registry(context: &CONTEXT) { #[cfg(test)] mod tests { + #[cfg(feature = "diagnostics")] + #[test] + fn first_pool_fault_preserves_dispatch() { + crate::pool::windows::tests::check_dispatch(super::handler); + } + use super::*; #[test] diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 141642d23..762a84954 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -27,6 +27,8 @@ pub mod masked; pub mod wide; #[cfg(windows)] mod patch; +#[cfg(any(all(windows, feature = "diagnostics"), test))] +mod pool; pub mod prepare; pub(crate) mod publish; pub mod resolution; @@ -51,6 +53,8 @@ pub use crash::{ }; #[cfg(windows)] pub use patch::patch_code; +#[cfg(all(windows, feature = "diagnostics"))] +pub use pool::windows::{PoolObserver, start_pool_observation}; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-loader/src/pool.rs b/crates/victory-loader/src/pool.rs new file mode 100644 index 000000000..4a5e63345 --- /dev/null +++ b/crates/victory-loader/src/pool.rs @@ -0,0 +1,206 @@ +//! Periodic, read-only pool observations for the identified main executable. + +mod residents; +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) mod windows; + +const BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93"; +const EMPTY: u32 = 0x1fffe; +const SLOTS: [usize; 3] = [0xa9ec938, 0xabbe2e8, 0x98d79a8]; +const TRAPS: [usize; 2] = [0x5149aec, 0x63966f]; + +fn enabled(value: Option<&str>, hash: &str, is_dll: bool) -> bool { + value == Some("1") && !is_dll && hash == BUILD +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Sample { + pointer: usize, + backing: u64, + metadata: u64, + stride: u32, + capacity: u32, + used: u32, + head: u64, +} + +impl Sample { + fn parse(pointer: usize, stride: u32, bytes: &[u8; 52]) -> Result { + let word = |i| u32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()); + let wide = |i| u64::from_le_bytes(bytes[i..i + 8].try_into().unwrap()); + let capacity = word(12); + let used = word(16); + let head = wide(32); + let index = head as u32; + if word(8) != stride + || !(1..=EMPTY).contains(&capacity) + || used > capacity + || (index != EMPTY && index >= capacity) + || word(48) != 0x1ffff + { + return Err("invalid-header"); + } + Ok(Self { + pointer, + backing: wide(0), + metadata: wide(40), + stride, + capacity, + used, + head, + }) + } + + fn activity(self, previous: Option) -> Result<(u32, Option), &'static str> { + let old = previous.ok_or("no-contiguous-sample")?; + if self.pointer != old.pointer + || self.capacity != old.capacity + || self.stride != old.stride + || self.backing == 0 + || self.backing != old.backing + || self.metadata == 0 + || self.metadata != old.metadata + { + return Err("storage-changed-or-unavailable"); + } + let tag = (self.head >> 32) as u32; + let old_tag = (old.head >> 32) as u32; + let delta = tag.wrapping_sub(old_tag); + let pops = + (tag >= old_tag).then(|| i64::from(self.used) - i64::from(old.used) + i64::from(delta)); + Ok((delta, pops)) + } +} + +#[derive(Clone, Copy)] +struct Map { + slots: [usize; 3], + traps: [usize; 2], +} + +impl Map { + fn new(base: usize, size: usize) -> Option { + base.checked_add(size)?; + if base == 0 + || SLOTS.iter().any(|rva| rva + 8 > size) + || TRAPS.iter().any(|rva| *rva >= size) + { + return None; + } + Some(Self { + slots: SLOTS.map(|rva| base + rva), + traps: TRAPS.map(|rva| base + rva), + }) + } + + fn select(self, at: usize, pointer: usize, globals: [Option; 3]) -> Option { + let candidates = match self.traps.iter().position(|trap| *trap == at)? { + 0 => 0..2, + _ => 2..3, + }; + let mut found = None; + for i in candidates { + if globals[i]? == pointer && pointer != 0 { + if found.is_some() { + return None; + } + found = Some(i); + } + } + found + } +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(super) fn header() -> [u8; 52] { + let mut bytes = [0; 52]; + bytes[..8].copy_from_slice(&0x1000_u64.to_le_bytes()); + bytes[8..12].copy_from_slice(&224_u32.to_le_bytes()); + bytes[12..16].copy_from_slice(&17_u32.to_le_bytes()); + bytes[16..20].copy_from_slice(&10_u32.to_le_bytes()); + bytes[32..40].copy_from_slice(&(9_u64 << 32 | u64::from(EMPTY)).to_le_bytes()); + bytes[40..48].copy_from_slice(&0x2000_u64.to_le_bytes()); + bytes[48..52].copy_from_slice(&0x1ffff_u32.to_le_bytes()); + bytes + } + + #[test] + fn accepts_only_opted_in_exact_original_main_and_bounded_rvas() { + assert!(enabled(Some("1"), BUILD, false)); + assert!(!enabled(None, BUILD, false)); + assert!(!enabled(Some("0"), BUILD, false)); + assert!(!enabled(Some("1"), &BUILD[..16], false)); + assert!(!enabled(Some("1"), BUILD, true)); + assert_eq!( + Map::new(0x1000, 0xc000000).unwrap().slots[2], + 0x1000 + SLOTS[2] + ); + assert!(Map::new(usize::MAX - 12, 0xc000000).is_none()); + assert!(Map::new(0x1000, 0xabbe2ef).is_none()); + } + + #[test] + fn matches_only_one_readable_global_at_its_own_trap() { + let map = Map { + slots: [11, 12, 13], + traps: [14, 15], + }; + let globals = [Some(21), Some(22), Some(23)]; + assert_eq!(map.select(14, 22, globals), Some(1)); + assert_eq!(map.select(15, 23, globals), Some(2)); + assert_eq!(map.select(14, 23, globals), None); + assert_eq!(map.select(91, 21, globals), None); + assert_eq!(map.select(14, 0, [Some(0); 3]), None); + assert_eq!(map.select(14, 21, [Some(21), Some(21), Some(23)]), None); + assert_eq!(map.select(14, 21, [Some(21), None, Some(23)]), None); + } + + #[test] + fn parses_complete_tag_and_rejects_malformed_headers() { + let bytes = header(); + let got = Sample::parse(0x800, 224, &bytes).unwrap(); + assert_eq!( + (got.used, got.capacity, got.head), + (10, 17, 9_u64 << 32 | u64::from(EMPTY)) + ); + assert!(Sample::parse(0x800, 272, &bytes).is_err()); + for (offset, value) in [ + (12, 0), + (12, EMPTY + 1), + (16, 18), + (32, 17), + (32, 0xffff_fffe), + (48, 0), + ] { + let mut bad = bytes; + bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + assert!(Sample::parse(0x800, 224, &bad).is_err()); + } + } + + #[test] + fn activity_preserves_signed_skew_marks_gaps_replacement_and_wrap() { + let a = Sample::parse(0x800, 224, &header()).unwrap(); + let b = Sample { + used: 6, + head: a.head + (3_u64 << 32), + ..a + }; + assert_eq!(b.activity(Some(a)), Ok((3, Some(-1)))); + assert!(b.activity(None).is_err()); + for changed in [ + Sample { pointer: 1, ..a }, + Sample { backing: 0, ..a }, + Sample { metadata: 0, ..a }, + Sample { stride: 272, ..a }, + Sample { capacity: 18, ..a }, + ] { + assert!(b.activity(Some(changed)).is_err()); + } + let wrapped = Sample { head: 2, ..a }; + assert_eq!(wrapped.activity(Some(a)), Ok((0_u32.wrapping_sub(9), None))); + } +} diff --git a/crates/victory-loader/src/pool/residents.rs b/crates/victory-loader/src/pool/residents.rs new file mode 100644 index 000000000..aaf039965 --- /dev/null +++ b/crates/victory-loader/src/pool/residents.rs @@ -0,0 +1,605 @@ +//! Bounded observations of BUILDING slots and the title's removal queues. +use super::Sample; +pub(super) mod owner; +mod primary; +pub(super) mod request; +use std::io::{self, Seek, SeekFrom, Write}; + +const LIMIT: usize = 22_500; +const TIMING: usize = 384 + owner::COUNT * owner::BYTES; +const PASS: usize = TIMING + 64; +const PRIMARY: usize = PASS + 32; +const HEADER: usize = PRIMARY + primary::SIZE; +const RECORD: usize = 40; +const FRAME: usize = HEADER + LIMIT * RECORD + 8; +const INPUTS: usize = 0x77d8d90; +const MIXED: usize = 0x77d9070; +const VTABLE: usize = 0x62e3fe0; +#[cfg(all(windows, feature = "diagnostics"))] +pub(super) const IMAGE_RANGES: [(usize, usize); 13] = [ + (INPUTS, 248), + (MIXED, 16), + (VTABLE, 8), + (0xa024230, 232), + (primary::GLOBAL, 8), + (0xabcd210, 10), + (0x764aa00, 4), + (0x655ce30, 8), + (0x764b240, 8), + (0xab44324, 4), + (0xabbef44, 4), + (0x7bd24f8, 4), + (0x7450df8, 19), +]; + +fn word(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) +} + +fn wide(b: &[u8], at: usize) -> u64 { + u64::from_le_bytes(b[at..at + 8].try_into().unwrap()) +} + +type Reader<'a> = dyn FnMut(usize, &mut [u8]) -> bool + 'a; + +fn copy(read: &mut Reader<'_>, at: usize) -> Option<[u8; N]> { + let mut bytes = [0; N]; + read(at, &mut bytes).then_some(bytes) +} + +fn valid_queue(q: &[u8]) -> bool { + word(q, 4) <= word(q, 0) && (word(q, 0) == 0 || wide(q, 8) != 0) +} + +fn payload( + q: Option<&[u8]>, + limit: usize, + entries: &mut Vec, + check: &mut Vec, + read: &mut Reader<'_>, +) -> bool { + let Some(q) = q.filter(|q| valid_queue(q) && word(q, 4) as usize <= limit) else { + return false; + }; + let n = word(q, 4) as usize * WIDTH; + entries.resize(n, 0); + check.resize(n, 0); + let at = wide(q, 8) as usize; + n == 0 + || (at.is_multiple_of(WIDTH) + && at.checked_add(n).is_some() + && read(at, entries) + && read(at, check) + && entries == check) +} + +pub(super) struct Census { + frame: Vec, + meta: [Vec; 2], + slots: [Vec; 2], + input: Vec, + mixed: Vec, + check: Vec, + milestones: u8, + roster: owner::Roster, + primary: [primary::Pass; 2], +} + +impl Census { + pub(super) fn new() -> Self { + Self { + frame: vec![0; FRAME], + meta: Default::default(), + slots: Default::default(), + input: Vec::new(), + mixed: Vec::new(), + check: Vec::new(), + milestones: 0, + roster: Default::default(), + primary: Default::default(), + } + } + + fn read_queues(&mut self, base: usize, read: &mut Reader<'_>) -> (bool, bool) { + let table = copy::<248>(read, base + INPUTS); + let mix = copy::<16>(read, base + MIXED); + let mut input_ok = payload::<4>( + table + .as_ref() + .filter(|b| (2..=15).contains(&word(&b[..], 4))) + .map(|b| &b[24..40]), + LIMIT, + &mut self.input, + &mut self.check, + read, + ); + let mut mixed_ok = payload::<8>( + mix.as_ref().map(|b| &b[..]), + 65_536, + &mut self.mixed, + &mut self.check, + read, + ); + let end = copy::<248>(read, base + INPUTS); + let mut mask = 0_u32; + if let (Some(a), Some(b)) = (table, end) { + let count = word(&a, 4); + if count == word(&b, 4) && count <= 15 { + for i in 0..count as usize { + let offset = 8 + i * 16; + let q = &a[offset..offset + 16]; + if q == &b[offset..offset + 16] && valid_queue(q) { + self.frame[128 + i * 16..144 + i * 16].copy_from_slice(q); + mask |= 1 << i; + } + } + } + } + input_ok &= mask & 2 != 0; + if let Some(q) = + mix.filter(|q| valid_queue(q) && copy::<16>(read, base + MIXED) == Some(*q)) + { + self.frame[368..384].copy_from_slice(&q); + mask |= 1 << 15; + } else { + mixed_ok = false; + } + self.frame[28..32].copy_from_slice(&mask.to_le_bytes()); + (input_ok, mixed_ok) + } + + fn clock(&mut self, base: usize, read: &mut Reader<'_>) { + for (bit, rva, out) in [(1, 0xabbef44, 92), (2, 0x7bd24f8, 96)] { + if let Some(n) = + copy::<4>(read, base + rva).filter(|n| copy::<4>(read, base + rva) == Some(*n)) + { + self.frame[88] |= bit; + self.frame[out..out + 4].copy_from_slice(&n); + } + } + if let Some(b) = copy::<19>(read, base + 0x7450df8) + .filter(|b| copy::<19>(read, base + 0x7450df8) == Some(*b)) + { + self.frame[88] |= 4; + self.frame[89] = u8::from(b[8..10] == 9_u16.to_le_bytes() && &b[10..] == b"Prestream"); + self.frame[104..112].copy_from_slice(&b[..8]); + } + } + + pub(super) fn capture( + &mut self, + base: usize, + start: Option, + mut read: impl FnMut(usize, &mut [u8]) -> bool, + end: impl FnOnce() -> Option, + ) { + self.primary[0].read(base, &mut read); + self.capture_residents(base, start, &mut read, end); + self.primary[1].read(base, &mut read); + primary::encode( + &self.primary[0], + &self.primary[1], + &mut self.frame[PRIMARY..HEADER], + ); + } + + fn capture_residents( + &mut self, + base: usize, + start: Option, + mut read: impl FnMut(usize, &mut [u8]) -> bool, + end: impl FnOnce() -> Option, + ) { + self.frame.fill(0); + self.frame[..8].copy_from_slice(b"BRES0002"); + self.clock(base, &mut read); + owner::timing(base, &mut self.frame[TIMING..PASS], &mut read); + owner::admissions(base, &mut self.frame[PASS..PRIMARY], &mut read); + let Some(s) = start else { return }; + self.frame[32..40].copy_from_slice(&(s.pointer as u64).to_le_bytes()); + self.frame[40..48].copy_from_slice(&s.backing.to_le_bytes()); + self.frame[48..56].copy_from_slice(&s.metadata.to_le_bytes()); + self.frame[56..60].copy_from_slice(&s.capacity.to_le_bytes()); + self.frame[60..64].copy_from_slice(&s.used.to_le_bytes()); + self.frame[64..72].copy_from_slice(&s.head.to_le_bytes()); + let n = s.capacity as usize; + self.frame[24] = 2; + if !(1..=LIMIT).contains(&n) + || s.stride != 224 + || s.backing == 0 + || s.metadata == 0 + || !s.backing.is_multiple_of(8) + || !s.metadata.is_multiple_of(4) + || s.backing.checked_add((n * 224) as u64).is_none() + || s.metadata.checked_add((n * 4) as u64).is_none() + { + return; + } + for m in &mut self.meta { + m.resize(n * 4, 0); + } + for b in &mut self.slots { + b.resize(n * 224, 0); + } + self.frame[24] = 3; + if !read(s.metadata as usize, &mut self.meta[0]) + || !read(s.backing as usize, &mut self.slots[0]) + { + return; + } + let (input_ok, mixed_ok) = self.read_queues(base, &mut read); + if !read(s.backing as usize, &mut self.slots[1]) + || !read(s.metadata as usize, &mut self.meta[1]) + { + return; + } + let rows = &mut self.frame[HEADER..HEADER + n * RECORD]; + let input_ok = input_ok + && self + .input + .as_chunks::<4>() + .0 + .iter() + .all(|b| (word(b, 0) & 0xffff) < s.capacity); + let mut valid = 0_u32; + for (i, row) in rows.as_chunks_mut::().0.iter_mut().enumerate() { + if self.meta[0][i * 4..i * 4 + 4] != self.meta[1][i * 4..i * 4 + 4] { + continue; + } + let meta = word(&self.meta[0], i * 4); + row[4..8].copy_from_slice(&meta.to_le_bytes()); + if meta & 0x1ffff != 0x1ffff { + row[0] = 1; + continue; + } + let fields = |snapshot: &[u8]| { + let b = &snapshot[i * 224..][..224]; + ( + wide(b, 0), + b[0x30], + b[0x96] & 15, + b[0xb0] & 1, + word(b, 0x9c), + wide(b, 0x20), + wide(b, 0xa8), + (b[0xb4] >> 1) & 31, + word(b, 0xcc), + ) + }; + let a = fields(&self.slots[0]); + if a != fields(&self.slots[1]) { + row.fill(0); + continue; + } + let (vtable, ty, state, pending, handle, descriptor, reference, class, raw_id) = a; + let expected = (meta << 5 & 0xffc00000) | (1 << 17) | i as u32; + if vtable != (base + VTABLE) as u64 || ty != 1 || handle != expected { + row[0] = 3; + continue; + } + valid += 1; + row[..4].copy_from_slice(&[2, ty, state, pending]); + row[8..12].copy_from_slice(&handle.to_le_bytes()); + row[12] = u8::from(input_ok); + row[14] = u8::from(mixed_ok); + row[15] = class; + row[16..24].copy_from_slice(&descriptor.to_le_bytes()); + row[24..32].copy_from_slice(&reference.to_le_bytes()); + row[32..36].copy_from_slice(&raw_id.to_le_bytes()); + } + if input_ok { + for entry in self.input.as_chunks::<4>().0 { + let i = (word(entry, 0) & 0xffff) as usize; + let row = &mut rows[i * RECORD..][..RECORD]; + if row[0] == 2 { + row[12] = if row[12] == 1 { 2 } else { 3 }; + row[13] = if row[12] == 2 { entry[2] } else { 0 }; + } + } + } + if mixed_ok { + for entry in self.mixed.as_chunks::<8>().0 { + if let Some(off) = wide(entry, 0).checked_sub(s.backing) + && off.is_multiple_of(224) + && off / 224 < n as u64 + { + let row = &mut rows[off as usize / 224 * RECORD..][..RECORD]; + if row[0] == 2 { + row[14] = if row[14] == 1 { 2 } else { 3 }; + } + } + } + } + let (header, data) = self.frame.split_at_mut(HEADER); + let eligible = self.roster.select(&data[..n * RECORD]); + header[114..116].copy_from_slice(&(eligible as u16).to_le_bytes()); + header[112] = owner::observe_owners( + base, + &data[..n * RECORD], + s.backing, + s.metadata, + &mut header[384..TIMING], + &mut read, + &self.roster, + ) as u8; + header[76..80].copy_from_slice(&valid.to_le_bytes()); + self.frame[24] = 4; + let Some(e) = end().filter(|e| { + (e.pointer, e.backing, e.metadata, e.capacity, e.stride) + == (s.pointer, s.backing, s.metadata, s.capacity, s.stride) + }) else { + self.frame[76..80].fill(0); + self.frame[112..116].fill(0); + self.frame[384..TIMING].fill(0); + self.frame[HEADER..HEADER + n * RECORD].fill(0); + return; + }; + self.frame[72..76].copy_from_slice(&e.used.to_le_bytes()); + self.frame[80..88].copy_from_slice(&e.head.to_le_bytes()); + self.frame[24] = 1; + } + + pub(super) fn publish( + &mut self, + out: &mut (impl Write + Seek), + seq: u64, + ms: u64, + ) -> io::Result<()> { + self.frame[8..16].copy_from_slice(&seq.to_le_bytes()); + self.frame[16..24].copy_from_slice(&ms.to_le_bytes()); + self.frame[FRAME - 8..].copy_from_slice(&(!seq).to_le_bytes()); + let mut save = |slot: u64| { + out.seek(SeekFrom::Start(slot * FRAME as u64))?; + out.write_all(&self.frame) + }; + save(seq % 64)?; + let capacity = word(&self.frame, 56); + let used = word(&self.frame, 60); + if self.frame[24] == 1 && word(&self.frame, 76) > 0 { + for (i, threshold) in [0, 50, 80, 95].into_iter().enumerate() { + if self.milestones & (1 << i) == 0 && used > 0 && used * 100 >= capacity * threshold + { + save(64 + i as u64)?; + self.milestones |= 1 << i; + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pool::tests::header; + use std::io::Cursor; + + const BASE: usize = 0x1000_0000; + const BACKING: usize = 0x3000_0000; + const META: usize = 0x4000_0000; + const INPUT: usize = 0x5000_0000; + const MIXED: usize = 0x6000_0000; + + struct Memory { + sample: Sample, + slots: Vec, + meta: [u32; 3], + queues: [u8; 248], + mixed: [u8; 16], + input_entries: [u8; 8], + mixed_entries: [u8; 16], + } + + impl Memory { + fn new() -> Self { + let mut sample = Sample::parse(8, 224, &header()).unwrap(); + sample.capacity = 3; + sample.used = 2; + sample.backing = BACKING as u64; + sample.metadata = META as u64; + let mut slots = vec![0; 224 * 3]; + for index in [0, 2] { + let row = &mut slots[index * 224..][..224]; + row[..8].copy_from_slice(&((BASE + 0x62e3fe0) as u64).to_le_bytes()); + row[0x20..0x28].copy_from_slice(&70_u64.to_le_bytes()); + row[0x30] = 1; + row[0x96] = 0x85; + row[0x9c..0xa0].copy_from_slice(&(0x00c20000_u32 + index as u32).to_le_bytes()); + row[0xa8..0xb0].copy_from_slice(&60_u64.to_le_bytes()); + row[0xb0] = 3; + row[0xb4] = 10; + row[0xcc..0xd0].copy_from_slice(&51_u32.to_le_bytes()); + } + let mut queues = [0; 248]; + queues[4..8].copy_from_slice(&15_u32.to_le_bytes()); + queues[24..28].copy_from_slice(&7_u32.to_le_bytes()); + queues[28..32].copy_from_slice(&2_u32.to_le_bytes()); + queues[32..40].copy_from_slice(&(INPUT as u64).to_le_bytes()); + let mut mixed = [0; 16]; + mixed[..4].copy_from_slice(&3_u32.to_le_bytes()); + mixed[4..8].copy_from_slice(&2_u32.to_le_bytes()); + mixed[8..].copy_from_slice(&(MIXED as u64).to_le_bytes()); + let mut mem = Self { + sample, + slots, + meta: [0x7ffff, 0x20002, 0x7ffff], + queues, + mixed, + input_entries: [0; 8], + mixed_entries: [0; 16], + }; + mem.input_entries[..4].copy_from_slice(&0x240000_u32.to_le_bytes()); + mem.input_entries[4..].copy_from_slice(&0x130002_u32.to_le_bytes()); + for ptr in mem.mixed_entries.as_chunks_mut::<8>().0 { + ptr.copy_from_slice(&((BACKING + 448) as u64).to_le_bytes()); + } + mem + } + + fn read(&self, at: usize, out: &mut [u8]) -> bool { + let meta = self.meta.map(u32::to_le_bytes).concat(); + let data: &[u8] = match at { + BACKING => &self.slots, + META => &meta, + INPUT => &self.input_entries, + MIXED => &self.mixed_entries, + a if a == BASE + 0x77d8d90 => &self.queues, + a if a == BASE + 0x77d9070 => &self.mixed, + _ => return false, + }; + if data.len() != out.len() { + return false; + } + out.copy_from_slice(data); + true + } + } + + #[test] + fn published_snapshot_retains_only_matching_occupants_and_observed_queue_membership() { + let mem = Memory::new(); + let mut scratch = Census::new(); + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| mem.read(at, dst), + || Some(mem.sample), + ); + let rows = &scratch.frame[HEADER..HEADER + 3 * RECORD]; + assert_eq!(&rows[..4], &[2, 1, 5, 1]); + assert_eq!(&rows[4..8], &0x7ffff_u32.to_le_bytes()); + assert_eq!(&rows[8..12], &0xc20000_u32.to_le_bytes()); + assert_eq!(&rows[12..16], &[2, 0x24, 1, 5]); + assert_eq!(&rows[16..24], &70_u64.to_le_bytes()); + assert_eq!(&rows[24..32], &60_u64.to_le_bytes()); + assert_eq!(&rows[32..36], &51_u32.to_le_bytes()); + assert_eq!(rows[RECORD], 1); + assert_eq!(&rows[RECORD + 8..RECORD * 2], &vec![0; RECORD - 8]); + assert_eq!(&rows[2 * RECORD + 12..2 * RECORD + 15], &[2, 0x13, 3]); + assert_eq!(&scratch.frame[24..28], &1_u32.to_le_bytes()); + } + + #[test] + fn reuse_changed_fields_and_queue_races_cannot_be_reported_as_correlated() { + for (addr, byte, expected) in [(META, 0, 0), (BACKING, 0xa8, 0), (INPUT, 2, 2)] { + let mem = Memory::new(); + let mut scratch = Census::new(); + let mut passes = 0; + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| { + let ok = mem.read(at, dst); + if ok && at == addr { + passes += 1; + if passes == 2 { + dst[byte] ^= 1; + } + } + ok + }, + || Some(mem.sample), + ); + let row = &scratch.frame[HEADER..][..RECORD]; + assert_eq!(row[0], expected); + assert_eq!(row[12], 0); + if expected == 0 { + assert!(row.iter().all(|v| *v == 0)); + } + } + let mut mem = Memory::new(); + mem.meta[0] = 0x9ffff; + let mut scratch = Census::new(); + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| mem.read(at, dst), + || Some(mem.sample), + ); + let row = &scratch.frame[HEADER..][..RECORD]; + assert_eq!(row[0], 3); + assert_eq!(&row[8..], &vec![0; RECORD - 8]); + } + + #[test] + fn lost_backing_replaced_storage_and_oversize_counts_invalidate_observations() { + let mut mem = Memory::new(); + let mut scratch = Census::new(); + for (missing, replaced) in [(BACKING, false), (0, true)] { + let mut end = mem.sample; + if replaced { + end.metadata += 64; + } + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| at != missing && mem.read(at, dst), + || Some(end), + ); + assert_ne!(scratch.frame[24], 1); + assert!( + scratch.frame[HEADER..HEADER + RECORD * 3] + .iter() + .all(|b| *b == 0) + ); + } + mem.mixed[..8].copy_from_slice(&[1, 0, 1, 0, 1, 0, 1, 0]); + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| { + assert_ne!(at, MIXED); + mem.read(at, dst) + }, + || Some(mem.sample), + ); + assert_eq!(scratch.frame[HEADER + 14], 0); + assert_eq!(scratch.frame[HEADER + 12], 2); + let mut larger = mem.sample; + larger.capacity = 22501; + scratch.capture( + BASE, + Some(larger), + |at, _| { + assert_ne!(at, BACKING); + false + }, + || Some(larger), + ); + assert_ne!(scratch.frame[24], 1); + } + + #[test] + fn frame_footer_rejects_interrupted_wrap_and_milestones_are_retained() { + fn complete(bytes: &[u8]) -> Option { + if bytes.len() != FRAME || &bytes[..8] != b"BRES0002" { + return None; + } + let seq = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); + let footer = u64::from_le_bytes(bytes[FRAME - 8..].try_into().unwrap()); + (footer == !seq).then_some(seq) + } + let mem = Memory::new(); + let mut scratch = Census::new(); + scratch.capture( + BASE, + Some(mem.sample), + |at, dst| mem.read(at, dst), + || Some(mem.sample), + ); + let mut out = Cursor::new(Vec::new()); + scratch.publish(&mut out, 0, 111).unwrap(); + let old = out.get_ref()[..FRAME].to_vec(); + assert_eq!(complete(&old), Some(0)); + scratch.publish(&mut out, 64, 222).unwrap(); + let bytes = out.into_inner(); + assert_eq!(complete(&bytes[..FRAME]), Some(64)); + assert_eq!(complete(&bytes[64 * FRAME..65 * FRAME]), Some(0)); + assert_eq!(complete(&bytes[65 * FRAME..66 * FRAME]), Some(0)); + assert!(bytes.len() <= 68 * FRAME); + let mut partial = old; + partial[..FRAME - 8].copy_from_slice(&bytes[..FRAME - 8]); + assert_eq!(complete(&partial), None); + assert_eq!(complete(&bytes[..FRAME - 1]), None); + } +} diff --git a/crates/victory-loader/src/pool/residents/owner.rs b/crates/victory-loader/src/pool/residents/owner.rs new file mode 100644 index 000000000..e85485e93 --- /dev/null +++ b/crates/victory-loader/src/pool/residents/owner.rs @@ -0,0 +1,745 @@ +use super::{Reader, copy, wide, word}; + +pub(super) const COUNT: usize = 16; +pub(super) const BYTES: usize = 128; +const REG: usize = 0xa024230; +const MANAGER: usize = 0x764b240; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Owner { + pub(crate) record: usize, + pub(crate) pointer: usize, + pub(crate) array: usize, + pub(crate) count: u32, + stream_id: u32, + record_24: u32, + record_28: u32, + owner_c4: u32, +} + +fn pointer(read: &mut Reader<'_>, at: usize) -> Option { + let p = usize::from_le_bytes(copy(read, at)?); + (p != 0 && p.is_multiple_of(8)).then_some(p) +} + +pub(crate) fn owner(base: usize, id: u32, read: &mut Reader<'_>) -> Option { + let index = id & 0x3fffff; + let reg = copy::<104>(read, base.checked_add(REG)?)?; + if index == 0x3fffff + || index >= word(®, 16) + || id >> 28 != 0 + || (id >> 22) != word(®, 12) & 63 + { + return None; + } + let bits = wide(®, 96) as usize; + let records = wide(®, 56) as usize; + let stride = word(®, 64); + if bits == 0 || records == 0 || stride < 44 { + return None; + } + if copy::<1>(read, bits.checked_add((index / 8) as usize)?)?[0] & (1 << (index % 8)) == 0 { + return None; + } + let record = records.checked_add(index.checked_mul(stride)? as usize)?; + let r = copy::<44>(read, record)?; + let p = wide(&r, 0) as usize; + if p == 0 { + return Some(Owner { + record, + pointer: 0, + array: 0, + count: 0, + stream_id: word(®, 8).checked_add(index)? & 0xfffffff, + record_24: word(&r, 36), + record_28: word(&r, 40), + owner_c4: 0, + }); + } + if !p.is_multiple_of(8) { + return None; + } + let o = copy::<200>(read, p)?; + let array = wide(&o, 8) as usize; + let count = word(&o, 16); + if wide(&o, 0) != base.checked_add(0x655ce30)? as u64 + || word(&o, 20) != id + || !array.is_multiple_of(8) + || (count != 0 && array == 0) + || array.checked_add(count as usize * 8).is_none() + { + return None; + } + Some(Owner { + record, + pointer: p, + array, + count, + stream_id: word(®, 8).checked_add(index)? & 0xfffffff, + record_24: word(&r, 36), + record_28: word(&r, 40), + owner_c4: word(&o, 196), + }) +} + +fn bitmap(read: &mut Reader<'_>, at: usize, index: u32) -> Option<([u8; 16], u32)> { + let h = copy::<16>(read, at)?; + let p = wide(&h, 0) as usize; + let words = word(&h, 8); + let bits = word(&h, 12); + if p == 0 + || !p.is_multiple_of(4) + || index >= bits + || index / 32 >= words + || u64::from(bits) > u64::from(words) * 32 + { + return None; + } + let v = u32::from_le_bytes(copy(read, p.checked_add((index / 32) as usize * 4)?)?); + Some((h, v)) +} + +fn module_flags( + base: usize, + id: u32, + module: u8, + read: &mut Reader<'_>, +) -> Option<([usize; 7], u16)> { + let reg = base.checked_add(REG)?; + let modules = copy::<10>(read, base.checked_add(0xabcd210)?)?; + let table = wide(&modules, 0) as usize; + let n = u16::from_le_bytes(modules[8..10].try_into().unwrap()); + if table == 0 + || !table.is_multiple_of(8) + || u16::from(module) >= n + || pointer(read, table.checked_add(module as usize * 8)?)? != reg + { + return None; + } + let registry = copy::<232>(read, reg)?; + let vtable = wide(®istry, 0) as usize; + let index = id & 0x3fffff; + let bound = word(®istry, 16); + let occupancy = wide(®istry, 96) as usize; + let flags = wide(®istry, 224) as usize; + if id >> 28 != 0 + || index == 0x3fffff + || index >= bound + || id >> 22 != word(®istry, 12) & 63 + || vtable == 0 + || usize::from_le_bytes(copy(read, vtable.checked_add(0x98)?)?) + != base.checked_add(0x4f83000)? + || occupancy == 0 + || flags == 0 + || !flags.is_multiple_of(2) + { + return None; + } + let byte = copy::<1>(read, occupancy.checked_add(index as usize / 8)?)?[0]; + if byte & (1 << (index % 8)) == 0 { + return None; + } + let value = u16::from_le_bytes(copy(read, flags.checked_add(index as usize * 2)?)?); + Some(( + [ + table, + n as usize, + vtable, + occupancy, + flags, + bound as usize, + byte as usize, + ], + value, + )) +} + +fn upstream( + base: usize, + m: usize, + sid: u32, + id: u32, + module: u8, + read: &mut Reader<'_>, +) -> [u8; 16] { + let mut observe = || { + let bucket = m + .checked_add(160 * (sid % 503) as usize + 0x58) + .and_then(|at| bitmap(read, at, sid / 503)); + let global = m.checked_add(0x16850).and_then(|at| bitmap(read, at, sid)); + let flags = module_flags(base, id, module, read); + let generation = m.checked_add(0x16700).and_then(|at| copy::<2>(read, at)); + let age = base + .checked_add(0x764aa00) + .and_then(|at| copy::<4>(read, at)); + let ordinary = m + .checked_add(160 * (sid % 503) as usize + 0x68) + .and_then(|at| bitmap(read, at, sid / 503)); + (bucket, global, flags, generation, age, ordinary) + }; + let (b, g, f, n, a, ordinary) = observe(); + let end = observe(); + let mut out = [0; 16]; + if let Some((_, w)) = b.filter(|v| end.0 == Some(*v)) { + out[0] |= 1; + out[1] = 1 + u8::from(w & (1 << ((sid / 503) % 32)) != 0); + } + if let Some((_, w)) = g.filter(|v| end.1 == Some(*v)) { + out[0] |= 2; + out[2] = 1 + u8::from(w & (1 << (sid % 32)) != 0); + } + if let Some((_, v)) = f.filter(|v| end.2 == Some(*v)) { + out[0] |= 4; + out[4..6].copy_from_slice(&v.to_le_bytes()); + } + if let Some(v) = n.filter(|v| end.3 == Some(*v)) { + out[0] |= 8; + out[6..8].copy_from_slice(&v); + } + if let Some((_, w)) = ordinary.filter(|v| end.5 == Some(*v)) { + out[0] |= 32; + out[12] = 1 + u8::from(w & (1 << ((sid / 503) % 32)) != 0); + } + if let Some(v) = a.filter(|v| end.4 == Some(*v)) { + out[0] |= 16; + out[8..12].copy_from_slice(&v); + } + out +} + +fn gate(base: usize, sid: u32, id: u32, read: &mut Reader<'_>) -> (u8, [u8; 28], [u8; 16]) { + let mut lookup = || -> Option<_> { + if sid == 0xfffffff { + return None; + } + let m = pointer(read, base.checked_add(MANAGER)?)?; + let selector = m.checked_add(0x14)?; + let phase = u32::from_le_bytes(copy(read, selector)?); + if phase > 1 { + return None; + } + let at = m.checked_add((160 * (sid % 503) + 16 * phase + 32) as usize)?; + let descriptor = copy::<16>(read, at)?; + let n = word(&descriptor, 4) as usize; + if !super::valid_queue(&descriptor) || n > 64 { + return None; + } + let data = wide(&descriptor, 8) as usize; + let mut entries = [0_u8; 64 * 28]; + let mut check = [0_u8; 64 * 28]; + let bytes = n * 28; + if n > 0 + && (data == 0 + || !data.is_multiple_of(4) + || data.checked_add(bytes).is_none() + || !read(data, &mut entries[..bytes])) + { + return None; + } + let mut matches = entries[..bytes] + .as_chunks::<28>() + .0 + .iter() + .filter(|r| (word(&r[..], 0) & 0xfffffff) == sid); + let result = match (matches.next(), matches.next()) { + (Some(r), None) => (2, *r, upstream(base, m, sid, id, r[0x16], read)), + (None, _) => (1, [0; 28], [0; 16]), + _ => (3, [0; 28], [0; 16]), + }; + if (n > 0 && (!read(data, &mut check[..bytes]) || entries[..bytes] != check[..bytes])) + || copy(read, at)? != descriptor + || u32::from_le_bytes(copy(read, selector)?) != phase + || pointer(read, base.checked_add(MANAGER)?)? != m + { + return None; + } + let (status, entry, mut fields) = result; + if status == 2 { + fields[3] = phase as u8; + } + Some((status, entry, fields)) + }; + lookup().unwrap_or((0, [0; 28], [0; 16])) +} + +#[derive(Default)] +pub(super) struct Roster { + seen: std::collections::HashSet, + indices: Vec, + offset: usize, +} +impl Roster { + pub(super) fn select(&mut self, rows: &[u8]) -> usize { + self.indices.clear(); + self.seen.clear(); + for (index, row) in rows.as_chunks::<{ super::RECORD }>().0.iter().enumerate() { + if row[0] == 2 && !matches!(row[15], 15 | 21) && self.seen.insert(word(row, 32)) { + self.indices.push(index); + } + } + let population = self.indices.len(); + if population > COUNT { + let rotating = &mut self.indices[COUNT / 2..]; + let start = self.offset % rotating.len(); + rotating.rotate_left(start); + self.offset = (start + COUNT / 2) % rotating.len(); + self.indices.truncate(COUNT); + } + population + } +} + +#[cfg(test)] +fn cohort( + base: usize, + rows: &[u8], + backing: u64, + meta: u64, + out: &mut [u8], + read: &mut Reader<'_>, +) -> usize { + let mut roster = Roster::default(); + roster.select(rows); + observe_owners(base, rows, backing, meta, out, read, &roster) +} + +pub(super) fn observe_owners( + base: usize, + rows: &[u8], + backing: u64, + meta: u64, + out: &mut [u8], + read: &mut Reader<'_>, + roster: &Roster, +) -> usize { + let mut n = 0; + let mut array = Vec::new(); + let mut check = Vec::new(); + for &index in &roster.indices { + let row = &rows[index * super::RECORD..][..super::RECORD]; + let id = word(row, 32); + let entry = &mut out[n * BYTES..][..BYTES]; + n += 1; + entry[..4].copy_from_slice(&(index as u32).to_le_bytes()); + entry[4..8].copy_from_slice(&id.to_le_bytes()); + if let Some(o) = owner(base, id, read) { + let addr = backing + (index * 224) as u64; + let output_read = if o.pointer != 0 && o.count <= 4096 { + let bytes = o.count as usize * 8; + array.resize(bytes, 0); + check.resize(bytes, 0); + bytes == 0 || read(o.array, &mut array) + } else { + false + }; + let (g, gate, upstream) = gate(base, o.stream_id, id, read); + // Bracket the gate lookup: withdrawal can clear an output in place. + let (status, idx) = if output_read + && (array.is_empty() || (read(o.array, &mut check) && array == check)) + { + let mut found = array + .as_chunks::<8>() + .0 + .iter() + .enumerate() + .filter(|(_, b)| wide(&b[..], 0) == addr); + match (found.next(), found.next()) { + (Some((i, _)), None) => (2, i as u32), + (None, _) => (1, 0), + _ => (3, 0), + } + } else { + (0, 0) + }; + // Recheck the selected identity after the owner, output and gate reads. + let slot = copy::<224>(read, addr as usize); + let metadata = copy::<4>(read, meta as usize + index * 4); + if owner(base, id, read) == Some(o) + && metadata.is_some_and(|m| m[..] == row[4..8]) + && slot.is_some_and(|s| { + wide(&s, 0) == (base + 0x62e3fe0) as u64 + && s[0x30] == 1 + && word(&s, 0x9c) == word(row, 8) + && s[0xb4] >> 1 & 31 == row[15] + && word(&s, 0xcc) == id + }) + { + entry[8] = if o.pointer == 0 { 2 } else { 1 }; + entry[9] = status; + entry[10] = g; + entry[12..16].copy_from_slice(&idx.to_le_bytes()); + entry[16..24].copy_from_slice(&(o.record as u64).to_le_bytes()); + entry[24..32].copy_from_slice(&(o.pointer as u64).to_le_bytes()); + entry[32..40].copy_from_slice(&(o.array as u64).to_le_bytes()); + entry[40..44].copy_from_slice(&o.count.to_le_bytes()); + entry[44..48].copy_from_slice(&o.stream_id.to_le_bytes()); + entry[48..52].copy_from_slice(&o.record_24.to_le_bytes()); + entry[52..56].copy_from_slice(&o.record_28.to_le_bytes()); + entry[56..60].copy_from_slice(&o.owner_c4.to_le_bytes()); + entry[60..62].copy_from_slice(&gate[12..14]); + entry[62..64].copy_from_slice(&gate[20..22]); + entry[64] = gate[24]; + entry[66..68].copy_from_slice(&gate[26..28]); + entry[80..108].copy_from_slice(&gate); + entry[108..124].copy_from_slice(&upstream); + } + } + } + n +} + +pub(super) fn admissions(base: usize, out: &mut [u8], read: &mut Reader<'_>) { + let mut sample = || { + let m = pointer(read, base.checked_add(MANAGER)?)?; + let phase = u32::from_le_bytes(copy(read, m.checked_add(0x14)?)?); + if phase > 1 { + return None; + } + let attempts = copy::<4>(read, m.checked_add(0x16918)?); + let cost = copy::<1>(read, m.checked_add(0x16988)?); + Some((m, phase, attempts, cost)) + }; + if let (Some((m, phase, attempts, cost)), Some((m2, phase2, count2, cost2))) = + (sample(), sample()) + && m == m2 + && phase == phase2 + { + out[0] = 1; + out[8..16].copy_from_slice(&(m as u64).to_le_bytes()); + out[16..20].copy_from_slice(&phase.to_le_bytes()); + if let Some(v) = attempts.filter(|v| count2 == Some(*v)) { + out[0] |= 2; + out[20..24].copy_from_slice(&v); + } + if let Some(v) = cost.filter(|v| cost2 == Some(*v)) { + out[0] |= 4; + out[24] = v[0]; + } + } +} + +pub(super) fn timing(base: usize, out: &mut [u8], read: &mut Reader<'_>) { + fn observe(base: usize, read: &mut Reader<'_>) -> Option<[u64; 7]> { + let m = pointer(read, base.checked_add(MANAGER)?)?; + let record_28 = copy::<4>(read, base.checked_add(0xab44324)?)?; + let mode = copy::<4>(read, m)?; + let data = copy::<56>(read, m.checked_add(0x166c8)?)?; + let callback = copy::<8>(read, m.checked_add(0x168e0)?)?; + Some([ + m as u64, + u32::from_le_bytes(record_28) as u64, + u32::from_le_bytes(mode) as u64, + word(&data, 0) as u64, + wide(&data, 40), + u64::from_le_bytes(callback), + wide(&data, 48), + ]) + } + if let Some(fields) = observe(base, read).filter(|f| observe(base, read) == Some(*f)) { + out[0] = 1; + for (dst, value) in out[8..].as_chunks_mut::<8>().0.iter_mut().zip(fields) { + dst.copy_from_slice(&value.to_le_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + const BASE: usize = 0x1000_0000; + type Memory = BTreeMap>; + fn load(mem: &Memory, at: usize, out: &mut [u8]) -> bool { + let Some((base, source)) = mem.range(..=at).next_back() else { + return false; + }; + let Some(bytes) = source.get(at - base..at - base + out.len()) else { + return false; + }; + out.copy_from_slice(bytes); + true + } + fn registry() -> Memory { + let mut registry = vec![0; 0x68]; + registry[8..12].copy_from_slice(&600_u32.to_le_bytes()); + registry[12..16].copy_from_slice(&2_u32.to_le_bytes()); + registry[16..20].copy_from_slice(&11_u32.to_le_bytes()); + registry[56..64].copy_from_slice(&0x3000_u64.to_le_bytes()); + registry[64..68].copy_from_slice(&48_u32.to_le_bytes()); + registry[96..104].copy_from_slice(&0x5000_u64.to_le_bytes()); + let mut record = vec![0; 48]; + record[..8].copy_from_slice(&0x8000_u64.to_le_bytes()); + let mut object = vec![0; 200]; + object[..8].copy_from_slice(&((BASE + 0x655ce30) as u64).to_le_bytes()); + object[8..16].copy_from_slice(&0x9000_u64.to_le_bytes()); + object[16..20].copy_from_slice(&9_u32.to_le_bytes()); + object[20..24].copy_from_slice(&0x800005_u32.to_le_bytes()); + BTreeMap::from([ + (BASE + 0xa024230, registry), + (0x3000 + 48 * 5, record), + (0x5000, vec![32]), + (0x8000, object), + ]) + } + + #[test] + fn registry_requires_bounded_occupied_record_and_bidirectional_owner_identity() { + let mem = registry(); + let obs = |m: &Memory, id| owner(BASE, id, &mut |a, b| load(m, a, b)); + let o = obs(&mem, 0x800005).unwrap(); + assert_eq!( + (o.pointer, o.array, o.count, o.stream_id), + (0x8000, 0x9000, 9, 605) + ); + for (addr, offset) in [ + (0x5000, 0), + (0x8000, 0), + (0x8000, 20), + (BASE + 0xa024230, 16), + ] { + let mut bad = mem.clone(); + bad.get_mut(&addr).unwrap()[offset] = 0; + if addr == 0x8000 && offset == 0 { + bad.get_mut(&addr).unwrap()[0] = 1; + } + assert!(obs(&bad, 0x800005).is_none()); + } + assert!(obs(&mem, 0xc00005).is_none()); + assert!(obs(&mem, 0xbfffff).is_none()); + } + + fn resident_with_output() -> (Memory, [u8; super::super::RECORD], u64, u64) { + let mut mem = registry(); + let backing = 0xa000_u64; + let metadata = 0xb000_u64; + let id = 0x800005_u32; + let mut row = [0_u8; super::super::RECORD]; + row[0] = 2; + row[4..8].copy_from_slice(&0x7ffff_u32.to_le_bytes()); + row[8..12].copy_from_slice(&0xc20000_u32.to_le_bytes()); + row[15] = 12; + row[32..36].copy_from_slice(&id.to_le_bytes()); + let mut storage = vec![0; 224]; + storage[..8].copy_from_slice(&((BASE + 0x62e3fe0) as u64).to_le_bytes()); + storage[0x30] = 1; + storage[0x9c..0xa0].copy_from_slice(&row[8..12]); + storage[0xb4] = 24; + storage[0xcc..0xd0].copy_from_slice(&row[32..36]); + let mut array = vec![0; 9 * 8]; + array[56..64].copy_from_slice(&backing.to_le_bytes()); + mem.insert(0x9000, array); + mem.insert(backing as usize, storage); + mem.insert(metadata as usize, row[4..8].to_vec()); + (mem, row, backing, metadata) + } + + #[test] + fn confirmed_output_detached_record_and_reused_slot_are_distinct() { + let (mut mem, row, backing, metadata) = resident_with_output(); + let observe = |m: &Memory| { + let mut out = [0_u8; BYTES * COUNT]; + assert_eq!( + cohort(BASE, &row, backing, metadata, &mut out, &mut |a, b| load( + m, a, b + )), + 1 + ); + (out[8], out[9], word(&out, 12)) + }; + assert_eq!(observe(&mem), (1, 2, 7)); + mem.get_mut(&(0x3000 + 48 * 5)).unwrap()[..8].fill(0); + assert_eq!(observe(&mem), (2, 0, 0)); + mem.get_mut(&(metadata as usize)).unwrap()[2] ^= 2; + assert_eq!(observe(&mem), (0, 0, 0)); + } + + #[test] + fn rotation_preserves_eight_anchors_and_gives_each_eligible_id_one_turn() { + let mut rows = Vec::new(); + for id in (0..32_u32).chain(8..24) { + let mut row = [0; super::super::RECORD]; + row[0] = 2; + row[15] = if id == 30 { 15 } else { 12 }; + if id == 31 { + row[0] = 3; + } + row[32..36].copy_from_slice(&id.to_le_bytes()); + rows.extend_from_slice(&row); + } + let mut roster = Roster::default(); + for expected in [ + vec![8, 9, 10, 11, 12, 13, 14, 15], + vec![16, 17, 18, 19, 20, 21, 22, 23], + vec![24, 25, 26, 27, 28, 29, 8, 9], + ] { + assert_eq!(roster.select(&rows), 30); + assert_eq!(&roster.indices[..8], &[0, 1, 2, 3, 4, 5, 6, 7]); + assert_eq!(&roster.indices[8..16], &expected); + } + assert_eq!(roster.select(&rows[..3 * super::super::RECORD]), 3); + assert_eq!(&roster.indices, &[0, 1, 2]); + } + + #[test] + fn upstream_flags_and_independent_bitmap_words_require_stable_bounded_inputs() { + let id = 0x800005; + let sid = 605_u32; + let m = 0x12120000_usize; + let table = 0x14140000_usize; + let flags = 0x17170000_usize; + let bits = 0x16160000_usize; + let mut mem = registry(); + let reg = mem.get_mut(&(BASE + REG)).unwrap(); + reg.resize(232, 0); + reg[..8].copy_from_slice(&((BASE + 0x61ced80) as u64).to_le_bytes()); + reg[224..232].copy_from_slice(&flags.to_le_bytes()); + mem.insert( + BASE + 0x61cee18, + ((BASE + 0x4f83000) as u64).to_le_bytes().to_vec(), + ); + mem.insert( + BASE + 0xabcd210, + [table.to_le_bytes().as_slice(), &3_u16.to_le_bytes()].concat(), + ); + mem.insert(table + 8 * 2, ((BASE + REG) as u64).to_le_bytes().to_vec()); + mem.insert(flags + 10, 0x179_u16.to_le_bytes().to_vec()); + mem.insert(BASE + 0x764aa00, 77_u32.to_le_bytes().to_vec()); + mem.insert(m + 0x16700, 13_u16.to_le_bytes().to_vec()); + let mut bitmap = vec![0; 16]; + bitmap[..8].copy_from_slice(&bits.to_le_bytes()); + bitmap[8..12].copy_from_slice(&32_u32.to_le_bytes()); + bitmap[12..16].copy_from_slice(&1024_u32.to_le_bytes()); + let bucket = m + 0xa0 * 102 + 0x58; + mem.insert(bucket, bitmap.clone()); + let mut ordinary = bitmap.clone(); + ordinary[..8].copy_from_slice(&(bits + 0x1000).to_le_bytes()); + mem.insert(bucket + 0x10, ordinary); + mem.insert(bits + 0x1000, 0_u32.to_le_bytes().to_vec()); + mem.insert(m + 0x16850, bitmap); + mem.insert(bits, 2_u32.to_le_bytes().to_vec()); + mem.insert(bits + 4 * (605 / 32), 0_u32.to_le_bytes().to_vec()); + let observe = |memb: &Memory| upstream(BASE, m, sid, id, 2, &mut |at, b| load(memb, at, b)); + let out = observe(&mem); + assert_eq!(out[0], 63); + assert_eq!(out[12], 1); + assert_eq!((out[1], out[2]), (2, 1)); + assert_eq!(&out[4..6], &0x179_u16.to_le_bytes()); + assert_eq!(&out[6..8], &13_u16.to_le_bytes()); + assert_eq!(word(&out, 8), 77); + mem.get_mut(&bucket).unwrap()[12..16].copy_from_slice(&1_u32.to_le_bytes()); + let mut reads = 0; + let changed = upstream(BASE, m, sid, id, 2, &mut |at, b| { + let ok = load(&mem, at, b); + if at == bits + 4 * (605 / 32) { + reads += 1; + if reads == 2 { + b[0] ^= 1; + } + } + ok + }); + assert_eq!((changed[0], changed[1], changed[2]), (60, 0, 0)); + mem.insert(table + 16, 0xdead0000_usize.to_le_bytes().to_vec()); + let out = observe(&mem); + assert_eq!(out[0] & 4, 0); + } + + #[test] + fn gate_requires_stable_phase_header_and_unique_matching_record() { + let data = 0x7777_0000_usize; + let map = 0x6666_0000_usize; + let bucket = map + 0xa0 * 102 + 0x20; + let mut descriptor = vec![0; 16]; + descriptor[..4].copy_from_slice(&2_u32.to_le_bytes()); + descriptor[4..8].copy_from_slice(&2_u32.to_le_bytes()); + descriptor[8..16].copy_from_slice(&(data as u64).to_le_bytes()); + let mut records = vec![0; 56]; + records[..4].copy_from_slice(&605_u32.to_le_bytes()); + records[12..14].copy_from_slice(&9_u16.to_le_bytes()); + let mut mem = BTreeMap::from([ + (BASE + 0x764b240, (map as u64).to_le_bytes().to_vec()), + (map + 0x14, vec![0; 4]), + (bucket, descriptor), + (data, records), + ]); + let result = |m: &Memory| gate(BASE, 605, 0x800005, &mut |a, b| load(m, a, b)); + let (status, r, _) = result(&mem); + assert_eq!((status, r[12]), (2, 9)); + let mut duplicate = mem[&data].clone(); + duplicate[28..32].copy_from_slice(&605_u32.to_le_bytes()); + mem.insert(data, duplicate); + assert_eq!(result(&mem).0, 3); + mem.get_mut(&data).unwrap().fill(0); + assert_eq!(result(&mem).0, 1); + mem.get_mut(&bucket).unwrap()[4] = 65; + assert_eq!(result(&mem).0, 0); + } + + #[test] + fn cleared_output_cannot_be_joined_to_newly_published_stream_gate() { + let (mut mem, row, backing, metadata) = resident_with_output(); + let manager = 0x77770000_usize; + let data = 0x88880000_usize; + let mut bucket = vec![0; 16]; + bucket[..4].copy_from_slice(&1_u32.to_le_bytes()); + bucket[4..8].copy_from_slice(&1_u32.to_le_bytes()); + bucket[8..].copy_from_slice(&data.to_le_bytes()); + mem.insert(BASE + MANAGER, manager.to_le_bytes().to_vec()); + mem.insert(manager + 0x14, vec![0; 4]); + mem.insert(manager + 0x20 + 160 * (605 % 503), bucket); + mem.insert(data, vec![0; 28]); + let mut out = [0; BYTES * COUNT]; + let mut changed = false; + cohort(BASE, &row, backing, metadata, &mut out, &mut |addr, buf| { + if addr == BASE + MANAGER && !changed { + assert_eq!(wide(&mem[&0x9000], 56), backing); + assert_eq!(word(&mem[&data], 0), 0); + mem.get_mut(&0x9000).unwrap()[56..64].fill(0); + mem.get_mut(&data).unwrap()[..4].copy_from_slice(&605_u32.to_le_bytes()); + changed = true; + } + load(&mem, addr, buf) + }); + assert!(changed); + assert_eq!(&out[8..11], &[1, 0, 2]); + } + + const START: u64 = 0x1234_5678_9876_ffff; + fn timed_stream(change_start: bool) -> [u8; 64] { + let m = 0x13130000_usize; + let mut data = vec![0; 56]; + data[..4].copy_from_slice(&500_u32.to_le_bytes()); + data[40..48].copy_from_slice(&333_u64.to_le_bytes()); + data[48..56].copy_from_slice(&START.to_le_bytes()); + let mut mem = Memory::from([ + (BASE + MANAGER, m.to_le_bytes().to_vec()), + (BASE + 0xab44324, 2_u32.to_le_bytes().to_vec()), + (m, vec![0; 4]), + (m + 0x166c8, data), + (m + 0x168e0, vec![0; 8]), + ]); + let mut out = [0; 64]; + timing(BASE, &mut out, &mut |at, b| { + let ok = load(&mem, at, b); + if at == m + 0x166c8 && change_start { + mem.get_mut(&at).unwrap()[48..56].copy_from_slice(&(START + 1).to_le_bytes()); + } + ok + }); + out + } + + #[test] + fn timing_retains_interval_start_after_callback() { + let out = timed_stream(false); + assert_eq!(out[0], 1); + assert_eq!(wide(&out, 48), 0); + assert_eq!(wide(&out, 56), START); + } + + #[test] + fn timing_discards_changed_interval_start() { + assert_eq!(timed_stream(true), [0; 64]); + } +} diff --git a/crates/victory-loader/src/pool/residents/primary.rs b/crates/victory-loader/src/pool/residents/primary.rs new file mode 100644 index 000000000..297c5a9e7 --- /dev/null +++ b/crates/victory-loader/src/pool/residents/primary.rs @@ -0,0 +1,416 @@ +//! Two bounded protected copies of the primary streaming request pool. +use super::{Reader, copy, wide, word}; +const LIMIT: usize = 2048; +const STRIDE: usize = 168; +pub(super) const TABLE: usize = 80; +pub(super) const SIZE: usize = TABLE + LIMIT * 32; +pub(super) const GLOBAL: usize = 0x7bc5d90; + +#[derive(Clone, Copy, PartialEq, Eq, Default)] +struct Shape { + pool: usize, + backing: usize, + allocated: usize, + completed: usize, +} +struct Header { + shape: Shape, + count: u32, + sequence: u64, + head: u32, +} + +fn header(base: usize, read: &mut Reader<'_>) -> Result { + let pool = usize::from_le_bytes(copy(read, base.checked_add(GLOBAL).ok_or(2)?).ok_or(3)?); + if pool == 0 || !pool.is_multiple_of(8) { + return Err(2); + } + let h = copy::<152>(read, pool.checked_add(24).ok_or(2)?).ok_or(3)?; + let shape = Shape { + pool, + backing: wide(&h, 0) as usize, + allocated: wide(&h, 40) as usize, + completed: wide(&h, 56) as usize, + }; + let count = word(&h, 16); + if word(&h, 8) != STRIDE as u32 + || word(&h, 12) != LIMIT as u32 + || count > LIMIT as u32 + || word(&h, 64) != 64 + || word(&h, 68) != LIMIT as u32 + || [ + (shape.backing, STRIDE * LIMIT, 8), + (shape.allocated, 256, 4), + (shape.completed, 256, 4), + ] + .iter() + .any(|&(p, n, alignment)| { + p == 0 || !p.is_multiple_of(alignment) || p.checked_add(n).is_none() + }) + { + return Err(2); + } + Ok(Header { + shape, + count, + sequence: wide(&h, 144), + head: word(&h, 32), + }) +} + +fn module_range(base: usize, read: &mut Reader<'_>) -> Option<(u32, u32)> { + let r = copy::<20>(read, base.checked_add(0xa024230)?)?; + let first = word(&r, 8); + let count = word(&r, 16); + let end = first.checked_add(count)?; + (wide(&r, 0) == base.checked_add(0x61ced80)? as u64 + && (1..=0x3fffff).contains(&count) + && end <= 0xfffffff) + .then_some((first, end)) +} + +pub(super) struct Pass { + data: Vec, + allocated: [u8; 256], + completed: [u8; 256], + shape: Shape, + count: u32, + start: u64, + end: u64, + head_start: u32, + head_end: u32, + status: u8, + range: Option<(u32, u32)>, +} +impl Default for Pass { + fn default() -> Self { + Self { + data: Vec::new(), + allocated: [0; 256], + completed: [0; 256], + shape: Shape::default(), + count: 0, + start: 0, + end: 0, + head_start: 0, + head_end: 0, + status: 0, + range: None, + } + } +} +impl Pass { + pub(super) fn read(&mut self, base: usize, read: &mut Reader<'_>) { + self.range = module_range(base, read); + self.status = self.load(base, read).err().unwrap_or(1); + } + fn load(&mut self, base: usize, read: &mut Reader<'_>) -> Result<(), u8> { + let h = header(base, read)?; + self.data.resize(LIMIT * STRIDE, 0); + if !read(h.shape.allocated, &mut self.allocated) + || !read(h.shape.completed, &mut self.completed) + || !read(h.shape.backing, &mut self.data) + { + return Err(3); + } + let end = header(base, read)?; + if h.shape != end.shape { + return Err(4); + } + let occupied = self.allocated.iter().map(|b| b.count_ones()).sum::(); + if h.count != occupied || end.count != occupied { + return Err(5); + } + self.shape = h.shape; + self.count = h.count; + self.start = h.sequence; + self.end = end.sequence; + self.head_start = h.head; + self.head_end = end.head; + Ok(()) + } +} + +fn tuple(k: &[u8]) -> [u8; 32] { + let mut row = [0; 32]; + let sid = word(k, 0) & 0xfffffff; + row[0] = if k[137] == 0 && sid != 0xfffffff { + 2 + } else { + 4 + }; + row[1] = k[160]; + row[3] = k[137]; + row[4..8].copy_from_slice(&sid.to_le_bytes()); + row[8..16].copy_from_slice(&k[120..128]); + row[16..20].copy_from_slice(&k[144..148]); + row[20..22].copy_from_slice(&k[8..10]); + row[24..32].copy_from_slice(&k[152..160]); + row +} + +pub(super) fn encode(a: &Pass, b: &Pass, out: &mut [u8]) { + out.fill(0); + if let Some((low, high)) = a.range.filter(|range| b.range == Some(*range)) { + out[1] = 1; + out[12..16].copy_from_slice(&low.to_le_bytes()); + out[16..20].copy_from_slice(&high.to_le_bytes()); + } + if a.status != 1 || b.status != 1 { + out[0] = if a.status != 1 { a.status } else { b.status }; + return; + } + if a.shape != b.shape { + out[0] = 4; + return; + } + out[0] = 1; + out[2] = u8::from( + a.start == a.end + && a.end == b.start + && b.start == b.end + && a.head_start == a.head_end + && a.head_end == b.head_start + && b.head_start == b.head_end, + ); + out[72..76].copy_from_slice(&a.head_start.to_le_bytes()); + out[76..80].copy_from_slice(&b.head_end.to_le_bytes()); + out[4..8].copy_from_slice(&a.count.to_le_bytes()); + out[8..12].copy_from_slice(&b.count.to_le_bytes()); + for (i, v) in [ + a.shape.pool as u64, + a.shape.backing as u64, + a.shape.allocated as u64, + a.shape.completed as u64, + a.start, + b.end, + ] + .iter() + .enumerate() + { + out[24 + i * 8..32 + i * 8].copy_from_slice(&v.to_le_bytes()); + } + for (i, out) in out[TABLE..].as_chunks_mut::<32>().0.iter_mut().enumerate() { + let mask = 1 << (i % 8); + let byte = i / 8; + if (a.allocated[byte] ^ b.allocated[byte]) & mask != 0 + || (a.completed[byte] ^ b.completed[byte]) & mask != 0 + { + out[0] = 3; + continue; + } + if a.allocated[byte] & mask == 0 { + out[0] = if a.completed[byte] & mask == 0 { 1 } else { 3 }; + continue; + } + let k = i * STRIDE; + let first = tuple(&a.data[k..k + STRIDE]); + let second = tuple(&b.data[k..k + STRIDE]); + if first != second { + out[0] = 3; + continue; + } + *out = second; + out[2] = u8::from(b.completed[byte] & mask != 0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + const BASE: usize = 0x10000000; + const POOL: usize = 0x20000000; + const BACK: usize = 0x30000000; + const ALLOC: usize = 0x40000000; + const DONE: usize = 0x50000000; + struct Memory { + hdr: [u8; 152], + alloc: [u8; 256], + done: [u8; 256], + requests: Vec, + } + impl Memory { + fn new() -> Self { + let mut mem = Self { + hdr: [0; 152], + alloc: [0; 256], + done: [0; 256], + requests: vec![0; 344064], + }; + mem.hdr[..8].copy_from_slice(&BACK.to_le_bytes()); + mem.hdr[8..12].copy_from_slice(&168_u32.to_le_bytes()); + mem.hdr[12..16].copy_from_slice(&2048_u32.to_le_bytes()); + mem.hdr[16..20].copy_from_slice(&2_u32.to_le_bytes()); + mem.hdr[40..48].copy_from_slice(&ALLOC.to_le_bytes()); + mem.hdr[56..64].copy_from_slice(&DONE.to_le_bytes()); + mem.hdr[64..68].copy_from_slice(&64_u32.to_le_bytes()); + mem.hdr[68..72].copy_from_slice(&2048_u32.to_le_bytes()); + mem.alloc[0] = 6; + mem.done[0] = 2; + for i in 1..=2 { + let k = &mut mem.requests[168 * i..][..168]; + k[..4].copy_from_slice(&0xf0000017_u32.to_le_bytes()); + k[120..128].copy_from_slice(&35_u64.to_le_bytes()); + k[144..148].copy_from_slice(&500_u32.to_le_bytes()); + k[160] = if i == 1 { 2 } else { 4 }; + } + mem + } + fn read(&self, at: usize, bytes: &mut [u8]) -> bool { + let data: &[u8] = match at { + a if a == BASE + GLOBAL => &POOL.to_le_bytes(), + a if a == POOL + 24 => &self.hdr, + BACK => &self.requests, + ALLOC => &self.alloc, + DONE => &self.done, + _ => return false, + }; + if data.len() != bytes.len() { + return false; + } + bytes.copy_from_slice(data); + true + } + } + + #[test] + fn primary_preserves_two_matching_requests_and_completed_zero_stamp() { + let mut mem = Memory::new(); + let mut a = Pass::default(); + let mut b = Pass::default(); + a.read(BASE, &mut |at, bytes| mem.read(at, bytes)); + mem.hdr[144..152].copy_from_slice(&1_u64.to_le_bytes()); + b.read(BASE, &mut |at, bytes| mem.read(at, bytes)); + let mut out = vec![0; SIZE]; + encode(&a, &b, &mut out); + assert_eq!(out[0], 1); + assert_eq!((wide(&out, 56), wide(&out, 64)), (0, 1)); + assert_eq!(out[TABLE], 1); + let first = &out[TABLE + 32..TABLE + 64]; + assert_eq!(&first[..4], &[2, 2, 1, 0]); + assert_eq!( + ( + word(first, 4), + wide(first, 8), + word(first, 16), + wide(first, 24) + ), + (23, 35, 500, 0) + ); + assert_eq!(&out[TABLE + 64..TABLE + 68], &[2, 4, 0, 0]); + } + + #[test] + fn changed_release_head_prevents_continuous_join_with_stable_endpoint_identity() { + let mut mem = Memory::new(); + mem.requests[STRIDE + 8..STRIDE + 10].copy_from_slice(&[3, 9]); + let mut a = Pass::default(); + let mut b = Pass::default(); + a.read(BASE, &mut |at, dst| mem.read(at, dst)); + mem.hdr[32..36].copy_from_slice(&0x10005_u32.to_le_bytes()); + b.read(BASE, &mut |at, dst| mem.read(at, dst)); + let mut out = vec![0; SIZE]; + encode(&a, &b, &mut out); + assert_eq!((word(&out, 72), word(&out, 76)), (0, 0x10005)); + assert_eq!(out[2], 0); + assert_eq!(&out[TABLE + 32 + 20..TABLE + 32 + 22], &[3, 9]); + encode(&b, &b, &mut out); + assert_eq!(out[2], 1); + } + + #[test] + fn primary_reuse_and_torn_completion_invalidate_only_affected_slots() { + for (offset, in_done) in [(152, false), (120, false), (160, false), (0, true)] { + let mut mem = Memory::new(); + let mut a = Pass::default(); + let mut b = Pass::default(); + a.read(BASE, &mut |at, bytes| mem.read(at, bytes)); + if in_done { + mem.done[0] ^= 2; + } else { + mem.requests[STRIDE + offset] ^= 1; + } + b.read(BASE, &mut |at, bytes| mem.read(at, bytes)); + let mut out = vec![0; SIZE]; + encode(&a, &b, &mut out); + assert_eq!(out[TABLE + 32], 3); + assert!(out[TABLE + 33..TABLE + 64].iter().all(|&v| v == 0)); + assert_eq!(out[TABLE + 64], 2); + } + } + + #[test] + fn module_counts_require_the_concrete_registry_while_all_pool_counts_remain_available() { + let mem = Memory::new(); + let mut out = vec![0; SIZE]; + for (vtable, expected) in [(BASE + 0x61ced80, 1), (BASE + 0x61ced88, 0)] { + let mut pass = Pass::default(); + pass.read(BASE, &mut |at, b| { + if at != BASE + 0xa024230 { + return mem.read(at, b); + } + b[..8].copy_from_slice(&vtable.to_le_bytes()); + b[8..12].copy_from_slice(&20_u32.to_le_bytes()); + b[16..20].copy_from_slice(&100_u32.to_le_bytes()); + true + }); + encode(&pass, &pass, &mut out); + assert_eq!(out[0], 1); + assert_eq!(out[1], expected); + assert_eq!(out[TABLE + 32], 2); + assert_eq!(out[TABLE + 64], 2); + } + } + + #[test] + fn an_unoccupied_slot_requires_two_clear_completion_bits() { + let mut mem = Memory::new(); + let mut clear = Pass::default(); + let mut set = Pass::default(); + clear.read(BASE, &mut |at, b| mem.read(at, b)); + mem.done[0] |= 1; + set.read(BASE, &mut |at, b| mem.read(at, b)); + let mut out = vec![0; SIZE]; + for (a, b, expected) in [ + (&clear, &clear, 1), + (&clear, &set, 3), + (&set, &clear, 3), + (&set, &set, 3), + ] { + encode(a, b, &mut out); + assert_eq!(out[TABLE], expected); + assert_eq!(out[TABLE + 32], 2); + assert_eq!(out[TABLE + 3 * 32], 1); + } + } + + #[test] + fn malformed_or_unreadable_request_storage_cannot_look_empty() { + for (offset, unreadable) in [ + (8, 0), + (12, 0), + (40, 0), + (64, 0), + (68, 0), + (0, DONE), + (0, BACK), + ] { + let mut mem = Memory::new(); + let mut a = Pass::default(); + if unreadable == 0 { + mem.hdr[offset] ^= 1; + } + let expect_rejected_before_copy = unreadable == 0 && offset != 40; + a.read(BASE, &mut |at, bytes| { + if expect_rejected_before_copy { + assert_ne!(at, BACK); + } + at != unreadable && mem.read(at, bytes) + }); + let mut out = vec![0; SIZE]; + encode(&a, &a, &mut out); + assert_ne!(out[0], 1); + assert!(out[TABLE..].iter().all(|&v| v == 0)); + } + } +} diff --git a/crates/victory-loader/src/pool/residents/request.rs b/crates/victory-loader/src/pool/residents/request.rs new file mode 100644 index 000000000..ca342fabd --- /dev/null +++ b/crates/victory-loader/src/pool/residents/request.rs @@ -0,0 +1,168 @@ +use super::owner::Owner; +use super::{Reader, copy, wide, word}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Request { + pub(crate) source: usize, + pub(crate) key: u64, + pub(crate) override_byte: u8, + pub(crate) descriptor: usize, + pub(crate) task: usize, + pub(crate) list: usize, + pub(crate) index: u32, + pub(crate) end: u32, + pub(crate) count: u16, + pub(crate) array: usize, + pub(crate) id: u32, + pub(crate) matched_owner: Option, +} +pub(crate) fn capture( + base: usize, + registers: [usize; 6], + read: &mut Reader<'_>, +) -> Option { + let [sp, source, descriptor_slot, bitset, index, end] = registers; + if descriptor_slot != sp.checked_add(0xb8)? + || index >= end + || end > u16::MAX as usize + || source == 0 + { + return None; + } + let task = bitset.checked_sub(32)?; + let mut observe = || -> Option { + let stack = copy::<0x140>(read, sp)?; + for (offset, rva) in [ + (0x38, 0xa5db22), + (0x88, 0x5453ac7), + (0xd8, 0x23d0f9a), + (0x138, 0x23d1211), + ] { + if wide(&stack, offset) != base.checked_add(rva)? as u64 { + return None; + } + } + let descriptor = wide(&stack, 0xb8) as usize; + if descriptor == 0 + || usize::from_le_bytes(copy(read, descriptor)?) != base.checked_add(0x6501de0)? + { + return None; + } + let args = copy::<32>(read, task)?; + let list = wide(&args, 0) as usize; + let array = wide(&args, 16) as usize; + if list == 0 || array == 0 || !array.is_multiple_of(8) || args[24] != 12 { + return None; + } + let hdr = copy::<10>(read, list)?; + let data = wide(&hdr, 0) as usize; + let count = u16::from_le_bytes(hdr[8..10].try_into().unwrap()); + let size = word(&args, 12); + let start = word(&args, 8).checked_mul(size)?; + if size == 0 + || data == 0 + || !data.is_multiple_of(8) + || index < start as usize + || start.checked_add(size)?.min(u32::from(count)) as usize != end + || usize::from_le_bytes(copy(read, data.checked_add(index * 8)?)?) != source + { + return None; + } + let b = copy::<0x7e>(read, source)?; + Some(Request { + source, + key: wide(&b, 0x20), + override_byte: b[0x7d], + descriptor, + task, + list, + index: index as u32, + end: end as u32, + count, + array, + id: word(&args, 28), + matched_owner: None, + }) + }; + let mut r = observe()?; + if observe()? != r { + return None; + } + r.matched_owner = super::owner::owner(base, r.id, read).filter(|o| { + o.pointer != 0 + && o.array == r.array + && o.count >= r.end + && super::owner::owner(base, r.id, read) == Some(*o) + }); + Some(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + #[test] + fn failed_batch_requires_observed_stack_chunk_and_list_source_to_agree() { + let base = 0x10000000_usize; + let sp = 0x21000000_usize; + let src = 0x22000000_usize; + let desc = 0x23000000_usize; + let task = 0x24000000_usize; + let list = 0x25000000_usize; + let data = 0x26000000_usize; + let mut stack = vec![0; 0x140]; + for (i, rva) in [ + (0x38, 0xa5db22), + (0x88, 0x5453ac7), + (0xd8, 0x23d0f9a), + (0x138, 0x23d1211), + ] { + stack[i..i + 8].copy_from_slice(&(base + rva).to_le_bytes()); + } + stack[0xb8..0xc0].copy_from_slice(&desc.to_le_bytes()); + let mut source = vec![0; 0x7e]; + source[0x20..0x28].copy_from_slice(&123_u64.to_le_bytes()); + let mut args = vec![0; 32]; + args[..8].copy_from_slice(&list.to_le_bytes()); + args[8..12].copy_from_slice(&1_u32.to_le_bytes()); + args[12..16].copy_from_slice(&4_u32.to_le_bytes()); + args[16..24].copy_from_slice(&0x27000000_usize.to_le_bytes()); + args[24] = 12; + args[28..32].copy_from_slice(&99_u32.to_le_bytes()); + let mut hdr = vec![0; 10]; + hdr[..8].copy_from_slice(&data.to_le_bytes()); + hdr[8..10].copy_from_slice(&7_u16.to_le_bytes()); + let mut mem = BTreeMap::from([ + (sp, stack), + (src, source), + (desc, (base + 0x6501de0).to_le_bytes().to_vec()), + (task, args), + (list, hdr), + (data + 40, src.to_le_bytes().to_vec()), + ]); + let regs = [sp, src, sp + 0xb8, task + 32, 5, 7]; + let observe = |m: &BTreeMap>, args| { + capture(base, args, &mut |at, out| { + let Some((&p, b)) = m.range(..=at).next_back() else { + return false; + }; + let Some(b) = b.get(at - p..at - p + out.len()) else { + return false; + }; + out.copy_from_slice(b); + true + }) + }; + let r = observe(&mem, regs).unwrap(); + assert_eq!( + (r.key, r.index, r.end, r.count, r.id, r.matched_owner), + (123, 5, 7, 7, 99, None) + ); + let mut bad = regs; + bad[5] = 8; + assert!(observe(&mem, bad).is_none()); + mem.get_mut(&(data + 40)).unwrap()[0] ^= 1; + assert!(observe(&mem, regs).is_none()); + } +} diff --git a/crates/victory-loader/src/pool/windows.rs b/crates/victory-loader/src/pool/windows.rs new file mode 100644 index 000000000..c03a7508c --- /dev/null +++ b/crates/victory-loader/src/pool/windows.rs @@ -0,0 +1,763 @@ +use super::residents::{Census, IMAGE_RANGES, request}; +use super::{Map, Sample, TRAPS, enabled}; +use crate::LoadedImage; +use std::fmt; +use std::fs::File; +use std::io::{Seek, SeekFrom, Write}; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Sender}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; +use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, ReadProcessMemory}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, + VirtualQuery, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const NAMES: [&str; 3] = ["BUILDING", "OBJECT", "pool-256"]; +const STRIDES: [u32; 3] = [224, 272, 256]; +const SLOTS: u64 = 1200; +const ROW_BYTES: usize = 1024; + +fn region(at: usize, len: usize) -> Option { + let end = at.checked_add(len)?; + // SAFETY: VirtualQuery writes only the supplied fixed-size record. + let mut info = unsafe { std::mem::zeroed::() }; + // SAFETY: the output points to a writable, fully sized record. + let got = unsafe { VirtualQuery(at as _, &mut info, size_of_val(&info)) }; + if at == 0 + || got != size_of_val(&info) + || info.State != MEM_COMMIT + || info.Protect & PAGE_GUARD != 0 + || !matches!( + info.Protect & 0xff, + PAGE_READONLY + | PAGE_READWRITE + | PAGE_WRITECOPY + | PAGE_EXECUTE_READ + | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY + ) + || end > (info.BaseAddress as usize).checked_add(info.RegionSize)? + { + return None; + } + Some(info) +} + +fn read(at: usize) -> Option<[u8; N]> { + let mut bytes = [0; N]; + read_into(at, &mut bytes).then_some(bytes) +} + +fn read_into(mut at: usize, mut bytes: &mut [u8]) -> bool { + if at == 0 || at.checked_add(bytes.len()).is_none() { + return false; + } + let mut allocation = None; + while !bytes.is_empty() { + let Some(info) = region(at, 1) else { + return false; + }; + if allocation + .replace(info.AllocationBase) + .is_some_and(|a| a != info.AllocationBase) + { + return false; + } + let region_end = info.BaseAddress as usize + info.RegionSize; + let len = bytes.len().min(region_end - at); + let mut count = 0; + // SAFETY: the OS validates the source again and the destination contains len writable bytes. + let ok = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + at as _, + bytes.as_mut_ptr().cast(), + len, + &mut count, + ) + }; + if ok == 0 || count != len { + return false; + } + at += len; + bytes = &mut bytes[len..]; + } + true +} + +impl Map { + fn pointer(self, index: usize) -> Option { + Some(usize::from_le_bytes(read(self.slots[index])?)) + } + + fn sample(self, index: usize, pointer: usize) -> Result { + if pointer == 0 || !pointer.is_multiple_of(8) { + return Err("null-or-misaligned-header"); + } + let first = read(pointer).ok_or("unreadable-header")?; + let a = Sample::parse(pointer, STRIDES[index], &first)?; + let second = read(pointer).ok_or("unreadable-header")?; + let b = Sample::parse(pointer, STRIDES[index], &second)?; + if a != b || self.pointer(index) != Some(pointer) { + return Err("header-or-global-changed-during-read"); + } + Ok(b) + } +} + +impl fmt::Display for Sample { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "header={:#x} backing={:#x} metadata={:#x} stride={} capacity={} used={} head={:#018x} tag={}", + self.pointer, + self.backing, + self.metadata, + self.stride, + self.capacity, + self.used, + self.head, + self.head >> 32 + )?; + if self.backing == 0 || self.metadata == 0 { + write!(f, " live_header=unavailable-null-storage")?; + } + Ok(()) + } +} + +struct Registration { + map: Map, + start: Instant, + observed: bool, +} + +// The sampler works from its own map and never takes this mutex. +static REGISTRATION: Mutex> = Mutex::new(None); +static BASE: AtomicUsize = AtomicUsize::new(0); + +pub(crate) struct Fault { + ms: u128, + site_rva: usize, + candidate: &'static str, + pointer: usize, + rax: u64, + request: Option, + sample: Result, +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let active = if self.sample.is_ok() { + self.candidate + } else { + "unknown" + }; + write!( + f, + "pool observation elapsed_ms={} site_rva={:#x} active={active} rcx={:#x} fault_rax={:#018x} ", + self.ms, self.site_rva, self.pointer, self.rax + )?; + match self.sample { + Ok(sample) => { + write!(f, "{sample}")?; + if self.candidate == "BUILDING" { + if let Some(r) = self.request { + write!( + f, + " batch_source={:#x} key={:#x} override={} descriptor={:#x} task={:#x} list={:#x} index={} end={} list_count={} output_array={:#x} owner_id={:#x}", + r.source, + r.key, + r.override_byte, + r.descriptor, + r.task, + r.list, + r.index, + r.end, + r.count, + r.array, + r.id + )?; + if let Some(o) = r.matched_owner { + write!( + f, + " matched_owner={:#x} registry_record={:#x} output_count={}", + o.pointer, o.record, o.count + )?; + } else { + write!(f, " matched_owner=unavailable")?; + } + } else { + write!(f, " batch=unavailable")?; + } + } + Ok(()) + } + Err(reason) => write!( + f, + "global_candidate={} unavailable={reason}", + self.candidate + ), + } + } +} + +/// Only called for naturally dispatched first-chance breakpoints. +pub(crate) fn first_fault(at: usize, context: &CONTEXT) -> Option { + let base = BASE.load(Ordering::Acquire); + let site_rva = at.checked_sub(base)?; + if base == 0 || !TRAPS.contains(&site_rva) { + return None; + } + // Only registration, teardown or another matching fault can own the lock. + let mut entry = REGISTRATION.try_lock().ok()?; + let reg = entry.as_mut()?; + if !reg.map.traps.contains(&at) || std::mem::replace(&mut reg.observed, true) { + return None; + } + let pointer = context.Rcx as usize; + let mut fault = Fault { + ms: reg.start.elapsed().as_millis(), + site_rva, + pointer, + rax: context.Rax, + candidate: "unknown", + request: None, + sample: Err("exception-address-context-mismatch"), + }; + if context.Rip == at as u64 || context.Rip.checked_sub(1) == Some(at as u64) { + let globals = reg + .map + .slots + .map(|slot| read(slot).map(usize::from_le_bytes)); + if let Some(i) = reg.map.select(at, pointer, globals) { + fault.candidate = NAMES[i]; + fault.sample = reg.map.sample(i, pointer).and_then(|s| { + if s.metadata == 0 { + Err("null-metadata") + } else { + Ok(s) + } + }); + if i == 0 + && fault.sample.is_ok_and(|s| { + s.backing != 0 + && s.used == s.capacity + && s.head == context.Rax + && (s.head as u32) == super::EMPTY + }) + { + fault.request = request::capture( + base, + [ + context.Rsp as usize, + context.Rdi as usize, + context.R14 as usize, + context.R15 as usize, + context.R12 as usize, + context.Rbp as u32 as usize, + ], + &mut read_into, + ); + } + } else { + fault.sample = Err("no-unique-readable-global"); + } + } + Some(fault) +} + +fn history( + mut file: File, + map: Map, + start: Instant, + sidecar: Option<(File, usize)>, + mut stop_after_sample: impl FnMut() -> bool, +) -> std::io::Result<()> { + writeln!( + file, + "Most recent 1200 samples. Read 1024-byte slots. Discard short slots or slots without matching initial seq and final complete values. Sort complete slots by seq after wrap. Tag deltas count published pushes modulo 2^32 for an apparently continuous lifetime. Pop estimates include in-flight skew. Samples cannot detect every wrap, replacement or failed attempt." + )?; + let data_start = file.stream_position()?; + let mut previous = [None; 3]; + let mut residents = sidecar.map(|(file, base)| (file, base, Census::new())); + for seq in 0..u64::MAX { + let mut row = [b' '; ROW_BYTES]; + { + const FOOTER_BYTES: usize = b"complete=00000000000000000000\n".len(); + let (mut out, mut footer) = row.split_at_mut(ROW_BYTES - FOOTER_BYTES); + writeln!(footer, "complete={seq:020}")?; + writeln!(out, "seq={seq} elapsed_ms={}", start.elapsed().as_millis())?; + for i in 0..3 { + let pointer = map.pointer(i); + let sample = pointer + .ok_or("unreadable-global") + .and_then(|p| map.sample(i, p)); + write!(out, " {} ", NAMES[i])?; + match sample { + Ok(s) => { + write!(out, "{s} ")?; + match s.activity(previous[i]) { + Ok((r, Some(p))) => { + writeln!(out, "release_tag_delta_mod32={r} pop_estimate={p}")? + } + Ok((r, None)) => writeln!( + out, + "raw_tag_delta_mod32={r} pop_estimate_unavailable=tag-decreased-wrap-or-reset" + )?, + Err(reason) => writeln!(out, "delta_unavailable={reason}")?, + } + } + Err(reason) => writeln!(out, "unavailable={reason}")?, + } + previous[i] = sample.ok(); + } + } + file.seek(SeekFrom::Start( + data_start + (seq % SLOTS) * ROW_BYTES as u64, + ))?; + file.write_all(&row)?; + if let Some((file, base, census)) = &mut residents { + let ms = start.elapsed().as_millis() as u64; + let first = previous[0]; + census.capture(*base, first, read_into, || { + map.sample(0, first?.pointer).ok() + }); + if let Err(e) = census.publish(file, seq, ms) { + eprintln!("BUILDING resident history unavailable: {e}"); + residents = None; + } + } + if stop_after_sample() { + break; + } + } + Ok(()) +} + +/// Keeps the observation registered until the title is done. +pub struct PoolObserver { + stop: Sender<()>, + worker: Option>, +} + +impl Drop for PoolObserver { + fn drop(&mut self) { + let mut entry = REGISTRATION.lock().unwrap_or_else(|e| e.into_inner()); + BASE.store(0, Ordering::Release); + *entry = None; + drop(entry); + let _ = self.stop.send(()); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +/// Starts the opted-in observer for the identified original main image. +pub fn start_pool_observation(image: &LoadedImage, path: &Path) -> Option { + let flag = std::env::var("VICTORY_POOL_OBSERVE").ok(); + if flag.as_deref() != Some("1") { + return None; + } + if !enabled( + flag.as_deref(), + image.original_hash.to_hex().as_str(), + image.info().is_dll(), + ) { + eprintln!("pool observation unavailable: unrecognized original main image"); + return None; + } + let result = (|| -> anyhow::Result<_> { + let base = image.base(); + let map = Map::new(base, image.info().size_of_image as usize) + .ok_or_else(|| anyhow::anyhow!("pool ranges outside image"))?; + for (at, len) in map + .slots + .map(|at| (at, 8)) + .into_iter() + .chain(map.traps.map(|at| (at, 1))) + { + anyhow::ensure!( + region(at, len).is_some_and(|r| r.AllocationBase as usize == base), + "pool range unavailable in main image" + ); + } + let mut entry = REGISTRATION.lock().unwrap_or_else(|e| e.into_inner()); + anyhow::ensure!(entry.is_none(), "observer already registered"); + victory_core::ensure_outside_repo(path)?; + let file = File::create(path)?; + let sidecar = (|| -> anyhow::Result<_> { + let size = image.info().size_of_image as usize; + for (rva, len) in IMAGE_RANGES { + anyhow::ensure!( + rva + len <= size + && region(base + rva, len) + .is_some_and(|r| r.AllocationBase as usize == base), + "resident range outside main image" + ); + } + let dest = path.with_file_name("pool-residents.bin"); + victory_core::ensure_outside_repo(&dest)?; + Ok((File::create(dest)?, base)) + })() + .map_err(|e| eprintln!("BUILDING resident history unavailable: {e}")) + .ok(); + let start = Instant::now(); + let (stop, stopped) = mpsc::channel(); + let worker = std::thread::Builder::new() + .name("pool-observation".into()) + .spawn(move || { + let stop_after_sample = || { + !matches!( + stopped.recv_timeout(Duration::from_secs(1)), + Err(mpsc::RecvTimeoutError::Timeout) + ) + }; + if let Err(e) = history(file, map, start, sidecar, stop_after_sample) { + eprintln!("pool history unavailable: {e}"); + } + })?; + *entry = Some(Registration { + map, + start, + observed: false, + }); + BASE.store(base, Ordering::Release); + Ok(PoolObserver { + stop, + worker: Some(worker), + }) + })(); + match result { + Ok(guard) => Some(guard), + Err(e) => { + eprintln!("pool observation unavailable: {e}"); + None + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::pool::tests::header; + use windows_sys::Win32::Foundation::EXCEPTION_BREAKPOINT; + use windows_sys::Win32::System::Diagnostics::Debug::{EXCEPTION_POINTERS, EXCEPTION_RECORD}; + use windows_sys::Win32::System::Memory::{ + MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree, VirtualProtect, + }; + + #[test] + fn protected_reads_require_every_byte_and_preserve_guard_pages() { + // SAFETY: reserve two new pages and release the allocation after the reads. + unsafe { + let p = VirtualAlloc( + std::ptr::null(), + 8192, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ); + assert!(!p.is_null()); + let at = p as usize; + let mut old = 0; + // A single backing allocation may have adjacent readable regions with different protections. + assert_ne!( + VirtualProtect((at + 4096) as _, 4096, PAGE_READONLY, &mut old), + 0 + ); + let mut bulk = vec![9; 8192]; + assert!(read_into(at, &mut bulk)); + assert_eq!(bulk, vec![0; 8192]); + for protection in [PAGE_NOACCESS, PAGE_READWRITE | PAGE_GUARD] { + assert_ne!( + VirtualProtect((at + 4096) as _, 4096, protection, &mut old), + 0 + ); + assert_eq!(read::<8>(at + 4088), Some([0; 8])); + assert_eq!(read::<8>(at + 4092), None); + assert_eq!(read::<8>(at + 4096), None); + assert!(!read_into(at, &mut bulk)); + let mut page: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery((at + 4096) as _, &mut page, size_of_val(&page)); + assert_eq!(page.Protect, protection); + } + assert_ne!(VirtualFree(p, 0, MEM_RELEASE), 0); + assert_eq!(read::<8>(usize::MAX - 3), None); + } + } + + pub(crate) fn check_dispatch( + handler: unsafe extern "system" fn(*mut EXCEPTION_POINTERS) -> i32, + ) { + const CHILD: &str = "VICTORY_TEST_POOL_REPORT"; + let Some(log) = std::env::var_os(CHILD) else { + let dir = tempfile::tempdir().unwrap(); + for (file, identity, expected) in [ + ( + "readable.log", + "active=BUILDING", + "stride=224 capacity=17 used=10", + ), + ( + "unreadable.log", + "active=unknown", + "global_candidate=BUILDING unavailable=unreadable-header", + ), + ( + "wrong-stride.log", + "active=unknown", + "global_candidate=BUILDING unavailable=invalid-header", + ), + ("null-backing.log", "active=BUILDING", "backing=0x0"), + ( + "null-metadata.log", + "active=unknown", + "global_candidate=BUILDING unavailable=null-metadata", + ), + ] { + let log = dir.path().join(file); + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "crash::tests::first_pool_fault_preserves_dispatch", + "--nocapture", + ]) + .env(CHILD, &log) + .output() + .unwrap(); + assert!( + child.status.success(), + "{}", + String::from_utf8_lossy(&child.stderr) + ); + let text = std::fs::read_to_string(log).unwrap(); + assert_eq!(text.matches("pool observation").count(), 1); + assert!( + text.contains("site_rva=0x5149aec") + && text.contains(identity) + && text.contains(expected), + "{file}: {text}" + ); + assert!(text.contains("fault_rax=0x000000000007fffe")); + } + return; + }; + let unreadable = Path::new(&log).ends_with("unreadable.log"); + let mut fields = header(); + if Path::new(&log).ends_with("wrong-stride.log") { + fields[8..12].copy_from_slice(&272_u32.to_le_bytes()); + } else if Path::new(&log).ends_with("null-backing.log") { + fields[..8].fill(0); + } else if Path::new(&log).ends_with("null-metadata.log") { + fields[40..48].fill(0); + } + crate::log_crashes_to(log.into()); + #[repr(align(8))] + struct Header([u8; 52]); + let bytes = Header(fields); + let ptr = bytes.0.as_ptr() as usize; + let slots = [ + AtomicUsize::new(if unreadable { 8 } else { ptr }), + AtomicUsize::new(0), + AtomicUsize::new(0), + ]; + let map = Map { + slots: std::array::from_fn(|i| std::ptr::from_ref(&slots[i]) as usize), + traps: [0x10000000 + TRAPS[0], 0x10000000 + TRAPS[1]], + }; + *REGISTRATION.lock().unwrap() = Some(Registration { + map, + start: Instant::now(), + observed: false, + }); + BASE.store(0x10000000, Ordering::Release); + // SAFETY: zeroed synthetic exception records and context contain no owning references. + let (mut context, mut record): (CONTEXT, EXCEPTION_RECORD) = unsafe { std::mem::zeroed() }; + context.Rip = map.traps[0] as u64; + context.Rcx = slots[0].load(Ordering::Relaxed) as u64; + context.Rax = 0x7fffe; + context.EFlags = 0x246; + record.ExceptionAddress = map.traps[0] as _; + record.ExceptionCode = EXCEPTION_BREAKPOINT; + record.ExceptionFlags = 1; + let original_record = + read::<{ size_of::() }>(std::ptr::from_ref(&record) as usize) + .unwrap(); + let mut info = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + for _ in 0..2 { + let original_context = + read::<{ size_of::() }>(info.ContextRecord as usize).unwrap(); + // SAFETY: synthetic records stay live, with a zero stack pointer ending the ordinary stack walk. + assert_eq!(unsafe { handler(&mut info) }, 0); + assert_eq!( + read::<{ size_of::() }>(info.ContextRecord as usize).unwrap(), + original_context + ); + assert_eq!( + read::<{ size_of::() }>(info.ExceptionRecord as usize).unwrap(), + original_record + ); + slots[0].store(ptr, Ordering::Relaxed); + context.Rcx = ptr as u64; + } + // SAFETY: the same live synthetic records exercise an unhandled redelivery. + unsafe { crate::report_unhandled(&info) }; + let (stop, stopped) = mpsc::channel(); + let worker = std::thread::spawn(move || stopped.recv().unwrap()); + drop(PoolObserver { + stop, + worker: Some(worker), + }); + assert!(REGISTRATION.lock().unwrap().is_none()); + assert!(first_fault(map.traps[0], &context).is_none()); + } + + #[test] + fn a_replaced_global_invalidates_the_previously_selected_header() { + #[repr(align(8))] + struct Header([u8; 52]); + let original = Header(header()); + let pointer = original.0.as_ptr() as usize; + let slot = AtomicUsize::new(pointer); + let empty = 0_usize; + let map = Map { + slots: [ + std::ptr::from_ref(&slot) as usize, + std::ptr::from_ref(&empty) as usize, + std::ptr::from_ref(&empty) as usize, + ], + traps: [1, 2], + }; + let globals = map.slots.map(|at| read(at).map(usize::from_le_bytes)); + let i = map.select(1, pointer, globals).unwrap(); + slot.store(0, Ordering::Relaxed); + let sample = map.sample(i, pointer); + assert_eq!(sample, Err("header-or-global-changed-during-read")); + let output = Fault { + ms: 3, + site_rva: TRAPS[0], + candidate: NAMES[i], + pointer, + rax: 75, + request: None, + sample, + } + .to_string(); + assert!(output.contains("active=unknown")); + assert!(output.contains( + "global_candidate=BUILDING unavailable=header-or-global-changed-during-read" + )); + } + + #[test] + fn history_wrap_rejects_an_interrupted_slot_replacement() { + fn sequence(slot: &[u8]) -> Option { + if slot.len() != ROW_BYTES { + return None; + } + let text = std::str::from_utf8(slot).ok()?; + let first = text + .strip_prefix("seq=")? + .split_once(' ')? + .0 + .parse::() + .ok()?; + let (_, footer) = text.strip_suffix('\n')?.rsplit_once("complete=")?; + (footer.len() == 20 && footer.parse::().ok()? == first).then_some(first) + } + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("history.log"); + #[repr(align(8))] + struct Header([u8; 52]); + let mut fields = Header(header()); + let slots = [fields.0.as_mut_ptr() as usize, 0, 0]; + let map = Map { + slots: std::array::from_fn(|i| std::ptr::from_ref(&slots[i]) as usize), + traps: [1, 2], + }; + let mut count = 0; + let mut first = Vec::new(); + history( + File::create(&path).unwrap(), + map, + Instant::now(), + None, + || { + count += 1; + if count == 1 { + let bytes = std::fs::read(&path).unwrap(); + first = bytes[bytes.len() - ROW_BYTES..].to_vec(); + fields.0[16..20].copy_from_slice(&11_u32.to_le_bytes()); + std::hint::black_box(&fields); + } + count == SLOTS + 1 + }, + ) + .unwrap(); + let bytes = std::fs::read(path).unwrap(); + let header_end = bytes.iter().position(|&b| b == b'\n').unwrap() + 1; + let data = &bytes[header_end..]; + assert_eq!(data.len(), SLOTS as usize * ROW_BYTES); + assert_eq!(sequence(&first), Some(0)); + for (index, slot) in data.as_chunks::().0.iter().enumerate() { + assert_eq!( + sequence(slot), + Some(if index == 0 { SLOTS } else { index as u64 }) + ); + } + let new = &data[..ROW_BYTES]; + assert!(std::str::from_utf8(new).unwrap().contains("used=11")); + first[..40].copy_from_slice(&new[..40]); + assert!(std::str::from_utf8(&first).unwrap().contains("used=10")); + assert_eq!(sequence(&first), None); + assert_eq!(sequence(&new[..ROW_BYTES - 1]), None); + } + + #[test] + fn history_writes_one_complete_sample_and_stops_on_disconnect() { + let mut bytes = header(); + bytes[8..12].copy_from_slice(&272_u32.to_le_bytes()); + #[repr(align(8))] + struct Header([u8; 52]); + let bytes = Header(bytes); + let slots = [0, bytes.0.as_ptr() as usize, 0]; + let map = Map { + slots: std::array::from_fn(|i| std::ptr::from_ref(&slots[i]) as usize), + traps: [1, 2], + }; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("samples.log"); + let sidecar = dir.path().join("residents.bin"); + let (stop, stopped) = mpsc::channel::<()>(); + drop(stop); + history( + File::create(&path).unwrap(), + map, + Instant::now(), + Some((File::create(&sidecar).unwrap(), 0x10000)), + || stopped.recv().is_err(), + ) + .unwrap(); + let frame = std::fs::read(sidecar).unwrap(); + assert_eq!(&frame[..8], b"BRES0002"); + assert_eq!(&frame[8..16], &0_u64.to_le_bytes()); + assert_eq!(&frame[frame.len() - 8..], &u64::MAX.to_le_bytes()); + assert_eq!(frame[24], 0); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("seq=").count(), 1); + assert!(text.contains("OBJECT header=") && text.contains("stride=272 capacity=17 used=10")); + assert!(text.contains("BUILDING unavailable=") && text.contains("pool-256 unavailable=")); + assert!(text.contains("delta_unavailable=no-contiguous-sample")); + assert!(text.ends_with("complete=00000000000000000000\n")); + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index b95bd3d16..c0a1a5d4e 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -24,6 +24,8 @@ use crate::{ #[derive(Debug, Clone)] pub struct LoadedImage { module: HMODULE, + #[cfg(feature = "diagnostics")] + pub(crate) original_hash: blake3::Hash, path: PathBuf, info: ImageInfo, } @@ -76,6 +78,8 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { } let loaded = LoadedImage { module, + #[cfg(feature = "diagnostics")] + original_hash: prepared.original_hash, path, info: prepared.info.clone(), }; diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index ca4f3fc87..33b16196b 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -34,6 +34,59 @@ pub(crate) enum V { Inst(u32), } +/// A fenced raw-data scratch write, including writes to unused guest SGPRs. +#[cfg(test)] +#[derive(Debug)] +pub(crate) struct ScalarExchange { + pub source: (Option, u32), + pub lower_read: bool, + pub addend: Option, +} + +#[cfg(test)] +#[derive(Default)] +struct ScalarExchangeTrace { + fenced: bool, + pending: Option<(V, (Option, u32))>, + reading: Option<(V, usize)>, + exchanges: Vec, +} + +#[cfg(test)] +impl ScalarExchangeTrace { + fn store(&mut self, slot: V, source: Option<(Option, u32)>) { + self.pending = if self.fenced { + source.map(|s| (slot, s)) + } else { + None + }; + self.fenced = false; + self.reading = None; + } + + fn barrier(&mut self) { + self.reading = self.pending.take().map(|(slot, source)| { + self.exchanges.push(ScalarExchange { + source, + lower_read: false, + addend: None, + }); + (slot, self.exchanges.len() - 1) + }); + self.fenced = true; + } + + fn scratch_read(&mut self, lower_of: Option, addend: Option) { + self.fenced = false; + if let Some((slot, i)) = self.reading + && lower_of == Some(slot) + { + self.exchanges[i].lower_read = true; + self.exchanges[i].addend = addend; + } + } +} + /// A global variable declaration (thread-group shared memory). struct Global { name: String, @@ -606,6 +659,101 @@ impl Module { } } + /// Trace each raw byte address and extract through its scratch write and + /// two fences. Record any live lower-slot read and its immediate add consumer. + #[cfg(test)] + pub fn live_scalar_exchanges(&self) -> Vec { + let op = |v| match v { + V::Inst(i) => Some(&self.insts[i as usize].op), + _ => None, + }; + let call = |v, name| match op(v)? { + Op::Call(f, args) if self.funcs[*f as usize].name == name => Some(args), + _ => None, + }; + let component = |v| { + let own = call(v, "dx.op.waveReadLaneFirst.i32")?; + let Op::Cast(Cast::Bitcast, raw) = op(own[1])? else { + return None; + }; + let Op::Extract(load, k) = op(*raw)? else { + return None; + }; + let args = call(*load, "dx.op.rawBufferLoad.f32")?; + let mask = self.int_value(args[4])?; + (self.int_value(args[5]) == Some(4) && mask & (1 << k) != 0) + .then(|| (self.constant_sum(args[2]), *k)) + }; + let slot = |v| match op(v)? { + Op::Gep(_, V::Global(g), index) if self.globals[*g as usize].name == "half_words" => { + index.last().copied() + } + _ => None, + }; + let plan = self.plan(); + let mut adds = Map::default(); + for &b in &plan.layout { + for &i in &self.blocks[b].body { + if plan.live[i as usize] + && let Op::Bin(Bin::Add, a, b) = self.insts[i as usize].op + { + for (value, constant) in [(a, b), (b, a)] { + if let Some(n) = self.int_value(constant) { + adds.entry(value) + .and_modify(|add| *add = None) + .or_insert(Some(n)); + } + } + } + } + } + let mut results = Vec::new(); + for b in plan.layout { + let mut trace = ScalarExchangeTrace::default(); + for &i in self.blocks[b] + .body + .iter() + .filter(|&&i| plan.live[i as usize]) + { + match self.insts[i as usize].op { + Op::Store(ptr, value) if let Some(index) = slot(ptr) => { + trace.store(index, component(value)); + } + Op::Load(ptr) if let Some(index) = slot(ptr) => { + let lower_of = match op(index) { + Some(Op::Bin(Bin::And, a, mask)) + if self.int_value(*mask).map(|n| n as u32) == Some(!1) => + { + Some(*a) + } + _ => None, + }; + trace.scratch_read(lower_of, adds.get(&V::Inst(i)).copied().flatten()); + } + _ if call(V::Inst(i), "dx.op.barrier") + .is_some_and(|args| self.int_value(args[1]) == Some(9)) => + { + trace.barrier(); + } + _ => {} + } + } + results.extend(trace.exchanges); + } + results + } + + /// Written branch targets and the surviving block of each requested site. + #[cfg(test)] + pub fn written_cfg(&self, sites: &[usize]) -> (Vec>, Vec) { + let plan = self.plan(); + let mut edges = vec![Vec::new(); self.blocks.len()]; + for &b in &plan.layout { + edges[b] = successors(self.term(b)).iter().map(|&s| plan.to(s)).collect(); + } + (edges, sites.iter().map(|&b| plan.to(b)).collect()) + } + /// Calls of functions named `name` that [`Module::write`] writes, and the /// blocks holding them. #[cfg(test)] @@ -715,22 +863,23 @@ impl Module { shape } + #[cfg(test)] + fn constant_sum(&self, v: V) -> Option { + if let V::Inst(i) = v + && let Op::Bin(Bin::Add, a, b) = self.insts[i as usize].op + { + return Some(i64::from( + (self.constant_sum(a)? as i32).wrapping_add(self.constant_sum(b)? as i32), + )); + } + self.int_value(v) + } + /// The arguments of each call of a function named `name` that /// [`Module::write`] writes, as integers where they are constants or /// sums of constants (lowering adds offsets up unfolded), else `None`. #[cfg(test)] pub fn written_call_args(&self, name: &str) -> Vec>> { - fn sum(m: &Module, v: V) -> Option { - match v { - V::Inst(i) => match m.insts[i as usize].op { - Op::Bin(Bin::Add, a, b) => Some(i64::from( - (sum(m, a)? as i32).wrapping_add(sum(m, b)? as i32), - )), - _ => None, - }, - v => m.int_value(v), - } - } let plan = self.plan(); let mut calls = Vec::new(); for &b in &plan.layout { @@ -739,7 +888,7 @@ impl Module { && plan.live[i as usize] && self.funcs[*f as usize].name == name { - calls.push(args.iter().map(|&a| sum(self, a)).collect()); + calls.push(args.iter().map(|&a| self.constant_sum(a)).collect()); } } } @@ -1356,10 +1505,34 @@ impl Writer { } } +#[cfg(test)] +pub(crate) mod lds_tests; + #[cfg(test)] mod tests { use super::*; + #[test] + fn scalar_exchange_trace_requires_fence_after_scratch_read() { + let slot = V::Inst(0); + for lower in [None, Some(slot)] { + for refenced in [false, true] { + let mut trace = ScalarExchangeTrace::default(); + trace.barrier(); + trace.store(slot, Some((Some(4), 0))); + trace.barrier(); + trace.scratch_read(lower, Some(1)); + if refenced { + trace.barrier(); + } + trace.store(slot, Some((Some(4), 1))); + trace.barrier(); + assert_eq!(trace.exchanges[0].lower_read, lower.is_some()); + assert_eq!(trace.exchanges.len(), 1 + usize::from(refenced)); + } + } + } + #[test] fn vbr_and_blocks() { let mut w = Writer::default(); diff --git a/crates/victory-shader/src/emit/bitcode/lds_tests.rs b/crates/victory-shader/src/emit/bitcode/lds_tests.rs new file mode 100644 index 000000000..573073e54 --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/lds_tests.rs @@ -0,0 +1,59 @@ +use super::*; + +#[derive(Debug, PartialEq)] +pub(crate) enum GuestEvent { + Fence, + Load, + Store, +} + +pub(crate) struct GuestLds { + pub globals: Vec<(String, u32)>, + pub events: Vec>, +} + +impl Module { + pub(crate) fn guest_lds_trace(&self) -> GuestLds { + let plan = self.plan(); + let globals = self + .globals + .iter() + .filter(|g| g.space == 3) + .map(|g| { + let TypeDef::Array(n, t) = self.types[g.ty.0 as usize] else { + panic!("shared array") + }; + assert_eq!(self.types[t.0 as usize], TypeDef::Int(32)); + (g.name.clone(), n) + }) + .collect(); + let mut events: Vec> = (0..self.blocks.len()).map(|_| Vec::new()).collect(); + let guest = |p| { + matches!(p, V::Inst(i) if matches!( + self.insts[i as usize].op, Op::Gep(_, V::Global(g), _) if self.globals[g as usize].name == "lds")) + }; + for &b in &plan.layout { + for &i in self.blocks[b] + .body + .iter() + .filter(|&&i| plan.live[i as usize]) + { + let event = match &self.insts[i as usize].op { + // The fixture writes a UAV, so guest phase fences carry the UAV + // bit too. Ticket and scalar-publication fences use mode 9. + Op::Call(f, a) + if self.funcs[*f as usize].name == "dx.op.barrier" + && self.int_value(a[1]) == Some(11) => + { + GuestEvent::Fence + } + Op::Load(p) if guest(*p) => GuestEvent::Load, + Op::Store(p, _) if guest(*p) => GuestEvent::Store, + _ => continue, + }; + events[b].push(event); + } + } + GuestLds { globals, events } + } +} diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 54a64759d..7f9ca6656 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -95,7 +95,11 @@ fn console(l: u32) -> [u32; 8] { ] } -fn native(words: &[u32], wave64: bool, threads: u32, lds_bytes: u32) -> NativeProgram { +pub(super) fn native(words: &[u32], wave64: bool, threads: u32, lds_bytes: u32) -> NativeProgram { + native_for_groups(words, wave64, threads, lds_bytes, 1) +} + +fn native_for_groups(words: &[u32], wave64: bool, threads: u32, lds_bytes: u32, groups: u32) -> NativeProgram { let range = |kind, table_offset_dwords, dwords| UsedResource { kind, root: RootType::Table, @@ -124,14 +128,21 @@ fn native(words: &[u32], wave64: bool, threads: u32, lds_bytes: u32) -> NativePr range(ResourceType::Uav, 16, 4), ], io: StageIo::Cs(ComputeIo { - // One user-data SGPR; LDS in blocks of 512 bytes (bits 15-23). - rsrc2: 1 << 1 | lds_bytes.div_ceil(512) << 15, + // One user SGPR, optional group X, LDS in blocks of 512 bytes. + rsrc2: 1 << 1 | u32::from(groups > 1) << 7 | lds_bytes.div_ceil(512) << 15, threads: [threads, 1, 1], }), code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), } } +pub(super) fn live_sources(out: &lower::Lowered) -> Vec<(Option, u32)> { + out.live_scalar_exchanges + .iter() + .filter_map(|x| x.lower_read.then_some(x.source)) + .collect() +} + fn lowered( native: &NativeProgram, host_wave32: bool, @@ -170,43 +181,73 @@ fn lower_halves_limited( literal: bool, limits: bool, ) -> Result { - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = structure::structure(&p).expect("structure"); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + lower_with_resources_limited(native, host_wave32, narrow_waves, literal, limits, |_, _| {}) +} + +fn lower_with_resources( + native: &NativeProgram, + host_wave32: bool, + narrow_waves: bool, + literal: bool, + adjust: impl FnOnce(&ir::Program, &mut resource::Resources), +) -> Result { + lower_with_resources_limited(native, host_wave32, narrow_waves, literal, false, adjust) +} + +fn lower_with_resources_limited( + native: &NativeProgram, + host_wave32: bool, + narrow_waves: bool, + literal: bool, + limits: bool, + adjust: impl FnOnce(&ir::Program, &mut resource::Resources), +) -> Result { + let (p, st) = crate::range::build(&native.code, native.wave64, native.vgprs)?; + let st = st?; + let mut res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + adjust(&p, &mut res); let io = io::raise(&p, native).expect("io::raise"); - let parts = lower::Parts { - native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - view_marks: false, - atomic_locks: false, - atomic_lock_rounds: false, - atomic_umax: false, - bias_as_gradients: false, - narrow_waves, - uav_size_level0: false, - halves_rendezvous: true, - host_wave32, - }; - let threads = match &native.io { - StageIo::Cs(cs) => cs.threads.iter().product::(), - _ => 0, - }; - if literal && !limits && threads == 64 { + let parts = parts(native, &p, &st, &res, &io, host_wave32, narrow_waves); + if literal && !limits && matches!(&native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64) { lower::lower_literal(&parts, None, false) } else { lower::lower_limited(&parts, None, false, literal, limits) } } +pub(super) fn parts<'a>( + native: &'a NativeProgram, + p: &'a ir::Program, + st: &'a structure::Structured, + res: &'a resource::Resources, + io: &'a io::Io, + host_wave32: bool, + narrow_waves: bool, +) -> lower::Parts<'a> { + lower::Parts { + native, + p, + st, + io, + res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: false, + atomic_locks: false, + atomic_lock_rounds: false, + atomic_umax: false, + bias_as_gradients: false, + narrow_waves, + uav_size_level0: false, + halves_rendezvous: true, + host_wave32, + } +} + #[cfg(windows)] -fn shader(l: lower::Lowered) -> super::HostShader { +pub(super) fn shader(l: lower::Lowered) -> super::HostShader { super::HostShader { stage: HwStage::Cs, dxil: l.dxil, @@ -1035,6 +1076,7 @@ fn differences_in( literal, &[0; 4], ) + .0 } /// [`differences_in`] with custom contents for the structured SRV buffer at @@ -1051,8 +1093,46 @@ fn differences_with_buffer( narrow_waves: bool, literal: bool, buf_data: &[u32], -) -> Vec { - let n = native(words, wave64, threads, lds_bytes); +) -> (Vec, usize) { + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: buf_data, + stride: Stride::Structured(16), + }, + View::RawUav((want.len() / per_lane * 8) as u32), + ]; + differences_with_views( + wave64, + words, + threads, + per_lane, + want, + lds_bytes, + narrow_waves, + literal, + &views, + ) +} + +#[allow(clippy::too_many_arguments)] +#[cfg(windows)] +fn differences_with_views( + wave64: bool, + words: &[u32], + threads: u32, + per_lane: usize, + want: &[u32], + lds_bytes: u32, + narrow_waves: bool, + literal: bool, + views: &[View<'_>], +) -> (Vec, usize) { + let lanes = want.len() / per_lane; + assert_eq!(lanes * per_lane, want.len()); + let groups = u32::try_from(lanes).unwrap() / threads; + assert_eq!(groups * threads, lanes as u32); + let n = native_for_groups(words, wave64, threads, lds_bytes, groups); let forms = if literal { vec![( "literal halves", @@ -1075,14 +1155,20 @@ fn differences_with_buffer( shader(lowered_with(&n, false, narrow_waves).expect("one wave32")), )] }; - let views = [ - View::Texture(1, 1, &[[0.0; 4]]), - View::Buffer { - data: buf_data, - stride: Stride::Structured(16), - }, - View::RawUav(threads * 8), - ]; + compare_dispatches(&forms, groups, per_lane, want, views) +} + +#[cfg(windows)] +pub(super) fn compare_dispatches( + forms: &[(&str, super::HostShader)], + groups: u32, + per_lane: usize, + want: &[u32], + views: &[View<'_>], +) -> (Vec, usize) { + let lanes = want.len() / per_lane; + assert_eq!(want.len(), lanes * per_lane, "incomplete expected row"); + let stride = per_lane.max(8); // Older fixtures reserve eight dwords even for a shorter row. let _one = super::valu_tests::ONE_AT_A_TIME .lock() .unwrap_or_else(|e| e.into_inner()); @@ -1091,13 +1177,17 @@ fn differences_with_buffer( eprintln!("no SM 6.6 hardware device; skipped"); } let mut failed = Vec::new(); + let mut dispatches = 0; for (adapter, host) in &hosts { let wave32 = host.wave32().unwrap_or(false); - for (form, shader) in &forms { + for (form, shader) in forms { let label = format!("{adapter} ({form})"); // A host of 32-lane waves only ever runs the halves. NVIDIA // refuses the console's own form; D3DMetal makes its pipeline // and then runs nothing. + if matches!(*form, "publication wave32" | "owner wave32") && !wave32 { + continue; + } if *form == "wave64" && wave32 { eprintln!("{label}: one wave64 on a host of 32-lane waves; skipped"); continue; @@ -1112,14 +1202,16 @@ fn differences_with_buffer( &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], - views: &views, + views, samplers: &[], - groups: [1, 1, 1], + groups: [groups, 1, 1], }, ) .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0].len(), lanes * stride, "{label}: incomplete readback"); + dispatches += 1; let wrong: Vec = out[0] - .chunks(8) + .chunks(stride) .zip(want.chunks(per_lane)) .enumerate() .filter(|(_, (got, want))| got[..per_lane] != **want) @@ -1131,13 +1223,13 @@ fn differences_with_buffer( }) .collect(); eprintln!( - "{label}: {} lanes of {threads} differ from the console", + "{label}: {} lanes of {lanes} differ from the console", wrong.len() ); failed.extend(wrong); } } - failed + (failed, dispatches) } /// A DPP row mask names the console's rows 0-3: with `row_mask:0xc` only @@ -1885,7 +1977,7 @@ fn literal_wave64_vcc_hi_offset_matches_the_console_on_every_gpu() { true, true, &[0, 0, 0, 0, 7, 0, 0, 0], - ); + ).0; assert!(failed.is_empty(), "{}", failed.join("\n")); } @@ -2222,6 +2314,7 @@ fn early_out_program(keep_below: bool, limit: u32) -> Vec { w } +#[cfg(windows)] fn console_early_out(keep_below: bool, limit: u32, l: u32) -> [u32; 8] { let active = |t: u32| if keep_below { t < limit } else { t >= limit }; if !active(l) { @@ -2318,6 +2411,7 @@ fn diamond_program() -> Vec { w } +#[cfg(windows)] fn console_diamond(l: u32) -> [u32; 3] { if l < 36 { let sum: u32 = (0..36).sum(); @@ -2353,6 +2447,7 @@ fn half_add_reduction() -> Vec { } /// Exact IEEE-754 f16 encoding of an exact non-negative integer `n` in `0..=65504`. +#[cfg(windows)] fn u32_to_f16_bits(n: u32) -> u32 { if n == 0 { return 0; @@ -2578,7 +2673,8 @@ fn uniform_buffer_load_loop_across_halves_matches_the_console_on_every_gpu() { true, false, &[trips, 0, 0, 0], - )); + ) + .0); } assert!(failed.is_empty(), "{}", failed.join("\n")); } @@ -3059,6 +3155,7 @@ impl Side { } } + #[cfg(windows)] fn takes(self, l: u32) -> bool { match self { Side::Even => l.is_multiple_of(2), @@ -3193,6 +3290,7 @@ fn ballot_in_a_loop_in_an_if(side: Side, limit: u32) -> Vec { /// The console's [`ballot_below`]`(limit)` in lane `l` of a group of /// `threads` where the lanes `active` runs it: the count of its console /// wave's active lanes below `limit`, and their high dword. +#[cfg(windows)] fn console_ballot(threads: u32, l: u32, active: impl Fn(u32) -> bool, limit: u32) -> [u32; 2] { let wave = l & !63; let on = |t: u32| t < threads && active(t) && t < limit; @@ -3264,6 +3362,7 @@ fn lane_masks_in_divergent_code_meet_between_halves() { } let halves = lowered(&native(words, true, 128, 0), true).expect("halves"); assert_eq!(halves.wave_size, Some(32)); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut halves.dxil.clone()) @@ -3319,6 +3418,7 @@ fn lane_masks_in_divergent_code_meet_between_halves() { /// console wave with no upper half (96), and the branch in a loop run /// twice (the epochs). #[test] +#[cfg(windows)] fn lane_masks_in_divergent_code_match_the_console_on_every_gpu() { let mut failed = Vec::new(); let cases = [ @@ -4115,7 +4215,7 @@ fn a_first_lane_read_only_active_lanes_see_matches_the_console_on_every_gpu() { false, false, &[41, 0, 0, 0], - ); + ).0; failed.extend( found .into_iter() @@ -4250,7 +4350,7 @@ fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() .collect(); let found = differences_with_buffer( true, &words, threads, 1, &want, 0, false, false, &[41, 0, 0, 0], - ); + ).0; failed.extend( found .into_iter() @@ -4385,7 +4485,7 @@ fn a_first_lane_read_of_an_alike_value_in_a_region_matches_the_console_on_every_ .collect(); let found = differences_with_buffer( true, &words, threads, 2, &want, 0, false, false, &[0; 4], - ); + ).0; failed.extend(found.into_iter().map(|m| { format!("{label}(mbcnt={with_mbcnt}, inside={inside}) {threads} threads: {m}") })); @@ -4745,7 +4845,6 @@ const PERM_PAYLOAD: u32 = 0xDEAD_BE00; /// combination. The same-row form also checks full EXEC with BOUND_CTRL /// set. Each masked or potentially out-of-bounds read starts with `v1` /// holding [`PERM_OLD`]. EXEC is whole again for every store. -#[cfg(windows)] fn permlane16_program(lanes: u32, other_row: bool) -> Vec { let wave64 = lanes > 32; let full = |w: &mut Vec| { @@ -6023,3 +6122,797 @@ fn a_register_index_waterfall_matches_the_console_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +#[derive(Clone, Copy, Debug)] +enum Prefix { + Stable, + TwoGroups, + Unfenced, + LoopStore, + LateStore, + LaneCarry, + SplitLimit, +} + +/// Each lane publishes one dword, then waves read unequal-length prefixes. +/// The XOR carry crosses a back edge as a first-lane scalar. Wave zero skips +/// the loop entirely, and a partial last wave consumes only its own prefix. +fn bvh_prefix(case: Prefix) -> Vec { + let mut w = PROLOGUE.to_vec(); + // Two 512-thread groups publish different data and write disjoint outputs. + if matches!(case, Prefix::TwoGroups) { + w.extend([ + 0x8F0F_8901, // s_lshl_b32 s15, s1, 9 (group base) + 0x4A20_000F, // v_add_nc_u32 v16, s15, v0 + 0x3420_2085, // v_lshlrev_b32 v16, 5, v16 + ]); + } else { + w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 + } + let shift = if matches!(case, Prefix::SplitLimit) { + 5 + } else { + 6 + }; + w.extend([ + 0x3404_0082, // v_lshlrev_b32 v2, 2, v0 (LDS offset) + 0x4A06_008B, // v_add_nc_u32 v3, 11, v0 + ]); + if matches!(case, Prefix::TwoGroups) { + w.push(0x4A06_060F); // v_add_nc_u32 v3, s15, v3 + } + w.extend([ + 0xD834_0000, + 0x0000_0302, // ds_write_b32 v2, v3 + S_WAITCNT_LGKM, + ]); + if !matches!(case, Prefix::Unfenced) { + w.push(0xBF8A_0000); // s_barrier + } + w.extend([ + 0x2C08_0080 | shift, // v_lshrrev_b32 v4, shift, v0 (prefix length) + 0x7E12_0289, // v_mov_b32 v9, 9 + 0xBE92_0389, // s_mov_b32 s18, 9 (carry) + 0xBE93_0380, // s_mov_b32 s19, 0 (cursor) + 0xBE98_047E, // s_mov_b64 s[24:25], exec + 0x7DA2_0880, // v_cmpx_lt_u32 exec, 0, v4 + ]); + let skip = w.len(); + w.extend([0, 0xBF82_0001]); // skip empty prefixes; enter after the feedback + let feedback = w.len(); + w.extend([ + 0x7E24_0509, // v_readfirstlane_b32 s18, v9 + 0x7E0A_0213, // v_mov_b32 v5, s19 + 0x340A_0A82, // v_lshlrev_b32 v5, 2, v5 + 0xD8D8_0000, + 0x0600_0005, // ds_read_b32 v6, v5 + S_WAITCNT_LGKM, + ]); + if matches!(case, Prefix::LoopStore) { + w.extend([0xD834_0000, 0x0000_0302]); // the next read can race this write + } + w.push(0x3A12_0C12); // v_xor_b32 v9, s18, v6 + if matches!(case, Prefix::LaneCarry) { + w.push(0x3A12_1300); // v_xor_b32 v9, v0, v9 + } + w.extend([ + 0x8013_8113, // s_add_u32 s19, s19, 1 + 0x7DA2_0813, // v_cmpx_lt_u32 exec, s19, v4 + ]); + w.push(0xBF89_0000 | ((feedback as i32 - w.len() as i32 - 1) as u32 & 0xffff)); + w[skip] = s_cbranch_execz(w.len() - skip - 1); + w.push(0xBEFE_0418); // s_mov_b64 exec, s[24:25] + if matches!(case, Prefix::LateStore) { + w.extend([0xD834_0000, 0x0000_0902]); // alias a slower wave's reads + } + w.extend(store(9, 0)); + w.push(S_ENDPGM); + w +} + +/// A value can be identical across one console wave and different in the next. +fn bvh_wave_owner() -> Vec { + let mut words = PROLOGUE.to_vec(); + words.extend([ + 0x3420_0085, // v16 = x * 32 (output byte address) + 0x3404_0082, // v2 = x * 4 + 0xD834_0000, 0x0000_0002, // LDS[x] = x + S_WAITCNT_LGKM, 0xBF8A_0000, // publish all group-local words + 0x2C08_0086, // v4 = x >> 6 + 0x340A_0882, // v5 = v4 * 4 + 0xD8D8_0000, 0x0600_0005, // v6 = LDS[x >> 6] + S_WAITCNT_LGKM, + 0x7E24_0506, // s18 = firstlane(v6) + 0x7E12_0212, // v9 = s18 + ]); + words.extend(store(9, 0)); + words.push(S_ENDPGM); + words +} + +#[test] +fn bvh_first_lane_preserves_console_wave_ownership() { + for (words, threads) in [(bvh_wave_owner(), 128), (bvh_prefix(Prefix::Stable), 256)] { + let n = native(&words, true, threads, threads * 4); + let lower = |ticket| { + super::with_thread_ticket(ticket, || lowered_with(&n, true, true).unwrap()) + }; + let ticket = lower(true); + assert_eq!(ticket.wave_size, Some(32), "{threads} threads"); + // Each local thread ID must come from the chosen lane mapping. A raw + // threadIdInGroup broadcast would be identical with tickets disabled. + assert_ne!(ticket.dxil, lower(false).dxil, "{threads} threads"); + } +} + +#[test] +fn bvh_first_lane_shapes_lower() { + for threads in [512, 256, 128, 96, 64, 32] { + let (groups, case) = if threads == 512 { (2, Prefix::TwoGroups) } else { (1, Prefix::Stable) }; + let n = native_for_groups(&bvh_prefix(case), true, threads, 4 * threads, groups); + lower_halves(&n, true, false, threads == 64) + .unwrap_or_else(|e| panic!("{threads} threads: {e}")); + } + for case in [ + Prefix::SplitLimit, + Prefix::Unfenced, + Prefix::LoopStore, + Prefix::LateStore, + Prefix::LaneCarry, + ] { + // Lockstep predication can exchange these reads. The recurrence proof + // itself must not elide the exchange when any premise fails. + let why = lower::NO_PREDICATION.with(|off| { + let previous = off.replace(true); + let why = refusal(&bvh_prefix(case), 512, 2048); + off.set(previous); + why + }); + assert!(why.contains("first-lane read"), "{case:?}: {why}"); + } +} + +#[cfg(windows)] +pub(super) fn in_bounded_gpu_child(test: &str) -> bool { + use std::process::Command; + use std::time::{Duration, Instant}; + + const CHILD: &str = "VICTORY_WAVE_GPU_TEST_CHILD"; + if std::env::var(CHILD).as_deref() == Ok(test) { + return true; + } + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test, "--nocapture"]) + .env(CHILD, test) + .spawn() + .expect("start GPU child"); + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait().expect("poll GPU child") { + assert!(status.success(), "{test} exited {status}"); + return false; + } + if start.elapsed() > Duration::from_secs(45) { + child.kill().expect("terminate stalled GPU child"); + child.wait().expect("reap GPU child"); + panic!("{test} exceeded 45 seconds"); + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +#[test] +#[cfg(windows)] +fn bvh_first_lane_shapes_match_console_on_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::bvh_first_lane_shapes_match_console_on_gpu") { + return; + } + let compare = |words: &[u32], threads, lds, literal, want: &[u32]| { + let (failed, dispatches) = + differences_with_buffer(true, words, threads, 1, want, lds, true, literal, &[0; 4]); + assert!(dispatches > 0, "no hardware dispatch for {threads} threads"); + assert!(failed.is_empty(), "{}", failed.join("\n")); + }; + for threads in [32, 64, 96, 128, 256, 512] { + let (groups, case) = if threads == 512 { + (2, Prefix::TwoGroups) + } else { + (1, Prefix::Stable) + }; + let want: Vec<_> = (0..groups * threads) + .map(|id| { + let wave = (id % threads) / 64; + (0..wave).fold(9, |carry, i| carry ^ (id / threads * 512 + i + 11)) + }) + .collect(); + compare( + &bvh_prefix(case), + threads, + 4 * threads, + threads == 64, + &want, + ); + } + let wave_ids: Vec<_> = (0..128).map(|id| id / 64).collect(); + compare(&bvh_wave_owner(), 128, 512, false, &wave_ids); + // Select single boundary lanes, both half-end lanes, and the empty mask. + // Empty EXEC selects console lane zero, including in a partial tail wave. + for (mask, index) in [(63, 0), (63, 31), (63, 32), (63, 63), (31, 31), (63, 64)] { + let mask_words = [ + 0x3606_0080 | mask, // v_and_b32 v3, mask, v0 + 0x7D84_0680 | index, // v_cmp_eq_u32 vcc, index, v3 + ]; + let words = readfirstlane_in_branch(&mask_words, true, false); + let threads = 96; + let want: Vec<_> = (0..threads) + .map(|id| { + let base = id & !63; + (base..threads.min(base + 64)) + .find(|l| l & mask == index) + .unwrap_or(base) + }) + .collect(); + compare(&words, threads, 0, false, &want); + } +} + +#[derive(Clone, Copy, Debug)] +enum VoteExit { + Straight, + Drain, + Join, + ReplacedExec, +} + +/// Save EXEC, write both EXEC and SCC from a mask, then restore EXEC before +/// using the original SCC to choose a mask. Each selected lane writes 29. +fn wave32_restored_vote(candidate: u32, exit: VoteExit, partial: bool) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v16 = local x * 32 + 0x7e0a_02ab, // v5 = 43 (inactive lanes retain this) + 0xbe98_037e, // save full EXEC in s24 + ]); + if partial { + w.extend([0xbefe_03ff, 0x0000_ffff]); // low 16 lanes + } + w.extend([ + 0xbe92_037e, // save caller's EXEC in s18 + 0x7d84_0080 | candidate.trailing_zeros(), // VCC = candidate lane + 0xbe96_036a, // save the comparison mask in s22 + 0x7da4_0080, // EXEC now contains only lane zero + 0xbe96_4716, // s22 = EXEC = s22 & ~EXEC; SCC = EXEC != 0 + ]); + let branch = w.len(); + match exit { + VoteExit::Straight => {} + VoteExit::Drain => w.push(0xbf89_fffe), // repeat the update while EXEC != 0 + VoteExit::Join => w.push(0xbf89_0000), // empty EXEC falls directly into the select block + VoteExit::ReplacedExec => w.extend([ + 0xbefe_0380, // overwrite EXEC without changing SCC + 0xbf89_fffd, // tests the overwritten EXEC, not the SCC producer's + ]), + } + w.extend([ + 0xbefe_0312, // restore caller's EXEC without changing SCC + 0x7d84_0080, // VCC = (x == 0) + 0x8513_807e, // s19 = SCC ? EXEC : 0 + 0x8814_6a13, // s20 = s19 | VCC + 0xd501_0005, + (128 + 17) | ((128 + 29) << 9) | (20 << 18), // v5 = s20[x] ? 29 : 17 + 0xbefe_0318, // restore full EXEC for readback + ]); + w.extend(store(5, 0)); + w.push(S_ENDPGM); + if matches!(exit, VoteExit::Join) { + // Nonempty EXEC takes a detour back to the same select with SCC still set. + let detour = w.len(); + w[branch] |= (detour - branch - 1) as u32; + let back = (branch as isize - detour as isize) as u16; + w.push(0xbf82_0000 | u32::from(back)); + } + w +} + +#[test] +fn wave32_drained_exec_scc_lowers_at_its_exit() { + for partial in [false, true] { + let candidate = if partial { 1 << 7 } else { 1 << 31 }; + let n = native( + &wave32_restored_vote(candidate, VoteExit::Drain, partial), + false, + 32, + 0, + ); + lower_halves(&n, true, true, false).unwrap(); + } + // A mask update alone cannot prove SCC false. A second incoming edge + // or a branch on a different EXEC cannot prove it either. + for (candidate, exit) in [ + (1, VoteExit::Straight), + (1 << 31, VoteExit::Straight), + (1 << 31, VoteExit::Join), + (1 << 31, VoteExit::ReplacedExec), + ] { + let n = native(&wave32_restored_vote(candidate, exit, false), false, 32, 0); + let why = lower_halves(&n, true, true, false) + .err() + .expect("unproven SCC"); + assert!( + why.to_string().contains("a lane mask read as data"), + "{exit:?}: {why}" + ); + } +} + +#[test] +#[cfg(windows)] +fn wave32_drained_exec_scc_matches_console_on_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::wave32_drained_exec_scc_matches_console_on_gpu") { + return; + } + for partial in [false, true] { + let candidate = if partial { 1 << 7 } else { 1 << 31 }; + let words = wave32_restored_vote(candidate, VoteExit::Drain, partial); + let expected: Vec<_> = (0..32) + .map(|lane| { + if partial && lane >= 16 { + 43 + } else if lane == 0 { + 29 + } else { + 17 + } + }) + .collect(); + let (failed, dispatches) = + differences_with_buffer(false, &words, 32, 1, &expected, 0, true, false, &[0; 4]); + assert!(dispatches > 0, "no wave32 device dispatch"); + assert!(failed.is_empty(), "{}", failed.join("\n")); + } +} + +#[derive(Clone, Copy)] +enum LatchChoice { + Scalar(u32), + LaneVote, + SplitSelector, +} + +/// The first set mask bit selects a lane. Its value and a first-lane +/// result decide whether the scalar counter advances by one or two. +fn two_latch_first_lane(mask: &[u32], choice: LatchChoice) -> Vec { + let mut words = PROLOGUE.to_vec(); + words.extend([ + 0x3420_0085, // v16 = v0 * 32 (output byte offset). + 0x7E04_0280, // v2 = 0 (result before any iteration). + 0xBE9C_0380, // s28 = 0 (iteration count). + ]); + let seed = match choice { + LatchChoice::LaneVote => None, + LatchChoice::Scalar(value) => Some(value), + LatchChoice::SplitSelector => Some(40), + }; + if let Some(seed) = seed { + words.extend(MASK_LANES_40_41); + words.extend([ + 0x8794_6a7e, // s[20:21] = EXEC & VCC + 0xbe99_1414, // s25 = first set bit of s[20:21] + ]); + if matches!(choice, LatchChoice::SplitSelector) { + // The per-lane form takes different incoming edges for this + // scalar phi. An indexed read with that selector can disagree. + words.extend([ + 0x7d88_00a0, + 0xbf87_0002, + 0xbe99_0380, + 0xbf82_0001, + 0xbe99_03a8, + ]); + } + words.extend([0xd760_0018, 0x0000_3300]); // s24 = v0[s25] + words.extend([0x4a0c_0080 | seed, 0x7e34_0506]); // s26 = firstlane(v0 + seed) + } + let head = words.len(); + words.extend([0xBF06_821C, 0]); // s_cmp_eq_u32 s28, 2; s_cbranch_scc1 exit. + words.extend([ + 0x4A08_0087, // v4 = v0 + 7. + 0x4A08_081C, // v4 += s28. + ]); + words.extend_from_slice(mask); + words.extend([ + 0xBE96_246A, // s_and_saveexec_b64 s[22:23], vcc. + 0x7E18_0504, // v_readfirstlane_b32 s12, v4. + 0xBEFE_0416, // s_mov_b64 exec, s[22:23]. + 0x7E04_020C, // v2 = s12. + ]); + let (compare, branch) = match choice { + LatchChoice::LaneVote => (0x7d88_00a0, 0xbf87_0000), // per-lane VCC + _ => (0xbf06_1a18, 0xbf85_0000), // s_cmp_eq_u32 s24, s26 + }; + words.push(compare); + let fork = words.len(); + words.push(0); + words.extend([0x811C_821C, 0]); // s28 += 2; s_branch head. + let choose_one = words.len(); + words.extend([0x811C_811C, 0]); // s28 += 1; s_branch head. + let exit = words.len(); + words.extend(store(2, 0)); + words.push(S_ENDPGM); + for (at, to, opcode) in [ + (head + 1, exit, 0xBF85_0000), + (fork, choose_one, branch), + (fork + 2, head, 0xBF82_0000), + (choose_one + 1, head, 0xBF82_0000), + ] { + words[at] = opcode | u32::from((to as isize - at as isize - 1) as i16 as u16); + } + words +} + +const TWO_LATCH_CASES: [(&[u32], u32); 4] = [ + (&MASK_LANES_8_9, 16), + (&MASK_LANES_40_41, 48), + (&MASK_LANES_12_44, 20), + (&MASK_EMPTY, 8), +]; + +/// Load a dispatch-invariant word from this program's own constant table. +/// Adding zero or one to the broadcast seed selects a different latch. +fn two_latch_code_table(value: u32) -> Vec { + let mut words = two_latch_first_lane(&MASK_LANES_8_9, LatchChoice::Scalar(40)); + let header = words.iter().position(|&w| w == 0xbf06_821c).unwrap(); + let mut load = [ + 0xbe82_1f00, // s_getpc_b64 s[2:3] + 0xf400_0781, + 0xfa00_0000, // s_load_dword s30, s[2:3], table offset + S_WAITCNT_LGKM, + 0x801a_1e1a, // s26 += s30 + ]; + load[2] |= ((words.len() + load.len() - header - 1) * 4) as u32; + words.splice(header..header, load); + words.push(value); + words +} + +#[test] +fn two_latch_code_table_loads_can_choose_the_latch() { + for data in [0, 1] { + let n = native(&two_latch_code_table(data), true, 64, 0); + assert_eq!(lowered_with(&n, true, true).unwrap().wave_size, Some(32)); + } +} + +#[test] +fn two_latch_scalar_reads_lower_in_one_full_wave() { + for (mask, _) in TWO_LATCH_CASES { + for seed in [40, 41] { + let words = two_latch_first_lane(mask, LatchChoice::Scalar(seed)); + let n = native(&words, true, 64, 0); + lowered(&n, false).expect("native wave64 control"); + let split = lowered_with(&n, true, true).expect("one wave in two halves"); + assert_eq!(split.wave_size, Some(32)); + } + } +} + +#[test] +fn two_latch_unproved_arrivals_keep_the_first_lane_refusal() { + let refused = |mask, choice, threads| { + let words = two_latch_first_lane(mask, choice); + let n = native(&words, true, threads, 0); + let error = lowered_with(&n, true, true) + .err() + .expect("unproved exchange"); + assert!( + error + .to_string() + .contains("a first-lane read of a value that may differ"), + "{error}" + ); + }; + for (mask, _) in TWO_LATCH_CASES { + refused(mask, LatchChoice::LaneVote, 64); + } + refused(&MASK_LANES_40_41, LatchChoice::SplitSelector, 64); + for threads in [48, 128] { + refused(&MASK_LANES_8_9, LatchChoice::Scalar(40), threads); + } +} + +#[test] +fn two_latch_waterfall_read_keeps_its_per_lane_value() { + let words = two_latch_first_lane(&MASK_LANES_8_9, LatchChoice::Scalar(40)); + let n = native(&words, true, 64, 0); + // Exercise the resource tracker's contract: it marks descriptor reads + // that forward the lane's own VGPR in place of an actual broadcast. + let result = lower_with_resources(&n, true, true, false, |p, res| { + let value = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name() == "v_readfirstlane_b32") + .find_map(|i| i.write(ir::Reg::S(26))) + .unwrap(); + res.waterfall.reads.push(value); + }); + let error = result + .err() + .expect("a lane-local descriptor read cannot choose a uniform latch"); + assert!( + error + .to_string() + .contains("a first-lane read of a value that may differ"), + "{error}" + ); +} + +#[test] +#[cfg(windows)] +fn two_latch_scalar_reads_match_console_on_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::two_latch_scalar_reads_match_console_on_gpu") { + return; + } + for (data, expected) in [(0, 16), (1, 15)] { + let words = two_latch_code_table(data); + let (failed, dispatches) = differences_with_buffer( + true, + &words, + 64, + 1, + &[expected; 64], + 0, + true, + false, + &[0; 4], + ); + assert!(dispatches > 0, "no code-table dispatch"); + assert!(failed.is_empty(), "{}", failed.join("\n")); + } + for (mask, at_one) in TWO_LATCH_CASES { + // Seed 40 selects the +1 latch and the last iteration is i=1. + // Seed 41 selects +2, exiting immediately after iteration i=0. + for (seed, result) in [(40, at_one), (41, at_one - 1)] { + let words = two_latch_first_lane(mask, LatchChoice::Scalar(seed)); + let (failed, dispatches) = differences_with_buffer( + true, + &words, + 64, + 1, + &[result; 64], + 0, + true, + false, + &[0; 4], + ); + assert!(dispatches > 0, "no hardware dispatch"); + assert!(failed.is_empty(), "{}", failed.join("\n")); + } + } +} + +#[test] +fn two_latch_mutable_scalar_load_cannot_prove_convergence() { + let mut words = two_latch_first_lane(&MASK_LANES_8_9, LatchChoice::Scalar(40)); + let head = words.iter().position(|&w| w == 0xBF06_821C).unwrap(); + // Read a root pointer's word, then write 1 to a distinct word per lane. + // Lane zero writes the one the scalar load just read. The two host + // waves can read different values before arriving at the next exchange. + let add = [ + 0xF400_0781, + 0xFA00_0040, + S_WAITCNT_LGKM, // s30 = *(s[2:3]+0x40) + 0x7e0e_0281, // v7 = 1 + 0x37 << 26 | 0x1C << 18 | 2 << 14 | 0x40, + (2 << 16) | (7 << 8) | 16, + 0x801a_1e1a, // s26 = broadcast_seed + s30 + ]; + words.splice(head..head, add); + let mut n = native(&words, true, 64, 0); + n.layout.push(RootParam { + root: RootType::Constants, + user_data: 2, + slot: 1, + sgprs: 2, + table_offset_dwords: 0, + base_register: 0, + }); + if let StageIo::Cs(cs) = &mut n.io { + cs.rsrc2 = 4 << 1; + } + let result = lowered_with(&n, true, true); + let error = result.err().expect("accepted mutable scalar latch"); + assert!( + error + .to_string() + .contains("a first-lane read of a value that may differ"), + "{error}" + ); +} + +/// The scalar read ignores EXEC. Its dynamic byte offset is lane 40's ID +/// minus 32. Lane zero then overwrites both words at that same address. +fn two_latch_buffer(mask: &[u32]) -> Vec { + let mut words = two_latch_first_lane(mask, LatchChoice::Scalar(40)); + let header = words.iter().position(|&w| w == 0xbf06_821c).unwrap(); + let mut input = vec![0xf408_0b02, 0xfa00_0020, S_WAITCNT_LGKM]; // table SRV s[44:47] + input.extend_from_slice(mask); + input.extend([ + 0xbe96_246a, // save EXEC in s[22:23] and intersect it with VCC + 0xf424_0796, + 0x301f_ffe0, // s_buffer_load_dwordx2 s[30:31], s[44:47], s24-32 + S_WAITCNT_LGKM, + 0xbefe_0416, // restore EXEC + 0x801a_1e1a, // s26 += s30 (latch choice) + 0x7e10_021f, // v8 = s31 (second captured word) + 0x7e0e_0287, // v7 = 7 + ]); + input.extend(store(7, 8)); + input.extend(store(0, 12)); + input.extend(store(8, 4)); + words.splice(header..header, input); + words +} + +#[test] +fn two_latch_buffer_publishes_every_dword() { + for (mask, _) in TWO_LATCH_CASES { + let words = two_latch_buffer(mask); + let n = native(&words, true, 64, 0); + lowered_with(&n, false, true).expect("native wave64 control"); + let split = lowered_with(&n, true, true).expect("published scalar-buffer result"); + let mut constants = words.clone(); + let at = constants.iter().position(|&w| w == 0xf424_0796).unwrap(); + constants[at..at + 2].copy_from_slice(&[0xbe9e_0380, 0xbe9f_0381]); + let control = lowered_with(&native(&constants, true, 64, 0), true, true).unwrap(); + assert_eq!(split.wave_size, Some(32)); + assert_eq!(split.barriers, control.barriers + 4, "two exchanges"); + } +} + +#[test] +fn lockstep_while_preserves_two_latch_scalar_publication() { + let mut words = while_loop_first_lane(true); + words.pop(); + let store_at = words.len() - 2; + words[store_at..].copy_from_slice(&store(2, 16)); + words.extend(&two_latch_buffer(&MASK_LANES_40_41)[PROLOGUE.len()..]); + let split = lowered_with(&native(&words, true, 64, 0), true, true) + .expect("lockstep while and published two-latch loop lower together"); + assert_eq!(split.wave_size, Some(32)); + assert_eq!(live_sources(&split).len(), 2, "both published words stay live"); +} + +#[test] +#[cfg(windows)] +fn two_latch_buffer_matches_pre_store_words_on_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::two_latch_buffer_matches_pre_store_words_on_gpu") + { + return; + } + for (mask, at_one) in TWO_LATCH_CASES { + let words = two_latch_buffer(mask); + for choice in [0, 1] { + let mut input = vec![0x1357_9bdf; 64 * 8]; + input[2] = choice; + input[3] = 0x2468_ace1; + let mut expected = input.clone(); + for (lane, row) in expected.as_chunks_mut::<8>().0.iter_mut().enumerate() { + row[..4].copy_from_slice(&[at_one - choice, input[3], 7, lane as u32]); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&input), + ]; + let (failed, dispatches) = + differences_with_views(true, &words, 64, 8, &expected, 0, true, false, &views); + assert!(dispatches > 0, "no scalar-buffer dispatch"); + assert!(failed.is_empty(), "{}", failed.join("\n")); + } + } +} + +#[test] +fn two_latch_buffer_requires_proved_arrival_and_source() { + let words = two_latch_buffer(&MASK_LANES_8_9); + let refused = |n: &NativeProgram| { + let why = lowered_with(n, true, true) + .err() + .expect("unproved scalar-buffer exchange"); + assert!( + why.to_string() + .contains("a first-lane read of a value that may differ"), + "{why}" + ); + }; + for threads in [48, 128] { + refused(&native(&words, true, threads, 0)); + } + let at = words.iter().position(|&w| w == 0xf424_0796).unwrap(); + for cache_bit in [14, 16] { + let mut coherent = words.clone(); + coherent[at] |= 1 << cache_bit; + refused(&native(&coherent, true, 64, 0)); + } + let n = native(&words, true, 64, 0); + for descriptor in [false, true] { + let error = lower_with_resources(&n, true, true, false, |p, res| { + let read = res + .descriptors + .iter() + .find(|d| p.blocks[d.site.0].insts[d.site.1].name() == "s_buffer_load_dwordx2") + .unwrap(); + if descriptor { + let resource::Source::Loaded { load, .. } = read.source else { + unreachable!() + }; + res.waterfall.loads.push(load); + } else { + let offset = p.blocks[read.site.0].insts[read.site.1] + .read(ir::Reg::S(24)) + .unwrap(); + res.waterfall.reads.push(offset); + } + }) + .err() + .expect("waterfall input to a scalar-buffer read"); + assert!( + error + .to_string() + .contains("a first-lane read of a value that may differ"), + "{error}" + ); + } + let mut cbv = native(&words, true, 64, 0); + cbv.used[1].kind = ResourceType::Cbv; + refused(&cbv); + let mut wide = n.clone(); + wide.used[1].dwords = 8; + refused(&wide); + let mut interior = n.clone(); + interior.used[1].table_offset_dwords -= 1; + refused(&interior); + + // The additional read in the loop supplies the latch choice itself. + let mut inside = words.clone(); + let head = inside.iter().position(|&w| w == 0xbf06_821c).unwrap(); + inside[head + 2..head + 4].copy_from_slice(&words[at..at + 2]); + let first = inside.iter_mut().find(|w| **w == 0x7e18_0504).unwrap(); + *first = 0x7e18_0500; // firstlane(v0), independent of the replaced v4 + let compare = inside.iter_mut().find(|w| **w == 0xbf06_1a18).unwrap(); + *compare = 0xbf06_1a1e; // s_cmp_eq_u32 s30, s26 + refused(&native(&inside, true, 64, 0)); +} + +#[test] +fn two_latch_buffer_requires_bijective_half_ids() { + let mut words = two_latch_buffer(&MASK_LANES_8_9); + let at = words.iter().position(|&w| w == 0x3420_0085).unwrap(); + words.splice(at..at, [0x3406_0285, 0x4a00_0103]); // v0 = y * 32 + x + let mut n = native(&words, true, 64, 0); + n.io = StageIo::Cs(ComputeIo { + rsrc2: 1 << 1 | 1 << 11, + threads: [32, 2, 1], + }); + let lower = |ticket| super::with_thread_ticket(ticket, || lowered_with(&n, true, true)); + assert_eq!(lower(true).unwrap().wave_size, Some(32)); + let why = lower(false) + .err() + .expect("two 16x2 host tiles can round to the same half"); + assert!( + why.to_string() + .contains("a first-lane read of a value that may differ"), + "{why}" + ); +} + +mod indexed; + +pub(super) mod literal_lds; +pub(super) mod literal_publish; +mod terminal_owner; +mod normal_publication; diff --git a/crates/victory-shader/src/emit/halves_tests/indexed.rs b/crates/victory-shader/src/emit/halves_tests/indexed.rs new file mode 100644 index 000000000..97adc1ee9 --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/indexed.rs @@ -0,0 +1,595 @@ +use super::*; + +const MASKS: [u64; 5] = [ + u64::MAX, + 0xffff_ffff, + 0xffff_ffff_0000_0000, + 0, + 0x5050_5050_5050_5050, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Case { + Interval, + LastRegister, + SeparateMove, + KeyEscapes, + KeyPhi, + M0Escapes, + MaskEscapes, + SavedEscapes, + FlagEscapes, + WrongIndex, + WrongSelect, + WrongRetry, + OverwriteIndex, + ExtraWork, + ExtraAccess, + WrongM0, + OutOfFile, + BothIndexed, +} + +fn program(max: u32, active: u64, square: bool, case: Case) -> NativeProgram { + let vop1 = |op: u32, dst: u32, src: u32| 0x7E00_0000 | dst << 17 | op << 9 | src; + let vop2 = |op: u32, dst: u32, src0: u32, src1: u32| op << 25 | dst << 17 | src1 << 9 | src0; + let vcmp = |op: u32, src0: u32, src1: u32| 0x7C00_0000 | op << 17 | src1 << 9 | src0; + let sop1 = |op: u32, dst: u32, src: u32| 0xBE80_0000 | dst << 16 | op << 8 | src; + let sop2_64 = + |op: u32, dst: u32, a: u32, b: u32| 0x8000_0000 | op << 23 | dst << 16 | b << 8 | a; + let set_branch = |words: &mut [u32], op: u32, at: usize, dest: usize| { + let rel = i16::try_from(dest as isize - at as isize - 1).unwrap(); + words[at] = 0xBF80_0000 | op << 16 | u32::from(rel as u16); + }; + let v = |r: u32| 256 + r; + let c = |n: u32| 128 + n; + let exec = 126; + let m0 = 124; + let vcc = 106; + let base = if case == Case::LastRegister { 29 } else { 8 }; + let mut w = PROLOGUE.to_vec(); + if case == Case::SeparateMove { + // A separate in-file relative read of v0. v7 is reused by the selector below. + w.extend([sop1(3, m0, c(0)), vop1(0x43, 7, v(0))]); + } + if square { + w.extend([vop2(0x1a, 1, c(3), 1), vop2(0x25, 0, v(1), 0)]); // v0 = y * 8 + x + } + let (bits, selected) = match active { + u64::MAX => (0, 0), + 0xffff_ffff => (32, 0), + 0xffff_ffff_0000_0000 => (32, 32), + 0 => (0, 1), + 0x5050_5050_5050_5050 => (5, 4), + _ => unreachable!(), + }; + w.extend([ + vop2(0x16, 1, c(5), 0), // v1 = lane >> 5 + vop2(0x1d, 2, v(1), 0), // v2 = lane ^ v1 + vop2(0x1b, 2, c(1), 2), // v2 = lo + vop2(0x16, 3, c(1), 0), // v3 = lane >> 1 + vop2(0x1b, 3, c(3), 3), // v3 &= 3 + vop2(0x13, 3, c(max), 3), // v3 = hi + vop1(1, base, c(10)), // three private array slots + vop1(1, base + 1, c(20)), + vop1(1, base + 2, c(30)), + vop1(1, 11, 40), // v11: unavailable first dword of UAV descriptor + vop1(1, 6, c(0)), + vop2(0x1b, 7, c(bits), 0), + vcmp(0xd2, c(selected), 7), // EXEC from the flat thread ID + vcmp(0xc3, v(2), 3), // v_cmp_le_u32 vcc, v2, v3 + sop1(0x24, 8, vcc), // save full EXEC and select lanes with lo <= hi + 0, // skip loop on the empty selection + sop1(4, 10, exec), // keep the pending lanes of the outer loop + ]); + let after_entry_branch = w.len() - 2; + let outer = w.len(); + w.push(sop1(4, exec, 10)); // outer iteration restores pending lanes + w.push(sop1(4, 12, exec)); // save outer iteration's active set + for write in [false, true] { + let waterfall = w.len(); + let key = if !write && case == Case::KeyPhi { + 24 + } else { + 20 + }; + w.extend([ + vop1(2, key, v(2)), // s20 = current index of first active lane + vcmp(0xc2, key, 2), // compare the same index + sop1(0x24, 14, vcc), // save remaining and select matches + sop1(3, m0, key), + if write { + vop1(0x42, base, v(5)) + } else { + vop1(0x43, 5, v(base)) + }, + sop2_64(0x13, exec, exec, 14), // retry exactly the remaining nonmatches + 0, + ]); + if !write { + match case { + Case::WrongIndex => w[waterfall + 1] = vcmp(0xc2, 20, 3), + Case::WrongSelect => w[waterfall + 2] = sop1(0x24, 14, exec), + Case::WrongM0 => w[waterfall + 3] = sop1(3, m0, c(1)), + Case::OutOfFile => w[waterfall + 4] = vop1(0x43, 5, v(30)), + Case::BothIndexed => w[waterfall + 4] = vop1(0x44, 5, v(8)), + Case::OverwriteIndex => w[waterfall + 4] = vop1(0x43, 2, v(8)), + Case::WrongRetry => w[waterfall + 5] = sop2_64(0x13, exec, vcc, exec), + Case::ExtraWork => w.insert(waterfall + 1, vop2(0x25, 6, c(1), 6)), + Case::ExtraAccess => w.insert(waterfall + 5, vop1(0x43, 6, v(8))), + _ => {} + } + } + if write && case == Case::OverwriteIndex { + // Isolate the read's stability rejection from admission of the separate write loop. + w.insert(waterfall + 5, vop1(1, 6, v(6))); + } + let back = w.len() - 1; + set_branch(&mut w, 9, back, waterfall); + w.push(sop1(4, exec, 12)); // next work starts with the iteration's mask + if !write { + let observed = match case { + Case::KeyEscapes => Some(20), + Case::M0Escapes => Some(m0), + Case::MaskEscapes => Some(vcc), + Case::SavedEscapes => Some(14), + Case::FlagEscapes => Some(253), + _ => None, + }; + if let Some(reg) = observed { + w.push(vop1(1, 6, reg)); + } + w.push(vop2(0x25, 5, v(0), 5)); // update with a lane-specific value + w.push(vop2(0x25, 5, c(1), 5)); + } + } + w.extend([ + vop2(0x25, 2, c(1), 2), // current++ + vcmp(0xd4, v(2), 3), // v_cmpx_gt_u32 exec, v2, v3 + sop2_64(0x15, 10, 10, exec), // retire done lanes + 0, + ]); + let back = w.len() - 1; + set_branch(&mut w, 5, back, outer); + let done = w.len(); + set_branch(&mut w, 8, after_entry_branch, done); + w.extend([ + sop1(4, exec, 8), + vop2(0x1a, 16, c(5), 0), // v16 = 32 bytes per lane + ]); + for (slot, reg) in (base as u8..=base as u8 + 2).enumerate() { + w.extend(store(reg, 4 * slot as u32)); + } + if case == Case::KeyPhi { + w.push(vop1(1, 6, 24)); // join the loop's key with the entry value + } + if !matches!( + case, + Case::Interval | Case::LastRegister | Case::SeparateMove + ) { + w.extend(store(6, 12)); + } + w.push(S_ENDPGM); + let mut n = native(&w, true, 64, 0); + if square { + n.io = StageIo::Cs(ComputeIo { + rsrc2: 1 << 1 | 1 << 11, + threads: [8, 8, 1], + }); + } + n +} + +fn lane_result(lane: u32) -> [u32; 3] { + let lo = (lane ^ (lane >> 5)) & 1; + let hi = ((lane >> 1) & 3).min(2); + let mut array = [10, 20, 30]; + for i in lo..=hi { + array[i as usize] += lane + 1; + } + array +} + +// CPU model of the two equality waterfalls. Each outer iteration reads +// all active lanes' slots and then updates the same lane/slot pairs. +fn grouped(mut pending: u64) -> [[u32; 3]; 64] { + let mut array = [[10, 20, 30]; 64]; + let mut index = std::array::from_fn::<_, 64, _>(|lane| (lane ^ (lane >> 5)) & 1); + let hi = std::array::from_fn::<_, 64, _>(|lane| ((lane >> 1) & 3).min(2)); + for lane in 0..64 { + if index[lane] > hi[lane] { + pending &= !(1 << lane); + } + } + while pending != 0 { + let mut values = [0; 64]; + for write in [false, true] { + let mut remaining = pending; + while remaining != 0 { + let first = remaining.trailing_zeros() as usize; + let slot = index[first]; + for lane in 0..64 { + if remaining & (1 << lane) == 0 || index[lane] != slot { + continue; + } + if write { + array[lane][slot] = values[lane] + lane as u32 + 1; + } else { + values[lane] = array[lane][slot]; + } + remaining &= !(1 << lane); + } + } + } + for lane in 0..64 { + if pending & (1 << lane) != 0 { + index[lane] += 1; + if index[lane] > hi[lane] { + pending &= !(1 << lane); + } + } + } + } + array +} + +/// Range, resource tracking and normal lowering follow the runtime entry point. +fn lower_program(n: &NativeProgram, split: bool) -> Result { + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs)?; + let st = st?; + let res = resource::track(&p, &n.layout, n.stage, Some(&st))?; + let io = io::raise(&p, n)?; + lower::lower_pruned( + &lower::Parts { + native: n, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + view_marks: false, + atomic_locks: false, + atomic_lock_rounds: false, + atomic_umax: false, + bias_as_gradients: false, + narrow_waves: split, + uav_size_level0: false, + halves_rendezvous: true, + host_wave32: split, + }, + None, + false, + false, + ) +} + +#[test] +fn index_groups_match_independent_lane_intervals() { + for active in MASKS { + let actual = grouped(active); + for (lane, row) in actual.iter().enumerate() { + let want = if active & (1 << lane) == 0 { + [10, 20, 30] + } else { + lane_result(lane as u32) + }; + assert_eq!(*row, want, "EXEC={active:#x}, lane={lane}"); + } + } + assert_eq!(lane_result(1), [10, 20, 30]); + assert_eq!(lane_result(6), [17, 27, 37]); + assert_eq!(lane_result(38), [10, 59, 69]); +} + +#[test] +fn bounded_indexed_moves_emit_without_literal_retry() { + for square in [false, true] { + for active in MASKS { + let n = program(2, active, square, Case::Interval); + lower_program(&n, false).expect("native wave64"); + let split = lower_program(&n, true).expect("indexed wave32"); + // The two lane-local moves require neither a host wave size nor a group exchange. + assert_eq!(split.wave_size, None); + assert_eq!(split.barriers, 0); + } + } + let sentinel = program(3, u64::MAX, false, Case::Interval); + for split in [false, true] { + let why = lower_program(&sentinel, split) + .err() + .expect("lane 6 visits descriptor slot 3"); + assert!( + why.to_string() + .contains("a descriptor's address or format read as data"), + "{why}" + ); + } +} + +#[test] +fn proved_last_register_is_in_file() { + let n = program(2, u64::MAX, false, Case::LastRegister); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())).unwrap(); + assert_eq!(res.waterfall.reads.len(), 2); + lower_program(&n, true).expect("wave32, array ends on final VGPR"); +} + +#[test] +fn index_proof_uses_the_bounded_per_lane_ir() { + for max in [2, 3] { + let n = program(max, u64::MAX, false, Case::Interval); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())).unwrap(); + assert_eq!(res.waterfall.reads.len(), 2); + assert_eq!(res.waterfall.compares.len(), 2); + assert!(res.waterfall.loads.is_empty()); + let expected: Vec<_> = (8..=8 + max as u8).map(ir::Reg::V).collect(); + for i in p.blocks.iter().flat_map(|b| &b.insts) { + let slots = match i.name() { + "v_movrels_b32" => i + .reads + .iter() + .take_while(|(r, _)| matches!(r, ir::Reg::V(_))) + .map(|r| r.0) + .collect::>(), + "v_movreld_b32" => i.writes.iter().map(|r| r.0).collect(), + _ => continue, + }; + assert_eq!(slots, expected); + } + let raw = ir::build(&n.code, n.wave64, n.vgprs).unwrap(); + let st = structure::structure(&raw).unwrap(); + assert_range_refusal(resource::track(&raw, &n.layout, n.stage, Some(&st)).unwrap_err()); + let literal = structure::split_literal(&raw).unwrap(); + let res = resource::track(&raw, &n.layout, n.stage, Some(&literal)).unwrap(); + assert!(res.waterfall.reads.is_empty()); + } +} + +fn assert_range_refusal(error: crate::ShaderError) { + assert!( + matches!( + error, + crate::ShaderError::Unsupported { + what: "an indexed-waterfall program with a relative VGPR operand not proved inside its register file", + .. + } + ), + "{error}" + ); +} + +#[test] +fn waterfall_validation_precedes_host_selection() { + let n = program(2, u64::MAX, false, Case::OutOfFile); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let error = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())).unwrap_err(); + assert_range_refusal(error); + + let n = program(2, u64::MAX, false, Case::SeparateMove); + let (mut p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let st = st.unwrap(); + assert_eq!( + resource::track(&p, &n.layout, n.stage, Some(&st)) + .unwrap() + .waterfall + .reads + .len(), + 2 + ); + let separate = p.blocks[0] + .insts + .iter() + .position(|i| i.name() == "v_movrels_b32") + .unwrap(); + assert_eq!(p.blocks[0].insts[separate].m0_max, Some(0)); + // The actual read stays v0. Missing or too loose a proof must veto the whole rewrite. + for bound in [None, Some(32)] { + p.blocks[0].insts[separate].m0_max = bound; + assert_range_refusal(resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap_err()); + } +} + +#[test] +fn index_waterfalls_require_isolated_stable_in_file_access() { + for case in [ + Case::KeyEscapes, + Case::KeyPhi, + Case::M0Escapes, + Case::MaskEscapes, + Case::SavedEscapes, + Case::FlagEscapes, + Case::WrongIndex, + Case::WrongSelect, + Case::WrongRetry, + Case::OverwriteIndex, + Case::ExtraWork, + Case::WrongM0, + Case::BothIndexed, + ] { + let n = program(2, u64::MAX, false, case); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())) + .unwrap_or_else(|e| panic!("{case:?}: {e}")); + let first = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "v_readfirstlane_b32") + .unwrap() + .writes[0] + .1; + assert!( + !res.waterfall.reads.contains(&first), + "{case:?} was rewritten" + ); + if case == Case::KeyPhi { + assert!( + p.blocks + .iter() + .flat_map(|b| &b.phis) + .any(|phi| phi.args.contains(&first)) + ); + } + let why = lower_program(&n, true) + .err() + .unwrap_or_else(|| panic!("{case:?} unexpectedly emitted")); + assert!( + why.to_string() + .contains("a first-lane read of a value that may differ"), + "{case:?}: {why}" + ); + } +} + +#[test] +fn two_bounded_relative_moves_keep_the_per_half_waterfall() { + let n = program(2, u64::MAX, false, Case::ExtraAccess); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())).unwrap(); + let first = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "v_readfirstlane_b32") + .unwrap() + .writes[0] + .1; + assert!( + !res.waterfall.reads.contains(&first), + "two reads need the original loop" + ); + let split = lower_program(&n, true).expect("bounded moves lower independently in each half"); + assert_eq!(split.barriers, 0, "no exchange across host halves"); +} + +#[cfg(windows)] +#[test] +fn indexed_wave32_matches_every_lane_on_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::indexed::indexed_wave32_matches_every_lane_on_gpu", + ) { + return; + } + for square in [false, true] { + for (active, case) in MASKS + .into_iter() + .map(|m| (m, Case::Interval)) + .chain([ + (u64::MAX, Case::LastRegister), + (u64::MAX, Case::ExtraAccess), + ]) + { + let n = program(2, active, square, case); + let form = [( + "halves", + shader(lower_program(&n, true).expect("indexed wave32")), + )]; + let input = vec![0x1357_9bdf; 64 * 8]; + let mut expected = input.clone(); + for (lane, row) in expected.as_chunks_mut::<8>().0.iter_mut().enumerate() { + if active & (1 << lane) != 0 { + row[..3].copy_from_slice(&lane_result(lane as u32)); + if case == Case::ExtraAccess { + let lo = (lane ^ (lane >> 5)) & 1; + let hi = ((lane >> 1) & 3).min(2); + // Last visit reads the final slot before updating it. + row[3] = if lo <= hi { 10 * (hi as u32 + 1) } else { 0 }; + } + } + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Raw, + }, + View::RawUavData(&input), + ]; + let (wrong, dispatches) = compare_dispatches(&form, 1, 8, &expected, &views); + assert!(dispatches > 0, "no indexed dispatch"); + assert!( + wrong.is_empty(), + "{case:?}, square={square}, EXEC={active:#x}: {}", + wrong.join("\n") + ); + } + } +} + +/// Both proofs feed real reads; the lane-select waterfall activates the +/// whole-program admission check on the three preceding scalar-indexed reads. +fn range_proof_program() -> NativeProgram { + use crate::range::tests::{SELECT_TWO_OR_ELEVEN, equality_words, selection_words}; + + let mut words = PROLOGUE.to_vec(); + let equality = equality_words(); + words.extend(&equality[..equality.len() - 1]); + words.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 + for (reg, offset) in [(20, 0), (21, 4), (22, 8)] { + words.extend(store(reg, offset)); + } + let selection = selection_words(SELECT_TWO_OR_ELEVEN); + words.extend(&selection[..selection.len() - 1]); + words.push(0xbefe_04c1); // restore all 64 lanes after the waterfall + words.extend(store(18, 12)); + words.push(S_ENDPGM); + native(&words, true, 64, 0) +} + +#[test] +fn range_proof_fixture_compiles_with_all_four_reads_in_file() { + let n = range_proof_program(); + let (p, st) = crate::range::build(&n.code, n.wave64, n.vgprs).unwrap(); + let relative: Vec<_> = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name() == "v_movrels_b32") + .collect(); + assert_eq!( + relative.iter().map(|i| i.m0_max).collect::>(), + [Some(4), Some(5), Some(6), Some(11)] + ); + assert!(relative.iter().all(|i| i.relative_in_file(p.vgprs))); + let facts = resource::track(&p, &n.layout, n.stage, Some(&st.unwrap())) + .unwrap() + .waterfall; + assert_eq!((facts.reads.len(), facts.compares.len()), (1, 1)); + lower_program(&n, true).unwrap(); +} + +#[cfg(windows)] +#[test] +fn range_proof_reads_match_every_lane_on_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::indexed::range_proof_reads_match_every_lane_on_gpu", + ) { + return; + } + let form = [( + "halves", + shader(lower_program(&range_proof_program(), true).unwrap()), + )]; + let input = vec![0x1357_9bdf; 64 * 8]; + let mut expected = input.clone(); + for (lane, row) in expected.as_chunks_mut::<8>().0.iter_mut().enumerate() { + // Second scalar trip reads v29, v30 and v31. Even lanes select v31, odd lanes v22. + row[..4].copy_from_slice(&[29, 30, 31, if lane % 2 == 0 { 31 } else { 22 }]); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Raw, + }, + View::RawUavData(&input), + ]; + let (wrong, dispatches) = compare_dispatches(&form, 1, 8, &expected, &views); + assert!(dispatches > 0, "no range proof dispatch"); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} diff --git a/crates/victory-shader/src/emit/halves_tests/literal_lds.rs b/crates/victory-shader/src/emit/halves_tests/literal_lds.rs new file mode 100644 index 000000000..e68029f83 --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/literal_lds.rs @@ -0,0 +1,209 @@ +use super::*; + +/// Each lane initializes an adjacent pair. Every visit reads its partner's pair, +/// overwrites its own, then lanes 0 and 32 successively overwrite pair zero. +pub(in crate::emit) fn paired(threads: [u32; 3], bytes: u32) -> NativeProgram { + let valu = |op: u32, dst: u32, src: u32, v: u32| op | dst << 17 | v << 9 | src; + let add = |dst, src, v| valu(0x4a00_0000, dst, src, v); + let shift = |dst, v, bits| valu(0x3400_0000, dst, 128 + bits, v); + let read = |dst: u32, addr| [0xd8dc_0100, dst << 24 | addr, S_WAITCNT_LGKM]; + let write = |addr: u32| [0xd838_0100, 7 << 16 | 6 << 8 | addr, S_WAITCNT_LGKM]; + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0xf408_0b02, + 0xfa00_0020, + S_WAITCNT_LGKM, // input table descriptor + shift(8, 1, threads[0].trailing_zeros()), + add(8, 256, 8), // flat logical lane = x + y * size_x + shift(16, 8, 5), + shift(2, 8, 3), + valu(0x3a00_0000, 4, 160, 8), + shift(4, 4, 3), // partner byte address + 0x7e0a_0280, // v5 = pair zero's byte address + add(6, 130, 8), + add(7, 180, 8), + ]); + w.extend(write(2)); + w.extend([0xbe94_0383, 0xbe98_0380]); // three visits, byte offset zero + let top = w.len(); + w.extend([ + 0xf424_0796, + 0x3000_0000, + S_WAITCNT_LGKM, // two new scalar words each visit + ]); + w.extend(read(10, 4)); + w.extend([add(6, 30, 10), add(7, 31, 11)]); + w.extend(write(2)); + w.push(0xbefe_0481); // EXEC = bit 0 + w.extend(write(2)); + w.extend([0xbefe_0480, 0xbeff_0381]); // EXEC = bit 32 + w.extend(write(4)); + w.push(0xbefe_04c1); // restore every lane + w.extend(read(14, 5)); + for (i, reg) in [10, 11, 6, 7, 14, 15].into_iter().enumerate() { + w.extend(store(reg, 4 * i as u32)); + } + w.extend([0x8018_8818, 0x8094_8114, 0xbf07_8014]); // offset += 8; --trips != 0 + w.push(0xbf85_0000 | (top.wrapping_sub(w.len() + 1) as u32 & 0xffff)); + w.push(S_ENDPGM); + let mut n = native(&w, true, 64, bytes); + n.used[1].kind = ResourceType::Cbv; + let StageIo::Cs(cs) = &mut n.io else { + unreachable!() + }; + cs.threads = threads; + cs.rsrc2 |= 1 << 11; // the guest requests both x and y + n +} + +/// Walk the written CFG including both arms of every per-lane store. A lane +/// can skip either component, but cannot skip a phase fence. Publication +/// fences are absent from this trace. +fn check_phases(out: &lower::Lowered) { + use super::super::bitcode::lds_tests::GuestEvent::*; + use std::collections::HashSet; + let mut seen = HashSet::new(); + let mut pending = vec![(0, None)]; + let mut barriers = [None; 6]; + let mut components: [HashSet<_>; 6] = Default::default(); + while let Some((b, mut phase)) = pending.pop() { + if !seen.insert((b, phase)) { + continue; + } + for (i, event) in out.guest_lds.events[b].iter().enumerate() { + match event { + Fence => { + let next = match phase { + None => 0, + Some(5) => 1, + Some(n) => n + 1, + }; + let expected = barriers[next].get_or_insert((b, i)); + assert_eq!(*expected, (b, i), "a path missed a guest phase fence"); + phase = Some(next); + } + Load | Store => { + let n = phase.expect("a guest phase fence before the access"); + assert_eq!(matches!(event, Load), matches!(n, 1 | 5)); + components[n].insert((b, i)); + } + } + } + let succ = &out.barrier_cfg.0[b]; + if succ.is_empty() { + assert_eq!(phase, Some(5), "exit before the final LDS read"); + } + pending.extend(succ.iter().map(|&s| (s, phase))); + } + assert_eq!( + barriers.into_iter().flatten().collect::>().len(), + 6 + ); + assert_eq!(components.map(|c| c.len()), [2; 6]); +} + +#[test] +fn literal_lds_pairs_have_ordered_phases() { + for threads in [[8, 8, 1], [64, 1, 1]] { + for bytes in [512, 32_256] { + let out = lower_halves(&paired(threads, bytes), true, true, true).unwrap(); + if bytes == 512 { + eprintln!( + "paired LDS {threads:?}, cap {}, {} bytes, DXBC {:02x?}", + super::super::loop_limit(), + out.dxil.len(), + &out.dxil[4..20] + ); + } + assert_eq!(out.wave_size, Some(32)); + assert_eq!(out.split_barriers, 6); + assert_eq!(live_sources(&out), [(None, 0), (None, 1)]); + let mut globals = out.guest_lds.globals.clone(); + globals.sort(); + assert_eq!( + globals, + [ + ("half_words".into(), 2), + ("lds".into(), bytes / 4), + ("wave_ticket".into(), 1) + ] + ); + check_phases(&out); + } + } +} + +const RECORDS: [[u32; 2]; 3] = [[7, 19], [3, 23], [17, 31]]; +const SENTINEL: u32 = 0xa5c3_9b17; + +fn serial(visits: usize) -> Vec { + let mut output = [[SENTINEL; 8]; 64]; + let mut slots: [[u32; 2]; 64] = std::array::from_fn(|l| [l as u32 + 2, l as u32 + 52]); + for record in RECORDS.into_iter().take(visits) { + let partner: [[u32; 2]; 64] = std::array::from_fn(|l| slots[l ^ 32]); + let own: [[u32; 2]; 64] = partner.map(|p| [p[0] + record[0], p[1] + record[1]]); + slots = own; + for (mask, address_xor) in [(1u64, 0), (1u64 << 32, 32)] { + for (l, value) in own.iter().enumerate() { + if mask & (1 << l) != 0 { + slots[l ^ address_xor] = *value; + } + } + } + for (l, row) in output.iter_mut().enumerate() { + row[..2].copy_from_slice(&partner[l]); + row[2..4].copy_from_slice(&own[l]); + row[4..6].copy_from_slice(&slots[0]); + } + } + output.concat() +} + +#[test] +fn literal_lds_serial_opposite_writers() { + let one = serial(1); + assert_eq!(&one[..8], &[34, 84, 41, 103, 9, 71, SENTINEL, SENTINEL]); + let two = serial(2); + assert_eq!( + &two[32 * 8..33 * 8], + &[9, 71, 12, 94, 12, 94, SENTINEL, SENTINEL] + ); + assert_ne!(two, serial(3)); +} + +#[cfg(windows)] +#[test] +fn literal_lds_pairs_match_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::literal_lds::literal_lds_pairs_match_gpu") { + return; + } + let input = RECORDS.concat(); + let start = vec![SENTINEL; 64 * 8]; + let views = [ + View::Texture(1, 1, &[[0.; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&start), + ]; + let limit = super::super::loop_limit(); + let want = serial(limit as usize); + for threads in [[8, 8, 1], [64, 1, 1]] { + let out = lower_halves(&paired(threads, 512), true, true, true).unwrap(); + eprintln!( + "paired LDS {threads:?}, cap {limit}, {} bytes, DXBC {:02x?}", + out.dxil.len(), + &out.dxil[4..20] + ); + let (errors, ran) = + compare_dispatches(&[("publication wave32", shader(out))], 1, 8, &want, &views); + assert!(ran > 0, "no physical wave32 device"); + assert!( + errors.is_empty(), + "{threads:?} cap {limit}: {}", + errors.join("\n") + ); + eprintln!("matched {} words (128 untouched) {want:?}", want.len()); + } +} diff --git a/crates/victory-shader/src/emit/halves_tests/literal_publish.rs b/crates/victory-shader/src/emit/halves_tests/literal_publish.rs new file mode 100644 index 000000000..923a99384 --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/literal_publish.rs @@ -0,0 +1,554 @@ +use super::*; + +pub(in crate::emit) fn program(mask: &[u32]) -> Vec { + publication(mask, None) +} + +fn publication(mask: &[u32], cbv_width: Option) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0xf408_0b02, + 0xfa00_0020, + S_WAITCNT_LGKM, // table buffer descriptor s[44:47] + 0x3420_0085, // v16 = 32 * lane + ]); + if cbv_width.is_some() { + w.push(0xbe9c_0382); // enter the inner loop twice + } + let entry = w.len(); + w.extend([ + 0xf420_0516, + 0xfa00_0000, + S_WAITCNT_LGKM, // s20 = trips + ]); + let width_op = cbv_width.map_or(1, u32::trailing_zeros) << 18; + if cbv_width.is_some() { + w.extend([ + 0xf420_0896 | width_op, + 0xfa00_0010, + S_WAITCNT_LGKM, // s[34..] = initial markers, immediate byte offset 16 + 0xbe98_03a0, // s24 = first visit record's byte offset, 32 + ]); + } else { + w.extend([ + 0xbe98_0388, // s24 = first pair's byte offset, 8 + 0xbe9a_0380, // s26 = sum of visit markers + ]); + } + w.push(0xbf06_8014); // trips == 0 + let zero = w.len(); + w.push(0); + let top = w.len(); + w.extend(mask); + w.extend([ + 0x87fe_6a7e, // exec &= vcc + 0xf420_0796 | width_op, + 0x3000_0000, + S_WAITCNT_LGKM, // visit record at s24, even if EXEC is empty + ]); + if let Some(width) = cbv_width { + for k in 0..width { + let total = 34 + k; + let word = 30 + k; + w.push(0x8000_0000 | total << 16 | word << 8 | total); // componentwise sum + } + } else { + w.push(0x801a_1f1a); // s26 += marker + } + w.push(0xbf06_801e); // A zero width skips this reservation. + let skip_width = w.len(); + w.push(0); + let empty = w.len(); + w.push(0); + w.extend([ + 0xbe8c_147e, // s12 = first active lane + 0xbe8d_107e, // s13 = active count + 0x930d_1e0d, // total = count * width + 0xd765_000a, + 0x0001_007e, // v10 = rank in EXEC + 0xd766_000a, + 0x0002_147f, + 0x7d84_000c, // vcc = lane == leader + 0xbe96_246a, // save mask and elect leader + 0x7e0c_020d, // v6 = total + 0xe0c8_401c, + 0x800a_0600, // reserve total, returning old counter + 0xbf8c_3f70, // wait for VMEM result + 0x7e1e_0506, // s15 = leader's returned base + 0xbefe_0416, // restore work mask + 0xd569_000a, + 0x0200_3d0a, // v10 *= width + 0x4a14_140f, // v10 += base + ]); + w.extend(store(10, 4)); + w[skip_width] = 0xbf85_0000 | (w.len() - skip_width - 1) as u32; + w[empty] = 0xbf88_0000 | (w.len() - empty - 1) as u32; + w.extend([ + 0xbefe_04c1, // restore full EXEC + if cbv_width.is_some() { + 0x8018_9018 + } else { + 0x8018_8818 + }, // step to next record + 0x8094_8114, // --trips + 0xbf07_8014, // trips != 0 + ]); + w.push(0xbf85_0000 | ((top as i32 - w.len() as i32 - 1) as u32 & 0xffff)); + w[zero] = 0xbf85_0000 | (w.len() - zero - 1) as u32; + if let Some(width) = cbv_width { + for (k, slot) in (0..width).zip(MARK_SLOTS) { + w.push(0x7e0c_0200 | (34 + k)); // v6 = sum for this component + w.extend(store(6, slot as u32 * 4)); + } + w.extend([0x809c_811c, 0xbf07_801c]); // --s28 != 0 + w.push(0xbf85_0000 | ((entry as i32 - w.len() as i32 - 1) as u32 & 0xffff)); + } else { + w.push(0x7e0c_021a); // v6 = markers visited (also under empty EXEC) + w.extend(store(6, 0)); + } + w.push(S_ENDPGM); + w +} + +#[test] +fn literal_publication_captures_each_visit() { + let words = program(&MASK_LANES_40_41); + let lower = + |words: &[u32]| lower_halves(&native(words, true, 64, 0), true, true, true).unwrap(); + let split = lower(&words); + assert_eq!( + live_sources(&split), + [(Some(0), 0), (None, 0), (None, 1)], + "live lower-half words" + ); + let mut fixed = words.clone(); + fixed[5..7].fill(0xbf80_0000); + let count = fixed.iter().position(|&w| w == 0xf420_0516).unwrap(); + fixed[count..count + 2].copy_from_slice(&[0xbe94_0383, 0xbf80_0000]); + let pair = fixed.iter().position(|&w| w == 0xf424_0796).unwrap(); + fixed[pair..pair + 2].copy_from_slice(&[0xbe9e_0383, 0xbe9f_0382]); + assert_eq!( + split.barriers, + lower(&fixed).barriers + 6, + "three scalar dword exchanges" + ); +} + +fn fixed_table_cbv(mask: &[u32], width: u32) -> NativeProgram { + let mut n = native(&publication(mask, Some(width)), true, 64, 0); + n.used[1].kind = ResourceType::Cbv; + n +} + +#[test] +fn literal_publication_fixed_table_cbv() { + for width in [1, 2, 4] { + for (lanes, _) in MASKS { + let n = fixed_table_cbv(lanes, width); + let out = lower_halves(&n, true, true, true).unwrap(); + let components = std::iter::once((Some(0), 0)) + .chain((0..width).map(|k| (Some(16), k))) + .chain((0..width).map(|k| (None, k))); + assert_eq!(live_sources(&out), components.collect::>()); + let mask = Some(i64::from((1 << width) - 1)); + assert_eq!( + out.raw_load_args, + [(Some(0), Some(1)), (Some(16), mask), (None, mask)] + ); + assert_eq!(out.wave_size, Some(32)); + } + } +} + +const MASKS: [(&[u32], u64); 5] = [ + (&[0x7d84_0100], u64::MAX), // v_cmp_eq_u32 vcc, v0, v0 + (&MASK_LANES_8_9, 3 << 8), + (&MASK_LANES_40_41, 3 << 40), + (&MASK_LANES_12_44, 1 << 12 | 1 << 44), + (&MASK_EMPTY, 0), +]; + +const MARK: u32 = 0x1357_9bdf; +const PAIRS: [(u32, u32); 3] = [(3, 19), (0, 31), (5, 43)]; + +const CBV_INITIAL: [u32; 4] = [13, 23, 37, 47]; +const CBV_RECORDS: [[u32; 4]; 3] = [[3, 19, 59, 67], [7, 31, 73, 89], [5, 43, 97, 113]]; +const MARK_SLOTS: [usize; 4] = [0, 2, 3, 4]; + +fn expected( + active: u64, + trips: usize, + entries: usize, + limit: usize, + cbv_width: Option, +) -> Vec { + let mut rows = [[MARK; 8]; 64]; + let mut counter = 11; + for _ in 0..entries.min(limit) { + let mut totals = if cbv_width.is_some() { + CBV_INITIAL + } else { + [0; 4] + }; + for i in 0..trips.min(limit) { + let (width, record) = if cbv_width.is_some() { + let record = CBV_RECORDS[i]; + (record[0], record) + } else { + let (width, marker) = PAIRS[i]; + (width, [width, marker, 0, 0]) + }; + for (total, value) in totals.iter_mut().zip(record) { + *total += value; + } + for (lane, row) in rows.iter_mut().enumerate() { + if width > 0 && active & (1 << lane) != 0 { + row[1] = counter; + counter += width; + } + } + } + for row in &mut rows { + if let Some(width) = cbv_width { + for (slot, total) in MARK_SLOTS.into_iter().zip(totals).take(width) { + row[slot] = total; + } + } else { + row[0] = totals[1]; + } + } + } + rows[0][7] = counter; + rows.concat() +} + +#[test] +fn literal_publication_trace_is_per_visit() { + // Each tuple is one allowed observation by each half on that visit. + // A reservation runs on the nonzero branch. Only one common snapshot + // per visit follows one legal wave trace throughout. + let reads = [(0, 3), (3, 0), (0, 5)]; + let trace = |select: fn(usize, (u32, u32)) -> (u32, u32)| { + let mut trace = [Vec::new(), Vec::new()]; + for (i, &pair) in reads.iter().enumerate() { + let (lo, hi) = select(i, pair); + trace[0].push(lo != 0); + trace[1].push(hi != 0); + } + trace + }; + let wanted = vec![false, true, false]; + assert_eq!(trace(|_, (lo, _)| (lo, lo)), [wanted.clone(), wanted]); + for [lo, hi] in [ + trace(|_, pair| pair), + trace(|i, (lo, hi)| (lo, if i == 0 { lo } else { hi })), + ] { + assert_ne!(lo, hi); + } + let upper = expected(3 << 40, 1, 1, 8, None); + assert_eq!( + [upper[40 * 8 + 1], upper[41 * 8 + 1], upper[7]], + [11, 14, 17] + ); + let empty = expected(0, 3, 2, 1, None); + assert_eq!((empty[7], empty[0], empty[1]), (11, 19, MARK)); + assert_eq!(expected(3 << 40, 3, 2, 2, None)[7], 23); + let cbv = expected(3 << 40, 3, 2, 2, Some(4)); + assert_eq!(cbv[..8], [23, MARK, 73, 169, 203, MARK, MARK, 51]); + assert_eq!(cbv[40 * 8 + 1], 37); + assert_eq!(cbv[41 * 8 + 1], 44); +} + +#[cfg(windows)] +#[test] +fn literal_publication_matches_gpu() { + if !in_bounded_gpu_child("emit::halves_tests::literal_publish::literal_publication_matches_gpu") + { + return; + } + for (mask, bits) in MASKS { + let mut words = program(mask); + let entry = words.iter().position(|&w| w == 0xf420_0516).unwrap(); + words.insert(entry, 0xbe9c_0382); // two separate entries into the inner loop + words.pop(); + words.extend([0x809c_811c, 0xbf07_801c]); // --s28 != 0 + words.push(0xbf85_0000 | ((entry as i32 - words.len() as i32) as u32 & 0xffff)); + words.push(S_ENDPGM); + let n = native(&words, true, 64, 0); + let forms = [( + "publication wave32", + shader(lower_halves(&n, true, true, true).unwrap()), + )]; + for trips in [0, 1, 3] { + let mut input = [0u32; 8]; + input[0] = trips as u32; + for (pair, (width, marker)) in input[2..].as_chunks_mut::<2>().0.iter_mut().zip(PAIRS) { + pair.copy_from_slice(&[width, marker]); + } + let mut start = vec![MARK; 64 * 8]; + start[7] = 11; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&start), + ]; + let want = expected(bits, trips, 2, super::super::loop_limit() as usize, None); + let (errors, ran) = compare_dispatches(&forms, 1, 8, &want, &views); + assert!(ran > 0, "no physical wave32 device"); + assert!( + errors.is_empty(), + "mask {bits:#x}, trips {trips}: {}", + errors.join("\n") + ); + } + } +} + +#[cfg(windows)] +#[test] +fn literal_publication_fixed_table_cbv_matches_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::literal_publish::literal_publication_fixed_table_cbv_matches_gpu", + ) { + return; + } + let limit = super::super::loop_limit() as usize; + for width in [1, 2, 4] { + for (mask, bits) in MASKS { + let n = fixed_table_cbv(mask, width); + let out = lower_halves(&n, true, true, true).unwrap(); + eprintln!( + "cap {limit} CBV x{width} mask {bits:#018x}: {} bytes, checksum {:02x?}", + out.dxil.len(), + &out.dxil[4..20] + ); + let forms = [("publication wave32", shader(out))]; + for trips in [0, 1, 3] { + let mut input = vec![trips as u32, 0, 0, 0]; + input.extend(CBV_INITIAL); + input.extend(CBV_RECORDS.into_iter().flatten()); + let mut start = vec![MARK; 64 * 8]; + start[7] = 11; + // The guest declares a CBV, but the runtime binds a raw SRV. + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&start), + ]; + let want = expected(bits, trips, 2, limit, Some(width as usize)); + let (errors, ran) = compare_dispatches(&forms, 1, 8, &want, &views); + assert!(ran > 0, "no physical wave32 device"); + assert!( + errors.is_empty(), + "CBV x{width}, mask {bits:#x}, trips {trips}, cap {limit}: {}", + errors.join("\n") + ); + } + } + } +} + +/// Exercise the final literal IR directly, including rejected geometries +/// which the normal retry dispatcher already excludes. +fn refused( + n: &NativeProgram, + change: impl FnOnce(&mut ir::Program, &mut structure::Structured, &mut resource::Resources), + reason: &str, +) { + let mut p = ir::build(&n.code, true, n.vgprs).unwrap(); + let mut st = structure::split_literal(&p).unwrap(); + let mut res = resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + change(&mut p, &mut st, &mut res); + let io = io::raise(&p, n).unwrap(); + let err = lower::lower(&parts(n, &p, &st, &res, &io, true, true)) + .err() + .expect("unsafe publication accepted"); + assert!(err.to_string().contains(reason), "{err}"); +} + +#[test] +fn literal_publication_requires_full_wave_and_exact_source() { + let words = program(&MASK_LANES_40_41); + let geometry = "one ticketed wave64 and zero guest LDS"; + for (threads, lds) in [(48, 0), (128, 0), (64, 512)] { + refused(&native(&words, true, threads, lds), |_, _, _| {}, geometry); + } + let n = native(&words, true, 64, 0); + super::super::with_thread_ticket(false, || refused(&n, |_, _, _| {}, geometry)); + let pair = words.iter().position(|&w| w == 0xf424_0796).unwrap(); + let mut ordinary = words.clone(); + ordinary[pair] = 0xf404_0782; // s_load_dwordx2 s[30:31], s[4:5], s24 + refused( + &native(&ordinary, true, 64, 0), + |_, _, _| {}, + "unsupported source or width", + ); + let mut descriptor_data = words.clone(); + let out = descriptor_data + .iter() + .position(|&w| w == 0x7e0c_021a) + .unwrap(); + descriptor_data[out] = 0x7e0c_022c; // v6 = numeric word zero of the SRV + refused( + &native(&descriptor_data, true, 64, 0), + |_, _, _| {}, + "descriptor word read as numeric data", + ); + for bit in [14, 16] { + let mut changed = words.clone(); + changed[pair] |= 1 << bit; + refused( + &native(&changed, true, 64, 0), + |_, _, _| {}, + "cached or predicated", + ); + } + let mut wide = words.clone(); + wide[pair] = 0xf42c_0796; // x8 + refused( + &native(&wide, true, 64, 0), + |_, _, _| {}, + "unsupported source or width", + ); + let mut interior = n.clone(); + interior.used[1].table_offset_dwords -= 1; + refused(&interior, |_, _, _| {}, "unsupported source or width"); + let mut uav = n.clone(); + uav.used[1].kind = ResourceType::Uav; + refused(&uav, |_, _, _| {}, "unsupported source or width"); + for (which, reason) in [ + (0, "a resource waterfall"), + (1, "cached or predicated"), + (2, "unsupported source or width"), + ] { + refused( + &n, + |p, st, res| { + let desc = res + .descriptors + .iter_mut() + .find(|d| p.blocks[d.site.0].insts[d.site.1].name() == "s_buffer_load_dwordx2") + .unwrap(); + let (b, i) = desc.site; + match which { + 0 => res.waterfall.loads.push(desc.site), + 1 => st.guards[b][i] = Some(structure::Bool::FALSE), + _ => desc.source = resource::Source::Constant(vec![0; 4]), + } + }, + reason, + ); + } +} + +#[test] +fn literal_publication_requires_initialized_phi_and_common_edges() { + let words = program(&MASK_LANES_40_41); + let init = words.iter().position(|&w| w == 0xbe98_0388).unwrap(); + for source in [0xbf80_0000, 0xb918_0004] { + // missing phi entry, hardware state as entry offset + let mut changed = words.clone(); + changed[init] = source; + refused( + &native(&changed, true, 64, 0), + |_, _, _| {}, + "without common initialized operands", + ); + } + + let unknown = 0xb909_0004; // hardware state may differ by half + let compare = 0xbf06_8009; + for (tested, branch) in [ + (0xbf06_8014, None), // one half can leave before the loop + (0xbf07_8014, None), // divergent counter histories at the latch + (0xbf06_801e, Some(0xbf85_0001)), // two edges join after a single NOP + ] { + let mut changed = words.clone(); + let i = changed.iter().position(|&w| w == tested).unwrap(); + // Replace a same-size compare pair; keep branch destinations intact. + changed[i] = compare; + changed[init + 1] = unknown; // overwrites the marker sum initialization + if let Some(branch) = branch { + changed[i + 1] = branch; + changed[i + 2] = 0xbf80_0000; + } + refused( + &native(&changed, true, 64, 0), + |_, _, _| {}, + "branch without common group control flow", + ); + } +} + +#[test] +fn literal_publication_cbv_requires_all_descriptor_and_destination_dwords() { + let mut words = program(&MASK_LANES_40_41); + let pair = words.iter().position(|&w| w == 0xf424_0796).unwrap(); + words[pair] = 0xf428_0796; + let mut n = native(&words, true, 64, 0); + n.used[1].kind = ResourceType::Cbv; + for (reg, op, reason) in [ + (47, "s_load_dwordx4", "unsupported source or width"), + (33, "s_buffer_load_dwordx4", "guarded or incomplete"), + ] { + refused( + &n, + |p, _, _| { + let reg = ir::Reg::S(reg); + let def = p + .blocks + .iter_mut() + .flat_map(|b| &mut b.insts) + .find(|i| i.name() == op && i.write(reg).is_some()) + .unwrap(); + def.writes.retain(|&(r, _)| r != reg); + }, + reason, + ); + } +} + +#[test] +fn literal_publication_four_dwords_include_unused_components() { + let mut words = program(&MASK_LANES_40_41); + let pair = words.iter().position(|&w| w == 0xf424_0796).unwrap(); + words[pair] = 0xf428_0796; + let unused = words.clone(); + // Give the additional components real consumers without changing the CFG. + words[pair + 3] = 0x801a_201f; // s26 = s31 + s32 + let add = words.iter().position(|&w| w == 0x8018_8818).unwrap(); + words.splice(add..add, [0x801a_211a]); // s26 += s33 + // One added instruction between each forward skip and the latch. + let back = words + .iter_mut() + .find(|w| **w & 0xffff_8000 == 0xbf85_8000) + .unwrap(); + *back -= 1; + let zero = words.iter_mut().find(|w| **w >> 16 == 0xbf85).unwrap(); + *zero += 1; + for kind in [ResourceType::Srv, ResourceType::Cbv] { + let lower = |words: &[u32]| { + let mut n = native(words, true, 64, 0); + n.used[1].kind = kind; + lower_halves(&n, true, true, true).unwrap() + }; + let used = lower(&words); + assert_eq!( + live_sources(&used), + [(Some(0), 0), (None, 0), (None, 1), (None, 2), (None, 3)] + ); + assert_eq!( + used.barriers, + lower(&unused).barriers, + "unused dwords must still publish" + ); + } +} + +pub(in crate::emit) mod wide; diff --git a/crates/victory-shader/src/emit/halves_tests/literal_publish/wide.rs b/crates/victory-shader/src/emit/halves_tests/literal_publish/wide.rs new file mode 100644 index 000000000..683e9e6d4 --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/literal_publish/wide.rs @@ -0,0 +1,193 @@ +use super::*; + +pub(in crate::emit) fn fixture( + width: u32, + kind: ResourceType, + mask: &[u32], + sparse: bool, +) -> NativeProgram { + let op = 0xf420_0016 | width.trailing_zeros() << 18; // table s[44:47] + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0xf408_0b02, + 0xfa00_0020, + S_WAITCNT_LGKM, + 0x3420_0087, // v16 = 128 * lane + 0xf420_0516, + 0xfa00_0000, + S_WAITCNT_LGKM, // s20 = trips + ]); + let used = |k: u32| !sparse || k == width - 1; + for k in (0..width).filter(|&k| used(k)) { + w.push(0xbe80_0380 | (64 + k) << 16); // initialize each accumulator + } + w.push(0xbf06_8014); // trips == 0 + let skip = w.len(); + w.push(0); + let top = w.len(); + w.extend(mask); + w.extend([0x87fe_6a7e, 0xbf06_8214]); // exec &= vcc; remaining trips == 2 + let select = w.len(); + w.push(0); + let record = |w: &mut Vec, byte: u32, tag: u32| { + w.extend([op | 80 << 6, 0xfa00_0000 | byte, S_WAITCNT_LGKM]); // s[80..] + for k in (0..width).filter(|&k| used(k)) { + let word = 80 + k; + w.push(0x8000_0000 | word << 16 | (128 + tag + k) << 8 | word); + } + }; + record(&mut w, 4, 1); + let join = w.len(); + w.push(0); + w[select] = 0xbf85_0000 | (w.len() - select - 1) as u32; + record(&mut w, 84, 17); + w[join] = 0xbf82_0000 | (w.len() - join - 1) as u32; + for k in (0..width).filter(|&k| used(k)) { + let total = 64 + k; + w.push(0x8000_0000 | total << 16 | (80 + k) << 8 | total); + } + w.push(0x7e0c_0214); // active lanes record the remaining trips + w.extend(store(6, 120)); + w.extend([0xbefe_04c1, 0x8094_8114, 0xbf07_8014]); // full EXEC, --trips != 0 + w.push(0xbf85_0000 | ((top as i32 - w.len() as i32 - 1) as u32 & 0xffff)); + w[skip] = 0xbf85_0000 | (w.len() - skip - 1) as u32; + for k in (0..width).filter(|&k| used(k)) { + w.push(0x7e0c_0200 | (64 + k)); // store the corresponding SGPR + w.extend(store(6, 4 * k)); + } + w.push(S_ENDPGM); + let mut n = native(&w, true, 64, 0); + n.used[1].kind = kind; + n +} + +#[test] +fn literal_publication_wide_dataflow() { + for kind in [ResourceType::Srv, ResourceType::Cbv] { + for width in [8, 16] { + for (mask, _) in MASKS { + for sparse in [false, true] { + let n = fixture(width, kind, mask, sparse); + let out = lower_halves(&n, true, true, true).unwrap(); + assert_eq!(out.wave_size, Some(32)); + let mut chunks = out.raw_load_args.clone(); + chunks.sort_unstable(); + let expected_chunks = std::iter::once((Some(0), Some(1))) + .chain([4, 84].into_iter().flat_map(|base| { + (0..width / 4).map(move |j| (Some(base + 16 * i64::from(j)), Some(15))) + })) + .collect::>(); + assert_eq!(chunks, expected_chunks); + let exchanges = &out.live_scalar_exchanges; + assert_eq!(exchanges.len(), (1 + 2 * width) as usize); + assert_eq!(exchanges[0].source, (Some(0), 0)); + assert!(exchanges[0].lower_read); + let mut records = exchanges[1..] + .chunks_exact(width as usize) + .collect::>(); + records.sort_by_key(|run| run[0].source.0); + for (record, (run, base)) in records.into_iter().zip([4, 84]).enumerate() { + for (k, x) in (0..width).zip(run) { + assert_eq!(x.source, (Some(base + i64::from(k / 4) * 16), k % 4)); + let used = !sparse || k == width - 1; + assert_eq!(x.lower_read, used); + assert_eq!( + x.addend, + used.then_some(1 + 16 * record as i64 + i64::from(k)) + ); + } + } + } + } + } + } +} + +const SEEDS: [u32; 16] = [3, 7, 11, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]; +const RECORD: [u32; 16] = [ + 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, +]; + +fn expected_words(width: usize, sparse: bool, mask: u64, trips: u32, cap: u32) -> Vec { + let mut rows = [[MARK; 32]; 64]; + let visits = trips.min(cap); + for (lane, row) in rows.iter_mut().enumerate() { + for k in 0..width { + if !sparse || k == width - 1 { + row[k] = (0..visits) + .map(|visit| { + if trips - visit == 2 { + RECORD[k] + 17 + k as u32 + } else { + SEEDS[k] + 1 + k as u32 + } + }) + .sum(); + } + } + if visits != 0 && mask & (1 << lane) != 0 { + row[30] = trips - visits + 1; + } + } + rows.concat() +} + +#[test] +fn literal_publication_wide_expected_words() { + let out = expected_words(16, true, 1 << 40, 3, 2); + assert_eq!(out.len(), 2048); + assert_eq!(out[15], 270); // 71 + 16 on visit one, 151 + 32 on visit two + assert_eq!(out[40 * 32 + 30], 2); + assert_eq!(out.iter().filter(|&&x| x == MARK).count(), 1983); +} + +#[cfg(windows)] +#[test] +fn literal_publication_wide_matches_gpu() { + if !in_bounded_gpu_child( + concat!(module_path!(), "::literal_publication_wide_matches_gpu") + .trim_start_matches("victory_shader::"), + ) { + return; + } + let cap = crate::emit::loop_limit(); + for kind in [ResourceType::Srv, ResourceType::Cbv] { + for width in [8, 16] { + for (mask, bits) in MASKS { + for sparse in [false, true] { + let out = lower_halves(&fixture(width, kind, mask, sparse), true, true, true) + .unwrap(); + eprintln!( + "cap {cap} {kind:?} x{width} mask {bits:016x} sparse {sparse}: {} bytes, checksum {:02x?}", + out.dxil.len(), + &out.dxil[4..20] + ); + let forms = [("publication wave32", shader(out))]; + for trips in [0, 3] { + let mut input = vec![trips]; + input.extend(SEEDS); + input.resize(21, MARK); + input.extend_from_slice(&RECORD[..width as usize]); + let start = vec![MARK; 64 * 32]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&start), + ]; + let want = expected_words(width as usize, sparse, bits, trips, cap); + let (errors, ran) = compare_dispatches(&forms, 1, 32, &want, &views); + assert!(ran > 0, "no physical wave32 device"); + assert!( + errors.is_empty(), + "{kind:?} x{width}, mask {bits:x}, trips {trips}, sparse {sparse}, cap {cap}: {}", + errors.join("\n") + ); + } + } + } + } + } +} diff --git a/crates/victory-shader/src/emit/halves_tests/normal_publication.rs b/crates/victory-shader/src/emit/halves_tests/normal_publication.rs new file mode 100644 index 000000000..dbd09399b --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/normal_publication.rs @@ -0,0 +1,375 @@ +use super::*; + +mod saved_exec; + +/// Group 0 conditionally loads a pair. Group 1 either skips or reads its own pair. +/// The first merged scalar chooses the loop latch. The join reads both SGPRs after EXEC is restored. +fn program(mask: &[u32], per_group: bool) -> Vec { + let mut w = two_latch_first_lane(&MASK_LANES_8_9, LatchChoice::Scalar(40)); + let iteration = w.iter().position(|&x| x == 0xbf06_1a18).unwrap(); + w.splice(iteration..iteration, store(2, 12)); + // The added per-iteration store shifts both back edges and the exit. + let header = w.iter().position(|&x| x == 0xbf06_821c).unwrap(); + w[header + 1] += 2; + for word in &mut w[iteration..] { + if *word >> 16 == 0xbf82 && *word & 0x8000 != 0 { + *word -= 2; + } + } + let mut prefix = vec![ + 0x8f0f_8601, // s15 = group_id.x << 6 + 0x4a22_000f, // v17 = group base + lane + 0x3420_2285, // v16 = byte offset of output row + 0xf408_0b02, + 0xfa00_0020, // load the fixed table SRV + S_WAITCNT_LGKM, + 0xbe9e_0391, // old s30 = 17 + 0x801f_9501, // old s31 = group_id.x + 21 + ]; + // A compare on the global ID makes the second group empty. + if per_group { + prefix.push(0x8f12_8301); // s18 = group_id.x * 8 + prefix.push(mask[0]); // use local lanes; both groups can enter + } else if mask == MASK_LANES_12_44 { + prefix.extend([0x3606_22ff, 95]); // v3 = global ID & 95 + } else { + prefix.push(mask[0] | (17 << 9)); + } + prefix.push(mask[1]); + prefix.extend([ + 0xbe96_246a, // save and intersect EXEC + 0xbf88_0005, // skip the body on empty EXEC + 0x7e1c_0500, // firstlane(v0) requires converged execution in this arm + 0xbefe_0480, // clear EXEC inside the visited arm; SMEM still executes + 0xf424_0796, + if per_group { 0x2400_0008 } else { 0xfa00_0008 }, + S_WAITCNT_LGKM, + 0xbefe_0416, // restore full EXEC + 0x7e0c_021e, // v6 = merged s30 + 0x7e0e_021f, // v7 = merged s31 + ]); + prefix.extend([ + 0x7e24_0506, // s18 = firstlane(v6), full EXEC after the join + 0x8712_8112, // low bit of the merged first word + 0x801a_121a, // an even first word chooses the +1 loop latch + ]); + prefix.extend(store(6, 4)); + prefix.extend(store(7, 8)); + w.splice(header..header, prefix); + w +} + +#[test] +fn predicated_fixed_pair_publishes_both_components() { + for (mask, _) in TWO_LATCH_CASES { + for dynamic in [false, true] { + let mut w = program(mask, dynamic); + let n = native_for_groups(&w, true, 64, 0, 2); + let split = lowered_with(&n, true, true).expect("predicated normal publication"); + eprintln!( + "mask={mask:x?} per_group={dynamic} cap={} DXIL MD5={:02x?}", + super::super::loop_limit(), + super::super::container::md5(&split.dxil) + ); + assert_eq!(split.wave_size, Some(32)); + let at = (!dynamic).then_some(8); + assert_eq!(live_sources(&split), [(at, 0), (at, 1)]); + let [load] = split.raw_loads[0][..] else { + panic!("one SRV load") + }; + let (cfg, fences) = &split.barrier_cfg; + let [join] = cfg[load][..] else { + panic!("load has one exit") + }; + assert_eq!(fences.iter().filter(|&&b| b == load).count(), 4); + assert!( + cfg.iter() + .enumerate() + .any(|(head, edges)| edges == &[load, join] + && fences.iter().filter(|&&b| b == head).count() >= 2) + ); + let pair = w.iter().position(|&x| x == 0xf424_0796).unwrap(); + w[pair..pair + 2].copy_from_slice(&[0xbe9e_0383, 0xbe9f_0385]); + let control = lowered_with(&native_for_groups(&w, true, 64, 0, 2), true, true).unwrap(); + assert_eq!( + split.shape.branches, + control.shape.branches + 1, + "whole-group visit" + ); + assert_eq!( + split.barriers, + control.barriers + if dynamic { 10 } else { 6 } + ); + } + } +} + +#[test] +fn predicated_publication_rejects_wrong_visit_guards_and_partial_results() { + let mut w = program(&MASK_LANES_40_41, false); + let branch = w.iter().position(|&x| x == 0xbf88_0005).unwrap(); + w[branch] = 0xbf89_0005; // body on EXEC empty; some inactive lanes do not prove emptiness + let n = native_for_groups(&w, true, 64, 0, 2); + let error = lowered_with(&n, true, true).err().expect("unproved visit"); + assert!( + error.to_string().contains("without a proved predicated"), + "{error}" + ); + + let n = native_for_groups(&program(&MASK_LANES_40_41, false), true, 64, 0, 2); + for (fault, refusal) in [ + ("guard", "guarded or incomplete scalar-buffer publication"), + ( + "component", + "guarded or incomplete scalar-buffer publication", + ), + ("edge", "without a proved predicated"), + ] { + let mut p = ir::build(&n.code, n.wave64, n.vgprs).unwrap(); + let mut st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &n).unwrap(); + let (b, i) = res + .descriptors + .iter() + .map(|d| d.site) + .find(|&(b, i)| p.blocks[b].insts[i].name() == "s_buffer_load_dwordx2") + .unwrap(); + match fault { + "guard" => st.guards[b][i] = Some(structure::Bool::FALSE), + "component" => { + p.blocks[b].insts[i].writes.pop(); + } + _ => { + let d = p.blocks[b].preds[0]; + let branch = p.blocks[d].insts.last().unwrap(); + let mask = st.masks[&branch.read(ir::Reg::S(ir::EXEC)).unwrap()]; + let structure::LaneExit::Branch { when, .. } = &mut st.exits[d] else { + unreachable!() + }; + *when = mask; // EXECZ must skip on zero, even after path simplification + } + } + let error = lower::lower(&parts(&n, &p, &st, &res, &io, true, true)) + .err() + .expect("unproved publication"); + assert!(error.to_string().contains(refusal), "{error}"); + } +} + +#[cfg(windows)] +#[test] +fn predicated_publication_matches_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::normal_publication::predicated_publication_matches_gpu", + ) { + return; + } + for (mask, _) in TWO_LATCH_CASES { + for per_group in [false, true] { + check_publication_gpu( + &program(mask, per_group), + [mask != MASK_EMPTY, mask != MASK_EMPTY && per_group], + &format!("mask={mask:x?} per_group={per_group}"), + ); + } + } +} + +#[cfg(windows)] +fn check_publication_gpu(words: &[u32], visits: [bool; 2], case: &str) { + let limit = super::super::loop_limit(); + let input = [5, 7, 112, 197, 227, 251]; + let start = vec![0x1357_2468; 2 * 64 * 8]; + let n = native_for_groups(words, true, 64, 0, 2); + let forms = [( + "publication wave32", + shader(lowered_with(&n, true, true).unwrap()), + )]; + eprintln!( + "{case} cap={limit} DXIL MD5={:02x?}", + super::super::container::md5(&forms[0].1.dxil) + ); + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&start), + ]; + let mut want = start.clone(); + for (lane, row) in want.as_chunks_mut::<8>().0.iter_mut().enumerate() { + let group = lane / 64; + let pair = if visits[group] { + [input[2 + 2 * group], input[3 + 2 * group]] + } else { + [17, 21 + group as u32] + }; + row[1..3].copy_from_slice(&pair); + let iterations = if pair[0] % 2 == 0 { 2 } else { 1 }; + row[3] = 14 + iterations.min(limit); + if iterations < limit { + row[0] = 14 + iterations; + } + } + let (errors, ran) = compare_dispatches(&forms, 2, 8, &want, &views); + assert!(ran > 0, "physical wave32 required"); + assert!(errors.is_empty(), "{}", errors.join("\n")); +} + +#[test] +fn predicated_publication_rejects_a_guarded_raw_view() { + let mut w = program(&MASK_LANES_8_9, false); + w.splice(PROLOGUE.len()..PROLOGUE.len(), [0xf400_0c02, 0xfa00_0000]); // unrelated scalar read + let mut n = native_for_groups(&w, true, 64, 0, 2); + n.layout.push(RootParam { + root: RootType::Descriptor, + user_data: 4, + slot: 1, + sgprs: 2, + table_offset_dwords: 0, + base_register: 0, + }); + let mut used = n.used[1]; + used.root = RootType::Descriptor; + used.user_data = 4; + n.used.push(used); + let error = lower_with_resources(&n, true, true, false, |p, res| { + let mut view = res + .descriptors + .iter() + .find(|d| p.blocks[d.site.0].insts[d.site.1].name() == "s_buffer_load_dwordx2") + .unwrap() + .clone(); + // Exercise the plan/emitter boundary directly. The planner sees its + // fixed SRV; the final view for the same site takes the bounds-checked + // root-memory route. No contradictory metadata is ever dispatched. + view.source = resource::Source::Built { + address: resource::Address { + param: 1, + offset: 0, + dynamic: None, + }, + bits: 0, + words: [0; 2], + }; + res.descriptors.push(view); + let (_, other) = res + .scalar + .iter_mut() + .find(|((b, i), _)| p.blocks[*b].insts[*i].name() == "s_load_dword") + .unwrap(); + other.param = resource::MEMORY; + }) + .err() + .expect("conditional raw view"); + assert!( + error.to_string().contains("through a guarded raw view"), + "{error}" + ); +} + +#[test] +fn nested_publication_requires_the_inner_exec_to_stay_inside_the_outer() { + for restore in [false, true] { + let mut w = program(&MASK_LANES_40_41, true); + let body = w.iter().position(|&x| x == 0x8f12_8301).unwrap(); + let mut outer = vec![ + 0x7d88_00a0, // compare the local lane ID with 32 + 0xbea0_246a, // save outer EXEC in s[32:33] + 0, // skip the entire remaining program if no lane entered + ]; + if restore { + outer.push(0xbefe_0420); // allow lanes outside the outer arm again + } + // A group-ID branch rejoins before the inner guard, preserving its + // dominating outer predicate on both physical paths. + outer.extend([0xbf06_8001, 0xbf85_0001, 0xbf80_0000]); + outer[2] = s_cbranch_execz(w.len() + outer.len() - 1 - (body + 3)); + w.splice(body..body, outer); + let n = native_for_groups(&w, true, 64, 0, 2); + let result = lowered_with(&n, true, true); + if restore { + let error = result.err().expect("unproved nested EXEC"); + assert!( + error.to_string().contains("without a proved predicated"), + "{error}" + ); + } else { + assert_eq!(live_sources(&result.unwrap()), [(None, 0), (None, 1)]); + } + } +} + +/// Exercise only the visit proof on normal IR. Neither negative program enters code generation. +fn visit_admitted(w: &[u32], heads: &[usize]) -> bool { + let n = native_for_groups(w, true, 64, 0, 2); + let p = ir::build(&n.code, n.wave64, n.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + io::raise(&p, &n).unwrap(); + let gates: Vec<_> = heads + .iter() + .map(|&d| { + assert_eq!(p.blocks[d].insts.last().unwrap().name(), "s_cbranch_execz"); + let structure::LaneExit::Branch { + not_taken: body, .. + } = st.exits[d] + else { + panic!("EXEC branch") + }; + assert_eq!(p.blocks[body].preds, [d]); + (body, d) + }) + .collect(); + let body = gates.last().unwrap().0; + assert!(res.descriptors.iter().any(|desc| desc.site.0 == body + && p.blocks[body].insts[desc.site.1].name() == "s_buffer_load_dwordx2")); + let order = ir::reverse_postorder(&p.blocks); + let mut ranks = vec![usize::MAX; p.blocks.len()]; + for (i, &b) in order.iter().enumerate() { + ranks[b] = i; + } + let idom = ir::idoms(&p.blocks, &order, &ranks); + lower::publication_gates(&p, &st, &gates, &Default::default(), &idom) +} + +#[test] +fn quad_expansion_of_empty_exec_cannot_authorize_a_scalar_read() { + let mut w = program(&MASK_EMPTY, false); + let at = w.iter().position(|&x| x == 0xbf88_0005).unwrap(); + assert!(visit_admitted(&w, &[0])); + w.insert(at, 0xbefe_0a7e); // WQM of the empty EXEC still has zero visitors + assert!(!visit_admitted(&w, &[0])); + w.remove(at); + w.insert(PROLOGUE.len(), 0xbefe_0a7e); // WQM of the full entry EXEC is exact + assert!(visit_admitted(&w, &[0])); +} + +#[test] +fn divergent_mask_phi_cannot_authorize_a_scalar_read() { + let mut w = program(&MASK_LANES_40_41, true); + let pos = w.iter().position(|&x| x == 0x8f12_8301).unwrap(); + let mut prefix = [ + 0x7d88_00a0, + 0xbea0_246a, + 0, // outer mask = lanes 0..31 + 0x2c06_0081, + 0x7d84_0684, + 0xbea4_246a, // A = lanes 8 and 9; save outer EXEC + 0xbf88_0002, // whole guest wave takes the nonempty arm + 0xbefe_087e, + 0x88fe_817e, // that arm sets EXEC = !A | 1 + 0x87fe_247e, // join: EXEC &= saved outer mask + ]; + prefix[2] = s_cbranch_execz(w.len() + prefix.len() - 1 - (pos + 3)); + w.splice(pos..pos, prefix); + let at = w.iter().position(|&x| x == 0xbf88_0005).unwrap(); + w[at - 3..at].copy_from_slice(&[0xbf80_0000, 0xbf80_0000, 0xbe96_047e]); + // Guest takes one predecessor for the wave, leaving 30 visitors. With + // per-lane selection, lanes 8/9 clear their own bits and all others skip. + assert!(!visit_admitted(&w, &[0, 3])); + w[pos + 8] = 0xbf80_0000; // EXEC = !A; the per-lane mask phi can fold to false + assert!(!visit_admitted(&w, &[0, 3])); +} diff --git a/crates/victory-shader/src/emit/halves_tests/normal_publication/saved_exec.rs b/crates/victory-shader/src/emit/halves_tests/normal_publication/saved_exec.rs new file mode 100644 index 000000000..caa21296b --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/normal_publication/saved_exec.rs @@ -0,0 +1,85 @@ +use super::*; + +const CASES: [(&str, &[u32], bool); 3] = [ + ("upper", &MASK_LANES_40_41, true), + ("inner_empty", &MASK_LANES_8_9, false), + ("outer_empty", &MASK_EMPTY, false), +]; + +fn saved_exec_program(mask: &[u32]) -> Vec { + let mut w = program(mask, true); + let inner = w.iter().position(|&word| word == 0xbf88_0005).unwrap(); + let prefix = [ + 0x7d84_00a8, // select lane 40 within the existing outer EXEC + 0xbea6_246a, // s[38:39] = outer EXEC, EXEC &= VCC + 0xbea0_047e, // keep the narrower inner mask + 0xbefe_0426, // restore the outer mask for the first branch + s_cbranch_execz(18), // skip to the original full EXEC restore + 0xbefe_0420, // enter with the inner mask + 0xbea2_04c1, // s[34:35] = -1 + 0xbf06_8001, // group 0 takes the next skip + 0xbf85_0001, + 0xbea2_0480, // group 1 sets s[34:35] to zero + 0xbea0_2422, // save the inner mask, then apply the joined operand + 0xbea4_0420, // s[36:37] = saved inner mask + 0xbf06_8001, + 0xbf85_0001, // copies in the previous block dominate the restore + 0xbf80_0000, + 0xbefe_0424, // restore the old EXEC before the inner visit + ]; + w.splice(inner..inner, prefix); + w.insert(inner + prefix.len() + 6, 0xbea6_0380); // distinct inner join + w +} + +#[test] +fn saved_pair_restores_upper_lanes_across_a_join() { + let w = saved_exec_program(&MASK_LANES_40_41); + assert!(visit_admitted(&w, &[0, 5])); +} + +#[test] +fn restored_exec_publishes_both_scalar_components() { + for (case, mask, _) in CASES { + let n = native_for_groups(&saved_exec_program(mask), true, 64, 0, 2); + let split = lowered_with(&n, true, true).expect("restored EXEC publication"); + assert_eq!(live_sources(&split), [(None, 0), (None, 1)]); + eprintln!( + "{case} cap={} DXIL MD5={:02x?}", + super::super::super::loop_limit(), + super::super::super::container::md5(&split.dxil) + ); + } +} + +#[cfg(windows)] +#[test] +fn restored_exec_publication_matches_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::normal_publication::saved_exec::restored_exec_publication_matches_gpu", + ) { + return; + } + for (case, mask, visit) in CASES { + check_publication_gpu(&saved_exec_program(mask), [visit; 2], case); + } +} + +#[test] +fn narrowed_exec_and_partial_saved_pairs_cannot_authorize_a_visit() { + let w = saved_exec_program(&MASK_LANES_40_41); + let at = w.iter().position(|&word| word == 0xbefe_0424).unwrap(); + for replacement in [ + 0xbf80_0000, // keep the narrowed EXEC produced by saveexec + 0xbefe_0422, // use the joined operand + ] { + let mut bad = w.clone(); + bad[at] = replacement; + assert!(!visit_admitted(&bad, &[0, 5])); + } + for overwrite in [0xbea4_0322, 0xbea5_0323] { + let mut bad = w.clone(); + bad[at - 1] = overwrite; // replace one dword on a single predecessor + assert!(!visit_admitted(&bad, &[0, 5])); + } +} diff --git a/crates/victory-shader/src/emit/halves_tests/terminal_owner.rs b/crates/victory-shader/src/emit/halves_tests/terminal_owner.rs new file mode 100644 index 000000000..d2476c5e8 --- /dev/null +++ b/crates/victory-shader/src/emit/halves_tests/terminal_owner.rs @@ -0,0 +1,338 @@ +use super::*; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Change { + None, + LoadedCoordinate, + MissingInit, + WrongPhiInput, + SecondEntry, + LiveJoin, + RestoreExec, + EnlargeExec, + EmptyExec, + HighExec, + Barrier, + ReadLane, + UnmaskedVote, + ScalarDecision, + MaskDecision, +} + +fn fixture(leader: Option, change: Change) -> (NativeProgram, usize) { + let mut words = PROLOGUE.to_vec(); + words.extend([ + 0x8F0F_8801, // s15 = group_id.x * 256 + 0x3404_0284, // v2 = y * 16 + 0x4A04_0500, // v2 = x + v2 + 0x3406_0482, // v3 = 4 * v2 + 0x4A08_040F, // v4 = s15 + v2 + 0x4A08_0889, // v4 += 9 + 0xD834_0000, + 0x0000_0403, // LDS[v2] = v4 + S_WAITCNT_LGKM, + 0xBF8A_0000, + if change == Change::MissingInit { + 0x7E0A_0280 + } else { + 0x7E0C_0280 + }, // initialize flag + 0xBE94_047E, // save full EXEC in s[20:21] + ]); + match leader { + Some(leader) if change == Change::LoadedCoordinate => { + words.extend([0xD8D8_0000, 0x0D00_0003, S_WAITCNT_LGKM]); // v13 = LDS[v3] + words.push(0x7DA4_1A80 | leader); + } + Some(leader) => words.push(0x7DA4_0480 | leader), // EXEC &= v2 == leader + None => words.extend([ + 0x3618_04FF, + 0xffff_ffdf, // v12 = v2 & ~32 + 0x7DA4_1880, // EXEC &= (v12 == 0), keeps {0, 32} + ]), + } + let select = words.len(); + words.extend([ + s_cbranch_execz(1), + if change == Change::WrongPhiInput { + 0x7E0C_0304 + } else { + 0x7E0C_02C1 + }, // v4 or -1 + S_MOV_EXEC_S20, + 0xBF8A_0000, + 0x7DA4_0CC1, // EXEC &= v6 == -1 + ]); + let empty = words.len(); + words.extend([ + 0, + 0x3420_0885, // v16 = output byte address = v4 * 32 + 0x7E14_0283, // v10 running sum = 3 + 0xBE92_0380, // s18 iteration = 0 + ]); + match change { + Change::RestoreExec => words.push(S_MOV_EXEC_S20), + Change::EnlargeExec => words.push(0xBEFE_04C1), // EXEC = -1 + Change::EmptyExec => words.push(0xBEFE_0480), // EXEC = 0 + Change::HighExec => words.push(0xBEFF_0380), // EXEC_HI = 0, clears leader 40 + Change::Barrier => words.push(0xBF8A_0000), + Change::ReadLane => words.extend([0xD760_0013, 0x0001_0109]), // v_readlane_b32 s19, v9, 0 + _ => {} + } + let loop_start = words.len(); + words.extend([ + 0x7E0A_0212, // v5 = s18 + 0x340A_0A82, // v5 *= 4 + 0x4A0A_0B03, // v5 = v3 + v5 + 0xD8D8_0000, + 0x0900_0005, // v9 = LDS[flat + iteration] + S_WAITCNT_LGKM, + 0x4A12_130A, // v9 = v10 + v9 + 0x7E26_0509, // s19 = firstlane(v9) + 0x8012_8112, // s18 += 1 + 0x7E14_0213, // v10 = s19 + 0xBF09_FF13, + 200, // SCC = s19 >= 200 + ]); + let branch = if change == Change::UnmaskedVote { + words.push(0xBEEA_0414); // VCC = saved full EXEC, including nonowners + 0xBF86_0000 // s_cbranch_vccz + } else { + 0xBF84_0000 // s_cbranch_scc0 + }; + let latch = words.len(); + words.push(branch | ((loop_start as i32 - latch as i32 - 1) as u32 & 0xffff)); + if matches!(change, Change::ScalarDecision | Change::MaskDecision) { + if change == Change::ScalarDecision { + words.extend([0xBF09_FF13, 250]); // s_cmp_ge_u32 s19, 250 (205 vs 308) + } else { + words.push(0xBE98_087E); // s_not_b64 s[24:25], exec sets SCC; owner bit is zero + } + words.push(0xBF85_0002); // s_cbranch_scc1 skips the observable store at +8 + words.extend(store(10, 8)); + } + let store_start = words.len(); + words.extend(store(10, 0)); + words.push(0x7E16_0212); // v11 = s18 + words.extend(store(11, 4)); + words.push(S_ENDPGM); + let exit = if change == Change::LiveJoin { + store_start + } else { + words.len() - 1 + }; + words[empty] = s_cbranch_execz(exit - empty - 1); + if change == Change::SecondEntry { + words[select] = s_cbranch_execz(empty - select); // bypass reaches the live continuation + } + let mut program = native_for_groups(&words, true, 256, 1024, 2); + let StageIo::Cs(cs) = &mut program.io else { + unreachable!() + }; + cs.rsrc2 |= 1 << 11; // x and y per-thread IDs + cs.threads = [16, 16, 1]; + (program, latch * 4) +} + +#[test] +fn terminal_owner_first_lane_lowers() { + let mut failures = Vec::new(); + for leader in [Some(0), Some(40), None] { + let (program, latch) = fixture(leader, Change::None); + assert_eq!( + lower_halves(&program, false, true, false) + .unwrap() + .wave_size, + Some(64) + ); + for retry in [false, true] { + let result = lower_halves(&program, true, true, retry); + if leader.is_some() { + match result { + Ok(shader) => assert_eq!( + (shader.wave_size, shader.owner_reads, shader.barriers), + (Some(32), 1, 3) + ), + Err(e) => failures.push(format!("{leader:?}, retry={retry}: {e}")), + } + } else { + let Err(crate::ShaderError::Unsupported { offset, what }) = result else { + panic!("two halves must retain the named first-lane refusal") + }; + assert_eq!(offset, latch); + assert!(what.contains("a first-lane read of a value that may differ")); + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn terminal_owner_rejects_unproved_participation() { + for change in [ + Change::LoadedCoordinate, + Change::MissingInit, + Change::WrongPhiInput, + Change::SecondEntry, + Change::LiveJoin, + Change::RestoreExec, + Change::EnlargeExec, + Change::EmptyExec, + Change::HighExec, + Change::Barrier, + Change::ReadLane, + ] { + let (n, latch) = fixture(Some(40), change); + let Err(crate::ShaderError::Unsupported { offset, what }) = + lower_halves(&n, true, true, false) + else { + panic!("{change:?}: expected the normal-path refusal") + }; + assert_eq!(offset, latch, "{change:?}"); + assert!( + what.contains(if change == Change::HighExec { + "a lane mask whose lanes depend" + } else { + "a first-lane read" + }), + "{change:?}: {what}" + ); + } + let (vote, _) = fixture(Some(40), Change::UnmaskedVote); + assert_eq!( + lower_halves(&vote, true, true, false).unwrap().owner_reads, + 0 + ); + let (n, latch) = fixture(Some(40), Change::None); + let p = ir::build(&n.code, n.wave64, n.vgprs).unwrap(); + let mut st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &n).unwrap(); + let (b, i) = p + .blocks + .iter() + .enumerate() + .find_map(|(b, block)| { + block + .insts + .iter() + .position(|i| i.name() == "v_readfirstlane_b32") + .map(|i| (b, i)) + }) + .unwrap(); + st.guards[b][i] = Some(structure::Bool::FALSE); + let guarded = parts(&n, &p, &st, &res, &io, true, true); + let Err(crate::ShaderError::Unsupported { offset, what }) = + lower::lower_pruned(&guarded, None, false, false) + else { + panic!("a per-site guard can clear the selected owner") + }; + assert_eq!(offset, latch); + assert!(what.contains("a first-lane read")); + let Err(crate::ShaderError::Unsupported { offset, what }) = + super::super::with_thread_ticket(false, || lower_halves(&n, true, true, false)) + else { + panic!("a tiled group needs lane tickets"); + }; + assert_eq!(offset, latch); + assert!(what.contains("a first-lane read")); +} + +#[test] +fn terminal_owner_scc_decision_preserves_conditional_store() { + for change in [Change::ScalarDecision, Change::MaskDecision] { + let (n, latch) = fixture(Some(40), change); + let p = ir::build(&n.code, n.wave64, n.vgprs).unwrap(); + let (b, decision) = p + .blocks + .iter() + .enumerate() + .find(|(_, block)| { + block + .insts + .last() + .is_some_and(|i| i.name() == "s_cbranch_scc1") + }) + .unwrap(); + let ir::Exit::Branch { taken, not_taken } = decision.exit else { + unreachable!() + }; + let store_offset = |b: usize| { + p.blocks[b].insts.iter().find_map(|i| match i.fields { + gfx10::Fields::Buffer { offset, .. } if i.name() == "buffer_store_dword" => { + Some(offset) + } + _ => None, + }) + }; + assert_eq!( + (store_offset(not_taken), store_offset(taken)), + (Some(8), Some(0)) + ); + let result = lower_halves(&n, true, true, false); + if change == Change::ScalarDecision { + let (base, _) = fixture(Some(40), Change::None); + let base = lower_halves(&base, true, true, false).unwrap(); + let decision = result.unwrap(); + assert_eq!(decision.owner_reads, 1); + assert_eq!(decision.shape.branches, base.shape.branches + 1); + } else { + let st = structure::structure(&p).unwrap(); + assert!(matches!( + st.exits[b], + structure::LaneExit::Branch { + when: structure::Bool::FALSE, + .. + } + )); + let Err(crate::ShaderError::Unsupported { offset, what }) = result else { + panic!("the other 63 bits set SCC even though the owner's bit is clear"); + }; + assert_eq!(offset, latch); + assert!(what.contains("a first-lane read")); + } + } +} + +#[cfg(windows)] +#[test] +fn terminal_owner_matches_two_groups_on_gpu() { + if !in_bounded_gpu_child( + "emit::halves_tests::terminal_owner::terminal_owner_matches_two_groups_on_gpu", + ) { + return; + } + for (leader, group0, group1) in [(0, [220, 14], [268, 1]), (40, [205, 4], [308, 1])] { + let (n, _) = fixture(Some(leader), Change::None); + let forms = [( + "owner wave32", + shader(lower_halves(&n, true, true, false).unwrap()), + )]; + let input = vec![0x1357_9bdf; 512 * 8]; + let mut expected = input.clone(); + for (group, result) in [group0, group1].into_iter().enumerate() { + let row = group * 256 + leader as usize + 9; + let visits = super::super::loop_limit().min(result[1]); + // Sum of the first visits LDS words, starting at this group's payload. + let sum = 3 + visits * row as u32 + visits * (visits - 1) / 2; + assert!(visits < result[1] || sum == result[0]); + expected[8 * row..8 * row + 2].copy_from_slice(&[sum, visits]); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Raw, + }, + View::RawUavData(&input), + ]; + eprintln!( + "leader={leader}, cap={}, checking {} dwords", + super::super::loop_limit(), + expected.len() + ); + let (wrong, dispatches) = compare_dispatches(&forms, 2, 8, &expected, &views); + assert!(dispatches > 0, "no dispatch for leader {leader}"); + assert!(wrong.is_empty(), "leader {leader}: {}", wrong.join("\n")); + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 0e3a56ffb..155089ae7 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1475,6 +1475,8 @@ pub enum View<'a> { Levels(u32, u32), /// A raw buffer UAV of this many dwords, zeroed. RawUav(u32), + /// A raw buffer UAV initialized with these dwords. + RawUavData(&'a [u32]), /// An RGBA32F texture UAV (width, height), zeroed. TextureUav(u32, u32), /// An R32_UINT texture UAV (width, height), zeroed (atomics). @@ -1529,7 +1531,7 @@ pub fn view_strides(views: &[View]) -> Vec { views .iter() .map(|v| match *v { - View::Buffer { stride: Stride::Raw, .. } | View::RawUav(_) => 4, + View::Buffer { stride: Stride::Raw, .. } | View::RawUav(_) | View::RawUavData(_) => 4, View::Buffer { stride: Stride::Typed, .. } => 16, View::Buffer { stride: Stride::Structured(n), .. } => n, View::Buffer { stride: Stride::Format(f, n), .. } | View::TypedUav(f, _, n) => n | kind(f), @@ -1982,12 +1984,13 @@ impl Host { dev.CreateShaderResourceView(&b, Some(&desc), at); keep.push(b); } - View::Memory(_) | View::NullPair => { - let n = match *v { - View::Memory(data) => data.len() as u32, - _ => 0, + View::RawUavData(_) | View::Memory(_) | View::NullPair => { + let data = match *v { + View::RawUavData(data) | View::Memory(data) => Some(data), + _ => None, }; - let b = if let View::Memory(data) = *v { + let n = data.map_or(0, |d| d.len() as u32); + let b = if let Some(data) = data { let bytes = u64::from(n) * 4; let b = make( D3D12_HEAP_TYPE_DEFAULT, @@ -2029,10 +2032,12 @@ impl Host { }, }, }; - let mut next = at; - next.ptr += view_size; - dev.CreateShaderResourceView(b.as_ref(), Some(&srv), at); - dev.CreateUnorderedAccessView(b.as_ref(), None, Some(&uav), next); + let mut uav_at = at; + if !matches!(v, View::RawUavData(_)) { + dev.CreateShaderResourceView(b.as_ref(), Some(&srv), at); + uav_at.ptr += view_size; + } + dev.CreateUnorderedAccessView(b.as_ref(), None, Some(&uav), uav_at); if let Some(b) = b { let rb = make( D3D12_HEAP_TYPE_READBACK, diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6769b102b..5726dd44a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -33,6 +33,8 @@ mod first_lane; #[path = "half_views.rs"] mod half_views; mod halves; +mod literal_lds; +mod literal_publish; mod marks; mod meet; mod packed; @@ -40,6 +42,7 @@ mod round_mode; mod mesh; mod predicate; mod retry; +mod terminal_owner; mod thread_limits; #[cfg(test)] use barriers::split_wave_barriers; @@ -51,12 +54,15 @@ use mesh::prune_signature; pub(crate) use meet::MeetSite; use super::bitcode::Rmw; use packed::packed_half; +use predicate::reads_mask_as_data; +#[cfg(test)] +pub(in crate::emit) use predicate::publication_gates; use round_mode::round16; pub(super) use round_mode::round16_after; #[cfg(any(test, all(windows, feature = "host")))] pub(crate) use retry::lower; pub(crate) use retry::lower_limited; -#[cfg(all(test, windows))] +#[cfg(test)] pub(crate) use retry::{lower_literal, lower_pruned}; type Why = &'static str; @@ -65,7 +71,7 @@ type Why = &'static str; thread_local! { /// Set by a test that probes the value analysis behind a refusal, which /// selective predication would otherwise route around. - static NO_PREDICATION: std::cell::Cell = const { std::cell::Cell::new(false) }; + pub(super) static NO_PREDICATION: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Whether the current test turned selective predication off. @@ -147,12 +153,20 @@ pub(crate) struct Lowered { /// Written typed-buffer calls, for structural tests of the dynamic path. #[cfg(test)] pub typed_buffer_calls: TypedBufferCalls, + #[cfg(test)] + pub owner_reads: usize, /// What the written module holds, for structural tests. #[cfg(test)] pub shape: Shape, - /// Barriers added for narrow host waves ([`split_wave_barriers`]). + #[cfg(test)] + pub guest_lds: super::bitcode::lds_tests::GuestLds, + /// Barriers added for narrow host waves. #[cfg(test)] pub split_barriers: usize, + #[cfg(test)] + pub live_scalar_exchanges: Vec, + #[cfg(test)] + pub barrier_cfg: (Vec>, Vec), /// Group barriers written (`dx.op.barrier`), for structural tests of /// the exchanges between 32-lane halves. #[cfg(test)] @@ -389,6 +403,8 @@ struct Lower<'a> { halves: bool, /// Why such a program cannot run in halves. halves_refused: Option, + /// All mutable scalar data reads on this literal path require publication. + literal_publication: bool, /// Selective acyclic divergent-branch predication plan (`predicate`). pred: predicate::PredicatePlan, /// Per-lane active predicate for each IR block under predication. @@ -562,33 +578,6 @@ const LANE_MASK: Why = "a lane mask read as data"; const MASK_CYCLE: Why = "a lane mask whose lanes depend on its own value"; const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; -/// Instructions that read a lane mask (not EXEC implicitly, not a lane's -/// bit) as a number. -fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { - let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); - let ops: Vec<&Operand> = match &i.fields { - // A mask operation (its result a mask) is no data use. - Fields::Sop { .. } - if i.writes - .iter() - .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) => - { - return false; - } - Fields::Sop { src, .. } => src.iter().collect(), - Fields::Valu(v) - if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") => - { - v.src.iter().collect() - } - _ => return false, - }; - ops.into_iter().any(|op| match *op { - Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask), - _ => false, - }) -} - /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]), /// by row: whether two per dword. fn half_outputs(io: &StageIo) -> HashMap { @@ -668,6 +657,24 @@ fn smem_dwords(name: &str) -> Option { } } +/// The last resource range starting at or before a table descriptor. +fn table_kind(native: &NativeProgram, a: Address, first: u8) -> Option<&UsedResource> { + let rp = native.layout.get(a.param)?; + if rp.root != RootType::Table { + return None; + } + let dword = (a.offset / 4) + u32::from(first); + native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords) +} + /// Where a program's constant table starts in its code: where its /// instructions end, unless a load at a fixed offset reads below that (then /// at `lowest`, the lowest offset any load or descriptor names). The @@ -693,7 +700,7 @@ impl<'a> Lower<'a> { per_vertex_center: bool, meet_plan: &'a Set, meet_found: &'a std::cell::RefCell>, - ) -> Self { + ) -> Result { let p = x.p; let mut phi_at = Map::default(); for (b, block) in p.blocks.iter().enumerate() { @@ -706,10 +713,13 @@ impl<'a> Lower<'a> { s.outputs = x.outputs.clone(); if let Some(keep) = keep { s.repack_signatures = true; - if x.native.stage == HwStage::Ps { - prune_signature(&mut s.inputs, keep); - } else if x.native.stage == HwStage::Ms { - prune_signature(&mut s.outputs, keep); + let elements = match x.native.stage { + HwStage::Ps => Some(&mut s.inputs), + HwStage::Ms => Some(&mut s.outputs), + _ => None, + }; + if let Some(elements) = elements { + prune_signature(elements, keep); } } let insts = || p.blocks.iter().flat_map(|b| &b.insts); @@ -732,6 +742,7 @@ impl<'a> Lower<'a> { } else { HashSet::new() }; + let mut literal_control = None; let mut split_barriers = Set::default(); let mut pred = predicate::PredicatePlan::empty(Vec::new()); if let StageIo::Cs(cs) = x.native.io { @@ -779,26 +790,48 @@ impl<'a> Lower<'a> { }) } || halves::needs_first_lane(x, &mut alike_cache, &first_alone); let wave = if x.native.wave64 { 64 } else { 32 }; - let group = cs.threads.iter().product::(); + let group = if x.st.literal && s.lds_dwords != 0 { + literal_lds::group_size(cs.threads)? + } else { + cs.threads.iter().product::() + }; let one_wave = group <= wave; let one_wave_lds = (x.narrow_waves || x.st.literal) && one_wave && group > 32 && s.lds_dwords > 0; let step_plan = if x.st.literal { // Whole-wave control flow keeps its own branches. - predicate::PredicatePlan::empty(in_step(p, x.st)) + if let Some(proof) = literal_publish::prove(x, group, s.lds_dwords, bad)? { + let mut plan = predicate::PredicatePlan::empty(proof.step.clone()); + split_barriers = proof.guest_barriers; + plan.scalar_publications = proof.sites; + literal_control = Some((proof.step, vec![false; p.blocks.len()], proof.common)); + plan + } else { + predicate::PredicatePlan::empty(in_step(p, x.st)) + } } else if x.native.wave64 && group > 32 && (x.host_wave32 || one_wave_lds) && !predication_off() { let base_step = in_step(p, x.st); - predicate::PredicatePlan::build(p, x.st, base_step, one_wave_lds, x.host_wave32) + let mapped_group = (console_lanes && x.host_wave32) + .then(|| (x, halves::uses_lane_tickets(group, 32, s.lds_dwords, true), &first_alone)); + predicate::PredicatePlan::build( + p, + x.st, + base_step, + one_wave_lds, + x.host_wave32, + mapped_group.filter(|_| group == 64), + mapped_group.filter(|&(_, tickets, _)| group > 64 && tickets).map(|(x, ..)| x), + ) } else { predicate::PredicatePlan::empty(Vec::new()) }; // The console's one wave is several host waves: LDS no longer // passes between its lanes without a barrier. - let mut synced = false; - if one_wave_lds { + let mut synced = !split_barriers.is_empty(); + if one_wave_lds && !synced { // shortcut: a read in divergent code of what divergent code // wrote gets no barrier (none could be placed there); the // program then runs as before. @@ -887,10 +920,19 @@ impl<'a> Lower<'a> { } } } - let (step, cap_escaped, group_scalars) = step_and_cap(p, x.st, halves); + let literal_publication = literal_control.is_some(); + let (step, cap_escaped, group_scalars) = + literal_control.unwrap_or_else(|| step_and_cap(p, x.st, halves)); let one_host_wave = s.threads.is_some_and(|t| t.iter().product::() <= 32); let meet = (halves && !one_host_wave && x.halves_rendezvous) .then(|| meet::meet_regions(p, x.st, &step)); + if let (Some(owner), Some(meet)) = (&pred.owner, &meet) + && owner.overlaps_meet(meet) + { + // An independently planned exchange can also insert a barrier at its join. + // Only multi-wave groups reach this proof, so no split-wave LDS plan changes. + pred = predicate::PredicatePlan::build(p, x.st, step.clone(), false, true, None, None); + } let mut l = Lower { s, x, @@ -943,6 +985,7 @@ impl<'a> Lower<'a> { console_lanes, halves, halves_refused, + literal_publication, step: if !halves { Vec::new() } else if pred.step.is_empty() { @@ -968,7 +1011,13 @@ impl<'a> Lower<'a> { meet_epoch: Map::default(), level: 0, alike: if halves { - alike_cache.unwrap_or_else(|| halves::lane_uniform(x)) + let mut alike = alike_cache.unwrap_or_else(|| halves::lane_uniform(x)); + // A value shared by one console wave can differ in the next. + // Its proof may elide an exchange only after mapping host lanes. + if console_lanes { + halves::shared_loop_first_lanes(x, &first_alone, &mut alike); + } + alike } else { HashSet::new() }, @@ -1028,7 +1077,7 @@ impl<'a> Lower<'a> { mode16: Some(0), }; l.lay_out_meet(); - l + Ok(l) } /// The dword of the program's code at byte `byte` (a constant table @@ -1385,14 +1434,21 @@ impl<'a> Lower<'a> { .shapes .values() .any(|s| matches!(s, super::wave::Shape::CountF64Hi(..))); - !section + // A section replacing a proved lane read must still + // return a whole-wave value at its live scalar output. + let interior = &p.blocks[b].insts[start + 1..section.end]; + let scalars_preserved = !self.literal_publication || interior.iter() + .flat_map(|inst| &inst.writes) + .filter(|(_, v)| self.group_scalars.contains(v)) + .all(|(_, v)| matches!(section.shapes.get(v), + Some(super::wave::Shape::K(_) | super::wave::Shape::Active(..)))); + scalars_preserved && !section .shapes .values() .any(|s| matches!(s, super::wave::Shape::Half(..))) - && p.blocks[b].insts[start + 1..section.end].iter().all(|i| { - matches!(i.fields, Fields::Valu(_)) - || (count_f64 && matches!(i.fields, Fields::Sop { .. })) - }) + && interior.iter() + .all(|i| matches!(i.fields, Fields::Valu(_)) + || (count_f64 && matches!(i.fields, Fields::Sop { .. }))) }); } for (&start, sec) in &found { @@ -1725,7 +1781,17 @@ impl<'a> Lower<'a> { self.level = self.cur; self.exit(b)?; } + if let Some(&(b, i)) = self.pred.scalar_publications.iter().next() { + return Err(unsupported( + p.blocks[b].insts[i].machine.offset, + "a skipped scalar-buffer publication", + )); + } self.fill_phis()?; + #[cfg(test)] + if let Some(owner) = &self.pred.owner { + owner.verify_emission(&self); + } let user_data = self.user_reads.values().copied().collect(); self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); @@ -1815,6 +1881,8 @@ impl<'a> Lower<'a> { ], }, #[cfg(test)] + owner_reads: self.pred.owner.as_ref().map_or(0, |o| o.emitted.len()), + #[cfg(test)] shape: { let (blocks, instructions, branches) = self.s.m.written_shape(); Shape { @@ -1827,8 +1895,14 @@ impl<'a> Lower<'a> { } }, #[cfg(test)] + guest_lds: self.s.m.guest_lds_trace(), + #[cfg(test)] split_barriers: self.split_barriers.len(), #[cfg(test)] + live_scalar_exchanges: self.s.m.live_scalar_exchanges(), + #[cfg(test)] + barrier_cfg: self.s.m.written_cfg(&self.s.m.written_call_blocks("dx.op.barrier")), + #[cfg(test)] barriers: self.s.m.written_calls("dx.op.barrier"), #[cfg(test)] wave_size: self.s.wave_size, @@ -4148,17 +4222,6 @@ impl<'a> Lower<'a> { Ok(()) } - /// Thread-group sync with a shared-memory fence, and a UAV fence when - /// the program writes UAVs (the waits before an s_barrier make those - /// writes visible on the console). - fn group_barrier(&mut self) { - let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; - let mode = self.s.m.i32(mode); - let void = self.s.t.void; - self.s - .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); - } - // ---- instructions ---- fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { @@ -4223,7 +4286,9 @@ impl<'a> Lower<'a> { }; match r { Ok(()) => Ok(()), - Err(why) if effect => Err(unsupported(offset, why)), + Err(why) if effect || self.pred.scalar_publications.contains(&(b, i)) => { + Err(unsupported(offset, why)) + } Err(why) => { for &(_, v) in &inst.writes { self.vals.insert(v, Val::Missing(why)); @@ -4783,6 +4848,11 @@ impl<'a> Lower<'a> { return self.memory_smem(inst, a); } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { + if self.literal_publication { + // The tracker supplies the handle. Its storage words have no + // proved numeric value on the publication path. + return Err("a literal descriptor word read as numeric data"); + } return self.descriptor_data(inst, site); }; let count = match rest { @@ -4840,10 +4910,25 @@ impl<'a> Lower<'a> { && matches!(src, Source::Built { address, .. } if self.x.native.layout.get(address.param).is_some_and(|p| p.root == RootType::Descriptor)); if srv || root_uav { + let publish = self.pred.scalar_publications.contains(&site); + if publish && (self.x.st.guards[site.0][site.1].is_some() + || (0..count).any(|k| inst.write(Reg::S(code + k as u8)).is_none())) + { + return Err("a guarded or incomplete scalar-buffer publication"); + } let (h, addr) = self.raw_view(site, src, addr, 4 * count, (11, 0), false, None)?; - for (k, x) in self.raw_run(h, addr, count).into_iter().enumerate() { + if publish && (self.cur != c || self.memory_offsets.contains(&addr)) { + return Err("a scalar-buffer publication through a guarded raw view"); + } + let words = if publish { + self.published_scalar_words(h, addr, count)? + } else { + self.raw_run(h, addr, count) + }; + for (k, x) in words.into_iter().enumerate() { self.write(inst, Reg::S(code + k as u8), x, None); } + self.pred.scalar_publications.remove(&site); return Ok(()); } let h = self.handle(site, src, false, (13, 0x1_0000))?; @@ -6077,22 +6162,7 @@ impl<'a> Lower<'a> { let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else { return None; }; - let a = self.scalar.get(load)?; - let rp = self.x.native.layout.get(a.param)?; - if rp.root != RootType::Table { - return None; - } - let dword = (a.offset / 4) + u32::from(*first); - self.x - .native - .used - .iter() - .filter(|u| { - u.root == RootType::Table - && u.user_data == rp.user_data - && u.table_offset_dwords <= dword - }) - .max_by_key(|u| u.table_offset_dwords) + table_kind(self.x.native, *self.scalar.get(load)?, *first) } /// A handle for the descriptor `src` read at `site`; the heap index of @@ -6613,6 +6683,18 @@ impl<'a> Lower<'a> { Some(Operand::Scalar { .. }) if name != "v_readfirstlane_b32" => None, _ => self.guard(b, i)?, }; + if self.halves + && name == "v_readfirstlane_b32" + && guard.is_none() + && self.cur == self.level + && let Some(owner) = &mut self.pred.owner + && owner.sites.contains(&(b, i)) + { + #[cfg(test)] + owner.emitted.push(self.cur); + let own = self.src(inst, 0)?; + return self.write_i(inst, own, None); + } if let Some(d) = v.dpp { let (x, enable) = self.dpp(inst, d, guard)?; guard = match (guard, enable) { @@ -7451,7 +7533,14 @@ impl<'a> Lower<'a> { .first() .is_some_and(|w| self.x.st.restored.contains_key(&w.1)) => { - let a = self.i32_of(self.x.st.restored[&inst.writes[0].1])?; + let source = self.x.st.restored[&inst.writes[0].1]; + if self.literal_publication + && !(halves::uniform_selector(inst, &self.group_scalars) + && self.group_scalars.contains(&source)) + { + return Err("an unproved restored scalar in literal publication"); + } + let a = self.i32_of(source)?; int(self, a) } "v_writelane_b32" diff --git a/crates/victory-shader/src/emit/lower/barriers.rs b/crates/victory-shader/src/emit/lower/barriers.rs index 4155b65a0..ada6e68af 100644 --- a/crates/victory-shader/src/emit/lower/barriers.rs +++ b/crates/victory-shader/src/emit/lower/barriers.rs @@ -172,7 +172,52 @@ pub(crate) fn step_and_cap( st: &Structured, need_step: bool, ) -> (Vec, Vec, Set) { - step_and_cap_with(p, st, &st.exits, &Set::default(), need_step) + step_and_cap_with(p, st, &st.exits, &Set::default(), need_step, None) +} + +/// VCC dwords with scalar definitions that structuring has not classified as masks. +pub(super) fn scalar_scratch(p: &Program, st: &Structured) -> Set { + // A plain number the compiler keeps in VCC_LO or VCC_HI as a spare + // scalar register, not a lane mask: written alone (besides + // SCC) by a scalar ALU instruction, and not a mask the structure knows + // (`masks`, `highs`, `other`). Such a value may be read as data like any + // SGPR; callers still need every value it is computed from + // to be alike, so this admits no lane mask: + // - EXEC on entry, and any phi, is no instruction's write; + // - `v_cmp`/`v_cmpx` and other VALU results are never alike (`own`), so + // neither is anything a scalar instruction computes from them; + // - a saved copy of either (`s_mov_b64 s[10:11], exec`, + // `s_and_saveexec_b64`) reads the mask and so is not alike, and nor is + // a later move of the copy back into VCC; a spill through + // `v_writelane`/`v_readlane` goes by `st.restored`; + // - a 64-bit write (`s_and_b64 vcc, …`, `s_mov_b64 vcc, …`) is left out + // whatever it reads: in wave64 halves VCC_HI is the upper 32 lanes' + // bits, which differ between the host waves; + // - EXEC is never scratch: a write to it changes which lanes run. + p + .blocks + .iter() + .flat_map(|b| b.insts.iter()) + .filter(|i| matches!(i.fields, Fields::Sop { .. })) + .filter_map(|i| { + let mut words = i.writes.iter().filter(|w| w.0 != Reg::Scc); + match (words.next(), words.next()) { + (Some(&(Reg::S(k), v)), None) if k == VCC || k == VCC + 1 => Some(v), + _ => None, + } + }) + .filter(|v| !st.masks.contains_key(v) && !st.highs.contains_key(v) && !st.other.contains_key(v)) + .collect() +} + +/// One full console wave whose host halves already own the console lane IDs. +/// Outside these loops, codegen uses the original convergence result. +pub(super) struct WaveReads<'a> { + pub(super) plan: &'a predicate::PredicatePlan, + pub(super) per_lane: &'a Set, + pub(super) immutable: &'a Set, + pub(super) loop_blocks: &'a Set, + pub(super) base_step: &'a [bool], } /// [`step_and_cap`] evaluated over `exits` (either `st.exits` or exits after @@ -181,12 +226,13 @@ pub(crate) fn step_and_cap( /// both group-uniform SGPRs and group-uniform VGPRs, so a uniform loop bound /// loaded via `buffer_load` / `global_load` / `image_load` / `ds_read` and /// moved through `v_readfirstlane_b32` stays group-uniform. -pub(crate) fn step_and_cap_with( +pub(super) fn step_and_cap_with( p: &Program, st: &Structured, exits: &[LaneExit], uniform_branches: &Set, need_step: bool, + one_wave: Option>, ) -> (Vec, Vec, Set) { let n = p.blocks.len(); // Reverse postorder ranks, as lowering numbers them: a Jump to a block at @@ -272,7 +318,7 @@ pub(crate) fn step_and_cap_with( let mask = |r: Reg| matches!(r, Reg::S(k) if [EXEC, EXEC + 1, VCC, VCC + 1].contains(&k)); // Scalar writes no host wave can compute alike: other lanes' values, // hardware state, atomics, coherent loads (the group may write them). - let own = |inst: &Inst| { + let own = |inst: &Inst, site: Site| { let name = inst.name(); match &inst.fields { Fields::Sop { .. } => { @@ -281,7 +327,11 @@ pub(crate) fn step_and_cap_with( || name.contains("waveid") } Fields::Smem { cache, .. } => { - !(name.starts_with("s_load") || name.starts_with("s_buffer_load")) || cache.glc + !(name.starts_with("s_load") || name.starts_with("s_buffer_load")) + || cache.glc + // The two host waves may load an ordinary buffer on + // opposite sides of a store, even at a uniform address. + || one_wave.as_ref().is_some_and(|wave| !wave.immutable.contains(&site)) } _ => true, } @@ -321,42 +371,7 @@ pub(crate) fn step_and_cap_with( || st.highs.contains_key(&v) || st.scc_votes.contains_key(&v)) }; - // A plain number the compiler keeps in VCC_LO or VCC_HI as a spare - // scalar register, not a lane mask: written alone (besides - // SCC) by a scalar ALU instruction, and not a mask the structure knows - // (`masks`, `highs`, `other`). Such a value may be read as data like any - // SGPR; `from_scalar` below still needs every value it is computed from - // to be alike, so this admits no lane mask: - // - EXEC on entry, and any phi, is no instruction's write; - // - `v_cmp`/`v_cmpx` and other VALU results are never alike (`own`), so - // neither is anything a scalar instruction computes from them; - // - a saved copy of either (`s_mov_b64 s[10:11], exec`, - // `s_and_saveexec_b64`) reads the mask and so is not alike, and nor is - // a later move of the copy back into VCC; a spill through - // `v_writelane`/`v_readlane` goes by `st.restored`; - // - a 64-bit write (`s_and_b64 vcc, …`, `s_mov_b64 vcc, …`) is left out - // whatever it reads: in wave64 halves VCC_HI is the upper 32 lanes' - // bits, which differ between the host waves; - // - EXEC is never scratch: a write to it changes which lanes run. - let scratch_defs: Set = p - .blocks - .iter() - .flat_map(|b| b.insts.iter()) - .filter(|i| matches!(i.fields, Fields::Sop { .. })) - .filter_map(|i| { - let mut words = i.writes.iter().filter(|w| w.0 != Reg::Scc); - match (words.next(), words.next()) { - (Some(&(Reg::S(k), v)), None) if k == VCC || k == VCC + 1 => Some(v), - _ => None, - } - }) - .collect(); - let scratch = |v: Value| { - scratch_defs.contains(&v) - && !st.masks.contains_key(&v) - && !st.highs.contains_key(&v) - && !st.other.contains_key(&v) - }; + let scratch = scalar_scratch(p, st); // Group-uniform VGPRs: optimistically all non-entry VGPRs, narrowed with // `alike` in lockstep. Entry VGPRs (`v0`/`v1`/`v2` thread ids) are never // group-uniform. @@ -518,7 +533,11 @@ pub(crate) fn step_and_cap_with( let mut next_v: Set = Set::default(); for (b, block) in p.blocks.iter().enumerate() { // Every host wave enters by the same edge. - let entered = step[b] && block.preds.iter().all(|&q| step[q]); + let entered = step[b] + && block.preds.iter().all(|&q| step[q]) + && one_wave.as_ref().is_none_or(|wave| { + !wave.plan.linear_merges.contains(&b) && !wave.plan.skip_joins.contains_key(&b) + }); for phi in &block.phis { if scalar(phi.reg) && (tracked(phi.value) || entered && phi.args.iter().all(|a| alike.contains(a))) @@ -529,13 +548,37 @@ pub(crate) fn step_and_cap_with( next_v.insert(phi.value); } } + let mapped = one_wave + .as_ref() + .filter(|wave| step[b] && (wave.base_step[b] || wave.loop_blocks.contains(&b))); for (i, inst) in block.insts.iter().enumerate() { let name = inst.name(); // Group-uniform scalar ops. let from_scalar = inst.reads.iter().all(|&(r, v)| { - scalar(r) && (!mask(r) || tracked(v) || scratch(v)) && alike.contains(&v) + scalar(r) && (!mask(r) || tracked(v) || scratch.contains(&v)) && alike.contains(&v) + }); + // A tracked, active AND-mask has no numeric scalar form: + // reading its dwords ballots it at its definition. In a + // converged, single-wave group both halves get the same pair. + if mapped.is_some() + && name == "s_and_b64" + && let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } = &inst.fields + && let (Some(lo), Some(hi)) = + (inst.write(Reg::S(*code)), inst.write(Reg::S(code + 1))) + && st.active.contains(&lo) + && st.mask_bits(lo, Some(hi)).is_some() + && st.highs.get(&hi) == Some(&lo) + { + next.extend([lo, hi]); + } + let wave_read = mapped.is_some_and(|wave| { + matches!(&inst.fields, Fields::Valu(v) if matches!(v.src.first(), Some(Operand::Vector { .. }))) + && inst.writes.first().is_some_and(|w| !wave.per_lane.contains(&w.1)) }); - let lane_read = st.literal + let lane_read = (st.literal || wave_read) && step[b] && match name { "v_readfirstlane_b32" => true, @@ -549,12 +592,17 @@ pub(crate) fn step_and_cap_with( } _ => false, }; - if from_scalar && !own(inst) || lane_read || st.literal { - next.extend(inst.writes.iter().filter_map(|&(r, v)| { - (scalar(r) && (tracked(v) || from_scalar && !own(inst) || lane_read)) - .then_some(v) - })); - if from_scalar && !own(inst) || lane_read { + let published = one_wave + .as_ref() + .is_some_and(|wave| wave.plan.scalar_publications.contains(&(b, i))); + let common = from_scalar && !own(inst, (b, i)) || lane_read || published; + if common || st.literal { + next.extend( + inst.writes.iter().filter_map(|&(r, v)| { + (scalar(r) && (tracked(v) || common)).then_some(v) + }), + ); + if common { continue; } } @@ -570,7 +618,10 @@ pub(crate) fn step_and_cap_with( } // Guarded VGPR writes only stay group-uniform when the guard // itself is group-uniform (for simplicity, require no guard). - if st.guards[b][i].is_some() { + // This additional proof starts from scalar operations and + // real broadcasts. A predicated vector write can retain a + // different old value even without an instruction-level guard. + if one_wave.is_some() || st.guards[b][i].is_some() { continue; } // Buffer / global / LDS loads at group-uniform addresses. @@ -723,7 +774,7 @@ pub(crate) fn in_step_with( exits: &[LaneExit], uniform_branches: &Set, ) -> Vec { - step_and_cap_with(p, st, exits, uniform_branches, true).0 + step_and_cap_with(p, st, exits, uniform_branches, true, None).0 } /// Per block, whether each lane of the group runs it exactly once: no cycle @@ -756,3 +807,16 @@ pub(crate) fn once_per_lane(p: &Program) -> Vec { }) .collect() } + +impl Lower<'_> { + /// Thread-group sync with a shared-memory fence, and a UAV fence when + /// the program writes UAVs (the waits before an s_barrier make those + /// writes visible on the console). + pub(super) fn group_barrier(&mut self) { + let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + let mode = self.s.m.i32(mode); + let void = self.s.t.void; + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } +} diff --git a/crates/victory-shader/src/emit/lower/first_lane.rs b/crates/victory-shader/src/emit/lower/first_lane.rs index b07476fdc..5395f8574 100644 --- a/crates/victory-shader/src/emit/lower/first_lane.rs +++ b/crates/victory-shader/src/emit/lower/first_lane.rs @@ -501,12 +501,9 @@ pub(super) fn index_waterfalls(x: &Parts) -> HashSet { if read.name() != "v_readfirstlane_b32" { continue; } - let (Some(&(_, s)), Some(v)) = ( + let (Some(&(key @ Reg::S(_), s)), Some(&(index, v))) = ( read.writes.first(), - read.reads - .iter() - .find(|(r, _)| matches!(r, Reg::V(_))) - .map(|r| r.1), + read.reads.iter().find(|(r, _)| matches!(r, Reg::V(_))), ) else { continue; }; @@ -534,6 +531,10 @@ pub(super) fn index_waterfalls(x: &Parts) -> HashSet { .all(|&(_, w)| save.reads.iter().any(|&(_, r)| r == w)); let drops = drop.name() == "s_xor_b64" && drop.writes.iter().any(|w| w.0 == Reg::S(EXEC)) + && [EXEC, EXEC + 1].into_iter().all(|code| { + let reg = Reg::S(code); + drop.read(reg).is_some() && drop.read(reg) == save.write(reg) + }) && saved.len() == 2 && saved .iter() @@ -543,15 +544,15 @@ pub(super) fn index_waterfalls(x: &Parts) -> HashSet { } // The body: `s_mov_b32 m0, s`, and vector operations on each lane's // own registers. - let mut m0s = Vec::new(); + let mut m0 = None; + let mut access = false; let body_ok = insts[3..last - 1].iter().all(|i| { let name = i.name(); if name == "s_mov_b32" - && i.writes.iter().all(|w| w.0 == Reg::S(M0)) - && i.reads.iter().all(|&(_, r)| r == s) + && i.reads == [(key, s)] + && let [(Reg::S(M0), v)] = i.writes.as_slice() { - m0s.extend(i.writes.iter().map(|w| w.1)); - return true; + return m0.replace(*v).is_none(); } if matches!(name, "s_nop" | "s_waitcnt") { return true; @@ -559,18 +560,31 @@ pub(super) fn index_waterfalls(x: &Parts) -> HashSet { let Fields::Valu(f) = &i.fields else { return false; }; + if crate::ir::relative_operands(name) != (false, false) { + if !matches!(name, "v_movrels_b32" | "v_movreld_b32") + || m0.is_none() + || i.read(Reg::S(M0)) != m0 + || !i.relative_in_file(p.vgprs) + { + return false; + } + access = true; + } f.dpp.is_none() && f.sdwa.is_none() - && i.writes.iter().all(|w| matches!(w.0, Reg::V(_))) + && i.writes.iter().all(|w| matches!(w.0, Reg::V(_)) && w.0 != index) && !["lane", "mbcnt", "permlane", "interp", "cmp"] .iter() .any(|n| name.contains(n)) }); - let seen_inside = only_in(s, b) - && m0s.iter().all(|&m| only_in(m, b)) - && cmp.writes.iter().all(|w| only_in(w.1, b)) - && saved.iter().all(|&m| only_in(m, b)); - if body_ok && !m0s.is_empty() && seen_inside { + let seen_inside = insts.iter().enumerate().all(|(at, i)| { + i.writes.iter().all(|&(r, v)| { + matches!(r, Reg::V(_)) + || (at == last - 1 && matches!(r, Reg::S(code) if code == EXEC || code == EXEC + 1)) + || only_in(v, b) + }) + }); + if body_ok && access && seen_inside { out.insert(s); } } diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 3e41df40c..59c902d9c 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -68,6 +68,17 @@ use super::*; /// Console lanes per host wave in halves. const HALF: u32 = 32; +/// Both the lane mapping and any proof relying on its bijection must +/// reserve room for the ticket counter alongside the half-exchange scratch. +pub(super) fn uses_lane_tickets(group: u32, wave: u32, lds_dwords: u32, halves: bool) -> bool { + let half_dwords = if halves { + group.div_ceil(2 * HALF) * 2 + } else { + 0 + }; + group > wave && super::super::thread_ticket() && lds_dwords + half_dwords < GROUP_SHARED_DWORDS +} + impl Lower<'_> { /// Whether a wave64 program whose lanes follow the console's runs in /// halves: the host's waves are 32 lanes at most. @@ -101,15 +112,7 @@ impl Lower<'_> { let i32t = self.s.t.i32; let wave = self.s.wave_size.expect("set with console lanes"); let group: u32 = self.s.threads.map_or(wave, |t| t.iter().product()); - let half_dwords = if self.halves { - group.div_ceil(2 * HALF) * 2 - } else { - 0 - }; - let use_ticket = group > wave - && super::super::thread_ticket() - && self.s.lds_dwords + half_dwords < GROUP_SHARED_DWORDS; - let f = if use_ticket { + let f = if uses_lane_tickets(group, wave, self.s.lds_dwords, self.halves) { let arr = self.s.m.array(1, i32t); let counter = self.s.m.global("wave_ticket", arr, 3); let zero = self.s.m.i32(0); @@ -684,21 +687,9 @@ const GROUP_SHARED_DWORDS: u32 = 8192; /// in the other half, and the value is not known to be the same there. pub(super) const FIRST_ACROSS: Why = "a first-lane read of a value that may differ between 32-lane halves (wave64 on a 32-lane host)"; -/// Whether `x` (a wave64 compute program) has a non-waterfall -/// `v_readfirstlane_b32` whose vector source may differ between lanes of the -/// console wave: such a read needs console-wave lane order (and halves on a -/// 32-lane host) so both halves see the same first active lane. Not one each -/// host half can make by itself (`alone`, [`super::first_lane::read_alone`]). -pub(super) fn needs_first_lane( - x: &Parts, - alike: &mut Option>, - alone: &HashSet, -) -> bool { - if !x.native.wave64 { - return false; - } +fn first_lane_sources<'a>(x: &'a Parts, alone: &'a HashSet) -> impl Iterator + 'a { let wf = &x.res.waterfall.reads; - let is_vec_first = |i: &Inst| -> Option { + let is_vec_first = move |i: &Inst| -> Option { if i.name() != "v_readfirstlane_b32" || i.writes .first() @@ -714,13 +705,28 @@ pub(super) fn needs_first_lane( _ => None, } }; - let mut srcs = x + x .p .blocks .iter() .flat_map(|b| &b.insts) .filter_map(is_vec_first) - .peekable(); +} + +/// Whether `x` (a wave64 compute program) has a non-waterfall +/// `v_readfirstlane_b32` whose vector source may differ between lanes of the +/// console wave: such a read needs console-wave lane order (and halves on a +/// 32-lane host) so both halves see the same first active lane. Excludes +/// reads each host half can make by itself (see [`super::first_lane::read_alone`]). +pub(super) fn needs_first_lane( + x: &Parts, + alike: &mut Option>, + alone: &HashSet, +) -> bool { + if !x.native.wave64 { + return false; + } + let mut srcs = first_lane_sources(x, alone).peekable(); if srcs.peek().is_none() { return false; } @@ -1728,6 +1734,167 @@ pub(super) fn lane_uniform(x: &Parts) -> HashSet { } } +/// In a wave-dependent loop, both host halves can compute the same recurrence +/// without meeting. Prove induction over SSA phis, including the branches +/// selecting their incoming edges. Only return proven first-lane sources. +pub(super) fn shared_loop_first_lanes( + x: &Parts, + alone: &HashSet, + alike: &mut HashSet, +) { + let Some(tid) = wave_tid(x) else { return }; + let (p, st) = (x.p, x.st); + let wanted: HashSet<_> = first_lane_sources(x, alone) + .filter(|v| !alike.contains(v)) + .collect(); + if wanted.is_empty() || !p.blocks[0].preds.is_empty() { + return; + } + // A group barrier reached exactly once, before any branch. Any write + // afterwards, even beyond the loop exit, could race a slower half's load. + let entry = &p.blocks[0].insts; + let Some(fence) = entry.iter().rposition(|i| i.name() == "s_barrier") else { + return; + }; + let writes_lds = |i: &Inst| match i.fields { + Fields::Ds { gds: false, .. } => { + !(i.name().starts_with("ds_read") + || i.name().starts_with("ds_swizzle") + || i.name().contains("permute")) + } + Fields::Buffer { lds, .. } => lds, + Fields::Flat { lds, .. } => { + lds || i.name().starts_with("flat_store_") || i.name().starts_with("flat_atomic_") + } + _ => false, + }; + if entry[fence + 1..] + .iter() + .chain(p.blocks[1..].iter().flat_map(|b| &b.insts)) + .any(writes_lds) + { + return; + } + let Some(regions) = branch_regions(p, st) else { return }; + let mut candidates: HashSet<_> = p + .blocks + .iter() + .flat_map(|b| { + b.phis + .iter() + .map(|f| f.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + }) + .collect(); + // Start with possible definitions, then eliminate each whose dependency + // fails. Every reachable phi must pass its entry edge as well as its back + // edge; uninitialized program inputs never enter the candidate set. + loop { + let mut wave_all = vec![true; p.blocks.len()]; + for (b, region) in ®ions { + let LaneExit::Branch { when, .. } = st.exits[*b] else { + continue; + }; + if !st + .bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Lane(v) if candidates.contains(v))) + { + for (all, inside) in wave_all.iter_mut().zip(region) { + *all &= !inside; + } + } + } + let mut next = HashSet::new(); + for (b, block) in p.blocks.iter().enumerate().filter(|(b, _)| wave_all[*b]) { + if block.preds.iter().all(|&q| wave_all[q]) { + next.extend( + block + .phis + .iter() + .filter(|phi| { + matches!(phi.reg, Reg::V(_) | Reg::S(0..=105)) + && !x.res.waterfall.reads.contains(&phi.value) + && phi.args.iter().all(|v| candidates.contains(v)) + }) + .map(|phi| phi.value), + ); + } + for (i, inst) in block.insts.iter().enumerate() { + if st.guards[b][i].is_some() { + continue; + } + let operand = |op: &Operand| match *op { + Operand::Literal(_) | Operand::Const(128..=208) => true, + Operand::Scalar { + code: code @ 0..=105, + dwords: 1, + } => inst.read(Reg::S(code)).is_some_and(|v| { + candidates.contains(&v) + && !st.masks.contains_key(&v) + && !st.highs.contains_key(&v) + }), + Operand::Vector { reg, dwords: 1 } => inst + .read(Reg::V(reg)) + .is_some_and(|v| candidates.contains(&v)), + _ => false, + }; + let proven = match &inst.fields { + Fields::Sop { src, .. } + if matches!( + inst.name(), + "s_mov_b32" | "s_add_i32" | "s_add_u32" | "s_lshl_b32" + ) => + { + src.iter().all(operand) + } + Fields::Valu(v) if v.dpp.is_none() && v.sdwa.is_none() => { + let wave_id = inst.name() == "v_lshrrev_b32" + && v.neg == 0 + && v.abs == 0 + && v.opsel == 0 + && matches!(v.src.as_slice(), + [Operand::Const(134..=159), Operand::Vector { reg, dwords: 1 }] + if inst.read(Reg::V(*reg)) == Some(tid)); + wave_id + || (matches!( + inst.name(), + "v_mov_b32" + | "v_lshlrev_b32" + | "v_xor_b32" + | "v_add_nc_u32" + | "v_readfirstlane_b32" + | "v_cmpx_lt_u32" + | "v_cmpx_eq_u32" + | "v_cmpx_ne_u32" + ) && v.src.iter().all(operand)) + } + Fields::Ds { + gds: false, + addr: Some(addr), + .. + } => inst.name() == "ds_read_b32" && (b != 0 || i > fence) && operand(addr), + _ => false, + }; + if proven { + next.extend( + inst.writes + .iter() + .filter(|(r, v)| *r != Reg::Scc && !x.res.waterfall.reads.contains(v)) + .map(|w| w.1), + ); + } + } + } + if next == candidates { + alike.extend(wanted.intersection(&next).copied()); + return; + } + candidates = next; + } +} + /// The VGPR dwords `inst` names as explicit source operands — its address /// words and, where its data operand is a source (a store or an atomic), /// those too — or `None` where its fields do not say. A written VGPR among diff --git a/crates/victory-shader/src/emit/lower/literal_lds.rs b/crates/victory-shader/src/emit/lower/literal_lds.rs new file mode 100644 index 000000000..6099af86b --- /dev/null +++ b/crates/victory-shader/src/emit/lower/literal_lds.rs @@ -0,0 +1,210 @@ +//! Paired LDS phases in one ticketed guest wave. The caller has already +//! proved all reachable branch decisions and cap edges common to both halves. +use super::*; + +/// Only unguarded definitions in the entry block establish lane addresses. +/// A phi or an instruction that preserves an old VGPR never supplies a fact. +fn entry_value(inst: &Inst, facts: &Map) -> Option<(Value, [u32; 64])> { + use crate::gfx10::Encoding; + let Fields::Valu(v) = &inst.fields else { + return None; + }; + if !matches!(inst.machine.encoding, Encoding::Vop1 | Encoding::Vop2) + || v.sdwa.is_some() + || v.dpp.is_some() + { + return None; + } + let operand = |op: &Operand| match *op { + Operand::Const(c) => Some([crate::resource::inline(c)?; 64]), + Operand::Literal(k) => Some([k; 64]), + Operand::Vector { reg, dwords: 1 } => facts.get(&inst.read(Reg::V(reg))?).copied(), + _ => None, + }; + let a = operand(v.src.first()?)?; + let values = match (inst.name(), v.src.as_slice()) { + ("v_mov_b32", [_]) => a, + (op, [_, b]) => { + let b = operand(b)?; + match op { + "v_add_nc_u32" => std::array::from_fn(|l| a[l].wrapping_add(b[l])), + "v_lshlrev_b32" => std::array::from_fn(|l| b[l].wrapping_shl(a[l])), + "v_xor_b32" => std::array::from_fn(|l| b[l] ^ a[l]), + _ => return None, + } + } + _ => return None, + }; + let [(Reg::V(_), value)] = inst.writes.as_slice() else { + return None; + }; + Some((*value, values)) +} + +pub(super) fn group_size(threads: [u32; 3]) -> Result { + threads + .into_iter() + .try_fold(1, u32::checked_mul) + .ok_or_else(|| unsupported(0, "overflow in a literal LDS group size")) +} + +pub(super) fn prove( + x: &Parts, + order: &[usize], + lds: u32, + scalar: &Set, +) -> Result, Stop> { + let mut phases = Set::default(); + if lds == 0 { + return Ok(phases); + } + let StageIo::Cs(cs) = x.native.io else { + unreachable!() + }; + if group_size(cs.threads)? != 64 { + return Err(unsupported( + 0, + "paired literal LDS outside one complete wave64", + )); + } + // Keep declaration-only programs on their original refusal path. + if !order.iter().any(|&b| { + x.p.blocks[b] + .insts + .iter() + .any(|i| matches!(i.fields, Fields::Ds { .. })) + }) { + return Err(unsupported( + 0, + "literal scalar publication without one ticketed wave64 and zero guest LDS", + )); + } + if scalar.iter().any(|&(b, i)| { + !matches!( + x.p.blocks[b].insts[i].name(), + "s_buffer_load_dword" | "s_buffer_load_dwordx2" | "s_buffer_load_dwordx4" + ) + }) { + return Err(unsupported(0, "a wide scalar publication with guest LDS")); + } + if cs.thread_id_vgprs() > 3 { + return Err(unsupported( + 0, + "a reserved thread ID layout in paired literal LDS", + )); + } + let mut facts = Map::default(); + for &(v, input) in &x.io.inputs { + if let Input::ThreadIdInGroup(c) = input { + let [sx, sy, _] = cs.threads; + let lanes = std::array::from_fn(|l| match c { + 0 => l as u32 % sx, + 1 => (l as u32 / sx) % sy, + _ => l as u32 / (sx * sy), + }); + facts.insert(v, lanes); + } + } + let mut initialized = Set::default(); + for &b in order { + for (i, inst) in x.p.blocks[b].insts.iter().enumerate() { + let fail = |why| unsupported(inst.machine.offset, why); + let unguarded_entry = b == 0 && x.st.guards[b][i].is_none(); + let name = inst.name(); + let safe = |op: &Operand| *op != Operand::Const(254); + let Fields::Ds { + addr: Some(Operand::Vector { reg, dwords: 1 }), + offset0, + offset1, + gds: false, + .. + } = inst.fields + else { + // Enumerate the non-LDS operations allowed alongside these phases. + let allowed = match &inst.fields { + Fields::Sop { src, .. } => { + src.iter().all(safe) + && matches!( + name, + "s_mov_b32" + | "s_mov_b64" + | "s_add_u32" + | "s_sub_u32" + | "s_cmp_lg_u32" + ) + } + Fields::Sopp { .. } => matches!( + name, + "s_waitcnt" | "s_cbranch_scc1" | "s_endpgm" | "s_branch" | "s_nop" + ), + Fields::Valu(v) => { + v.src.iter().all(safe) + && matches!( + name, + "v_mov_b32" | "v_add_nc_u32" | "v_lshlrev_b32" | "v_xor_b32" + ) + } + Fields::Smem { soffset, .. } => { + safe(soffset) + && matches!( + name, + "s_load_dwordx4" + | "s_buffer_load_dword" + | "s_buffer_load_dwordx2" + | "s_buffer_load_dwordx4" + ) + } + Fields::Buffer { + lds: false, + soffset, + .. + } => safe(soffset) && name == "buffer_store_dword", + _ => false, + }; + if !allowed { + return Err(fail("an unsupported operation in paired literal LDS")); + } + if unguarded_entry && let Some((v, lanes)) = entry_value(inst, &facts) { + facts.insert(v, lanes); + } + continue; + }; + let write = match name { + "ds_write2_b32" => true, + "ds_read2_b32" => false, + _ => return Err(fail("an unsupported operation in paired literal LDS")), + }; + let bases = inst + .read(Reg::V(reg)) + .and_then(|v| facts.get(&v)) + .ok_or_else(|| fail("a paired LDS address without an exact entry value"))?; + let mut words = Set::default(); + for &base in bases { + for offset in [offset0, offset1] { + let at = base.wrapping_add(4 * u32::from(offset)); + if at % 4 != 0 || at / 4 >= lds { + return Err(fail("an unaligned or out-of-range paired LDS address")); + } + if write && !words.insert(at) { + return Err(fail("overlapping writes within one paired LDS instruction")); + } + if !write && !initialized.contains(&at) { + return Err(fail( + "a paired LDS read without a dominating initialization", + )); + } + } + } + if write && unguarded_entry { + initialized.extend(words); + } + // A fence before each dynamic phase also separates the last visit + // from the next. Lower::run emits it before either guarded store. + phases.insert((b, i)); + } + } + Ok(phases) +} + +#[cfg(test)] +mod tests; diff --git a/crates/victory-shader/src/emit/lower/literal_lds/tests.rs b/crates/victory-shader/src/emit/lower/literal_lds/tests.rs new file mode 100644 index 000000000..88514be98 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/literal_lds/tests.rs @@ -0,0 +1,154 @@ +use super::*; +use crate::emit::halves_tests::{literal_lds::paired, parts}; + +/// Exercise final native admission only. A refusal never enters the lowerer. +fn admission(n: &NativeProgram) -> Result<(), Stop> { + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, n).unwrap(); + let x = parts(n, &p, &st, &res, &io, true, true); + let StageIo::Cs(cs) = n.io else { + unreachable!() + }; + literal_publish::prove( + &x, + 64, // The LDS proof must validate the native dimensions independently. + cs.lds_bytes() / 4, + &HashMap::new(), + ) + .map(|proof| assert!(proof.is_some())) +} + +fn refusal(n: &NativeProgram, expected: &str) { + let Err(Stop::Fail(err)) = admission(n) else { + panic!("expected {expected}") + }; + assert!(err.to_string().contains(expected), "{err}"); +} + +fn replace(n: &mut NativeProgram, before: u32, after: u32) { + let word = n + .code + .as_chunks_mut::<4>() + .0 + .iter_mut() + .find(|w| **w == before.to_le_bytes()) + .unwrap(); + word.copy_from_slice(&after.to_le_bytes()); +} + +#[test] +fn literal_lds_admission_refuses_wide_scalar_publication() { + use crate::emit::halves_tests::literal_publish::wide::fixture; + + for width in [8_u32, 16] { + let without_lds = fixture(width, ResourceType::Cbv, &[0x7d84_0100], true); + assert!(admission(&without_lds).is_ok(), "width {width}"); + + let mut n = paired([8, 8, 1], 512); + let load = 0xf420_0016 | width.trailing_zeros() << 18 | 80 << 6; + replace(&mut n, 0xf424_0796, load); // table CBV to s[80..] + replace(&mut n, 0x3000_0000, 0xfa00_0004); // NULL offset, immediate byte 4 + replace(&mut n, 0x4a0c_141e, 0x4a0c_1450); // v6 = s80 + v10 + replace(&mut n, 0x4a0e_161f, 0x4a0e_1651); // v7 = s81 + v11 + refusal(&n, "a wide scalar publication with guest LDS"); + } +} + +#[test] +fn literal_lds_admission_requires_ticket_and_guest_bounds() { + let n = paired([8, 8, 1], 32_256); + assert!(admission(&n).is_ok()); + crate::emit::with_thread_ticket(false, || refusal(&n, "one ticketed wave64")); + refusal(&paired([8, 8, 1], 32_768), "one ticketed wave64"); + let n = paired([8, 8, 1], 512); + for (threads, reason) in [ + ([0, 8, 1], "outside one complete wave64"), + ([32, 1, 1], "outside one complete wave64"), + ( + [1_073_741_840, 4, 1], + "overflow in a literal LDS group size", + ), + ] { + let mut invalid = n.clone(); + let StageIo::Cs(cs) = &mut invalid.io else { + unreachable!() + }; + cs.threads = threads; + refusal(&invalid, reason); + } + for (from, to, why) in [ + (0xd838_0100, 0xd838_8000, "out-of-range paired LDS"), // second component reaches 512 + (0x3404_1083, 0x3404_1081, "unaligned or out-of-range"), // two-byte lane spacing + (0xd838_0100, 0xd838_0000, "overlapping writes"), // components alias + (0x0007_0602, 0x0007_0605, "overlapping writes"), // all lanes write the same base + (0xd838_0100, 0xd8dc_0100, "dominating initialization"), // first phase reads + (0x3404_1083, 0x3404_3083, "exact entry value"), // data without address provenance + ] { + let mut program = n.clone(); + replace(&mut program, from, to); + refusal(&program, why); + } +} + +#[test] +fn literal_lds_admission_classifies_each_reachable_operation_and_cap_edge() { + let n = paired([64, 1, 1], 512); + for opcode in [ + 0xd800_0000, // ds_add_u32 + 0xd87c_0000, // ds_write_b16 + 0xd83c_0100, // ds_write2st64_b32 + 0xd83a_0100, // GDS + 0xd834_0000, // single dword + ] { + let mut program = n.clone(); + replace(&mut program, 0xd838_0100, opcode); + refusal(&program, "unsupported operation in paired literal LDS"); + } + let mut direct = n.clone(); + replace(&mut direct, 0x7e0a_0280, 0x7e0a_02fe); // src_lds_direct + refusal(&direct, "unsupported operation in paired literal LDS"); + let mut divergent = n; + replace(&mut divergent, 0xbe94_0383, 0xb914_0004); // hardware state as trip count + refusal(&divergent, "branch without common group control flow"); +} + +#[test] +fn literal_lds_admission_requires_a_defined_thread_id_layout() { + let mut n = paired([64, 1, 1], 512); + let StageIo::Cs(cs) = &mut n.io else { + unreachable!() + }; + cs.rsrc2 |= 3 << 11; + refusal(&n, "reserved thread ID layout"); +} + +#[test] +fn literal_lds_admission_requires_full_dominating_initialization() { + for setup in [ + &[0xbefe_0481][..], // only lane 0 executes the first store + &[ + 0xf420_0496, + 0xfa00_0000, + 0xbf8c_c07f, // s18 = table CBV word 0 + 0xbf07_8012, + 0xbf85_0003, // if s18 != 0, skip the first store and wait + ], + ] { + let mut n = paired([64, 1, 1], 512); + let mut code: Vec = n + .code + .as_chunks::<4>() + .0 + .iter() + .copied() + .map(u32::from_le_bytes) + .collect(); + let store = code.iter().position(|&w| w == 0xd838_0100).unwrap(); + code.insert(store + 3, 0xbefe_04c1); // full EXEC before the partner read + code.splice(store..store, setup.iter().copied()); + n.code = code.into_iter().flat_map(u32::to_le_bytes).collect(); + refusal(&n, "a paired LDS read without a dominating initialization"); + } +} diff --git a/crates/victory-shader/src/emit/lower/literal_publish.rs b/crates/victory-shader/src/emit/lower/literal_publish.rs new file mode 100644 index 000000000..14162e7a5 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/literal_publish.rs @@ -0,0 +1,772 @@ +//! Publication assumes both halves enter the same instruction visit. Prove +//! this by induction from dispatch entry: each branch picks one common edge, +//! so every header counter sees the same resets, increments and cap exits. +//! Scalar equality is local to the visit; a load can change on every trip. +use super::*; + +pub(super) struct Proof { + pub step: Vec, + pub common: Set, + pub sites: Set, + pub guest_barriers: Set, +} + +fn memory_sources(x: &Parts) -> (Map, Set) { + let addresses: Map<_, _> = x.res.scalar.iter().copied().collect(); + let handles: Set<_> = x + .res + .descriptors + .iter() + .flat_map(|d| d.source.leaves()) + .filter_map(|s| match s { + Source::Loaded { load, .. } + if addresses + .get(load) + .and_then(|a| x.native.layout.get(a.param)) + .is_some_and(|p| { + matches!( + p.root, + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap + ) + }) => + { + Some(*load) + } + _ => None, + }) + .collect(); + (addresses, handles) +} + +/// A folded graph must have valid numeric consumers even when it needs no +/// scalar publication or descriptor handles. +pub(super) fn folded_roles(x: &Parts, carries: &Set<(Site, Value)>) -> Result<(), ShaderError> { + let (addresses, handles) = memory_sources(x); + let order = crate::ir::reverse_postorder(&x.p.blocks); + symbolic_addresses(x, &order, &addresses, &handles, carries).map(drop) +} + +pub(super) fn prove( + x: &Parts, + group: u32, + lds: u32, + bad: &HashMap, +) -> Result, Stop> { + let (addresses, handles) = memory_sources(x); + let order = crate::ir::reverse_postorder(&x.p.blocks); + let memory = order.iter().flat_map(|&b| { + x.p.blocks[b] + .insts + .iter() + .enumerate() + .filter(|(_, inst)| matches!(inst.fields, Fields::Smem { .. })) + .map(move |(i, inst)| ((b, i), inst)) + }); + let immutable = |site: &Site| { + addresses + .get(site) + .is_some_and(|a| matches!(a.param, CODE | USER_DATA)) + }; + let code_buffers: Set<_> = x + .res + .descriptors + .iter() + .filter(|d| matches!(d.source, Source::Built { address, .. } if address.param == CODE)) + .map(|d| d.site) + .collect(); + let facts = super::retry::immutable::prove(x.p, x.st, x.res, x.native); + if !facts.carries.is_empty() { + folded_code(x.p, x.res, x.native, &facts.reads).map_err(Stop::Fail)?; + } + if memory + .clone() + .all(|(s, _)| immutable(&s) || handles.contains(&s) || code_buffers.contains(&s)) + { + // A descriptor role on one operand does not make every use of its + // storage a handle. Check the legacy exit before granting that exemption. + if x.host_wave32 && x.native.wave64 && (!handles.is_empty() || !facts.carries.is_empty()) { + symbolic_addresses(x, &order, &addresses, &handles, &facts.carries) + .map_err(Stop::Fail)?; + } + return Ok(None); + } + if !x.host_wave32 + || !x.native.wave64 + || group != 64 + || !halves::uses_lane_tickets(group, 32, lds, true) + { + return Err(unsupported( + 0, + "literal scalar publication without one ticketed wave64 and zero guest LDS", + )); + } + if x.res.waterfall != Default::default() { + return Err(unsupported( + 0, + "a resource waterfall in literal scalar publication", + )); + } + // Table CBVs already use the runtime's raw SRV representation. + let buffers: Map<_, _> = predicate::fixed_scalar_buffers(x, |kind| { + matches!(kind, ResourceType::Srv | ResourceType::Cbv) + }) + .filter_map(|(site, offset, load, first)| { + let inst = &x.p.blocks[site.0].insts[site.1]; + let def = &x.p.blocks[load.0].insts[load.1]; + direct_descriptor(inst, def, first).then_some((site, offset)) + }) + .collect(); + let mut sites = Set::default(); + for (s @ (b, i), inst) in memory.clone() { + let Fields::Smem { cache, .. } = inst.fields else { + unreachable!() + }; + if cache != Default::default() || x.st.guards[b][i].is_some() { + return Err(unsupported( + inst.machine.offset, + "a cached or predicated literal scalar memory access", + )); + } + if (handles.contains(&s) || immutable(&s)) && smem_dwords(inst.name()).is_some() { + continue; + } + if !buffers.contains_key(&s) + || !(matches!( + inst.name(), + "s_buffer_load_dword" | "s_buffer_load_dwordx2" | "s_buffer_load_dwordx4" + ) || wide_buffer_read(inst)) + { + return Err(unsupported( + inst.machine.offset, + "literal scalar publication from an unsupported source or width", + )); + } + sites.insert(s); + } + + let mut rank = vec![usize::MAX; x.p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + rank[b] = n; + } + let computed = &facts.reads; + // Reject at the producer: ordinary vector uses and lane reads do not + // require the original scalar to be in the common set. + for &((b, i), address) in &x.res.scalar { + if address.param == CODE && rank[b] != usize::MAX { + let inst = &x.p.blocks[b].insts[i]; + if !computed.contains_key(&(b, i)) && !bounded_immutable_read(x.native, inst, address) { + return Err(unsupported( + inst.machine.offset, + "a code read without a proved byte range in literal publication", + )); + } + } + } + let idom = crate::ir::idoms(&x.p.blocks, &order, &rank); + let mut definitions = Map::default(); + for &b in &order { + let block = &x.p.blocks[b]; + definitions.extend(block.phis.iter().map(|phi| (phi.value, b))); + definitions.extend( + block + .insts + .iter() + .flat_map(|inst| inst.writes.iter().map(|w| (w.1, b))), + ); + } + let dominates = |def: usize, mut pred: usize| { + while rank[pred] > rank[def] { + pred = idom[pred]; + } + def == pred + }; + let entry: Set<_> = x + .res + .params + .iter() + .filter_map(|&(v, p, d)| { + let rp = x.native.layout.get(p)?; + (d < rp.sgprs + && matches!( + rp.root, + RootType::Table + | RootType::Constants + | RootType::ResourceHeap + | RootType::SamplerHeap + )) + .then_some(v) + }) + .chain( + x.io.inputs + .iter() + .filter_map(|&(v, input)| matches!(input, Input::GroupId(_)).then_some(v)), + ) + .collect(); + let entry = + x.p.inputs + .iter() + .filter_map(|&(reg, v)| (matches!(reg, Reg::S(_)) && entry.contains(&v)).then_some(v)) + .collect::>(); + // Only backedge phi operands can use a hypothesis. On the first trip + // every forward operand must already have been produced in this pass. + let mut previous: Option> = None; + let scratch = barriers::scalar_scratch(x.p, x.st); + let mut common = loop { + let mut known = entry.clone(); + for &b in &order { + let block = &x.p.blocks[b]; + for phi in &block.phis { + if !matches!(phi.reg, Reg::S(_) | Reg::Scc) + || bad.contains_key(&phi.value) + || b == 0 + || phi.args.len() != block.preds.len() + || !block.preds.iter().any(|&p| rank[p] < rank[b]) + { + continue; + } + if block.preds.iter().zip(&phi.args).all(|(&p, v)| { + rank[p] == usize::MAX + || (definitions + .get(v) + .map_or_else(|| entry.contains(v), |&def| dominates(def, p)) + && if rank[p] < rank[b] { + known.contains(v) + } else { + previous.as_ref().is_none_or(|set| set.contains(v)) + }) + }) { + known.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let common = if sites.contains(&site) { + buffers[&site].is_none_or(|v| known.contains(&v)) + } else if immutable(&site) && matches!(inst.fields, Fields::Smem { .. }) { + inst.reads.iter().all(|&(_, v)| known.contains(&v)) + && (computed.contains_key(&site) + || bounded_immutable_read(x.native, inst, addresses[&site])) + } else { + match inst.name() { + "v_readfirstlane_b32" => { + matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_none() && v.sdwa.is_none() && matches!(v.src.first(), Some(Operand::Vector { .. }))) + } // literal lowering always ballots and exchanges + "v_readlane_b32" => { + halves::uniform_selector(inst, &known) + && inst + .writes + .first() + .and_then(|w| x.st.restored.get(&w.1)) + .is_none_or(|v| known.contains(v)) + } + _ => { + deterministic(inst, |v| scratch.contains(&v)) + && inst.reads.iter().all(|&(_, v)| known.contains(&v)) + } + } + }; + if common { + known.extend( + inst.writes + .iter() + .filter_map(|&(r, v)| matches!(r, Reg::S(_) | Reg::Scc).then_some(v)), + ); + } + } + } + if previous.as_ref() == Some(&known) { + break known; + } + previous = Some(known); + }; + for (site, inst) in memory { + if (sites.contains(&site) && buffers[&site].is_some_and(|v| !common.contains(&v))) + || (handles.contains(&site) && !inst.reads.iter().all(|&(_, v)| common.contains(&v))) + { + return Err(unsupported( + inst.machine.offset, + "a literal scalar memory address without common initialized operands", + )); + } + } + + let symbolic = + symbolic_addresses(x, &order, &addresses, &handles, &facts.carries).map_err(Stop::Fail)?; + common.retain(|v| !symbolic.contains(v)); + let step = check_control(x, &order, &rank, &common)?; + let guest_barriers = literal_lds::prove(x, &order, lds, &sites)?; + Ok(Some(Proof { + guest_barriers, + step, + common, + sites, + })) +} + +/// A table/heap address and the PC have relative host representations. Equality +/// across halves suffices for checked resource addressing, but says nothing +/// about their guest bits. A tracked descriptor also has a handle but no +/// numeric storage words. Follow both through copies, ALU results and phis. +fn symbolic_addresses( + x: &Parts, + order: &[usize], + addresses: &Map, + handles: &Set, + carries: &Set<(Site, Value)>, +) -> Result, ShaderError> { + let mut symbolic: Set<_> = x + .res + .params + .iter() + .filter_map(|&(v, p, _)| { + matches!( + x.native.layout.get(p)?.root, + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap + ) + .then_some(v) + }) + .collect(); + for &(b, i) in handles { + symbolic.extend(x.p.blocks[b].insts[i].writes.iter().map(|w| w.1)); + } + loop { + let before = symbolic.len(); + for &b in order { + let block = &x.p.blocks[b]; + for phi in &block.phis { + if phi.args.iter().any(|v| symbolic.contains(v)) { + symbolic.insert(phi.value); + } + } + for inst in &block.insts { + if inst.name() == "s_getpc_b64" + || matches!(inst.fields, Fields::Sop { .. } | Fields::Valu(_)) + && inst.reads.iter().any(|(_, v)| symbolic.contains(v)) + { + symbolic.extend(inst.writes.iter().map(|w| w.1)); + } + } + } + if before == symbolic.len() { + break; + } + } + + const WHY: Why = "a relocated address or descriptor word read as numeric data without guest-exact bits in literal publication"; + let refusal = |offset| ShaderError::Unsupported { offset, what: WHY }; + let exact_term = |a: &Address| a.dynamic.is_none_or(|v| !symbolic.contains(&v)); + let mut roles = Map::>::default(); + for d in &x.res.descriptors { + let leaves = d.source.leaves(); + if leaves + .iter() + .any(|s| matches!(s, Source::Built { address, .. } if !exact_term(address))) + { + return Err(refusal(x.p.blocks[d.site.0].insts[d.site.1].machine.offset)); + } + if !leaves + .iter() + .any(|s| matches!(s, Source::Built { address, .. } if address.param == MEMORY)) + { + roles.entry(d.site).or_default().push(d.role); + } + } + for &b in order { + for (i, inst) in x.p.blocks[b].insts.iter().enumerate() { + let site = (b, i); + let address = addresses.get(&site); + let relocated = |r: Reg| inst.read(r).is_some_and(|v| symbolic.contains(&v)); + if address.is_some_and(|a| !exact_term(a)) + || inst + .writes + .iter() + .any(|(_, v)| x.st.restored.get(v).is_some_and(|v| symbolic.contains(v))) + { + return Err(refusal(inst.machine.offset)); + } + // A predicated memory result can keep the old VGPR in inactive lanes. + // Never erase its symbolic provenance at an overlapping address/result. + if inst.writes.iter().any(|&(r, v)| { + matches!(r, Reg::S(106..)) && symbolic.contains(&v) + || matches!(r, Reg::V(_)) + && !matches!(inst.fields, Fields::Valu(_)) + && relocated(r) + }) { + return Err(refusal(inst.machine.offset)); + } + let reads = inst.reads.iter().filter(|(_, v)| symbolic.contains(v)); + if reads.clone().next().is_none() { + continue; + } + let descriptor = |role| roles.get(&site).is_some_and(|r| r.contains(&role)); + let contains = |op: Operand, r: Reg| match (op, r) { + (Operand::Scalar { code, dwords }, Reg::S(n)) + | (Operand::Vector { reg: code, dwords }, Reg::V(n)) => { + n.checked_sub(code).is_some_and(|k| k < dwords) + } + _ => false, + }; + let exact = |op: Operand| !reads.clone().any(|&(r, _)| contains(op, r)); + let base = address.is_some_and(|a| a.param != MEMORY); + let valid = match &inst.fields { + // The resource tracker must independently recognize the result as + // an address. A carry or a selector that depends on guest address + // bits is itself a numeric input, including for address formation. + Fields::Sop { .. } | Fields::Valu(_) => { + (deterministic(inst, |_| false) + || matches!( + inst.name(), + "s_bitset1_b32" + | "s_cmov_b32" + | "s_cmov_b64" + | "s_lshr_b64" + | "s_bfe_u32" + | "s_max_u32" + | "v_mov_b32" + | "v_add_nc_u32" + | "v_readfirstlane_b32" + )) + && (!relocated(Reg::Scc) + || inst + .read(Reg::Scc) + .is_some_and(|v| carries.contains(&(site, v)))) + } + Fields::Smem { + base: op, soffset, .. + } => { + inst.name().contains("_load_") + && (base || descriptor(Role::Resource)) + && exact(*soffset) + && reads.clone().all(|&(r, _)| contains(*op, r)) + } + Fields::Buffer { rsrc, soffset, .. } => { + descriptor(Role::Resource) + && exact(*soffset) + && reads.clone().all(|&(r, _)| contains(*rsrc, r)) + } + Fields::Image { rsrc, sampler, .. } => reads.clone().all(|&(r, _)| { + descriptor(Role::Resource) && contains(*rsrc, r) + || descriptor(Role::Sampler) && sampler.is_some_and(|s| contains(s, r)) + }), + Fields::Flat { + addr, saddr, data, .. + } if base => { + // With an SGPR base, the VGPR is a numeric offset. + let op = saddr + .filter(|s| !matches!(s, Operand::Scalar { code: NULL, .. })) + .or(*addr); + data.is_none_or(exact) + && reads + .clone() + .all(|&(r, _)| op.is_some_and(|o| contains(o, r))) + } + _ => false, + }; + if !valid { + return Err(refusal(inst.machine.offset)); + } + } + } + Ok(symbolic) +} + +fn check_control( + x: &Parts, + order: &[usize], + rank: &[usize], + common: &Set, +) -> Result, Stop> { + // Check *every* branch, including reconvergent ones. A common PC then + // implies a common predecessor on every visit, including all cap edges. + let mut step = vec![false; rank.len()]; + let mut masks = Vec::new(); + for &b in order { + let block = &x.p.blocks[b]; + // Lower::enter_loop resets on each forward edge and count_iteration + // advances the selected header. A counter at dispatch entry would + // have no incoming edge supplying its initial zero. + if (b == 0 && block.preds.iter().any(|&q| rank[q] != usize::MAX)) + || block + .phis + .iter() + .any(|phi| phi.args.len() != block.preds.len()) + { + return Err(unsupported( + block.offset, + "a literal publication block without an initialized entry", + )); + } + masks.extend(x.st.guards[b].iter().flatten().copied()); + let valid = match x.st.exits[b] { + LaneExit::End | LaneExit::Jump(_) => true, + LaneExit::Indirect => false, + LaneExit::Branch { when, .. } => { + x.st.bools.support(when).iter().all(|atom| match atom { + Atom::Uniform(v) => common.contains(v), + // The nested lane predicate and ballot insertion point must + // also succeed in Lower::atom with this exact common set. + Atom::Any(bit) => { + masks.push(*bit); + true + } + _ => false, + }) + } + }; + if !valid { + return Err(unsupported( + block + .insts + .last() + .map_or(block.offset, |i| i.machine.offset), + "a literal scalar publication branch without common group control flow", + )); + } + step[b] = true; + } + // Validate the lane predicates inside actual votes and EXEC guards. + // Mask joins can be cyclic. The SSA builder orders their incoming bits + // by the same predecessors as the ordinary phis. + let mut checked = Set::default(); + while let Some(mask) = masks.pop() { + if !checked.insert(mask) { + continue; + } + for atom in x.st.bools.support(mask) { + let valid = match atom { + Atom::Lane(_) | Atom::Constant(_) => true, + Atom::Any(bit) => { + masks.push(bit); + true + } + Atom::Uniform(v) => common.contains(&v), + Atom::OpaquePair(lo, hi) => common.contains(&lo) && common.contains(&hi), + Atom::PairPhi(lo, hi) => x.st.mask_inputs.get(&(lo, hi)).is_some_and(|args| { + masks.extend(args); + !args.is_empty() + }), + _ => false, + }; + if !valid { + return Err(unsupported( + 0, + "an unproved literal scalar publication mask", + )); + } + } + } + Ok(step) +} + +/// A direct table handle has no added base displacement. A nonnegative signed +/// 21-bit immediate plus even the last x16 byte fits in u32. Each four-dword +/// raw load independently bounds its dwords against the same view as the SMEM. +fn wide_buffer_read(inst: &Inst) -> bool { + let Fields::Smem { + data: Some(Operand::Scalar { code, dwords }), + base: Operand::Scalar { + code: base, + dwords: 4, + }, + soffset: Operand::Scalar { + code: NULL, + dwords: 1, + }, + offset, + .. + } = inst.fields + else { + return false; + }; + matches!( + (inst.name(), dwords), + ("s_buffer_load_dwordx8", 8) | ("s_buffer_load_dwordx16", 16) + ) && (0..(1 << 20)).contains(&offset) + && offset % 4 == 0 + && base.is_multiple_of(4) + && base <= VCC - 4 + && code.is_multiple_of(4) + && code <= VCC - dwords + && inst.writes.len() == usize::from(dwords) + && (0..dwords).all(|k| inst.write(Reg::S(code + k)).is_some()) +} + +/// Direct SSA dwords of the exact tracked resource entry. +fn direct_descriptor(inst: &Inst, def: &Inst, first: u8) -> bool { + let Fields::Smem { + base: Operand::Scalar { code, dwords: 4 }, + .. + } = inst.fields + else { + return false; + }; + let Fields::Smem { + data: Some(Operand::Scalar { code: dst, dwords }), + .. + } = def.fields + else { + return false; + }; + u16::from(first) + 4 <= u16::from(dwords) + && (0..4).all(|k| { + def.write(Reg::S(dst + first + k)) + .is_some_and(|v| inst.read(Reg::S(code + k)) == Some(v)) + }) +} + +/// A fold admits a graph the old literal path could refuse. Check every +/// remaining CODE producer before either publication plan can lower it. +pub(super) fn folded_code( + p: &Program, + res: &Resources, + native: &NativeProgram, + computed: &Map>, +) -> Result<(), ShaderError> { + let refusal = |inst: &Inst| ShaderError::Unsupported { + offset: inst.machine.offset, + what: "a code read without a proved byte range after literal edge folding", + }; + for &(site @ (b, i), address) in &res.scalar { + let inst = &p.blocks[b].insts[i]; + if address.param == CODE + && !computed.contains_key(&site) + && !bounded_immutable_read(native, inst, address) + { + return Err(refusal(inst)); + } + } + for d in &res.descriptors { + if d.source + .leaves() + .iter() + .any(|s| matches!(s, Source::Built { address, .. } if address.param == CODE)) + { + let inst = &p.blocks[d.site.0].insts[d.site.1]; + if !bounded_code_buffer(native, inst, &d.source) { + return Err(refusal(inst)); + } + } + } + Ok(()) +} + +fn bounded_code_buffer(native: &NativeProgram, inst: &Inst, source: &Source) -> bool { + let Source::Built { address, .. } = source else { + return false; + }; + let Fields::Smem { + offset, + soffset: Operand::Scalar { code: NULL, .. }, + data: Some(Operand::Scalar { dwords, .. }), + .. + } = inst.fields + else { + return false; + }; + // A fixed descriptor base is present in the emitted table. A positive + // displacement stays above it, including when the table starts mid-code. + inst.name().starts_with("s_buffer_load_dword") + && dwords > 0 + && address.dynamic.is_none() + && u32::try_from(offset) + .ok() + .and_then(|d| address.offset.checked_add(d)) + .is_some_and(|start| { + start.is_multiple_of(4) + && start + .checked_add(4 * u32::from(dwords)) + .is_some_and(|end| end as usize <= native.code.len()) + }) +} + +fn bounded_immutable_read(native: &NativeProgram, inst: &Inst, a: Address) -> bool { + let bytes = match (inst.name(), &inst.fields) { + ("global_load_ubyte" | "global_load_sbyte", _) => 1, + ("global_load_ushort" | "global_load_sshort", _) => 2, + ( + name, + Fields::Flat { + dst: Some(Operand::Vector { dwords, .. }), + .. + }, + ) if name.starts_with("global_load_dword") => 4 * u32::from(*dwords), + (name, _) => smem_dwords(name).unwrap_or(0) * 4, + }; + // code_dword rounds down to a word. Subword extraction can read any + // byte in that word, but cannot span two words. + let aligned = if bytes < 4 { + a.offset % 4 + bytes <= 4 + } else { + a.offset.is_multiple_of(4) + }; + bytes > 0 + && a.dynamic.is_none() + && aligned + && match a.param { + CODE => a + .offset + .checked_add(bytes) + .is_some_and(|end| end as usize <= native.code.len()), + USER_DATA if matches!(inst.fields, Fields::Smem { .. }) => { + (a.offset / 4..a.offset / 4 + bytes / 4).all(|d| { + native.layout.iter().any(|p| { + matches!(p.root, RootType::Table | RootType::Constants) + && d.checked_sub(p.user_data.into()) + .is_some_and(|n| n < p.sgprs) + }) + }) + } + _ => false, + } +} + +/// Only instructions with implemented deterministic scalar transfers. Special +/// operands (e.g. a hardware register) are not immediates or initialized SGPRs. +fn deterministic(inst: &Inst, scalar_scratch: impl Fn(Value) -> bool) -> bool { + let Fields::Sop { src, .. } = &inst.fields else { + return false; + }; + src.iter().all(|&op| match op { + Operand::Scalar { code, dwords } => { + code < VCC || code == NULL + || (dwords == 1 && (code == VCC || code == VCC + 1) + && inst.read(Reg::S(code)).is_some_and(&scalar_scratch)) + } + _ => scalar_constant(op).is_some(), + }) && matches!( + inst.name(), + "s_mov_b32" + | "s_mov_b64" + | "s_movk_i32" + | "s_getpc_b64" + | "s_add_i32" + | "s_add_u32" + | "s_addc_u32" + | "s_addk_i32" + | "s_sub_i32" + | "s_sub_u32" + | "s_mul_i32" + | "s_lshl_b32" + | "s_lshl_b64" + | "s_lshr_b32" + | "s_ashr_i32" + | "s_and_b32" + | "s_and_b64" + | "s_andn2_b64" + | "s_or_b32" + | "s_or_b64" + | "s_brev_b32" + | "s_cselect_b32" + | "s_cselect_b64" + | "s_cmp_eq_u32" + | "s_cmp_ge_u32" + | "s_cmp_gt_i32" + | "s_cmp_gt_u32" + | "s_cmp_le_u32" + | "s_cmp_lg_u32" + | "s_cmp_lt_u32" + ) +} + +#[cfg(test)] +mod tests; diff --git a/crates/victory-shader/src/emit/lower/literal_publish/tests.rs b/crates/victory-shader/src/emit/lower/literal_publish/tests.rs new file mode 100644 index 000000000..4d87ef389 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/literal_publish/tests.rs @@ -0,0 +1,276 @@ +use super::*; +use crate::emit::halves_tests::{literal_publish::program, native, parts}; +use crate::{io, ir, resource, structure}; + +fn admission( + n: &NativeProgram, + inspect: impl FnOnce(&mut Program, &mut Structured, &mut Resources), +) -> (Program, Result, Stop>) { + let mut p = ir::build(&n.code, true, n.vgprs).unwrap(); + let mut st = structure::split_literal(&p).unwrap(); + let mut res = resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let io = io::raise(&p, n).unwrap(); + inspect(&mut p, &mut st, &mut res); + let x = parts(n, &p, &st, &res, &io, true, true); + let result = prove(&x, 64, 0, &HashMap::new()); + (p, result) +} + +#[test] +fn literal_publication_numeric_source_admission() { + // Query the proof itself. These extra definitions have no memory or control uses. + let mut words = vec![ + 0xbebc_1f00, // PC pair in s[60:61] + 0xbebe_0301, // s62 copies the second root + 0xbebf_0302, // s63 copies group X + ]; + words.extend(program(&[0x7d84_0100])); + for root in [ + RootType::Constants, + RootType::Table, + RootType::ResourceHeap, + RootType::SamplerHeap, + ] { + let mut n = native(&words, true, 64, 0); + n.layout.push(crate::native::RootParam { + root, + user_data: 1, + slot: 1, + ..n.layout[0] + }); + let StageIo::Cs(cs) = &mut n.io else { + unreachable!() + }; + cs.rsrc2 = 2 << 1 | 1 << 7; + let (p, result) = admission(&n, |_, _, _| {}); + let proof = result.ok().flatten().unwrap(); + for (dword, expected) in [ + (60, false), + (61, false), + (62, root == RootType::Constants), + (63, true), + ] { + let v = p.blocks[0] + .insts + .iter() + .find_map(|i| i.write(Reg::S(dword))) + .unwrap(); + assert_eq!(proof.common.contains(&v), expected, "{root:?} s{dword}"); + } + let table = p.inputs.iter().find(|r| r.0 == Reg::S(0)).unwrap().1; + assert!(!proof.common.contains(&table)); + } +} + +#[test] +fn literal_publication_descriptor_only_admission_checks_all_uses() { + // Use the original descriptor prologue and final store. Query only admission. + let fixture = program(&[0x7d84_0100]); + for (source, allowed) in [(0x7e0c_0280, true), (0x7e0c_0228, false)] { + let mut words = fixture[..5].to_vec(); + words.extend([0x3420_0085, source]); // store a zero, or descriptor word zero + words.extend(&fixture[fixture.len() - 3..]); + let n = native(&words, true, 64, 0); + let (_, result) = admission(&n, |_, _, _| {}); + if allowed { + assert!(matches!(result, Ok(None))); + } else { + assert!( + matches!(result, Err(Stop::Fail(crate::ShaderError::Unsupported { what, .. })) if what.contains("descriptor word read as numeric data")) + ); + } + } +} + +#[test] +fn literal_publication_checks_each_operand_role() { + let n = native(&program(&[0x7d84_0100]), true, 64, 0); + // Exercise the validator on role metadata only. The original store's + // descriptor remains valid when its first word also names a numeric input. + let (_, result) = admission(&n, |p, _, res| { + let d = res + .descriptors + .iter() + .find(|d| p.blocks[d.site.0].insts[d.site.1].name() == "buffer_store_dword") + .unwrap(); + let inst = &mut p.blocks[d.site.0].insts[d.site.1]; + let Fields::Buffer { + rsrc: Operand::Scalar { code, .. }, + soffset, + .. + } = &mut inst.fields + else { + unreachable!() + }; + *soffset = Operand::Scalar { + code: *code, + dwords: 1, + }; + }); + assert!( + matches!(result, Err(Stop::Fail(crate::ShaderError::Unsupported { what, .. })) + if what.contains("without guest-exact bits")) + ); +} + +#[test] +fn literal_publication_requires_bounded_code_contents() { + let fixture = program(&[0x7d84_0100]); + // Drive source admission only. The source metadata varies; no negative + // program is lowered. The observed word passes through a lane read to a store. + for (read, width) in [ + (&[0xf404_0902, 0xfa00_0000, 0x7e0c_0225][..], 8), // scalar pair, v6 = s37 + (&[0xdc34_8000, 0x0604_0010][..], 8), // global dwordx2 to v[6:7] + (&[0xdc28_8000, 0x0604_0010][..], 2), // global ushort to v6 + (&[0xdc20_8000, 0x0604_0010][..], 1), // global ubyte to v6 + ] { + for strict in [false, true] { + let mut words = if strict { + fixture[..fixture.len() - 4].to_vec() + } else { + fixture[..5].to_vec() + }; + words.push(0x3420_0085); // v16 = lane * 32 + let at = 4 * words.len(); + words.extend(read); + words.extend([0x7e4c_0506, 0x8726_8126, 0x7e0c_0226]); // v6 = first(v6) & 1 + words.extend(&fixture[fixture.len() - 3..]); // store v6 and end + let n = native(&words, true, 64, 0); + let end = n.code.len() as u32; + for (offset, dynamic, proved) in [ + (end - width, false, true), + (end - width + 1, false, false), + (end - 4, false, width <= 4), + (1, false, width <= 2), + (3, false, width == 1), + (u32::MAX - 3, false, false), + (0, true, false), + ] { + let (_, result) = admission(&n, |p, _, res| { + let (_, address) = res + .scalar + .iter_mut() + .find(|((b, i), _)| p.blocks[*b].insts[*i].machine.offset == at) + .unwrap(); + *address = Address { + param: CODE, + offset, + dynamic: dynamic + .then(|| p.inputs.iter().find(|r| r.0 == Reg::V(0)).unwrap().1), + }; + }); + let admitted = match result { + Ok(proof) => { + assert_eq!(proof.is_some(), strict); + true + } + Err(Stop::Fail(crate::ShaderError::Unsupported { what, .. })) => { + assert!( + what.contains("code read without a proved byte range"), + "{what}" + ); + false + } + _ => panic!("unexpected admission result"), + }; + assert_eq!( + admitted, + !strict || proved, + "width {width}, offset {offset}, dynamic {dynamic}, strict {strict}" + ); + } + } + } +} + +#[test] +fn literal_publication_wide_admission_checks_each_run() { + use crate::emit::halves_tests::literal_publish::wide::fixture; + for width in [8, 16] { + let n = fixture(width, ResourceType::Srv, &[0x7d84_0100], true); + // Only query the final-IR proof. No refused form reaches emission. + for (case, admitted) in [ + ("last aligned immediate", true), + ("negative", false), + ("unaligned", false), + ("outside immediate", false), + ("register", false), + ("guard", false), + ("source", false), + ("missing middle", false), + ("missing last", false), + ("extra destination", false), + ("unaligned destination", false), + ("special destination", false), + ] { + let (_, result) = admission(&n, |p, st, res| { + let desc = res + .descriptors + .iter_mut() + .find(|d| { + p.blocks[d.site.0].insts[d.site.1] + .write(Reg::S(80)) + .is_some() + }) + .unwrap(); + let (b, i) = desc.site; + let count = p + .blocks + .iter() + .flat_map(|block| &block.insts) + .find_map(|inst| { + (inst.machine.words[0] == 0xbf06_8214) + .then(|| inst.read(Reg::S(20))) + .flatten() + }) + .unwrap(); + let inst = &mut p.blocks[b].insts[i]; + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + offset, + soffset, + .. + } = &mut inst.fields + else { + unreachable!() + }; + match case { + "last aligned immediate" => *offset = 0xffffc, + "negative" => *offset = -4, + "unaligned" => *offset = 6, + "outside immediate" => *offset = 1 << 20, + "register" => { + *soffset = Operand::Scalar { + code: 20, + dwords: 1, + }; + inst.reads.push((Reg::S(20), count)); + } + "guard" => st.guards[b][i] = Some(Bool::FALSE), + "source" => desc.source = Source::Constant(vec![0; 4]), + "missing middle" => inst.writes.retain(|&(r, _)| r != Reg::S(84)), + "missing last" => inst.writes.retain(|&(r, _)| r != Reg::S(79 + width as u8)), + "extra destination" => inst.writes.push((Reg::S(99), count)), + "unaligned destination" | "special destination" => { + let first = if case == "unaligned destination" { 81 } else { 100 }; + for (reg, _) in &mut inst.writes { + let Reg::S(word) = reg else { unreachable!() }; + *word = first + (*word - *code); + } + *code = first; + } + _ => unreachable!(), + } + }); + if admitted { + assert!(matches!(result, Ok(Some(_))), "{case}, width {width}"); + } else { + assert!( + matches!(result, Err(Stop::Fail(ShaderError::Unsupported { what, .. })) + if what.contains("unsupported source or width") || what.contains("cached or predicated")), + "{case}, width {width}" + ); + } + } + } +} diff --git a/crates/victory-shader/src/emit/lower/predicate.rs b/crates/victory-shader/src/emit/lower/predicate.rs index 435f0c46d..885dafdd7 100644 --- a/crates/victory-shader/src/emit/lower/predicate.rs +++ b/crates/victory-shader/src/emit/lower/predicate.rs @@ -109,6 +109,14 @@ pub(super) struct PredicatePlan { pub(super) early_conts: Map, /// Trivial `End` blocks bypassed by at least one `EarlyOut`. pub(super) skipped_ends: Set, + /// Scalar-buffer reads whose results codegen must publish to both halves. + pub(super) scalar_publications: Set, + /// Common SCC branches, established before assuming any publication. + publication_scc: Set, + /// Original immediate postdominators, before flattening any branch. + original_ipdom: Vec>, + /// First-lane sites physically reached by a single guest thread. + pub(super) owner: Option, /// Updated `in_step` vector reflecting predicated control flow. pub(super) step: Vec, } @@ -131,6 +139,10 @@ impl PredicatePlan { idom: Vec::new(), early_conts: Map::default(), skipped_ends: Set::default(), + scalar_publications: Set::default(), + publication_scc: Set::default(), + original_ipdom: Vec::new(), + owner: None, step, } } @@ -148,6 +160,8 @@ impl PredicatePlan { base_step: Vec, one_wave_lds: bool, host_wave32: bool, + mapped_wave: Option<(&Parts, bool, &HashSet)>, + ticketed_group: Option<&Parts>, ) -> Self { let n = p.blocks.len(); if n <= 1 { @@ -166,24 +180,110 @@ impl PredicatePlan { let idom = crate::ir::idoms(&p.blocks, &order, &rpo); let mut plan = PredicatePlan { - exits: Map::default(), - in_diamond: Set::default(), - diamond_joins: Map::default(), - skip_bodies: Map::default(), - skip_joins: Map::default(), - skipped_edges: Set::default(), - linear_merges: Set::default(), - lockstep_headers: Map::default(), - lockstep_exits: Map::default(), - in_lockstep_loop: Set::default(), - uniform_branches: Set::default(), - dead_blocks: Set::default(), idom, - early_conts: Map::default(), - skipped_ends: Set::default(), - step: base_step, + ..Self::empty(base_step) }; let mut eff_exits = st.exits.clone(); + // Each latch uses the same lowered counter at its header. A complete, + // mapped console wave can prove both latch choices from scalar + // broadcasts. Recheck participation after each CFG transformation. + let owner = ticketed_group.and_then(|x| terminal_owner::find(x, &order)); + let wave = mapped_wave + .map(|x| (x, two_latch_blocks(p, &rpo))) + .filter(|(_, blocks)| !blocks.is_empty()) + .map(|((x, tickets, first_alone), blocks)| { + let res = x.res; + // These fixed-address loads lower to data embedded in the + // program or supplied as dispatch root constants. + let immutable = res + .scalar + .iter() + .filter_map(|&(site, address)| { + (matches!(address.param, CODE | USER_DATA) && address.dynamic.is_none()) + .then_some(site) + }) + .collect(); + let before = blocks + .iter() + .map(|&b| rpo[b]) + .min() + .expect("nonempty loops"); + let buffers = if tickets { + fixed_scalar_buffers(x, |kind| kind == ResourceType::Srv) + .filter(|((b, _), ..)| rpo[*b] < before) + .map(|(site, offset, ..)| (site, offset)) + .collect() + } else { + Vec::new() + }; + let per_lane = res.waterfall.reads.iter().chain(first_alone).copied().collect(); + (per_lane, blocks, immutable, buffers) + }); + let update_step = |plan: &mut PredicatePlan, exits: &[LaneExit]| { + let mut step = barriers::in_step_with(p, st, exits, &plan.uniform_branches); + if let Some((per_lane, loop_blocks, immutable, buffers)) = &wave { + plan.scalar_publications.clear(); + let analyze = |plan: &Self| { + barriers::step_and_cap_with( + p, + st, + exits, + &plan.uniform_branches, + true, + Some(barriers::WaveReads { + plan, + per_lane, + immutable, + loop_blocks, + base_step: &step, + }), + ) + }; + // Establish arrival and offset without any published-value facts. + let (mut wave_step, _, alike) = analyze(plan); + plan.publication_scc = plan + .exits + .keys() + .copied() + .filter(|&d| { + let Some(branch) = p.blocks[d].insts.last() else { + return false; + }; + let LaneExit::Branch { when, .. } = st.exits[d] else { + return false; + }; + let (lo, hi) = match branch.name() { + "s_cbranch_scc0" => (Bool::TRUE, Bool::FALSE), + "s_cbranch_scc1" => (Bool::FALSE, Bool::TRUE), + _ => return false, + }; + branch.read(Reg::Scc).is_some_and(|v| { + alike.contains(&v) + && st.bools.node(when) == Some((Atom::Uniform(v), lo, hi)) + }) + }) + .collect(); + for &(site @ (b, _), offset) in buffers { + if step[b] + && wave_step[b] + && !plan.dead_blocks.contains(&b) + && offset.is_none_or(|v| alike.contains(&v)) + { + plan.scalar_publications.insert(site); + } + } + if !plan.scalar_publications.is_empty() { + wave_step = analyze(plan).0; + } + for &b in loop_blocks { + step[b] |= wave_step[b]; + } + } + step + }; + if wave.is_some() { + plan.step = update_step(&mut plan, &eff_exits); + } // Iteratively predicate eligible divergent branches and loops whose // regions contain candidate blocks needing `in_step`. @@ -191,9 +291,16 @@ impl PredicatePlan { let mut changed = false; let pdom = post_dominators(&eff_exits); let ipdom = immediate_post_dominators(&eff_exits, &pdom); + if wave.is_some() && plan.exits.is_empty() { + plan.original_ipdom.clone_from(&ipdom); + } for &d in &order { - if !plan.step[d] || plan.exits.contains_key(&d) || plan.dead_blocks.contains(&d) { + if owner.as_ref().is_some_and(|o| o.gate == d) + || !plan.step[d] + || plan.exits.contains_key(&d) + || plan.dead_blocks.contains(&d) + { continue; } let LaneExit::Branch { @@ -224,8 +331,7 @@ impl PredicatePlan { }) { plan.dead_blocks.insert(end_blk); } - plan.step = - barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + plan.step = update_step(&mut plan, &eff_exits); changed = true; break; } @@ -250,8 +356,7 @@ impl PredicatePlan { plan.skip_joins.insert(join, d); plan.skipped_edges.insert((d, join)); eff_exits[d] = LaneExit::Jump(body); - plan.step = - barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + plan.step = update_step(&mut plan, &eff_exits); changed = true; break; } @@ -283,8 +388,7 @@ impl PredicatePlan { } plan.diamond_joins.insert(join, d); plan.linear_merges.insert(join); - plan.step = - barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + plan.step = update_step(&mut plan, &eff_exits); changed = true; break; } @@ -315,8 +419,7 @@ impl PredicatePlan { plan.lockstep_exits.insert(exit, h); plan.uniform_branches.insert(latch); plan.in_lockstep_loop.extend(body); - plan.step = - barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + plan.step = update_step(&mut plan, &eff_exits); changed = true; break; } @@ -351,8 +454,7 @@ impl PredicatePlan { plan.lockstep_exits.insert(lp.exit, h); plan.uniform_branches.insert(lp.exiting); plan.in_lockstep_loop.extend(lp.body); - plan.step = - barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + plan.step = update_step(&mut plan, &eff_exits); changed = true; break; } @@ -367,10 +469,114 @@ impl PredicatePlan { for &b in &plan.dead_blocks { plan.step[b] = false; } + if let Some(owner) = owner { + if !owner.preserved(p, st, &eff_exits, &plan) { + // Keep the established predicate plan when a rewrite would invalidate ownership. + return Self::build(p, st, barriers::in_step(p, st), one_wave_lds, host_wave32, mapped_wave, None); + } + plan.owner = Some(owner); + } plan } } +/// A fixed buffer in the descriptor table and its scalar byte offset. +/// Waterfalls can replace a scalar with lane-local data. +pub(super) fn fixed_scalar_buffers<'a>( + x: &'a Parts, + accepts: fn(ResourceType) -> bool, +) -> impl Iterator, Site, u8)> + 'a { + let addresses: Map<_, _> = x.res.scalar.iter().copied().collect(); + x.res.descriptors.iter().filter_map(move |desc| { + let (b, i) = desc.site; + let inst = &x.p.blocks[b].insts[i]; + if desc.role != Role::Resource || !inst.name().starts_with("s_buffer_load_dword") { + return None; + } + let Fields::Smem { cache, soffset, .. } = inst.fields else { + return None; + }; + let Source::Loaded { load, first } = desc.source else { + return None; + }; + let address = *addresses.get(&load)?; + let binding = table_kind(x.native, address, first)?; + if cache != Default::default() + || address.dynamic.is_some() + || x.res.waterfall.loads.contains(&load) + || !accepts(binding.kind) + || binding.dwords != 4 + || !address.offset.is_multiple_of(4) + || address.offset / 4 + u32::from(first) != binding.table_offset_dwords + { + return None; + } + let offset = match soffset { + Operand::Scalar { code: NULL, .. } => None, + _ => Some(sgpr_operand(inst, soffset).filter(|v| !x.res.waterfall.reads.contains(v))?), + }; + Some((desc.site, offset, load, first)) + }) +} + +/// Natural loops with exactly two unconditional back edges to the same +/// header. Structurisation already checked that the reachable CFG is reducible. +fn two_latch_blocks(p: &Program, rpo: &[usize]) -> Set { + let mut blocks = Set::default(); + for (header, block) in p.blocks.iter().enumerate() { + let mut back = block + .preds + .iter() + .copied() + .filter(|&q| rpo[q] != usize::MAX && rpo[q] >= rpo[header]); + let (Some(a), Some(b), None) = (back.next(), back.next(), back.next()) else { + continue; + }; + if ![a, b] + .iter() + .all(|&q| p.blocks[q].exit == Exit::Jump(header)) + { + continue; + } + let mut body = Set::from_iter([header]); + let mut stack = vec![a, b]; + while let Some(q) = stack.pop() { + if body.insert(q) { + stack.extend(p.blocks[q].preds.iter().filter(|&&v| rpo[v] != usize::MAX)); + } + } + blocks.extend(body); + } + blocks +} + +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. +pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let ops: Vec<&Operand> = match &i.fields { + // A mask operation (its result a mask) is no data use. + Fields::Sop { .. } + if i.writes + .iter() + .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) => + { + return false; + } + Fields::Sop { src, .. } => src.iter().collect(), + Fields::Valu(v) + if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") => + { + v.src.iter().collect() + } + _ => return false, + }; + ops.into_iter().any(|op| match *op { + Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask), + _ => false, + }) +} + /// Blocks that contain an operation needing `in_step` in `halves` mode /// (cross-half wave ops, mask-as-data reads and their transitive mask sources, /// `v_readlane`/`v_readfirstlane`, or split-wave LDS accesses). @@ -1170,6 +1376,164 @@ fn immediate_post_dominators(exits: &[LaneExit], pdom: &[Vec]) -> Vec, +) -> Option<()> { + if !p.wave64 || st.literal || !matches!(branch.name(), "s_cbranch_execz" | "s_cbranch_execnz") { + return None; + } + let read_pair = + |inst: &Inst, code| Some((inst.read(Reg::S(code))?, inst.read(Reg::S(code + 1))?)); + let mut code = EXEC; + let mut pair = read_pair(branch, code)?; + let mask = st.mask_bits(pair.0, Some(pair.1))?; + for b in std::iter::successors(Some(head), |&b| (b != 0).then(|| idom[b])) { + for inst in p.blocks[b].insts.iter().rev() { + // SSA identities require both dwords to come from this very + // definition. No phi or one-dword update can match the pair. + if inst.write(Reg::S(code)) != Some(pair.0) + || inst.write(Reg::S(code + 1)) != Some(pair.1) + { + continue; + } + let Fields::Sop { + dst: + Some(Operand::Scalar { + code: dst, + dwords: 2, + }), + src, + .. + } = &inst.fields + else { + return None; + }; + if *dst != code { + return None; + } + code = match (inst.name(), src.as_slice()) { + ( + "s_mov_b64", + [ + Operand::Scalar { + code: from @ (0..=104 | EXEC), + dwords: 2, + }, + ], + ) => *from, + ("s_and_saveexec_b64", _) if code <= 104 => EXEC, + _ => return None, + }; + pair = read_pair(inst, code)?; + if code == EXEC && direct.contains(&pair.0) && direct.contains(&pair.1) { + return (st.mask_bits(pair.0, Some(pair.1)) == Some(mask)).then_some(()); + } + } + } + None +} + +/// Check the guest branches after identifying the flattened bodies supplying activity. +pub(in crate::emit) fn publication_gates( + p: &Program, + st: &Structured, + gates: &[(usize, usize)], + common_scc: &Set, + idom: &[usize], +) -> bool { + // BDD simplification can erase a mask phi. Walk the actual SSA operands + // on the proved path; a phi never establishes a wave-wide predecessor. + let mut direct: Set<_> = p.inputs.iter().map(|&(_, v)| v).collect(); + let exact_bits = |m, direct: &Set| { + st.bools.support(m).into_iter().all(|atom| match atom { + Atom::Lane(v) => direct.contains(&v), + Atom::Constant(_) => true, + _ => false, + }) + }; + let mut outer = None; + let mut enclosing = Vec::new(); + for &(body, d) in gates { + let LaneExit::Branch { + when, + taken, + not_taken, + } = st.exits[d] + else { + return false; + }; + let head = &p.blocks[d]; + for (i, inst) in head.insts.iter().enumerate() { + // WQM of the original full wave is an identity; the compute + // emitter approximates expansion of any other mask. + let full_wqm = || { + matches!(inst.reads.as_slice(), [lo, hi] if + lo.0 == Reg::S(EXEC) && hi.0 == Reg::S(EXEC + 1) + && p.inputs.contains(lo) && p.inputs.contains(hi)) + }; + if inst.reads.iter().all(|(_, v)| direct.contains(v)) + && st.guards[d][i].is_none_or(|g| exact_bits(g, &direct)) + && (inst.name() != "s_wqm_b64" || full_wqm()) + { + direct.extend(inst.writes.iter().map(|&(_, v)| v)); + } + } + let Some(branch) = head.insts.last() else { + return false; + }; + if !branch.reads.iter().all(|(_, v)| direct.contains(v)) + && restored_publication_exec(p, st, idom, d, branch, &direct).is_none() + { + return false; + } + let taken_edge = body == taken; + if !common_scc.contains(&d) { + let nonempty = match branch.name() { + "s_cbranch_execz" => not_taken, + "s_cbranch_execnz" => taken, + _ => return false, + }; + if body != nonempty { + return false; + } + let mask = branch + .read(Reg::S(EXEC)) + .zip(branch.read(Reg::S(EXEC + 1))) + .and_then(|(lo, hi)| st.mask_bits(lo, Some(hi))); + let Some(mask) = mask else { return false }; + // Quad approximates expansion and Phi selects by lane in normal + // code. Neither is an exact source for a wave-wide EXEC visit. + if !exact_bits(mask, &direct) || !exact_bits(when, &direct) { + return false; + } + // A disjoint restored EXEC could enter a nested guest arm + // even though no lane meets both flattened edge predicates. + if outer.is_some_and(|m| st.bools.meet(&[(mask, true), (m, false)])) { + return false; + } + // The structurizer can simplify an exit using lane reachability. + // It must still match the full EXEC bit on the inherited mask. + let mismatch = |exec, edge| { + st.bools + .meet(&[enclosing.as_slice(), &[(mask, exec), (when, edge)]].concat()) + }; + if mismatch(true, !taken_edge) || mismatch(false, taken_edge) { + return false; + } + outer = Some(mask); + } + enclosing.push((when, taken_edge)); + } + true +} + impl Lower<'_> { /// Per-lane active predicate for IR block `b`, if `b` executes under /// predication (`None` means all lanes in the workgroup are active). @@ -1177,6 +1541,101 @@ impl Lower<'_> { self.block_active.get(b).copied().flatten() } + /// Find the single-entry body supplying this block's emitted predicate. + /// Through intervening merges it must also dominate the block, which + /// must postdominate the body: every original surviving visit gets here. + fn scalar_publication_guard(&self, b: usize) -> Option<(usize, usize)> { + let active = self.pred_active(b)?; + let plan = &self.pred; + let mut dominators = std::iter::successors(Some(b), |&q| (q != 0).then(|| plan.idom[q])); + let (body, head) = dominators.find_map(|q| { + let d = plan + .early_conts + .get(&q) + .or_else(|| plan.skip_bodies.get(&q))?; + Some((q, *d)) + })?; + if self.x.p.blocks[body].preds != [head] + || self.pred_edge_active.get(&(head, body)) != Some(&active) + || self.on_cycle(b) + { + return None; + } + if body != b { + let postdominators = std::iter::successors(Some(body), |&q| plan.original_ipdom[q]); + if self.pred_active(body) != Some(active) + || self.on_cycle(body) + || !postdominators.take(plan.idom.len()).any(|q| q == b) + { + return None; + } + } + Some((body, head)) + } + + fn proved_scalar_visit(&self, mut b: usize) -> bool { + let mut gates = Vec::new(); + while b != 0 { + let Some((body, d)) = self.scalar_publication_guard(b) else { + return false; + }; + gates.push((body, d)); + b = d; + } + gates.reverse(); + publication_gates( + self.x.p, + self.x.st, + &gates, + &self.pred.publication_scc, + &self.pred.idom, + ) + } + + pub(super) fn published_scalar_words( + &mut self, + h: V, + mut addr: V, + count: u32, + ) -> Result, Why> { + if !self.across_here() { + return Err("a scalar-buffer publication outside converged instruction control flow"); + } + let active = self.pred_active(self.cur_ir); + let visit = if let Some(act) = active { + if self.x.st.literal || !self.proved_scalar_visit(self.cur_ir) { + return Err( + "a scalar-buffer publication without a proved predicated address or visit", + ); + } + // Inactive lanes need not hold the guest address. Broadcast an + // actual visitor's common byte offset before all lanes load it. + if self.s.m.int_value(addr).is_none() { + addr = self.first_lane_across(addr, Some(act))?; + } + Some(self.group_any_true(act, self.cur)?) + } else { + None + }; + let guard = self.begin_guarded(visit); + let load_block = self.cur; + let mut words = self.raw_run(h, addr, count); + if self.cur != load_block { + return Err("a scalar-buffer publication through a guarded raw view"); + } + // Both ticketed halves enter together, including logical lane zero + // when its EXEC bit is clear. SALU takes its value for each component. + for x in &mut words { + *x = self.first_lane_across(*x, None)?; + } + if guard.is_some() { + let zero = self.s.m.i32(0); + let pairs: Vec<_> = words.into_iter().map(|x| (x, zero)).collect(); + words = self.end_guarded(guard, &pairs); + } + Ok(words) + } + /// Computes `self.block_active[b]` at the start of IR block `b` (when /// `self.pred` is non-empty) and lowers phis at linearized merges or /// `SkipGuard` joins. diff --git a/crates/victory-shader/src/emit/lower/retry.rs b/crates/victory-shader/src/emit/lower/retry.rs index 4b3338af8..5c42cd6d9 100644 --- a/crates/victory-shader/src/emit/lower/retry.rs +++ b/crates/victory-shader/src/emit/lower/retry.rs @@ -4,6 +4,8 @@ use super::*; +pub(super) mod immutable; + #[cfg(any(test, all(windows, feature = "host")))] pub(crate) fn lower(parts: &Parts) -> Result { lower_pruned(parts, None, false, false) @@ -66,9 +68,24 @@ pub(crate) fn lower_literal( let native = parts.native; // Register-relative move bounds and resource paths must use the same // control flow as lowering. The per-lane move bounds do not apply here. - let p = crate::ir::build(&native.patched_code(), true, native.vgprs)?; - let st = crate::structure::split_literal(&p)?; - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let mut p = crate::ir::build(&native.patched_code(), true, native.vgprs)?; + let mut simplified = false; + let (st, res, carries) = loop { + let st = crate::structure::split_literal(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let facts = immutable::prove(&p, &st, &res, native); + if !facts.jumps.is_empty() + && let Some(folded) = crate::ir::folded(&p, &facts.jumps)? + { + p = folded; + simplified = true; + continue; + } + if simplified || !facts.carries.is_empty() { + literal_publish::folded_code(&p, &res, native, &facts.reads)?; + } + break (st, res, facts.carries); + }; if !res.waterfall.reads.is_empty() { return Err(ShaderError::Unsupported { offset: 0, @@ -76,20 +93,19 @@ pub(crate) fn lower_literal( }); } let io = crate::io::raise(&p, native)?; - lower_with_structure( - &Parts { - p: &p, - st: &st, - res: &res, - io: &io, - ..parts.clone() - }, - keep, - per_vertex_center, - // A group in literal halves takes one path: its lanes never leave - // past a count of threads (`Lower::can_leave_past_a_count`). - false, - ) + let x = Parts { + p: &p, + st: &st, + res: &res, + io: &io, + ..parts.clone() + }; + if simplified || !carries.is_empty() { + literal_publish::folded_roles(&x, &carries)?; + } + // A group in literal halves takes one path and cannot drop lanes + // past a dispatch's thread count. + lower_with_structure(&x, keep, per_vertex_center, false) } fn lower_with_structure( @@ -104,7 +120,8 @@ fn lower_with_structure( let mut plan: Set = Set::default(); loop { let found = std::cell::RefCell::new(Set::default()); - let r = Lower::new(parts, &bad, keep, per_vertex_center, &plan, &found).run(limits); + let r = + Lower::new(parts, &bad, keep, per_vertex_center, &plan, &found).and_then(|l| l.run(limits)); let found = found.into_inner(); if !found.is_empty() { plan.extend(found); @@ -124,3 +141,6 @@ fn lower_with_structure( } } } + +#[cfg(test)] +mod tests; diff --git a/crates/victory-shader/src/emit/lower/retry/immutable.rs b/crates/victory-shader/src/emit/lower/retry/immutable.rs new file mode 100644 index 000000000..41073d1b8 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/retry/immutable.rs @@ -0,0 +1,480 @@ +//! Literal SCC branches over a small, bounded set of immutable dwords. +use super::*; + +mod paired; + +struct Definitions<'a> { + p: &'a Program, + insts: Map, + phis: Map, + rank: Vec, + idom: Vec, +} + +impl<'a> Definitions<'a> { + fn new(p: &'a Program) -> Self { + let mut rank = vec![usize::MAX; p.blocks.len()]; + let mut insts = Map::default(); + let mut phis = Map::default(); + let order = crate::ir::reverse_postorder(&p.blocks); + for (n, &b) in order.iter().enumerate() { + rank[b] = n; + let block = &p.blocks[b]; + phis.extend(block.phis.iter().map(|phi| (phi.value, (b, phi)))); + for (i, inst) in block.insts.iter().enumerate() { + insts.extend(inst.writes.iter().map(|&(r, v)| (v, ((b, i), r)))); + } + } + let idom = crate::ir::idoms(&p.blocks, &order, &rank); + Self { + p, + insts, + phis, + rank, + idom, + } + } + + fn inst(&self, v: Value) -> Option<(&'a Inst, Reg)> { + let &((b, i), r) = self.insts.get(&v)?; + Some((&self.p.blocks[b].insts[i], r)) + } + + fn at(&self, (b, i): Site) -> &'a Inst { + &self.p.blocks[b].insts[i] + } + + fn dominates(&self, def: usize, mut b: usize) -> bool { + while self.rank[b] > self.rank[def] { + b = self.idom[b]; + } + b == def + } + + fn before(&self, def: Site, at: Site) -> bool { + if def.0 == at.0 { + def.1 < at.1 + } else { + self.dominates(def.0, at.0) + } + } + + fn read_at(&self, at: Site, reg: Reg) -> Option { + let v = self.at(at).read(reg)?; + let available = if let Some(&(def, r)) = self.insts.get(&v) { + r == reg && self.before(def, at) + } else { + let &(b, phi) = self.phis.get(&v)?; + phi.reg == reg && self.dominates(b, at.0) + }; + available.then_some(v) + } + + // Only ordinary SGPR dwords and exact eq/ne comparisons. A failed or + // overflowing transfer is unknown even when the emitter could wrap it. + fn number(&self, v: Value, state: &[(Value, Option)], fuel: &mut usize) -> Option { + *fuel = fuel.checked_sub(1)?; + if let Some(&(_, n)) = state.iter().find(|s| s.0 == v) { + return n; + } + let (inst, reg) = self.inst(v)?; + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + let mut arg = |i| self.operand(self.insts.get(&v)?.0, *src.get(i)?, state, fuel); + match (reg, inst.name()) { + (Reg::S(0..=105), "s_mov_b32") => arg(0), + (Reg::S(0..=105), "s_add_u32") => arg(0)?.checked_add(arg(1)?), + (Reg::S(0..=105), "s_add_i32") => { + Some((arg(0)? as i32).checked_add(arg(1)? as i32)? as u32) + } + (Reg::S(0..=105), "s_lshl_b32") => arg(0)?.checked_mul(1u32.checked_shl(arg(1)?)?), + (Reg::Scc, "s_cmp_eq_u32" | "s_cmp_eq_i32") => Some(u32::from(arg(0)? == arg(1)?)), + (Reg::Scc, "s_cmp_lg_u32" | "s_cmp_lg_i32") => Some(u32::from(arg(0)? != arg(1)?)), + _ => None, + } + } + + fn operand( + &self, + site: Site, + op: Operand, + state: &[(Value, Option)], + fuel: &mut usize, + ) -> Option { + match op { + Operand::Literal(_) | Operand::Const(_) => scalar_constant(op), + Operand::Scalar { code: NULL, .. } => Some(0), + Operand::Scalar { + code: c @ 0..=105, + dwords: 1, + } => self.number(self.read_at(site, Reg::S(c))?, state, fuel), + _ => None, + } + } + + /// The only loop state needed for this numeric displacement. Every phi + /// is initially unknown and gets its actual predecessor operand on entry. + fn index_phis(&self, mut pending: Vec) -> Option> { + let mut seen = Set::default(); + let mut values = Vec::new(); + while let Some(v) = pending.pop() { + if !seen.insert(v) { + continue; + } + if seen.len() > 64 { + return None; + } + if let Some(&(b, phi)) = self.phis.get(&v) { + if !matches!(phi.reg, Reg::S(0..=105)) + || phi.args.len() != self.p.blocks[b].preds.len() + { + return None; + } + for (&arg, &pred) in phi.args.iter().zip(&self.p.blocks[b].preds) { + let def = self + .insts + .get(&arg) + .filter(|(_, r)| *r == phi.reg) + .map(|&((b, _), _)| b) + .or_else(|| { + self.phis + .get(&arg) + .and_then(|&(b, incoming)| (incoming.reg == phi.reg).then_some(b)) + })?; + if *self.rank.get(pred)? == usize::MAX + || !self.p.blocks[pred].exit.successors().contains(&b) + { + return None; + } + if !self.dominates(def, pred) { + return None; + } + } + values.push(v); + pending.extend(phi.args.iter().copied()); + } else if let Some((inst, Reg::S(0..=105))) = self.inst(v) + && matches!( + inst.name(), + "s_mov_b32" | "s_add_u32" | "s_add_i32" | "s_lshl_b32" + ) + { + pending.extend(inst.reads.iter().map(|r| r.1)); + } + } + Some(values) + } + + fn taken(&self, b: usize, state: &[(Value, Option)]) -> Option { + let branch = self.p.blocks[b].insts.last()?; + let site = (b, self.p.blocks[b].insts.len() - 1); + let bit = self.number(self.read_at(site, Reg::Scc)?, state, &mut 64)? != 0; + match branch.name() { + "s_cbranch_scc1" => Some(bit), + "s_cbranch_scc0" => Some(!bit), + _ => None, + } + } + + /// Scalar load from the original PC pair plus an independently numeric + /// byte displacement. The resource address alone can denote a legacy + /// relocated value, which is insufficient for a content proof. + fn contents( + &self, + native: &NativeProgram, + site: Site, + a: Address, + first: u32, + budget: &mut usize, + ) -> Option<(Set, Option)> { + let (b, i) = site; + let inst = &self.p.blocks[b].insts[i]; + let Fields::Smem { + base: Operand::Scalar { code, dwords: 2 }, + soffset, + offset, + .. + } = inst.fields + else { + return None; + }; + if inst.name() != "s_load_dword" || a.param != CODE { + return None; + } + let dynamic = a.dynamic?; + let lo = self.read_at(site, Reg::S(code))?; + let (pc, _) = self.inst(lo)?; + let paired = if pc.name() == "s_getpc_b64" { + let hi = self.read_at(site, Reg::S(code.checked_add(1)?))?; + if pc.writes != [(Reg::S(code), lo), (Reg::S(code + 1), hi)] { + return None; + } + None + } else { + Some(self.paired(site, code, soffset, dynamic)?) + }; + let mut roots = Vec::new(); + let base = if let Some(pair) = &paired { + roots.push(pair.index); + if let Operand::Scalar { + code: c @ 0..=105, .. + } = pair.count + { + roots.push(self.read_at(pair.shift_site, Reg::S(c))?); + } + pair.base + } else { + roots.push(dynamic); + u32::try_from(pc.machine.offset).ok()?.checked_add(4)? + }; + if paired.is_some() + && let Operand::Scalar { + code: c @ 0..=105, .. + } = soffset + { + roots.push(self.read_at(site, Reg::S(c))?); + } + let phis = self.index_phis(roots)?; + let mut pending = vec![(0usize, phis.iter().map(|&v| (v, None)).collect::>())]; + let mut seen = Set::default(); + let mut words = Set::default(); + while let Some((from, state)) = pending.pop() { + if !seen.insert((from, state.clone())) { + continue; + } + // A proof budget limits compilation only. Partial traces never qualify. + *budget = budget.checked_sub(1)?; + if seen.len() > self.p.blocks.len().saturating_mul(16).min(8192) { + return None; + } + if from == b { + let delta = if let Some(pair) = &paired { + let index = self.number(pair.index, &state, &mut 64)?; + let count = self.operand(pair.shift_site, pair.count, &state, &mut 64)?; + paired::displacement(index, count)? + } else { + self.number(dynamic, &state, &mut 64)? + }; + let address = a.offset.checked_add(delta)?; + let guest = base + .checked_add(if paired.is_some() { delta } else { 0 })? + .checked_add(self.operand(site, soffset, &state, &mut 64)?)? + .checked_add_signed(offset)?; + if address != guest { + return None; + } + words.insert(table_word(&native.code, first, address)?); + } + let block = &self.p.blocks[from]; + let selected = match block.exit { + // A constant guard may hide a statically reachable second user + // of the same PC. Cover that path too when certifying the pair. + Exit::Branch { .. } if paired.is_some() && self.taken(from, &[]).is_some() => None, + Exit::Branch { taken, not_taken } => self + .taken(from, &state) + .map(|cond| if cond { taken } else { not_taken }), + _ => None, + }; + for to in block.exit.successors() { + // A selected conditional backedge may instead leave through + // its forward successor when that header exhausts its cap. + if selected.is_some_and(|s| s != to && self.rank[s] > self.rank[from]) { + continue; + } + let mut next = state.clone(); + for (v, value) in &mut next { + let &(header, phi) = self.phis.get(v)?; + if header == to { + let pred = self.p.blocks[to].preds.iter().position(|&p| p == from)?; + *value = self.number(*phi.args.get(pred)?, &state, &mut 64); + } + } + pending.push((to, next)); + } + } + (!words.is_empty()).then_some((words, paired.map(|p| p.roles))) + } +} + +fn table_word(code: &[u8], first: u32, address: u32) -> Option { + if address < first || !address.is_multiple_of(4) { + return None; + } + let bytes = code.get(address as usize..address.checked_add(4)? as usize)?; + Some(u32::from_le_bytes(bytes.try_into().ok()?)) +} + +pub(in crate::emit::lower) struct Facts { + pub(in crate::emit::lower) reads: Map>, + pub(in crate::emit::lower) carries: Set<(Site, Value)>, + pub(super) jumps: Vec<(usize, usize)>, +} + +pub(in crate::emit::lower) fn prove( + p: &Program, + st: &Structured, + res: &Resources, + native: &NativeProgram, +) -> Facts { + let mut facts = Facts { + reads: Map::default(), + jumps: Vec::new(), + carries: Set::default(), + }; + if !res + .scalar + .iter() + .any(|(_, a)| a.param == CODE && a.dynamic.is_some()) + { + return facts; + } + let defs = Definitions::new(p); + // A dynamic read below the emitter's first table word would be clamped. + // code_end is a conservative floor even when an independent fixed read + // makes the emitted table start earlier. + let Some(end) = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .map(|i| i.machine.offset + 4 * i.machine.words.len()) + .max() + .and_then(|n| u32::try_from(n).ok()) + else { + return facts; + }; + let mut budget = 65_536; + let mut paired_reads = Map::default(); + let mut roles = paired::Roles::default(); + for &(site, a) in &res.scalar { + if defs.rank[site.0] != usize::MAX + && let Some((words, paired)) = defs.contents(native, site, a, end, &mut budget) + { + if let Some(pair) = paired { + roles.extend(pair); + paired_reads.insert(site, words); + } else { + facts.reads.insert(site, words); + } + } + } + let legacy = !facts.reads.is_empty(); + if !paired_reads.is_empty() && roles.valid(&defs, st, res) { + facts.carries = roles.carries; + facts.reads.extend(paired_reads); + } + // Only the refused literal shape needs executable edge simplification. + if facts.reads.is_empty() + || !p.blocks.iter().enumerate().any(|(b, block)| { + matches!(block.exit, + Exit::Branch { taken, not_taken } if defs.rank[b] != usize::MAX && taken != not_taken && + defs.rank[taken] <= defs.rank[b] && defs.rank[not_taken] <= defs.rank[b]) + }) + { + return facts; + } + for (b, block) in p.blocks.iter().enumerate() { + let Exit::Branch { taken, not_taken } = block.exit else { + continue; + }; + let Some(branch) = block.insts.last() else { + continue; + }; + if !matches!(branch.name(), "s_cbranch_scc0" | "s_cbranch_scc1") { + continue; + } + let cond = legacy.then(|| defs.taken(b, &[])).flatten().or_else(|| { + let cmp_value = defs.read_at((b, block.insts.len() - 1), Reg::Scc)?; + let (cmp, Reg::Scc) = defs.inst(cmp_value)? else { + return None; + }; + let Fields::Sop { src, .. } = &cmp.fields else { + return None; + }; + let [a, b] = src[..] else { return None }; + let (values, constant) = [(a, b), (b, a)].into_iter().find_map(|(load, k)| { + let Operand::Scalar { code, dwords: 1 } = load else { + return None; + }; + let cmp_site = defs.insts.get(&cmp_value)?.0; + let (site, _) = defs.insts.get(&defs.read_at(cmp_site, Reg::S(code))?)?; + Some(( + facts.reads.get(site)?, + defs.operand(cmp_site, k, &[], &mut 64)?, + )) + })?; + let eq = match cmp.name() { + "s_cmp_eq_u32" | "s_cmp_eq_i32" => true, + "s_cmp_lg_u32" | "s_cmp_lg_i32" => false, + _ => return None, + }; + let taken_if_equal = eq == (branch.name() == "s_cbranch_scc1"); + if values.contains(&constant) { + (values.len() == 1).then_some(taken_if_equal) + } else { + Some(!taken_if_equal) + } + }); + if let Some(take) = cond { + let (selected, other) = if take { + (taken, not_taken) + } else { + (not_taken, taken) + }; + if defs.rank[selected] > defs.rank[b] || defs.rank[other] <= defs.rank[b] { + facts.jumps.push((b, selected)); + } + } + } + facts +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn immutable_table_declines_overflowing_transfers() { + let program = |op| { + let words = [0xbe8c_03ff, u32::MAX, op, 0xbf81_0000]; + let code = words + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + crate::ir::build(&code, true, 4).unwrap() + }; + for op in [0x800c_810c, 0x8f0c_810c] { + // unsigned +1, left shift 1 + let p = program(op); + let defs = Definitions::new(&p); + let value = p.blocks[0].insts[1].write(Reg::S(12)).unwrap(); + assert_eq!(defs.number(value, &[], &mut 64), None); + } + } + + #[test] + fn immutable_table_paired_shift_width() { + for (index, count, expected) in [ + (1, 0, Some(1)), + (1, 31, Some(1 << 31)), + (1, 32, None), + (1, 63, None), + (1, 64, Some(1)), + (1, 65, Some(2)), + (2, 63, None), + (0, 63, Some(0)), + (u32::MAX, 0, None), + (u32::MAX, 1, None), + ] { + assert_eq!(paired::displacement(index, count), expected); + } + } + + #[test] + fn immutable_table_original_dwords_only() { + let bytes = [0, 0, 0, 0, 0x23, 0x45, 0x67, 0x89, 0xff]; + assert_eq!(table_word(&bytes, 4, 4), Some(0x8967_4523)); + for (first, at) in [(4, 0), (0, 1), (0, 8), (0, 12), (0, u32::MAX - 3)] { + assert_eq!(table_word(&bytes, first, at), None); + } + } +} diff --git a/crates/victory-shader/src/emit/lower/retry/immutable/paired.rs b/crates/victory-shader/src/emit/lower/retry/immutable/paired.rs new file mode 100644 index 000000000..1af34b5df --- /dev/null +++ b/crates/victory-shader/src/emit/lower/retry/immutable/paired.rs @@ -0,0 +1,345 @@ +//! A PC pair has unknown guest bits. Only a complete low ADD / high ADDC +//! represents the same relative addition for every relocation. +use super::*; + +#[derive(Default)] +pub(super) struct Roles { + values: Set, + reads: Set<(Site, Reg, Value)>, + pub(super) carries: Set<(Site, Value)>, +} + +pub(super) struct Paired { + pub(super) base: u32, + pub(super) shift_site: Site, + pub(super) index: Value, + pub(super) count: Operand, + pub(super) roles: Roles, +} + +struct Add { + site: Site, + result: Value, + carry: Value, + src: [Operand; 2], +} + +impl Definitions<'_> { + fn add(&self, value: Value, name: &str) -> Option { + let &(site, reg) = self.insts.get(&value)?; + let inst = self.at(site); + let Fields::Sop { + dst: + Some(Operand::Scalar { + code: c @ 0..=105, + dwords: 1, + }), + src, + .. + } = &inst.fields + else { + return None; + }; + let carry = inst.write(Reg::Scc)?; + (inst.name() == name + && reg == Reg::S(*c) + && inst.writes == [(reg, value), (Reg::Scc, carry)]) + .then_some(Add { + site, + result: value, + carry, + src: src.as_slice().try_into().ok()?, + }) + } + + fn sgpr(&self, site: Site, op: Operand) -> Option<(Reg, Value)> { + let Operand::Scalar { + code: c @ 0..=105, + dwords: 1, + } = op + else { + return None; + }; + let r = Reg::S(c); + Some((r, self.read_at(site, r)?)) + } + + fn add_pair(&self, words: [Value; 2], roles: &mut Roles) -> Option<[Add; 2]> { + let lo = self.add(words[0], "s_add_u32")?; + let hi = self.add(words[1], "s_addc_u32")?; + if self.read_at(hi.site, Reg::Scc)? != lo.carry { + return None; + } + roles + .values + .extend([lo.result, lo.carry, hi.result, hi.carry]); + roles.reads.insert((hi.site, Reg::Scc, lo.carry)); + roles.carries.insert((hi.site, lo.carry)); + Some([lo, hi]) + } + + // Record precisely the base operand. The caller must certify the other + // explicit operand separately, including on an ADDC that also reads SCC. + fn base_operand(&self, add: &Add, name: &str, roles: &mut Roles) -> Option<(Value, Operand)> { + [(0, 1), (1, 0)].into_iter().find_map(|(base, other)| { + let (r, v) = self.sgpr(add.site, add.src[base])?; + (self.inst(v)?.0.name() == name).then(|| { + roles.reads.insert((add.site, r, v)); + (v, add.src[other]) + }) + }) + } + + /// The shifted register pair and GETPC must each come from a single + /// instruction, with neither high/low substitution nor special registers. + fn pair_result(&self, values: [Value; 2], name: &str) -> Option { + let &(site, _) = self.insts.get(&values[0])?; + let inst = self.at(site); + let Fields::Sop { + dst: + Some(Operand::Scalar { + code: c @ 0..=104, + dwords: 2, + }), + .. + } = inst.fields + else { + return None; + }; + (inst.name() == name + && inst.write(Reg::S(c)) == Some(values[0]) + && inst.write(Reg::S(c + 1)) == Some(values[1])) + .then_some(site) + } + + pub(super) fn paired( + &self, + sink: Site, + code: u8, + soffset: Operand, + dynamic: Value, + ) -> Option { + if code > 104 + || matches!(soffset, Operand::Scalar { code: c, .. } if c == code || c == code+1) + { + return None; + } + let mut roles = Roles::default(); + let words = [ + self.read_at(sink, Reg::S(code))?, + self.read_at(sink, Reg::S(code + 1))?, + ]; + roles.reads.extend([ + (sink, Reg::S(code), words[0]), + (sink, Reg::S(code + 1), words[1]), + ]); + let [lo, hi] = self.add_pair(words, &mut roles)?; + let (fixed_lo, shift_lo) = self.base_operand(&lo, "s_add_u32", &mut roles)?; + let (fixed_hi, shift_hi) = self.base_operand(&hi, "s_addc_u32", &mut roles)?; + let (_, shift_lo) = self.sgpr(lo.site, shift_lo)?; + let (_, shift_hi) = self.sgpr(hi.site, shift_hi)?; + if dynamic != shift_lo { + return None; + } + let shift_site = self.pair_result([shift_lo, shift_hi], "s_lshl_b64")?; + let Fields::Sop { src, .. } = &self.at(shift_site).fields else { + return None; + }; + let &[ + Operand::Scalar { + code: c @ 0..=104, + dwords: 2, + }, + count, + ] = src.as_slice() + else { + return None; + }; + let index = self.read_at(shift_site, Reg::S(c))?; + let high = self.read_at(shift_site, Reg::S(c + 1))?; + let &(sign, _) = self.insts.get(&high)?; + let sign_inst = self.at(sign); + let Fields::Sop { + dst: Some(Operand::Scalar { code: d, dwords: 1 }), + src, + .. + } = &sign_inst.fields + else { + return None; + }; + let &[value, bits] = src.as_slice() else { + return None; + }; + if sign_inst.name() != "s_ashr_i32" + || *d != c + 1 + || self.sgpr(sign, value)?.1 != index + || scalar_constant(bits)? & 31 != 31 + { + return None; + } + let dynamic_low_site = lo.site; + let [lo, hi] = self.add_pair([fixed_lo, fixed_hi], &mut roles)?; + if !self.before(hi.site, dynamic_low_site) { + return None; + } + let (pc_lo, low_adjustment) = self.base_operand(&lo, "s_getpc_b64", &mut roles)?; + let (pc_hi, high_adjustment) = self.base_operand(&hi, "s_getpc_b64", &mut roles)?; + let pc = self.at(self.pair_result([pc_lo, pc_hi], "s_getpc_b64")?); + if scalar_constant(high_adjustment)? != 0 { + return None; + } + let base = u32::try_from(pc.machine.offset) + .ok()? + .checked_add(4)? + .checked_add(scalar_constant(low_adjustment)?)?; + roles.values.extend([pc_lo, pc_hi]); + Some(Paired { + base, + shift_site, + count, + index, + roles, + }) + } +} + +/// The high input is the sign extension of this exact low input. Refuse +/// shifted-out bits and any result wider than the tracker's numeric term. +pub(super) fn displacement(index: u32, count: u32) -> Option { + let input = index as i32 as i64 as u64; + let shift = count & 63; + if input > (u64::MAX >> shift) { + return None; + } + u32::try_from(input << shift).ok() +} + +impl Roles { + pub(super) fn extend(&mut self, other: Self) { + self.values.extend(other.values); + self.reads.extend(other.reads); + self.carries.extend(other.carries); + } + + pub(super) fn valid(&self, defs: &Definitions, st: &Structured, res: &Resources) -> bool { + let protected = |v: &Value| self.values.contains(v); + let mut completed = Set::default(); + if !self + .carries + .iter() + .all(|&(_, carry)| completed.insert(carry)) + { + return false; + } + for (b, block) in defs.p.blocks.iter().enumerate() { + if defs.rank[b] == usize::MAX { + continue; + } + if block.phis.iter().flat_map(|p| &p.args).any(protected) { + return false; + } + for (i, inst) in block.insts.iter().enumerate() { + if inst + .reads + .iter() + .any(|&(r, v)| protected(&v) && !self.reads.contains(&((b, i), r, v))) + { + return false; + } + } + } + if res + .scalar + .iter() + .any(|(_, a)| a.dynamic.as_ref().is_some_and(protected)) + || res + .descriptors + .iter() + .any(|d| self.descriptor_use(&d.source)) + || res.waterfall.reads.iter().any(protected) + || st + .restored + .iter() + .chain(&st.highs) + .any(|(a, b)| protected(a) || protected(b)) + || st + .masks + .keys() + .chain(st.other.keys()) + .chain(st.scc_votes.keys()) + .chain(&st.active) + .any(protected) + || st + .mask_inputs + .keys() + .any(|(a, b)| protected(a) || protected(b)) + { + return false; + } + let mut pending: Vec<_> = st + .exits + .iter() + .filter_map(|e| match e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }) + .chain(st.guards.iter().flatten().flatten()) + .chain(&st.reach) + .chain(st.discards.values()) + .chain(st.masks.values()) + .chain(st.other.values()) + .chain(st.mask_inputs.values().flatten()) + .chain(st.scc_votes.values()) + .copied() + .collect(); + let mut seen = Set::default(); + while let Some(b) = pending.pop() { + if !seen.insert(b) { + continue; + } + if let Some((a, lo, hi)) = st.bools.node(b) { + match a { + Atom::Any(inner) => pending.push(inner), + Atom::PairPhi(a, b) | Atom::OpaquePair(a, b) + if protected(&a) || protected(&b) => + { + return false; + } + Atom::Lane(v) + | Atom::Uniform(v) + | Atom::Phi(v) + | Atom::Quad(v) + | Atom::Opaque(v) + if protected(&v) => + { + return false; + } + _ => {} + } + pending.extend([lo, hi]); + } + } + true + } + + fn descriptor_use(&self, source: &Source) -> bool { + let args = match source { + Source::Built { address, .. } => { + return address.dynamic.is_some_and(|v| self.values.contains(&v)); + } + Source::Select { scc, .. } | Source::Lanes { mask: scc, .. } + if self.values.contains(scc) => + { + return true; + } + Source::Select { args, .. } | Source::Lanes { args, .. } | Source::Phi { args, .. } => { + args + } + Source::LanePhi { args, .. } => { + return args.iter().flatten().any(|s| self.descriptor_use(s)); + } + _ => return false, + }; + args.iter().any(|s| self.descriptor_use(s)) + } +} diff --git a/crates/victory-shader/src/emit/lower/retry/tests.rs b/crates/victory-shader/src/emit/lower/retry/tests.rs new file mode 100644 index 000000000..676633dcc --- /dev/null +++ b/crates/victory-shader/src/emit/lower/retry/tests.rs @@ -0,0 +1,852 @@ +use super::*; +use crate::emit::halves_tests::{live_sources, native, parts}; + +/// Each outer entry adds ten. The inner loop runs old_index+2 times, then +/// preserves its progress in a per-lane UAV word before the two-way latch. +fn table_loop(words: [u32; 4]) -> NativeProgram { + fixture(words, false) +} + +fn fixture(words: [u32; 4], next_index: bool) -> NativeProgram { + fixture_with_input(words, next_index, true) +} + +fn fixture_with_input(words: [u32; 4], next_index: bool, publish: bool) -> NativeProgram { + fixture_address(words, next_index, publish, false) +} + +fn fixture_address( + words: [u32; 4], + next_index: bool, + publish: bool, + paired: bool, +) -> NativeProgram { + let mut code = vec![ + 0xbe84_0300, + 0xbe85_0380, + 0xf408_0a02, + 0xfa00_0040, + 0xbf8c_c07f, // UAV + ]; + if publish { + code.extend([ + 0xf408_0b02, + 0xfa00_0020, + 0xbf8c_c07f, // SRV s[44:47] + 0xf420_0696, + 0xfa00_0000, + 0xbf8c_c07f, // s26 = actual published input + ]); + } else { + code.push(0xbe9a_03bf); // s26 = 63 + } + code.extend([ + 0x3420_0085, // v16 = lane * 32 + 0xbe88_1f00, // s[8:9] = PC + ]); + let pc = code.len() * 4; + if paired { + code.extend([0x800a_ff08, 0, 0x820b_8009]); // s[10:11] = PC + table distance + } + code.extend([ + 0xbe94_0380, // s20 = 0, index + 0xbe95_0380, // s21 = 0, progress + 0xbe96_0380, // no previous table word + ]); + let outer = code.len(); + code.extend([ + 0x8015_8a15, // progress += 10 + 0x7d84_0080, // VCC = lane zero + 0xbe9c_046a, // s[28:29] = VCC + ]); + let skip = code.len(); + code.push(0); + let latch = code.len(); + if paired { + // Two separately formed addresses share the adjusted PC. Both use the + // same full displacement. Only the second result controls the branch. + // The constant guard skips the first use at runtime. Its block is + // still in the graph and must receive an independent certificate. + code.extend([0xbf06_8080, 0xbf85_0004]); + for dest in [36, 22] { + code.extend([ + 0x800c_1e0a, + 0x820d_1f0b, + 0xf400_0006 | (dest << 6), + 0xfa00_0000, + ]); + } + } else { + code.extend([0xf400_0584, 0]); + } + code.extend([0xbf8c_c07f, 0xbf06_8016]); // s22 = table word; == 0 + code.push(0xbe9c_0480); // direct latch entry enables no masked store + let branch = |at: usize, to: usize, opcode: u32| { + opcode | u32::from(i16::try_from(to as isize - at as isize - 1).unwrap() as u16) + }; + code.push(branch(code.len(), outer, 0xbf85_0000)); + code[skip] = branch(skip, code.len(), 0xbf82_0000); + let shift: &[u32] = if paired { + // Sign extend the old dword and shift the pair left by two. + &[0xbea2_0314, 0x9123_9f22, 0x8f9e_8222] + } else { + &[0x8f17_8214] + }; + if next_index { + code.push(0x8014_8114); + code.extend(shift); + } else { + code.extend(shift); + code.push(0x8014_8114); + } + code.extend([ + 0x8018_8114, // s24 = index + 1 (inner count) + 0x8015_8115, // inner: ++progress + 0x8098_8118, // --s24 + 0xbf07_8018, // s24 != 0 + 0xbf85_fffc, // if set, inner + ]); + for (register, offset) in [(21, 0), (22, 4), (26, 8)] { + code.extend([0x7e0c_0200 | register, 0xe070_1000 | offset, 0x800a_0610]); + } + code.extend([ + 0x7e0c_0215, // v6 = progress + 0xbefe_041c, // joined mask from the selected incoming edge + 0xe070_100c, + 0x800a_0610, // guarded store at slot 3 + 0xbefe_04c1, // restore every lane + ]); + code.push(0xbf06_8414); // index == 4 + code.push(branch(code.len(), latch, 0xbf84_0000)); + code.push(0xbf81_0000); + let distance = (code.len() * 4 - pc) as u32; + if paired { + code[pc / 4 + 1] = distance; + } else { + code[latch + 1] = (23 << 25) | distance; + } + code.extend(words); + native(&code, true, 64, 0) +} + +fn emit(n: &NativeProgram) -> Result { + let p = crate::ir::build(&n.code, true, n.vgprs)?; + let st = crate::structure::split_literal(&p)?; + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st))?; + let io = crate::io::raise(&p, n)?; + lower_literal(&parts(n, &p, &st, &res, &io, true, true), None, false) +} + +#[test] +fn immutable_table_paired_addresses() { + for (words, next, publish) in [ + ([2, 7, 5, 0], false, true), + ([0, 0, 0, 9], false, true), + ([0, 2, 7, 5], true, false), + ] { + let n = fixture_address(words, next, publish, true); + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let facts = immutable::prove(&p, &st, &res, &n); + let start = usize::from(next); + let expected: Set<_> = words[start..start + 3].iter().copied().collect(); + assert_eq!(facts.reads.len(), 2, "both uses of the shared base"); + assert!(facts.reads.values().all(|content| *content == expected)); + assert_eq!(facts.jumps.len(), 1); + assert_eq!(facts.carries.len(), 3, "one fixed and two dynamic carries"); + let (latch, selected) = facts.jumps[0]; + let Exit::Branch { taken, not_taken } = p.blocks[latch].exit else { + panic!("two-way latch") + }; + assert_eq!(selected, if words[start] == 0 { taken } else { not_taken }); + let q = crate::ir::folded(&p, &facts.jumps).unwrap().unwrap(); + let st = crate::structure::split_literal(&q).unwrap(); + let res = crate::resource::track(&q, &n.layout, n.stage, Some(&st)).unwrap(); + let final_facts = immutable::prove(&q, &st, &res, &n); + assert_eq!(final_facts.reads.len(), 2); + assert!( + final_facts + .reads + .values() + .all(|content| *content == expected) + ); + assert_eq!(final_facts.carries.len(), 3); + assert!(final_facts.jumps.is_empty()); + let io = crate::io::raise(&q, &n).unwrap(); + let x = parts(&n, &q, &st, &res, &io, true, true); + let proof = super::super::literal_publish::prove(&x, 64, 0, &HashMap::new()) + .ok() + .unwrap(); + assert_eq!(proof.is_some(), publish); + if let Some(proof) = proof { + for &(site, carry) in &final_facts.carries { + let high = &q.blocks[site.0].insts[site.1]; + assert!(!proof.common.contains(&carry)); + assert!(high.writes.iter().all(|(_, v)| !proof.common.contains(v))); + } + } + let emitted = emit(&n).unwrap(); + assert_eq!(live_sources(&emitted).len(), usize::from(publish)); + } +} + +#[test] +fn immutable_table_paired_requires_complete_operands_and_uses() { + let n = fixture_address([2, 7, 5, 0], false, true, true); + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let facts = immutable::prove(&p, &st, &res, &n); + assert_eq!(facts.reads.len(), 2); + let site = |name, reg| { + p.blocks + .iter() + .enumerate() + .find_map(|(b, block)| { + block + .insts + .iter() + .position(|i| i.name() == name && i.write(reg).is_some()) + .map(|i| (b, i)) + }) + .unwrap() + }; + let fixed_hi = site("s_addc_u32", Reg::S(11)); + let outer_hi = site("s_addc_u32", Reg::S(13)); + let fixed_lo = site("s_add_u32", Reg::S(10)); + let shift = site("s_lshl_b64", Reg::S(30)); + let sign = site("s_ashr_i32", Reg::S(35)); + let load = site("s_load_dword", Reg::S(36)); + let second = site("s_load_dword", Reg::S(22)); + let adjusted = p.blocks[fixed_lo.0].insts[fixed_lo.1] + .write(Reg::S(10)) + .unwrap(); + let pure = p.blocks[shift.0].insts[shift.1].write(Reg::Scc).unwrap(); + let refuse = |query: &Program, st: &Structured, res: &Resources| { + let f = immutable::prove(query, st, res, &n); + assert!(f.reads.is_empty() && f.carries.is_empty() && f.jumps.is_empty()); + }; + // Each query changes just a proof input on the original native graph. + for (b, i) in [fixed_hi, outer_hi] { + for replacement in [None, Some(pure)] { + let mut q = p.clone(); + let add = &mut q.blocks[b].insts[i]; + add.reads.retain(|(r, _)| *r != Reg::Scc); + if let Some(v) = replacement { + add.reads.push((Reg::Scc, v)); + } + refuse(&q, &st, &res); + } + } + for ((b, i), arg, replacement) in [ + (fixed_hi, 0, Operand::Scalar { code: 8, dwords: 1 }), // low PC as high + (fixed_hi, 1, Operand::Const(129)), // wrong high adjustment + (outer_hi, 1, Operand::Const(253)), // explicit SCC data in addition to implicit carry + ( + outer_hi, + 1, + Operand::Scalar { + code: 30, + dwords: 1, + }, + ), // low shift word as high + (sign, 1, Operand::Const(128)), // no sign extension + ( + shift, + 1, + Operand::Scalar { + code: 60, + dwords: 1, + }, + ), // unknown count + ] { + let mut q = p.clone(); + let Fields::Sop { src, .. } = &mut q.blocks[b].insts[i].fields else { + unreachable!() + }; + src[arg] = replacement; + refuse(&q, &st, &res); + } + let mut q = p.clone(); + let later_low = p.blocks[second.0].insts[second.1].read(Reg::S(12)).unwrap(); + q.blocks[load.0].insts[load.1] + .reads + .iter_mut() + .find(|(r, _)| *r == Reg::S(12)) + .unwrap() + .1 = later_low; + refuse(&q, &st, &res); // use before its definition + let mut q = p.clone(); + let skipped_low = p.blocks[load.0].insts[load.1].read(Reg::S(12)).unwrap(); + q.blocks[second.0].insts[second.1] + .reads + .iter_mut() + .find(|(r, _)| *r == Reg::S(12)) + .unwrap() + .1 = skipped_low; + refuse(&q, &st, &res); // the optional arm does not dominate the join + let mut q = p.clone(); + let Fields::Smem { soffset, .. } = &mut q.blocks[load.0].insts[load.1].fields else { + unreachable!() + }; + *soffset = Operand::Scalar { + code: 12, + dwords: 1, + }; + refuse(&q, &st, &res); // base low also used as numeric displacement + for escaped in [ + adjusted, + p.blocks[outer_hi.0].insts[outer_hi.1] + .write(Reg::Scc) + .unwrap(), + ] { + let mut q = p.clone(); + q.blocks[sign.0].insts[sign.1] + .reads + .push((Reg::S(60), escaped)); + refuse(&q, &st, &res); + let mut s = st.clone(); + s.restored.insert(pure, escaped); + refuse(&p, &s, &res); + let mut r = res.clone(); + r.descriptors[0].source = Source::Select { + scc: escaped, + args: vec![r.descriptors[0].source.clone()], + }; + refuse(&p, &st, &r); + let mut r = res.clone(); + r.descriptors[0].source = Source::Built { + address: Address { + param: CODE, + offset: 0, + dynamic: Some(escaped), + }, + bits: 0, + words: [0; 2], + }; + refuse(&p, &st, &r); + } + let mixed = fixture_address([2, 0, 5, 9], false, true, true); + let facts = immutable::prove(&p, &st, &res, &mixed); + assert_eq!(facts.reads.len(), 2); + assert!(facts.jumps.is_empty()); + // Strict admission without a fold still checks every CODE producer. + let io = crate::io::raise(&p, &mixed).unwrap(); + let mut r = res.clone(); + r.descriptors[0].source = Source::Built { + address: Address { + param: CODE, + offset: u32::MAX, + dynamic: None, + }, + bits: 0, + words: [0; 2], + }; + let x = parts(&mixed, &p, &st, &r, &io, true, true); + assert!( + matches!(super::super::literal_publish::prove(&x, 64, 0, &HashMap::new()), + Err(Stop::Fail(ShaderError::Unsupported{what, ..})) if what.contains("proved byte range")) + ); +} + +#[test] +fn immutable_table_two_counted_edges() { + for words in [[2, 7, 5, 0], [0, 0, 0, 9]] { + let lower = emit(&table_loop(words)).unwrap_or_else(|error| panic!("{words:?}: {error}")); + assert_eq!(live_sources(&lower), [(Some(0), 0)]); + } +} + +#[test] +fn immutable_table_old_and_new_index() { + for (words, next) in [ + ([2, 0, 5, 9], false), + ([0, 2, 4, 6], false), + ([2, 4, 6, 0], true), + ([0, 2, 4, 6], true), + ] { + let n = fixture(words, next); + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let facts = immutable::prove(&p, &st, &res, &n); + let start = usize::from(next); + let expected: Set<_> = words[start..start + 3].iter().copied().collect(); + assert_eq!(facts.reads.len(), 1, "{words:?}, next={next}"); + assert_eq!(facts.reads.values().next(), Some(&expected)); + assert_eq!(facts.jumps.len(), usize::from(!expected.contains(&0))); + + // Mixed words still select both counted edges. Common immutable + // contents prove the dynamic choice without folding the latch. + let lower = emit(&n).unwrap_or_else(|error| panic!("{words:?}, next={next}: {error}")); + assert_eq!(live_sources(&lower), [(Some(0), 0)]); + } +} + +fn trace(words: [u32; 4], next_index: bool, cap: usize) -> Vec<(u32, u32)> { + let (mut progress, mut previous) = (10, 0); + let mut trace = Vec::new(); + for index in 0..4.min(cap) { + progress += (index + 2).min(cap) as u32; + trace.push((progress, previous)); + if index == 3 { + break; + } + previous = words[index + usize::from(next_index)]; + if previous == 0 { + progress += 10; + } + } + trace +} + +#[test] +fn immutable_table_guest_visits_and_caps() { + assert_eq!( + trace([2, 7, 5, 0], false, 16384), + [(12, 0), (15, 2), (19, 7), (24, 5)] + ); + assert_eq!( + trace([0, 0, 0, 9], false, 16384), + [(12, 0), (25, 0), (39, 0), (54, 0)] + ); + assert_eq!( + trace([2, 0, 5, 9], false, 16384), + [(12, 0), (15, 2), (29, 0), (34, 5)] + ); + assert_eq!(trace([0, 2, 7, 5], true, 1), [(11, 0)]); + assert_eq!(trace([0, 2, 7, 5], true, 2), [(12, 0), (14, 2)]); +} + +#[cfg(windows)] +#[test] +fn immutable_table_matches_gpu() { + check_gpu( + "emit::lower::retry::tests::immutable_table_matches_gpu", + false, + ); +} + +#[cfg(windows)] +#[test] +fn immutable_table_paired_matches_gpu() { + check_gpu( + "emit::lower::retry::tests::immutable_table_paired_matches_gpu", + true, + ); +} + +#[cfg(windows)] +fn check_gpu(name: &str, paired: bool) { + use crate::emit::halves_tests::{compare_dispatches, in_bounded_gpu_child, shader}; + use crate::emit::host::{Stride, View}; + use crate::emit::validator::Validator; + if !in_bounded_gpu_child(name) { + return; + } + let mut validator = Validator::load(Validator::default_path().as_deref()); + if let Err(reason) = &validator { + eprintln!("DXIL validator unavailable: {reason}"); + } + const MARK: u32 = 0xa25c_19d3; + let seed = [MARK; 512]; + let input = [63; 8]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Raw, + }, + View::RawUavData(&seed), + ]; + for (words, next, publish) in [ + ([2, 7, 5, 0], false, true), + ([0, 0, 0, 9], false, true), + ([0, 2, 7, 5], true, !paired), + ([2, 0, 5, 9], false, true), + ] { + let n = fixture_address(words, next, publish, paired); + let result = trace(words, next, crate::emit::loop_limit() as usize); + let &(progress, previous) = result.last().unwrap(); + let mut expected = seed; + for lane in expected.as_chunks_mut::<8>().0 { + lane[..3].copy_from_slice(&[progress, previous, input[0]]); + } + // Lane zero writes on outer entries; other lanes retain the sentinel. + expected[3] = result + .iter() + .rev() + .find(|(_, prior)| *prior == 0) + .unwrap() + .0; + let legal = shader(emit(&n).unwrap()); + if let Ok(v) = &mut validator { + v.validate(&mut legal.dxil.clone()).unwrap(); + } + let forms = [("publication wave32", legal)]; + let (errors, dispatches) = compare_dispatches(&forms, 1, 8, &expected, &views); + assert!(dispatches > 0, "no physical wave32 device"); + assert!(errors.is_empty(), "{}", errors.join("\n")); + } +} + +#[test] +fn immutable_table_rebuilds_exits_joins_and_strict_sources() { + for (words, selected) in [([2, 7, 5, 0], false), ([0, 0, 0, 9], true)] { + let n = table_loop(words); + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let track = |p: &Program| { + let st = crate::structure::split_literal(p).unwrap(); + let res = crate::resource::track(p, &n.layout, n.stage, Some(&st)).unwrap(); + (st, res) + }; + let (st, res) = track(&p); + let before = immutable::prove(&p, &st, &res, &n); + let [((b, _), _)] = before.reads.iter().collect::>()[..] else { + panic!("one CODE read") + }; + let Exit::Branch { taken, not_taken } = p.blocks[*b].exit else { + panic!("two targets") + }; + let target = if selected { taken } else { not_taken }; + assert_eq!(before.jumps, [(*b, target)]); + let q = crate::ir::folded(&p, &before.jumps).unwrap().unwrap(); + let (st, res) = track(&q); + let after = immutable::prove(&q, &st, &res, &n); + assert!(after.jumps.is_empty()); + let (&(latch, _), contents) = after.reads.iter().next().unwrap(); + assert_eq!(*contents, words[..3].iter().copied().collect()); + let Exit::Jump(to) = q.blocks[latch].exit else { + panic!("one counted edge") + }; + assert_eq!(q.blocks[to].offset, p.blocks[target].offset); + let order = crate::ir::reverse_postorder(&q.blocks); + let rank = |b| order.iter().position(|&i| i == b).unwrap(); + assert!(rank(to) <= rank(latch)); + if !selected { + let block = &q.blocks[to]; + let phi = |r| { + block + .phis + .iter() + .find(|p| p.reg == Reg::S(r)) + .unwrap() + .value + }; + assert_eq!(st.mask_inputs[&(phi(28), phi(29))].len(), block.preds.len()); + } + let mut inner = 0; + for (b, block) in q.blocks.iter().enumerate() { + let preds: Vec<_> = q + .blocks + .iter() + .enumerate() + .filter(|(_, p)| p.exit.successors().contains(&b)) + .map(|(p, _)| p) + .collect(); + assert_eq!(block.preds, preds); + assert!(block.phis.iter().all(|p| p.args.len() == preds.len())); + if let LaneExit::Branch { + taken, not_taken, .. + } = st.exits[b] + && (rank(taken) <= rank(b) || rank(not_taken) <= rank(b)) + { + inner += 1; + } + } + assert_eq!( + inner, 1, + "one conditional counter with its own ordinary exit" + ); + let io = crate::io::raise(&q, &n).unwrap(); + let x = parts(&n, &q, &st, &res, &io, true, true); + assert!(matches!( + super::super::literal_publish::prove(&x, 64, 0, &HashMap::new()), + Ok(Some(_)) + )); + } +} + +#[test] +fn immutable_table_declines_incomplete_index_proofs() { + for paired in [false, true] { + check_incomplete_index_proofs(fixture_address([2, 7, 5, 0], false, true, paired)); + } +} + +fn check_incomplete_index_proofs(n: NativeProgram) { + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let no_read = + |p: &Program, r: &Resources| assert!(immutable::prove(p, &st, r, &n).reads.is_empty()); + let mut unknown = res.clone(); + let entry = unknown + .scalar + .iter_mut() + .find(|(_, a)| a.param == CODE) + .unwrap(); + let site = entry.0; + entry.1.param = MEMORY; + no_read(&p, &unknown); + let (b, i) = p + .blocks + .iter() + .enumerate() + .find_map(|(b, block)| { + block + .phis + .iter() + .position(|p| p.reg == Reg::S(20)) + .map(|i| (b, i)) + }) + .unwrap(); + let mut missing = p.clone(); + missing.blocks[b].phis[i].args.pop(); + no_read(&missing, &res); + let mut changed = p.clone(); + let phi = &mut changed.blocks[b].phis[i]; + phi.args.fill(phi.value); + no_read(&changed, &res); + // An extra entry into the body carries a value with no numeric proof. + let mut extra = p.clone(); + let inner = extra + .blocks + .iter() + .position(|block| { + !block.preds.contains(&0) && block.phis.iter().any(|phi| phi.reg == Reg::S(20)) + }) + .unwrap(); + let Exit::Jump(outer) = extra.blocks[0].exit else { + panic!("ordinary preheader") + }; + extra.blocks[0].exit = Exit::Branch { + taken: inner, + not_taken: outer, + }; + extra.blocks[inner].preds.insert(0, 0); + for phi in &mut extra.blocks[inner].phis { + phi.args.insert(0, p.inputs[0].1); + } + no_read(&extra, &res); + // Removing the exit test's numeric input admits an unbounded sequence. + // These are direct admission queries, never submitted for lowering. + let mut unbounded = p.clone(); + unbounded + .blocks + .iter_mut() + .flat_map(|b| &mut b.insts) + .find(|i| i.name() == "s_cmp_eq_u32" && i.read(Reg::S(20)).is_some()) + .unwrap() + .reads + .clear(); + no_read(&unbounded, &res); + for (original, word, replacement) in [ + ("s_add_u32", 0x9314_8114u32, "s_mul_i32"), + ("s_cmp_eq_u32", 0xbf08_8414, "s_cmp_gt_u32"), + ] { + let mut other = p.clone(); + let inst = other + .blocks + .iter_mut() + .flat_map(|b| &mut b.insts) + .find(|i| i.name() == original && i.read(Reg::S(20)).is_some()) + .unwrap(); + let bytes = [word, 0xbf81_0000] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + let mut machine = crate::gfx10::decode(&bytes).unwrap().remove(0); + assert_eq!(machine.name(), Some(replacement)); + machine.offset = inst.machine.offset; + inst.fields = machine.fields(true); + inst.machine = machine; + no_read(&other, &res); + } + assert_eq!(p.blocks[site.0].insts[site.1].name(), "s_load_dword"); +} + +#[test] +fn immutable_table_validates_remaining_producers_on_folded_legacy_graph() { + let n = fixture_with_input([2, 7, 5, 0], false, false); + assert!( + emit(&n).is_ok(), + "legal folded program with zero publications" + ); + let src = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let tracked = |p: &Program| { + let st = crate::structure::split_literal(p).unwrap(); + crate::resource::track(p, &n.layout, n.stage, Some(&st)).unwrap() + }; + let facts = immutable::prove( + &src, + &crate::structure::split_literal(&src).unwrap(), + &tracked(&src), + &n, + ); + assert_eq!(facts.jumps.len(), 1); + let q = crate::ir::folded(&src, &facts.jumps).unwrap().unwrap(); + let res = tracked(&q); + let st = crate::structure::split_literal(&q).unwrap(); + let io = crate::io::raise(&q, &n).unwrap(); + let x = parts(&n, &q, &st, &res, &io, true, true); + assert!(matches!( + super::super::literal_publish::prove(&x, 64, 0, &HashMap::new()), + Ok(None) + )); + let site = q + .blocks + .iter() + .enumerate() + .find_map(|(b, block)| { + block + .insts + .iter() + .position(|i| i.write(Reg::S(26)).is_some()) + .map(|i| (b, i)) + }) + .unwrap(); + // Query the final range gate only. Supply each producer class at the + // independent definition site. The original computed table stays live. + for (op, buffer, fixed_displacement) in [ + ([0xf404_0684, 0xfa00_0000], false, true), // scalar pair + ([0xdc34_8000, 0x0604_0010], false, true), // global pair + ([0xf424_0696, 0xfa00_0004], true, true), // scalar buffer pair, displacement four + ([0xf424_0696, 0x2800_0004], true, false), // scalar buffer pair, additional SGPR + ] { + let mut p = q.clone(); + let inst = &mut p.blocks[site.0].insts[site.1]; + let bytes = [op[0], op[1], 0xbf81_0000u32] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + let mut machine = crate::gfx10::decode(&bytes).unwrap().remove(0); + let offset = inst.machine.offset; + machine.offset = offset; + inst.fields = machine.fields(true); + inst.machine = machine; + let unknown = p.inputs[0].1; + let end = u32::try_from(n.code.len()).unwrap(); + let last_base = end - 8 - if buffer { 4 } else { 0 }; + for (base, dynamic, ok) in [ + (last_base, None, true), + (last_base, Some(unknown), false), + (last_base + 4, None, false), + ] { + let mut resources = res.clone(); + let address = Address { + param: CODE, + offset: base, + dynamic, + }; + if buffer { + resources.descriptors.push(crate::resource::Descriptor { + site, + role: Role::Resource, + source: Source::Built { + address, + bits: 0, + words: [u32::MAX, 0x1101_4fac], + }, + }); + } else { + resources.scalar.push((site, address)); + } + let facts = immutable::prove(&p, &st, &resources, &n); + assert_eq!( + facts.reads.len(), + 1, + "the independent table still has its proof" + ); + let result = + super::super::literal_publish::folded_code(&p, &resources, &n, &facts.reads); + if ok && fixed_displacement { + result.unwrap(); + } else { + assert!( + matches!(result,Err(ShaderError::Unsupported{offset:at,what}) if at==offset && what.contains("proved byte range")) + ); + } + } + } +} + +#[test] +fn immutable_table_folded_roles_without_handles_or_publication() { + let mut n = fixture_with_input([2, 7, 5, 0], false, false); + // Keep the CODE reader and the numeric mask consumer in the original + // loop. Removing its output stores and descriptor read leaves no handles. + for inst in crate::gfx10::decode(&n.code).unwrap() { + if matches!(inst.name(), Some("buffer_store_dword" | "s_load_dwordx4")) { + for word in n.code[inst.offset..inst.offset + 4 * inst.words.len()] + .as_chunks_mut::<4>() + .0 + { + word.copy_from_slice(&0xbf80_0000u32.to_le_bytes()); + } + } + } + let p = crate::ir::build(&n.code, true, n.vgprs).unwrap(); + let st = crate::structure::split_literal(&p).unwrap(); + let res = crate::resource::track(&p, &n.layout, n.stage, Some(&st)).unwrap(); + let jump = immutable::prove(&p, &st, &res, &n).jumps; + assert_eq!(jump.len(), 1); + let q = crate::ir::folded(&p, &jump).unwrap().unwrap(); + let st = crate::structure::split_literal(&q).unwrap(); + let res = crate::resource::track(&q, &n.layout, n.stage, Some(&st)).unwrap(); + assert!(res.descriptors.is_empty()); + assert!( + res.scalar + .iter() + .any(|(_, a)| a.param == CODE && a.dynamic.is_some()) + ); + let io = crate::io::raise(&q, &n).unwrap(); + let x = parts(&n, &q, &st, &res, &io, true, true); + assert!(matches!( + super::super::literal_publish::prove(&x, 64, 0, &HashMap::new()), + Ok(None) + )); + super::super::literal_publish::folded_roles(&x, &Set::default()).unwrap(); + let defs = || q.blocks.iter().flat_map(|b| &b.insts); + let pc = defs().find(|i| i.name() == "s_getpc_b64").unwrap().writes[0].1; + let root = res + .params + .iter() + .find(|(_, p, d)| (*p, *d) == (0, 0)) + .unwrap() + .0; + let integer = defs().find_map(|i| i.write(Reg::S(26))).unwrap(); + // These are source-role queries only. No guest encoding or addresses are + // changed, and none of the substituted metadata goes to lowering. + for (value, allowed) in [(integer, true), (pc, false), (root, false)] { + let mut query = q.clone(); + let consumer = query + .blocks + .iter_mut() + .flat_map(|b| &mut b.insts) + .find(|i| i.write(Reg::S(EXEC)).is_some() && i.read(Reg::S(28)).is_some()) + .unwrap(); + consumer + .reads + .iter_mut() + .find(|(reg, _)| *reg == Reg::S(28)) + .unwrap() + .1 = value; + let offset = consumer.machine.offset; + let checked = super::super::literal_publish::folded_roles( + &Parts { + p: &query, + ..x.clone() + }, + &Set::default(), + ); + if allowed { + checked.unwrap(); + } else { + assert!( + matches!(checked, Err(ShaderError::Unsupported{offset:at,what}) if at==offset && what.contains("without guest-exact bits")) + ); + } + } +} diff --git a/crates/victory-shader/src/emit/lower/terminal_owner.rs b/crates/victory-shader/src/emit/lower/terminal_owner.rs new file mode 100644 index 000000000..5da6ce2a9 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/terminal_owner.rs @@ -0,0 +1,472 @@ +//! A terminal EXEC split after a group barrier. Only the physical thread with +//! the selected in-group coordinate may reach the scalar continuation. +use super::*; + +pub(super) struct Owner { + pub(super) gate: usize, + selector: usize, + entry: usize, + end: usize, + body: Set, + pub(super) sites: Set, + #[cfg(test)] + pub(super) emitted: Vec, +} + +fn operands(i: &Inst) -> Option<&[Operand]> { + let Fields::Valu(v) = &i.fields else { + return None; + }; + (v.dpp.is_none() + && v.sdwa.is_none() + && v.abs == 0 + && v.neg == 0 + && v.neg_hi == 0 + && v.opsel == 0 + && v.opsel_hi == 0 + && !v.clamp + && v.omod == 0 + && v.carry.is_none()) + .then_some(v.src.as_slice()) +} + +fn immediate(op: Operand) -> Option { + match op { + Operand::Const(k) => crate::resource::inline(k), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +fn vector(i: &Inst, op: Operand) -> Option { + let Operand::Vector { reg, dwords: 1 } = op else { + return None; + }; + i.read(Reg::V(reg)) +} + +fn pair(i: &Inst, reg: u8) -> Option<(Value, Value)> { + Some((i.read(Reg::S(reg))?, i.read(Reg::S(reg + 1))?)) +} + +/// The initial two EXEC words, including exact saves/restores through scalar pairs. +/// A partially overwritten pair or an unchecked phi never proves full participation. +fn full_pairs(p: &Program, order: &[usize]) -> Set<(Value, Value)> { + let input = |reg| { + p.inputs + .iter() + .find_map(|&(r, v)| (r == Reg::S(reg)).then_some(v)) + }; + let mut full = Set::default(); + if let (Some(lo), Some(hi)) = (input(EXEC), input(EXEC + 1)) { + full.insert((lo, hi)); + } + for i in order.iter().flat_map(|&b| &p.blocks[b].insts) { + let Fields::Sop { + dst: Some(Operand::Scalar { code, dwords: 2 }), + src, + .. + } = &i.fields + else { + continue; + }; + let from = match (i.name(), src.as_slice()) { + ( + "s_mov_b64", + [ + Operand::Scalar { + code: src, + dwords: 2, + }, + ], + ) => *src, + ("s_and_saveexec_b64", _) if *code < EXEC => EXEC, + _ => continue, + }; + if pair(i, from).is_some_and(|v| full.contains(&v)) + && let (Some(lo), Some(hi)) = (i.write(Reg::S(*code)), i.write(Reg::S(*code + 1))) + { + full.insert((lo, hi)); + } + } + full +} + +fn full_exec(pairs: &Set<(Value, Value)>, i: &Inst) -> bool { + pair(i, EXEC).is_some_and(|v| pairs.contains(&v)) +} + +struct Selection { + exec: (Value, Value), + expected: u32, + source: Value, + empty: usize, + live: usize, +} + +/// A real lane-local negative test of the two EXEC words written by this +/// comparison, with the same empty/nonempty successors as the guest branch. +fn selection(x: &Parts, b: usize, full: &Set<(Value, Value)>) -> Option { + let block = &x.p.blocks[b]; + let [.., cmp, branch] = block.insts.as_slice() else { + return None; + }; + let LaneExit::Branch { + when, + taken, + not_taken, + } = x.st.exits[b] + else { + return None; + }; + let [k, v] = operands(cmp)? else { return None }; + let (lo, hi) = pair(branch, EXEC)?; + (cmp.name() == "v_cmpx_eq_u32" + && full_exec(full, cmp) + && x.st.guards[b][block.insts.len() - 2].is_none() + && cmp.write(Reg::S(EXEC)) == Some(lo) + && cmp.write(Reg::S(EXEC + 1)) == Some(hi) + && branch.name() == "s_cbranch_execz" + && block.exit == (Exit::Branch { taken, not_taken }) + && x.st.bools.node(when) == Some((Atom::Lane(lo), Bool::TRUE, Bool::FALSE)) + && x.st.reach[b] == Bool::TRUE) + .then_some(Selection { + exec: (lo, hi), + expected: immediate(*k)?, + source: vector(cmp, *v)?, + empty: taken, + live: not_taken, + }) +} + +fn flat_coordinate(x: &Parts, flat: Value, width: u32, full: &Set<(Value, Value)>) -> bool { + let entry = &x.p.blocks[0].insts; + let def = |v| { + entry.iter().enumerate().find_map(|(at, i)| { + (i.writes.iter().any(|&(_, w)| w == v) + && full_exec(full, i) + && x.st.guards[0][at].is_none()) + .then_some(i) + }) + }; + let coordinate = |i: &Inst, op, dim| { + vector(i, op).is_some_and(|v| x.io.inputs.contains(&(v, Input::ThreadIdInGroup(dim)))) + }; + let Some(i) = def(flat) else { return false }; + let shift = |op| immediate(op).is_some_and(|k| 1u32.checked_shl(k) == Some(width)); + match (i.name(), operands(i)) { + ("v_lshl_add_u32", Some(&[y, k, x_id])) => { + coordinate(i, y, 1) && shift(k) && coordinate(i, x_id, 0) + } + ("v_add_nc_u32", Some(&[a, b])) => [(a, b), (b, a)].into_iter().any(|(a, b)| { + coordinate(i, a, 0) + && vector(i, b).and_then(def).is_some_and(|s| { + s.name() == "v_lshlrev_b32" + && matches!(operands(s), Some(&[k, y]) if shift(k) && coordinate(s, y, 1)) + }) + }), + _ => false, + } +} + +pub(super) fn find(x: &Parts, order: &[usize]) -> Option { + let StageIo::Cs(cs) = x.native.io else { + return None; + }; + let [width, height, 1] = cs.threads else { + return None; + }; + let group = width.checked_mul(height)?; + if !group.is_multiple_of(64) + || x.st.literal + || !x.res.waterfall.compares.is_empty() + || !x.res.waterfall.reads.is_empty() + { + return None; + } + // Most compute programs have no such terminal barrier/compare at all. + let mut gates = order.iter().copied().filter(|&b| matches!(x.p.blocks[b].insts.as_slice(), + [.., barrier, cmp, branch] if barrier.name() == "s_barrier" && cmp.name() == "v_cmpx_eq_u32" && branch.name() == "s_cbranch_execz")); + gates.clone().next()?; + let full = full_pairs(x.p, order); + gates.find_map(|gate| { + let retest = selection(x, gate, &full)?; + let (entry, end) = (retest.live, retest.empty); + let bb = &x.p.blocks[gate]; + if retest.expected != u32::MAX + || end == entry + || x.p.blocks[end].exit != Exit::End + || !x.p.blocks[end].phis.is_empty() + || !x.p.blocks[end].insts.iter().all(|i| i.name() == "s_endpgm") + { + return None; + } + let phi = bb.phis.iter().find(|p| p.value == retest.source)?; + let [a, b] = bb.preds[..] else { return None }; + let [z, v] = phi.args[..] else { return None }; + let (selector, zero, body, one) = match (a, b) { + (a, b) if x.p.blocks[b].preds == [a] => (a, z, b, v), + (a, b) if x.p.blocks[a].preds == [b] => (b, v, a, z), + _ => return None, + }; + let select = selection(x, selector, &full)?; + let mov = |b: usize, v, val| { + x.p.blocks[b].insts.iter().enumerate().find_map(|(at, i)| { + (i.write(phi.reg) == Some(v) + && i.name() == "v_mov_b32" + && x.st.guards[b][at].is_none() + && matches!(operands(i), Some(&[k]) if immediate(k) == Some(val))) + .then_some(i) + }) + }; + let init = mov(selector, zero, 0)?; + let set = mov(body, one, retest.expected)?; + if x.st.exits[body] != LaneExit::Jump(gate) + || (select.empty, select.live) != (gate, body) + || select.expected >= group + || !flat_coordinate(x, select.source, width, &full) + || !full_exec(&full, init) + || set.read(phi.reg) != Some(zero) + || pair(set, EXEC) != Some(select.exec) + { + return None; + } + let mut owner = Owner { + gate, + selector, + entry, + end, + body: Set::default(), + sites: Set::default(), + #[cfg(test)] + emitted: Vec::new(), + }; + let mut stack = vec![entry]; + while let Some(b) = stack.pop() { + if b == end || !owner.body.insert(b) { + continue; + } + let block = &x.p.blocks[b]; + if b == gate + || b == 0 + || block.exit == Exit::Indirect + || !owner_branch(x, b, retest.exec) + || block + .phis + .iter() + .any(|p| matches!(p.reg, Reg::S(126 | 127))) + { + return None; + } + for (j, i) in block.insts.iter().enumerate() { + if i.writes + .iter() + .any(|&(r, _)| matches!(r, Reg::S(126 | 127))) + || x.st.guards[b][j].is_some() + || !lane_local(i) + || reads_mask_as_data(x.st, i) + { + return None; + } + if i.name() == "v_readfirstlane_b32" { + if pair(i, EXEC) != Some(retest.exec) + || !matches!(operands(i), Some(&[Operand::Vector { dwords: 1, .. }])) + { + return None; + } + owner.sites.insert((b, j)); + } + } + stack.extend(block.exit.successors()); + } + (!owner.sites.is_empty() + && owner.body.iter().all(|&b| { + x.p.blocks[b] + .preds + .iter() + .all(|&q| owner.body.contains(&q) || (q == gate && b == entry)) + })) + .then_some(owner) + }) +} + +/// With only one active guest bit, a VCC vote is local only when its other +/// bits are clear. Check the exact pair consumed by the scalar branch. +fn owner_branch(x: &Parts, b: usize, exec: (Value, Value)) -> bool { + let LaneExit::Branch { when, .. } = x.st.exits[b] else { + return true; + }; + let block = &x.p.blocks[b]; + let Some((branch, defs)) = block.insts.split_last() else { + return false; + }; + match branch.name() { + "s_cbranch_scc0" | "s_cbranch_scc1" => { + let Some(scc) = branch.read(Reg::Scc) else { + return false; + }; + let (lo, hi) = if branch.name() == "s_cbranch_scc1" { + (Bool::FALSE, Bool::TRUE) + } else { + (Bool::TRUE, Bool::FALSE) + }; + // A mask-result SCC votes over all 64 bits. Reach can simplify its + // owner bit to a constant even when the guest vote is the opposite. + x.st.bools.node(when) == Some((Atom::Uniform(scc), lo, hi)) + && defs.iter().any(|i| { + let name = i.name(); + i.write(Reg::Scc) == Some(scc) + && name.starts_with("s_cmp_") + && (name.ends_with("_i32") || name.ends_with("_u32")) + }) + } + "s_cbranch_vccz" | "s_cbranch_vccnz" => { + let Some((lo, hi)) = pair(branch, VCC) else { + return false; + }; + x.st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_) | Atom::Lane(_))) && + defs.iter().any(|i| matches!(i.name(), "s_and_b64" | "s_andn2_b64") + && i.write(Reg::S(VCC)) == Some(lo) && i.write(Reg::S(VCC+1)) == Some(hi) + && matches!(&i.fields, Fields::Sop { src, .. } if matches!(src.first(), Some(Operand::Scalar { code: EXEC, dwords: 2 }))) + && pair(i, EXEC) == Some(exec)) + } + _ => false, + } +} + +/// No inter-lane source, implicit derivative, atomic lock or barrier can +/// require participation by a lane that took the terminal exit. +fn lane_local(i: &Inst) -> bool { + let n = i.name(); + match &i.fields { + Fields::Valu(v) => { + v.dpp.is_none() + && !n.contains("perm") + && !n.contains("lane") + && !n.starts_with("v_mbcnt") + || n == "v_readfirstlane_b32" + } + Fields::Ds { .. } => n.starts_with("ds_read") && !n.contains("lane"), + Fields::Buffer { lds: false, .. } => n.contains("load") || n.contains("store"), + Fields::Image { .. } => matches!( + n, + "image_load" | "image_store" | "image_gather4_lz" | "image_sample_lz" + ), + Fields::Smem { .. } => n.starts_with("s_load_") || n.starts_with("s_buffer_load_"), + Fields::Sopp { .. } => { + n == "s_endpgm" + || n == "s_branch" + || n.starts_with("s_cbranch_") + || n.starts_with("s_waitcnt") + || n == "s_nop" + } + Fields::Sop { .. } => !n.contains("saveexec") && !n.contains("wqm"), + _ => false, + } +} + +impl Owner { + pub(super) fn overlaps_meet(&self, meet: &meet::Meet) -> bool { + meet.regions.iter().any(|r| { + self.body.contains(&r.branch) + || self.body.iter().any(|&b| r.blocks[b]) + || r.blocks[self.end] + || r.join + .is_some_and(|b| b == self.end || self.body.contains(&b)) + }) + } + + pub(super) fn preserved( + &self, + p: &Program, + st: &Structured, + exits: &[LaneExit], + plan: &predicate::PredicatePlan, + ) -> bool { + // Completed prefix skip guards restore their outer predicate at their joins. + // A wider or future rewrite must prove physical participation separately. + if !plan + .exits + .values() + .all(|e| matches!(e, predicate::FlatExit::SkipGuard { .. })) + || !plan.step[self.gate] + || !plan.step[self.selector] + || exits[self.gate] != st.exits[self.gate] + || exits[self.end] != LaneExit::End + { + return false; + } + for mut b in [self.gate, self.selector] { + while b != 0 { + if plan.skip_bodies.contains_key(&b) { + return false; + } + b = plan.skip_joins.get(&b).copied().unwrap_or(plan.idom[b]); + } + } + if self.body.iter().any(|&b| { + exits[b] != st.exits[b] + || plan.step[b] + || plan.skip_bodies.contains_key(&b) + || plan.skip_joins.contains_key(&b) + }) { + return false; + } + // Check incoming edges again on the CFG actually emitted. + exits.iter().enumerate().all(|(q, &exit)| { + let ok = |b| { + !self.body.contains(&b) + || self.body.contains(&q) + || (q == self.gate && b == self.entry) + }; + match exit { + LaneExit::Jump(b) => ok(b), + LaneExit::Branch { + taken, not_taken, .. + } => ok(taken) && ok(not_taken), + LaneExit::End | LaneExit::Indirect => true, + } + }) && p.blocks[self.entry].preds == [self.gate] + } +} + +#[cfg(test)] +impl Owner { + pub(super) fn verify_emission(&self, l: &Lower) { + assert_eq!(self.emitted.len(), self.sites.len()); + let mut blocks = vec![l.tail[self.gate].unwrap(), l.block[self.entry].unwrap()]; + blocks.extend(&self.emitted); + let (edges, sites) = l.s.m.written_cfg(&blocks); + let (&[gate, entry], reads) = sites.split_at(2) else { + unreachable!() + }; + let reach = |start, stop| { + let mut reached = Set::default(); + let mut work = vec![start]; + while let Some(b) = work.pop() { + if Some(b) != stop && reached.insert(b) { + work.extend(&edges[b]); + } + } + reached + }; + let &[a, b] = edges[gate].as_slice() else { + panic!("terminal owner lost its branch") + }; + let arms = [reach(a, None), reach(b, None)]; + let live = usize::from(!arms[0].contains(&entry)); + assert!(arms[live].contains(&entry) && !arms[1 - live].contains(&entry)); + let bypass = reach(0, Some(gate)); + assert!( + reads.iter().all(|r| arms[live].contains(r) + && !arms[1 - live].contains(r) + && !bypass.contains(r)) + ); + assert!( + l.s.m + .written_call_blocks("dx.op.barrier") + .iter() + .all(|b| !arms[live].contains(b)) + ); + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6d1f82abf..e1297ce40 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -251,7 +251,7 @@ mod crosslane_tests; mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; -#[cfg(all(test, windows))] +#[cfg(test)] mod halves_tests; pub mod heap_sources; pub use heap_sources::{BufferBinding, HeapIndexSource, ScalarSource}; @@ -771,24 +771,31 @@ struct Prepared<'a> { res: resource::Resources, } +/// Index of the first native program the runtime will translate. +pub fn runtime_program_index(programs: &[NativeProgram]) -> Result { + programs + .iter() + .position(|p| supports_stage(p.stage)) + .ok_or(ShaderError::Unsupported { + offset: 0, + what: "a container without a vertex, pixel, compute or mesh program", + }) +} + +/// Whether a native stage can be emitted as a standalone host shader. +pub fn supports_stage(stage: HwStage) -> bool { + matches!(stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms) +} + fn prepare(container: &[u8]) -> Result, ShaderError> { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) .or(c.part(FourCC::ACCC)) .ok_or(ShaderError::Malformed("no DXIL part"))?; - let native = crate::native_programs(dxil.data)? - .into_iter() - .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms - ) - }) - .ok_or(ShaderError::Unsupported { - offset: 0, - what: "a container without a vertex, pixel, compute or mesh program", - })?; + let mut programs = crate::native_programs(dxil.data)?; + let index = runtime_program_index(&programs)?; + let native = programs.swap_remove(index); // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). let (p, st) = crate::range::build(&native.patched_code(), native.wave64, native.vgprs)?; @@ -2586,8 +2593,13 @@ mod tests { return; } let ps = constant_color(); - let shaped = |v, p, rows: &[&[u8]], pr| -> Result { + let under_wine = super::host::under_wine(); + let shaped = |v, p, rows: &[&[u8]], pr| -> Result, String> { let ms = shaped_mesh(v, p, rows, pr).map_err(|e| e.to_string())?; + if under_wine && let Some(bytes) = over_limit_mesh_output_bytes(&ms.dxil) { + eprintln!("{bytes} bytes exceeds Metal's output limit; draw skipped under Wine"); + return Ok(None); + } let root = host.root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)])?; let pso = host.mesh_pipeline_with(&root, &ms.dxil, &ps)?; let texels = host.draw( @@ -2603,13 +2615,13 @@ mod tests { mesh_groups: 1, }, )?; - Ok(texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0])) + Ok(Some(texels.len() == 256 && texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]))) }; let draws = |v, p, vr: u32, pr| shaped(v, p, &vec![&[4u8][..]; vr as usize - 1], pr); // 17 rows of 59 components: whole rows would be over the limit. assert_eq!( shaped(128, 128, &HALF_FILLED, 0), - Ok(true), + Ok(Some(true)), "17 rows of 59 components" ); let one_more: Vec<&[u8]> = [&[&[4u8][..]; 15][..], &[&[1]]].concat(); @@ -2625,7 +2637,7 @@ mod tests { ] { assert_eq!( draws(v, p, vr, pr), - Ok(true), + Ok(Some(true)), "{v} vertices, {p} primitives, rows {vr} + {pr}" ); eprintln!( @@ -2697,13 +2709,18 @@ mod tests { Some(bytes), "{rows:?}, reversed {reversed}" ); + assert_eq!( + over_limit_mesh_output_bytes(&ms.dxil), + (bytes > METAL_MESH_OUTPUT_BYTES).then_some(bytes), + "{rows:?}, reversed {reversed}" + ); shaders.push(( format!("{front:?} {fours} x 4 {back:?} reversed {reversed}"), ms, )); } - // Where the hardware has mesh shaders: the shapes within the limit - // draw; D3DMetal makes no-op pipelines of the others. + // The shapes within the limit draw on mesh-capable hardware. + // D3DMetal can make no-op pipelines of the others and stall the test. #[cfg(windows)] { use super::host::{Draw, Host, Root}; @@ -2732,7 +2749,14 @@ mod tests { return; } let ps = constant_color(); + let under_wine = super::host::under_wine(); for ((label, ms), (.., bytes)) in shaders.iter().zip(cases) { + if under_wine && let Some(bytes) = over_limit_mesh_output_bytes(&ms.dxil) { + eprintln!( + "{label}: {bytes} bytes exceeds Metal's {METAL_MESH_OUTPUT_BYTES}-byte output limit; draw skipped under Wine" + ); + continue; + } let root = host .root_signature_for(&[(ms, D3D12_SHADER_VISIBILITY_MESH)]) .unwrap(); @@ -2753,11 +2777,12 @@ mod tests { }, ) }); - let drawn = drawn.map(|t| t.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0])); + let drawn = drawn.map(|t| { + t.len() == 256 && t.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]) + }); + eprintln!("{label}: {bytes} bytes, drawn {drawn:?}"); if bytes <= METAL_MESH_OUTPUT_BYTES { assert_eq!(drawn, Ok(true), "{label}: {bytes} bytes"); - } else { - eprintln!("{label}: {bytes} bytes, drawn {drawn:?}"); } } } @@ -4000,12 +4025,22 @@ mod tests { /// WARP) with the expected texels. #[test] fn linked_mesh_moves_clip_distances_out_of_the_way_of_vectors() { - // TEXCOORD0..12 four channels, 13 two, 14 one: rows 2 to 16. - let cols = |k: u32| match k { - 0..=12 => 4u8, - 13 => 2, - _ => 1, - }; + check_linked_clip_layout([4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 1], true); + } + + #[test] + fn linked_mesh_fills_three_component_alignment_gap() { + check_linked_clip_layout([4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 3, 1], true); + } + + #[test] + fn linked_mesh_refuses_live_bytes_above_the_budget() { + check_linked_clip_layout([4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 1], false); + } + + fn check_linked_clip_layout(widths: [u8; 15], fits: bool) { + let cols = |k: u32| widths[k as usize]; + let legacy_layout = cols(11) == 4; // v6 0.5, v7 1.0, v8 0.25, v10 0.0: x of TEXCOORD0 and TEXCOORD14 add // up to 1.0, y of TEXCOORD13 is 0.5, z of TEXCOORD5 0.25, w of // TEXCOORD12 1.0. @@ -4055,8 +4090,23 @@ mod tests { for k in 0..15u32 { let n = cols(k); sig.push(element("TEXCOORD", 0, k, k + 2, n, (1 << n) - 1)); + let source = if legacy_layout { + sources(k) + } else { + let first = 16 + 4 * k; + for ch in 0..u32::from(n) { + // Each varying is NDC x or y plus a distinct exact offset. + let value = (k + 16 * ch + 1) as f32 / 64.0; + let axis = 4 + ((k + ch) % 2); + words.extend([ + 3 << 25 | (first + ch) << 17 | axis << 9 | 0xFF, + value.to_bits(), + ]); + } + (0..4).fold(0, |regs, ch| regs | (first + ch) << (8 * ch)) + }; // exp param (the channels of the element) - words.extend([0xF800_0000 | ((1 << n) - 1) | ((32 + k) << 4), sources(k)]); + words.extend([0xF800_0000 | ((1 << n) - 1) | ((32 + k) << 4), source]); outputs.push(crate::native::VsOutput { usage: crate::native::Usage::Generic, row: k as u8 + 2, @@ -4071,13 +4121,13 @@ mod tests { 0xF800_00CF, // exp pos0 v4, v5, v6, v7 0x0706_0504, 0xF800_08D1, // exp pos1 v2 (clip distance 0.0 or 1.0: kept) done - 0x0202_0202, + if legacy_layout { 0x0202_0202 } else { 0x0404_0404 }, 0xBF81_0000, // s_endpgm ]); let ms_native = NativeProgram { stage: HwStage::Ms, wave64: false, - vgprs: 12, + vgprs: if legacy_layout { 12 } else { 76 }, layout: vec![], used: vec![], io: StageIo::Ms(crate::native::MeshIo { @@ -4139,7 +4189,12 @@ mod tests { }, code: ps_words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; - let ps_isg1 = container::signature(&sig, true); + let pixel_sig: Vec<_> = sig + .iter() + .filter(|e| legacy_layout || e.kind != 6) + .cloned() + .collect(); + let ps_isg1 = container::signature(&pixel_sig, true); let ps_osg1 = rows(&[("SV_Target", 16, false)], false); let ps_bytes = crate::dxbc::build(&[(FourCC::ISG1, &ps_isg1), (FourCC::OSG1, &ps_osg1)]); let pc = Container::parse(&ps_bytes).unwrap(); @@ -4178,13 +4233,64 @@ mod tests { res: &mres, }; let standalone = emit_pruned(&ms_in, Options::default(), None).unwrap(); - assert_eq!(mesh_bytes(&standalone.dxil), Some(30_720)); - assert_eq!(mesh_aligned_bytes(&standalone.dxil), Some(refused)); - let (linked_ms, linked_ps) = - link_prepared(&ms_in, Some(&ps_in), Options::default()).unwrap(); - assert!(linked_ps.is_some()); + if legacy_layout { + assert_eq!(mesh_bytes(&standalone.dxil), Some(30_720)); + assert_eq!(mesh_aligned_bytes(&standalone.dxil), Some(refused)); + assert_eq!(over_limit_mesh_output_bytes(&standalone.dxil), Some(refused)); + } + let full_ps = emit_pruned(&ps_in, Options::default(), None).unwrap(); + let reads = pixel_input_reads(&full_ps.dxil).unwrap(); + let original = emit_pruned(&ms_in, Options::default(), Some(&reads)).unwrap(); + let original_aligned = if legacy_layout { 32_768 } else { 33_792 }; + assert_eq!(mesh_aligned_bytes(&original.dxil), Some(original_aligned)); + assert_eq!( + mesh_bytes(&original.dxil), + Some(if fits { 30_720 } else { 31_232 }) + ); + + let linked = link_prepared(&ms_in, Some(&ps_in), Options::default()); + if !fits { + assert!(matches!( + linked, + Err(ShaderError::Unsupported { + what: "mesh outputs required by the next stage exceed 32 KiB", + .. + }) + )); + continue; + } + let (linked_ms, linked_ps) = linked.unwrap(); + let linked_ps = linked_ps.unwrap(); assert_eq!(mesh_bytes(&linked_ms.dxil), Some(30_720)); assert_eq!(mesh_aligned_bytes(&linked_ms.dxil), Some(32_768)); + let retained = pixel_input_reads(&linked_ps.dxil).unwrap().reads; + assert_eq!(retained.len(), reads.reads.len()); + for (semantic, &mask) in &reads.reads { + let relocated = retained[semantic]; + assert_eq!(relocated >> relocated.trailing_zeros(), mask); + } + let linked_container = Container::parse(&linked_ms.dxil).unwrap(); + let mut linked_outputs = + signature(linked_container.part(FourCC::OSG1).unwrap().data).unwrap(); + linked_outputs.sort_by_key(|e| (e.kind, e.index)); + for (i, e) in linked_outputs.iter().enumerate() { + let (name, index, width) = match e.kind { + 0 => ("TEXCOORD", i as u32, widths[i]), + 3 => ("SV_Position", 0, 4), + 6 => ("SV_ClipDistance", 0, 1), + _ => panic!("unexpected output semantic"), + }; + assert_eq!((e.name.as_str(), e.index, e.cols, e.comp), (name, index, width, 9)); + } + assert_eq!(linked_outputs.len(), 17); + if !legacy_layout { + let ps = Container::parse(&linked_ps.dxil).unwrap(); + let ps_inputs = signature(ps.part(FourCC::ISG1).unwrap().data).unwrap(); + assert!(ps_inputs.iter().all(|e| e.kind != 6)); + let scalar = ps_inputs.iter().find(|e| e.kind == 0 && e.index == 14).unwrap(); + assert_eq!(scalar.cols, 1); + assert_eq!(scalar.col, linked_outputs[14].col); + } // Written as the constant 1.0, the distance never clips: linked, // both stages leave it out (`lower::idle_clip`), and the vertex @@ -4223,12 +4329,13 @@ mod tests { }; assert!(!clip(&ms.dxil, FourCC::OSG1)); assert!(!clip(&ps.unwrap().dxil, FourCC::ISG1)); - assert_eq!(mesh_aligned_bytes(&ms.dxil), Some(30_208)); + // The two float3s leave one dword of alignment padding. + let idle_size = if legacy_layout { 30_208 } else { 30_720 }; + assert_eq!(mesh_aligned_bytes(&ms.dxil), Some(idle_size)); } #[cfg(windows)] { - let linked_ps = linked_ps.unwrap(); if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), ) { @@ -4288,21 +4395,46 @@ mod tests { ) }; let expected = [1.0, 0.5, 0.25, 1.0]; - // D3DMetal draws nothing with the standalone pair. - let full_ps = emit_pruned(&ps_in, Options::default(), None).unwrap(); - let standalone_drawn = draw(&standalone, &full_ps) - .map(|t| t.iter().filter(|t| **t == expected).count()); - eprintln!( - "{label}, scalar first {scalar_first}: {refused} bytes, \ - {standalone_drawn:?} of 256 texels drawn" - ); + if legacy_layout { + if super::host::under_wine() + && let Some(bytes) = over_limit_mesh_output_bytes(&standalone.dxil) + { + eprintln!( + "{label}, scalar first {scalar_first}: standalone {bytes} bytes exceeds Metal's output limit; draw skipped under Wine" + ); + } else { + let standalone_drawn = draw(&standalone, &full_ps) + .map(|t| t.iter().filter(|t| **t == expected).count()); + eprintln!( + "{label}, scalar first {scalar_first}: {refused} bytes, \ + {standalone_drawn:?} of 256 texels drawn" + ); + } + } let texels = draw(&linked_ms, &linked_ps) .unwrap_or_else(|e| panic!("{label}: linked mesh draw: {e}")); - assert!( - texels.iter().all(|t| *t == expected), - "{label}, scalar first {scalar_first}: unexpected pixel {:?}", - texels.first() - ); + assert_eq!(texels.len(), 256, "{label}, scalar first {scalar_first}"); + if legacy_layout { + assert!( + texels.iter().all(|t| *t == expected), + "{label}, scalar first {scalar_first}: unexpected pixel {:?}", + texels.first() + ); + } else { + for (i, pixel) in texels.iter().enumerate() { + let (x, y) = (i % 16, i / 16); + let axes = [(x as f32 + 0.5) / 8.0 - 1.0, 1.0 - (y as f32 + 0.5) / 8.0]; + let mut expect = [0.0f32; 4]; + for (k, &width) in widths.iter().enumerate() { + for (ch, channel) in expect.iter_mut().enumerate().take(width as usize) { + *channel += axes[(k + ch) % 2] + (k + 16 * ch + 1) as f32 / 64.0; + } + } + let drawn = pixel.iter().zip(expect).all(|(got, want)| (got - want).abs() < 1e-4); + assert_eq!(drawn, x >= 8, "{label}: ({x}, {y}) = {pixel:?}, shader colour {expect:?}"); + } + } + eprintln!("{label}, scalar first {scalar_first}: linked pixel oracle passed"); } } } diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 123a00b3f..5572f6922 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -42,6 +42,8 @@ pub struct Value(pub u32); #[derive(Debug, Clone, PartialEq, Eq)] pub struct Program { pub wave64: bool, + /// Allocated VGPR dwords per lane. + pub vgprs: u16, /// In code order, then copies made to give every loop one entry; block 0 /// is the entry. pub blocks: Vec, @@ -99,6 +101,8 @@ pub struct Phi { pub struct Inst { pub machine: Instruction, pub fields: Fields, + /// Upper bound supplied to this SSA build, before any VGPR-file truncation. + pub(crate) m0_max: Option, /// Every register dword read, with the value it holds. pub reads: Vec<(Reg, Value)>, /// Every register dword written, with the value it receives. @@ -110,6 +114,23 @@ impl Inst { self.machine.name().unwrap_or("") } + /// Whether every M0-relative operand has a proved endpoint inside the file. + pub(crate) fn relative_in_file(&self, vgprs: u16) -> bool { + let (source, destination) = relative_operands(self.name()); + if !source && !destination { + return true; + } + let (Some(bound), Fields::Valu(v)) = (self.m0_max, &self.fields) else { + return false; + }; + let fits = |operand: Option<&Operand>, indexed| { + let Some(Operand::Vector { reg, dwords }) = operand else { return false }; + let hi = if indexed { bound } else { 0 }; + u16::from(*reg) + u16::from(hi) + u16::from(*dwords) <= vgprs + }; + fits(v.src.first(), source) && fits(v.dst.as_ref(), destination) + } + /// The value `reg` holds when this instruction reads it. pub fn read(&self, reg: Reg) -> Option { self.reads.iter().find(|r| r.0 == reg).map(|r| r.1) @@ -264,6 +285,7 @@ pub fn build_bounded( blocks[b].insts.push(Inst { machine, fields, + m0_max: m0, reads, writes, }); @@ -276,6 +298,67 @@ pub fn build_bounded( what: "a branch to the program entry", }); } + assign_ssa(blocks, wave64, vgprs) +} + +/// Rebuild from the reachable machine instructions after dropping proven +/// branch edges. Node copies retain their identity until dead blocks are removed. +pub(crate) fn folded( + p: &Program, + jumps: &[(usize, usize)], +) -> Result, ShaderError> { + let mut blocks = p.blocks.clone(); + for &(b, to) in jumps { + blocks[b].insts.pop(); + blocks[b].exit = Exit::Jump(to); + } + let mut remap = vec![usize::MAX; blocks.len()]; + let mut order = reverse_postorder(&blocks); + // A proof includes the forward exit forced by a conditional backedge's + // cap. Keep the same counted edges on every surviving path. + let rank = |order: &[usize]| { + let mut ranks = vec![usize::MAX; blocks.len()]; + for (n, &b) in order.iter().enumerate() { + ranks[b] = n; + } + ranks + }; + let old = rank(&reverse_postorder(&p.blocks)); + let new = rank(&order); + if order.iter().any(|&b| { + blocks[b] + .exit + .successors() + .iter() + .any(|&t| (old[t] <= old[b]) != (new[t] <= new[b])) + }) { + return Ok(None); + } + order.sort_unstable(); + for (new, &old) in order.iter().enumerate() { + remap[old] = new; + } + let mut live = Vec::with_capacity(order.len()); + for (b, mut block) in blocks.into_iter().enumerate() { + if remap[b] == usize::MAX { + continue; + } + match &mut block.exit { + Exit::Jump(t) => *t = remap[*t], + Exit::Branch { taken, not_taken } => { + *taken = remap[*taken]; + *not_taken = remap[*not_taken]; + } + _ => {} + } + block.phis.clear(); + live.push(block); + } + link(&mut live); + assign_ssa(live, p.wave64, p.vgprs).map(Some) +} + +fn assign_ssa(mut blocks: Vec, wave64: bool, vgprs: u16) -> Result { split_irreducible(&mut blocks)?; let order = reverse_postorder(&blocks); @@ -338,6 +421,7 @@ pub fn build_bounded( remove_trivial_phis_steps(&mut blocks, values); Ok(Program { wave64, + vgprs, blocks, inputs, }) @@ -812,6 +896,16 @@ pub(crate) fn operand_reads(p: &Program, vgprs: u16, inst: &Inst) -> Vec { .map_or_else(Vec::new, |e| e.0.into_iter().map(|(reg, _)| reg).collect()) } +/// The source and destination operands indexed by M0. +pub(crate) fn relative_operands(name: &str) -> (bool, bool) { + match name { + "v_movrels_b32" => (true, false), + "v_movreld_b32" => (false, true), + "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true), + _ => (false, false), + } +} + /// Registers an instruction reads and writes, one per dword, or `None` if /// the IR drops it. fn effects( @@ -920,12 +1014,7 @@ fn effects( _ => return Err(unsupported()), }, Fields::Valu(v) => { - let (src_indexed, dst_indexed) = match name { - "v_movrels_b32" => (true, false), - "v_movreld_b32" => (false, true), - "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true), - _ => (false, false), - }; + let (src_indexed, dst_indexed) = relative_operands(name); // v[reg + M0] for any M0 that stays inside the program's VGPRs // (and below the proven bound). let indexed = |op: &Operand, out: &mut Vec<(Reg, Value)>| match *op { diff --git a/crates/victory-shader/src/range.rs b/crates/victory-shader/src/range.rs index f26091ecf..537ef3e07 100644 --- a/crates/victory-shader/src/range.rs +++ b/crates/victory-shader/src/range.rs @@ -7,11 +7,14 @@ //! `v_mov_b32`, or an unguarded `v_readfirstlane_b32`: the first active //! lane is then a lane that runs there) of a bounded value; `min`, `and` or //! `med3` (unsigned) with a bounded operand; a sum of bounded values that -//! cannot wrap; or a phi whose every incoming value is bounded on its edge, +//! cannot wrap; a plain dword selection with both value arms bounded; or a +//! phi whose every incoming value is bounded on its edge, //! where an unsigned compare of that value with a bounded one (`v_cmp*`, //! `s_cmp*`: `lt`, `le`, `eq` true or `gt`, `ge` false) that every lane //! taking the edge has passed also bounds it: a loop counter against a -//! bounded limit. A VGPR write under a guard keeps the old value in the +//! bounded limit. A scalar counter with a constant seed and positive fixed +//! stride is bounded if its latch exits at an exactly reachable equality. +//! A VGPR write under a guard keeps the old value in the //! other lanes, so it is bounded only if both are. Anything else (memory, //! signed compares, what a relative move writes) is unbounded, and a move //! with an unbounded index keeps today's range. @@ -81,10 +84,7 @@ pub fn build( } fn relative(inst: &Inst) -> bool { - matches!( - inst.name(), - "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" - ) + ir::relative_operands(inst.name()) != (false, false) } /// The largest M0 each relative move can see, by instruction offset @@ -150,9 +150,14 @@ impl Ranges<'_> { let h = match self.defs.get(&v).copied() { Some(Def::Phi(b, i)) => { let block = &p.blocks[b]; + let recurrence = self.recurrence_hi(b, i); let mut h = 0; for (k, &pred) in block.preds.iter().enumerate() { - h = h.max(self.edge_hi(block.phis[i].args[k], pred, b)); + let arg = block.phis[i].args[k]; + let bound = recurrence + .filter(|&(update, _)| update == arg) + .map_or(u32::MAX, |(_, h)| h); + h = h.max(self.edge_hi(arg, pred, b, bound)); } h } @@ -181,8 +186,80 @@ impl Ranges<'_> { h } + /// A two-input scalar phi seeded by a constant and updated only on a + /// backedge testing that exact sum for inequality with a constant limit. + fn recurrence_hi(&self, header: usize, i: usize) -> Option<(Value, u32)> { + let block = &self.p.blocks[header]; + let phi = &block.phis[i]; + let [a, b] = phi.args[..] else { return None }; + if !matches!(phi.reg, Reg::S(0..=105)) { + return None; + } + let seed = |v| { + let (mov, src) = self.scalar_def(v)?; + match (mov.name(), src) { + ("s_mov_b32", [op]) => unsigned_immediate(op), + _ => None, + } + }; + let (start, update, pred) = match (seed(a), seed(b)) { + (Some(n), None) => (n, b, block.preds[1]), + (None, Some(n)) => (n, a, block.preds[0]), + _ => return None, + }; + let latch = &self.p.blocks[pred]; + let ir::Exit::Branch { taken, not_taken } = latch.exit else { + return None; + }; + let branch = latch.insts.last()?; + if branch.name() != "s_cbranch_scc0" || taken != header || not_taken == header { + return None; + } + let scc = branch.read(Reg::Scc)?; + let Def::Inst(cmp_block, ci) = *self.defs.get(&scc)? else { + return None; + }; + let cmp = &self.p.blocks[cmp_block].insts[ci]; + if cmp_block != pred || cmp.name() != "s_cmp_eq_u32" { + return None; + } + let Fields::Sop { src, .. } = &cmp.fields else { + return None; + }; + let (compared, limit) = value_and_constant(cmp, src)?; + if compared != update || limit <= start { + return None; + } + let mut v = update; + let mut stride = 0u32; + while v != phi.value { + let (add, src) = self.scalar_def(v)?; + if !matches!(add.name(), "s_add_i32" | "s_add_u32") { + return None; + } + let (prev, step) = value_and_constant(add, src)?; + stride = stride.checked_add(step)?; + v = prev; + } + // Every partial sum is nonnegative and the last one fits at the limit. + (stride != 0 && (limit - start).is_multiple_of(stride)).then(|| (update, limit - stride)) + } + + /// Inputs of an ordinary scalar dword definition, excluding its SCC result. + fn scalar_def(&self, v: Value) -> Option<(&Inst, &[Operand])> { + let Def::Inst(b, i) = *self.defs.get(&v)? else { + return None; + }; + let inst = &self.p.blocks[b].insts[i]; + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + let reg = dst(inst)?; + (matches!(reg, Reg::S(0..=105)) && inst.write(reg) == Some(v)).then_some((inst, src)) + } + /// The largest value `a` has in lanes going from `pred` to `to`. - fn edge_hi(&mut self, a: Value, pred: usize, to: usize) -> u32 { + fn edge_hi(&mut self, a: Value, pred: usize, to: usize, mut best: u32) -> u32 { let mut facts = vec![(self.st.reach[pred], true)]; if let LaneExit::Branch { when, @@ -198,7 +275,6 @@ impl Ranges<'_> { .flat_map(|&(f, _)| self.st.bools.support(f)) .collect(); atoms.dedup(); - let mut best = u32::MAX; for atom in atoms { let (Atom::Lane(c) | Atom::Uniform(c)) = atom else { continue; @@ -274,6 +350,9 @@ impl Ranges<'_> { Fields::Sop { src, .. } => src, _ => return u32::MAX, }; + if let ("v_cndmask_b32", [x, y, _mask]) = (inst.name(), &src[..]) { + return self.operand_hi(inst, x).max(self.operand_hi(inst, y)); + } let s: Vec = src.iter().map(|o| self.operand_hi(inst, o)).collect(); match (inst.name(), &s[..]) { ("s_mov_b32" | "v_mov_b32" | "v_readfirstlane_b32", &[x]) => x, @@ -288,11 +367,24 @@ impl Ranges<'_> { } fn operand_hi(&mut self, inst: &Inst, op: &Operand) -> u32 { - match *op { - Operand::Const(c @ 128..=192) => u32::from(c - 128), - Operand::Literal(x) => x, - _ => value(inst, op).map_or(u32::MAX, |v| self.hi(v)), - } + unsigned_immediate(op).unwrap_or_else(|| value(inst, op).map_or(u32::MAX, |v| self.hi(v))) + } +} + +fn unsigned_immediate(op: &Operand) -> Option { + match *op { + Operand::Const(c @ 128..=192) => Some(u32::from(c - 128)), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +fn value_and_constant(inst: &Inst, src: &[Operand]) -> Option<(Value, u32)> { + let [x, y] = src else { return None }; + if let Some(c) = unsigned_immediate(y) { + Some((value(inst, x)?, c)) + } else { + Some((value(inst, y)?, unsigned_immediate(x)?)) } } @@ -300,7 +392,10 @@ impl Ranges<'_> { fn value(inst: &Inst, op: &Operand) -> Option { match *op { Operand::Vector { reg, dwords: 1 } => inst.read(Reg::V(reg)), - Operand::Scalar { code, dwords: 1 } if code != EXEC => inst.read(Reg::S(code)), + // Ordinary shaders cannot write trap temporaries; their nominal SSA writes supply no bound. + Operand::Scalar { code, dwords: 1 } if !matches!(code, 108..=123 | EXEC) => { + inst.read(Reg::S(code)) + } _ => None, } } @@ -322,7 +417,7 @@ fn dst(inst: &Inst) -> Option { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; const S_ENDPGM: u32 = 0xBF81_0000; @@ -355,6 +450,182 @@ mod tests { .collect() } + fn wave64_program(words: &[u32]) -> (Program, Structured) { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let (p, st) = build(&code, true, 32).unwrap(); + (p, st.unwrap()) + } + + pub(crate) fn equality_words() -> Vec { + let mut w: Vec<_> = (26..32).map(|r| vop1(1, r, 128 + r)).collect(); + w.push(0xbe80_0380); // s0 = 0 + for dst in 20..23 { + w.extend([0x8100_8100, M0_S0, vop1(0x43, dst, V + 25)]); // ++s0, read v[25+s0] + } + w.extend([0xbf06_8600, 0xbf84_fff5, S_ENDPGM]); // repeat unless s0 == 6 + w + } + + #[test] + fn recurrence_links_and_selector_arms_respect_scalar_register_roles() { + for (code, ordinary, bound) in [ + (105, true, 2), + (108, false, u32::MAX), + (123, false, u32::MAX), + (M0, false, 2), + ] { + let (p, st) = wave64_program(&[ + 0x8100_8181 | u32::from(code) << 16, // scalar result of 1 + 1 + vop1(1, 3, 128), // v3 = 0 + vop2(1, 4, u32::from(code), 3), // select scalar or zero + 0xbe83_0300 | u32::from(code), // copy the scalar into s3 + vop2(1, 5, 3, 3), // select copied scalar or zero + S_ENDPGM, + ]); + let insts = &p.blocks[0].insts; + let scalar = insts[0].write(Reg::S(code)).unwrap(); + let direct = insts[2].write(Reg::V(4)).unwrap(); + let copied = insts[4].write(Reg::V(5)).unwrap(); + let mut ranges = Ranges { + p: &p, + st: &st, + defs: insts + .iter() + .enumerate() + .flat_map(|(i, inst)| { + inst.writes.iter().map(move |&(_, v)| (v, Def::Inst(0, i))) + }) + .collect(), + memo: HashMap::new(), + busy: HashSet::new(), + }; + assert_eq!( + ( + ranges.scalar_def(scalar).is_some(), + ranges.hi(direct), + ranges.hi(copied) + ), + (ordinary, bound, bound), + "scalar register {code}" + ); + } + } + + #[test] + fn equality_latch_bounds_each_increment() { + let (p, _) = wave64_program(&equality_words()); + let moves: Vec<_> = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| relative(i)) + .collect(); + // Trips read v26..v28 then v29..v31. The last read reaches the final register. + assert_eq!( + moves.iter().map(|i| i.m0_max).collect::>(), + [Some(4), Some(5), Some(6)] + ); + assert!(moves.iter().all(|i| i.relative_in_file(p.vgprs))); + } + + #[test] + fn unchecked_latches_do_not_prove_in_file_accesses() { + let mut cases = Vec::new(); + for (case, word, replacement) in [ + ("skipped limit", 16, 0xbf06_8500), // trip advances by 3, limit 5 + ("variable step", 7, 0x8100_0100), // add s1 + ("unrelated compare", 16, 0xbf06_8601), // compare s1 + ("continue on equal", 17, 0xbf85_fff5), + ("unknown entry", 6, 0xbe80_0301), // seed from input s1 + ] { + let mut w = equality_words(); + w[word] = replacement; + cases.push((case, w)); + } + let mut w = equality_words(); + for n in [7, 10, 13] { + w[n] = 0x8100_8000; // add zero + } + cases.push(("zero stride", w)); + let mut w = equality_words(); + w.splice(6..7, [0xbe80_03ff, u32::MAX - 2]); // first trip wraps to zero + cases.push(("wrap", w)); + let mut w = equality_words(); + w.splice(7..8, [0x8100_ff00, u32::MAX]); // the sum of three steps exceeds u32::MAX + w[18] = 0xbf84_fff4; + cases.push(("overflowing stride", w)); + let mut w = equality_words(); + w.insert(13, 0xbe81_0300); // save s0 before its last increment + w[17] = 0xbf06_8601; // test that previous version instead of the update + w[18] = 0xbf84_fff4; + cases.push(("stale counter", w)); + let mut w = equality_words(); + w.splice(16..16, [0xbf06_8001, 0xbf85_fff5]); // if s1 == 0, bypass the latch + w[19] = 0xbf84_fff3; + cases.push(("second unchecked incoming edge", w)); + for (case, words) in cases { + let (p, _) = wave64_program(&words); + let moves: Vec<_> = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| relative(i)) + .collect(); + assert_eq!(moves.len(), 3, "{case}"); + assert!(moves.iter().all(|i| !i.relative_in_file(p.vgprs)), "{case}"); + } + } + + pub(crate) const SELECT_TWO_OR_ELEVEN: u32 = vop2(1, 2, 130, 3); + + pub(crate) fn selection_words(select: u32) -> Vec { + let mut w: Vec<_> = (20..32).map(|r| vop1(1, r, 128 + r)).collect(); + w.extend([ + vop1(1, 3, 139), + vop2(0x1b, 1, 129, 0), + 0x7d84_0280, // VCC = (tid & 1) == 0 + select, + vop1(2, 20, V + 2), + 0x7d84_0414, + 0xbe8e_246a, + 0xbefc_0314, // select first key + vop1(0x43, 18, V + 20), + 0x89fe_0e7e, + 0xbf89_fff9, + S_ENDPGM, + ]); + w + } + + #[test] + fn conditional_selection_bounds_both_waterfall_arms() { + for (select, bound) in [ + (vop2(0x1b, 2, 139, 0), Some(11)), // AND control + (SELECT_TWO_OR_ELEVEN, Some(11)), // select 2 or 11 + (vop2(1, 2, 140, 3), Some(12)), // select 12 or 11, past the file + (vop2(1, 2, 130, 0), None), // one unknown arm + ] { + let w = selection_words(select); + let (p, st) = wave64_program(&w); + let mov = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| relative(i)) + .unwrap(); + assert_eq!(mov.m0_max, bound); + let tracker = crate::resource::track(&p, &[], crate::HwStage::Cs, Some(&st)); + if bound == Some(11) { + assert!(mov.relative_in_file(p.vgprs)); + let facts = tracker.unwrap().waterfall; + assert_eq!((facts.reads.len(), facts.compares.len()), (1, 1)); + } else { + assert!(!mov.relative_in_file(p.vgprs)); + assert!(tracker.is_err()); + } + } + } + #[test] fn a_bound_must_survive_what_the_bounded_moves_write() { // v1 = v0 & 3, vN = v0 & 1; v[2 + v1] = v7; then v[8 + vN] is read. diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index f7ac06711..1b9da6bfc 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -12,6 +12,8 @@ //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. +mod indexed; + use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; @@ -132,13 +134,9 @@ pub struct Resources { pub waterfall: Waterfall, } -/// Waterfall loops over descriptors that differ between lanes: each pass -/// reads the first active lane's descriptor with `v_readfirstlane_b32`, -/// compares it with every lane's own (`v_cmp_eq`), and runs the access with -/// the lanes that match. Their accesses take each lane's own descriptor -/// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are -/// each lane's own too: the compares hold in every lane and one pass serves -/// all lanes. +/// Equality waterfalls that can serve every participating lane in one pass. +/// Each lane uses its own descriptor words ([`Source::Fetched`], [`Source::Lanes`]) +/// or integer VGPR index, so the key comparison is true for that lane. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Waterfall { /// The compares, true in every lane. @@ -297,6 +295,9 @@ pub fn track( out.waterfall.loads.extend(loads); } } + if stage == HwStage::Cs && p.wave64 && t.lanes.is_some_and(|st| !st.literal) { + t.indexed_waterfalls(&mut out.waterfall)?; + } Ok(out) } diff --git a/crates/victory-shader/src/resource/indexed.rs b/crates/victory-shader/src/resource/indexed.rs new file mode 100644 index 000000000..801dab500 --- /dev/null +++ b/crates/victory-shader/src/resource/indexed.rs @@ -0,0 +1,180 @@ +//! Integer equality waterfalls that perform one independent register move per lane. + +use super::{Tracer, Waterfall}; +use crate::ShaderError; +use crate::gfx10::{Fields, Operand, Valu}; +use crate::ir::{EXEC, Inst, M0, Reg, VCC}; + +impl Tracer<'_> { + pub(super) fn indexed_waterfalls(&self, out: &mut Waterfall) -> Result<(), ShaderError> { + let start = out.reads.len(); + let mut escapes = None; + for (b, block) in self.p.blocks.iter().enumerate() { + let Some(proof) = self.index_waterfall(b) else { + continue; + }; + // Only EXEC may return to this header through its own backedge. + // Every other scalar result (including both SCC writes) is private. + let external = escapes.get_or_insert_with(|| self.escaping_scalar_values()); + if block + .insts + .iter() + .flat_map(|i| &i.writes) + .any(|&(r, v)| !matches!(r, Reg::V(_)) && external[v.0 as usize]) + { + continue; + } + out.reads.extend(proof.reads); + out.compares.extend(proof.compares); + } + // A newly supported waterfall can expose a separate relative move to lowering. + if out.reads.len() != start + && let Some(inst) = self + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| !i.relative_in_file(self.p.vgprs)) + { + return Err(ShaderError::Unsupported { + offset: inst.machine.offset, + what: "an indexed-waterfall program with a relative VGPR operand not proved inside its register file", + }); + } + Ok(()) + } + + fn index_waterfall(&self, b: usize) -> Option { + let [first, cmp, select, copy, access, retry, _branch] = &self.p.blocks[b].insts[..] else { + return None; + }; + if first.name() != "v_readfirstlane_b32" + || cmp.name() != "v_cmp_eq_u32" + || select.name() != "s_and_saveexec_b64" + || copy.name() != "s_mov_b32" + || retry.name() != "s_xor_b64" + { + return None; + } + let (index, key) = plain_unary(first)?; + let index_reg = vector(index)?; + let key_reg = scalar(key, 1)?; + let value = first.write(Reg::S(key_reg))?; + let compare = plain(cmp)?; + let mask = compare.dst?; + let (saved, mask_src) = sop(select)?; + let exec = Operand::Scalar { + code: EXEC, + dwords: 2, + }; + let m0 = Operand::Scalar { + code: M0, + dwords: 1, + }; + if key_reg >= VCC + || scalar(mask, 2)? > VCC + || scalar(saved, 2)? > VCC + || compare.src != [key, index] + || cmp.read(Reg::S(key_reg))? != value + || cmp.read(Reg::V(index_reg))? != first.read(Reg::V(index_reg))? + || mask_src != [mask] + || sop(copy)? != (m0, &[key][..]) + || copy.read(Reg::S(key_reg))? != value + || sop(retry)? != (exec, &[exec, saved][..]) + || access.read(Reg::S(M0))? != copy.write(Reg::S(M0))? + || !self.stable_move(access, index_reg) + { + return None; + } + // Exact select/retry makes each lane run once, at its own unchanged index. + // The only effect is on that lane's VGPRs, so visit order is unobservable. + self.waterfall(b, &[4], &[value]).ok() + } + + fn stable_move(&self, inst: &Inst, index: u8) -> bool { + let Some((src, dst)) = plain_unary(inst).and_then(|(s, d)| Some((vector(s)?, vector(d)?))) + else { + return false; + }; + matches!(inst.name(), "v_movrels_b32" | "v_movreld_b32") + && [src, dst, index] + .iter() + .all(|&r| u16::from(r) < self.p.vgprs) + && inst.write(Reg::V(index)).is_none() + } + + fn escaping_scalar_values(&self) -> Vec { + let mut external = vec![false; self.defs.len()]; + for (b, block) in self.p.blocks.iter().enumerate() { + for &(reg, v) in block.insts.iter().flat_map(|i| &i.reads) { + if !matches!(reg, Reg::V(_)) && self.defs[v.0 as usize].is_some_and(|(d, _)| d != b) + { + external[v.0 as usize] = true; + } + } + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) { + continue; + } + for (&v, &pred) in phi.args.iter().zip(&block.preds) { + if !(pred == b + && matches!(phi.reg, Reg::S(126 | 127)) + && self.defs[v.0 as usize].is_some_and(|(d, _)| d == b)) + { + external[v.0 as usize] = true; + } + } + } + } + external + } +} + +fn scalar(op: Operand, width: u8) -> Option { + match op { + Operand::Scalar { code, dwords } if dwords == width => Some(code), + _ => None, + } +} + +fn vector(op: Operand) -> Option { + match op { + Operand::Vector { reg, dwords: 1 } => Some(reg), + _ => None, + } +} + +fn sop(inst: &Inst) -> Option<(Operand, &[Operand])> { + let Fields::Sop { + dst: Some(dst), + src, + .. + } = &inst.fields + else { + return None; + }; + Some((*dst, src)) +} + +fn plain(inst: &Inst) -> Option<&Valu> { + let Fields::Valu(f) = &inst.fields else { + return None; + }; + (f.abs == 0 + && f.neg == 0 + && f.neg_hi == 0 + && f.opsel == 0 + && f.opsel_hi == 0 + && !f.clamp + && f.omod == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && f.carry.is_none()) + .then_some(f) +} + +fn plain_unary(inst: &Inst) -> Option<(Operand, Operand)> { + let f = plain(inst)?; + let [src] = f.src[..] else { return None }; + Some((src, f.dst?)) +} diff --git a/docs/backend.md b/docs/backend.md index c951d7cde..bd4422391 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -23,3 +23,5 @@ The step 0 probe for that work, which needs no game files, is in issue #221. 6. **Choosing the host** with a switch. D3D12 stays the default. The Metal backend itself starts after step 2. It is first useful for title buffers, which is where the copies are. + +The [Direct Metal implementation plan](superpowers/plans/2026-11-27-direct-metal.md) places shared shader and tooling prerequisites before these backend milestones, with separate checks for memory, compute, rendering, and game behavior. Its [design](superpowers/specs/2026-11-27-direct-metal-design.md) records the scope and acceptance criteria. diff --git a/docs/macos.md b/docs/macos.md index 5a45140f5..04ef497c9 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -35,7 +35,7 @@ WINE="/Applications/Game Porting Toolkit.app/Contents/Resources/wine/bin/wine64" ## CrossOver Wine with D3DMetal, 24 November 2026 -`tools/macos/build-crossover-wine.sh` builds CodeWeavers' CrossOver 26.3 Wine (Wine 11.0) from its published source into `target/wine-cx`, using x86_64 FreeType and GnuTLS from `DEPS`. Copy the `redist/lib` folder of Apple's "Evaluation environment for Windows games" over `target/wine-cx/lib`, and run the tests with this command. +`tools/macos/build-crossover-wine.sh` builds CodeWeavers' CrossOver 26.3 Wine (Wine 11.0) from its published source into `target/wine-cx`, using x86_64 FreeType and GnuTLS from `DEPS`. Apply a qualifying Game Porting Toolkit using the setup command below, then run the tests. ```sh WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" tools/macos/test-wine.sh --workspace --no-fail-fast @@ -49,7 +49,7 @@ On an M4 with D3DMetal 4.0 beta 3 this gives 260 passed, 4 failed and 4 ignored. After these fixes the whole suite passed under CrossOver Wine with D3DMetal on an M4: 343 passed, 0 failed and 4 ignored. After the merge of 25 November 2026 and the fixes below it gives 481 passed, 0 failed and 7 ignored. -A Wine built with a macOS 27 SDK used to crash on macOS 26 at its first start, in `server_pipe`. Configure found `pipe2`, which only macOS 27 has (MarshallStunt, #50). Of the 33 functions Wine's configure checks for, it is the only one that macOS 27.0.1 exports and the macOS 26.5 SDK lacks. `build-crossover-wine.sh` now tells configure that `pipe2` is missing, and Wine falls back to `pipe` and `fcntl`. A Wine that crashes this way has to be built again: remove `target/crossover/build` and `target/wine-cx`, then run `./setup.sh`. +A Wine built with a macOS 27 SDK used to crash on macOS 26 at its first start, in `server_pipe`. Configure found `pipe2`, which only macOS 27 has (MarshallStunt, #50). Of the 33 functions Wine's configure checks for, it is the only one that macOS 27.0.1 exports and the macOS 26.5 SDK lacks. `build-crossover-wine.sh` now tells configure that `pipe2` is missing, and Wine falls back to `pipe` and `fcntl`. For a Wine that crashes this way, move `target/crossover/build` aside and follow the full rebuild steps below. ## Run-time HLSL and textures under Wine and D3DMetal @@ -118,6 +118,17 @@ Later work replaces the Windows host underneath the title. That needs a Rosetta Run `./setup.sh` from the top of the repository. It checks the Mac, installs the Homebrew tools, builds checksum-verified x86_64 GMP, Nettle, GnuTLS, FreeType and SDL2, builds CrossOver Wine, adds D3DMetal from the Game Porting Toolkit in Downloads, and builds VIctory. The only manual step is downloading the toolkit from Apple. A clean run on an M4 on 24 November 2026 finished without help, and the full suite then passed (343 passed, 0 failed). +The reference runtime requires **D3DMetal 4.0 beta 3 (`4.0b3`) or newer**. Setup and `tools/macos/victory.sh` read the installed framework version from its `Resources/Info.plist`. On a fresh installation, setup uses the newest Game Porting Toolkit disk image in Downloads. To refresh an existing installation, quit VIctory and Wine, sign in to [Apple Developer Downloads](https://developer.apple.com/download/all/?q=game%20porting%20toolkit), and select a qualifying image explicitly. + +```sh +GPTK_DMG="$HOME/Downloads/Game_Porting_Toolkit_4.0_beta_3.dmg" ./setup.sh +tools/macos/victory.sh gpu-check +``` + +Setup resolves a relative `GPTK_DMG` path from the directory where you invoke it. Setup validates the selected disk image and stages its redistributables in Wine's own directory. If extraction, validation, copying, or activation fails, setup keeps or restores the previous library directory. The toolkit refresh leaves saves and game caches alone. Rerunning setup with a supported toolkit, current Wine build and no `GPTK_DMG` reuses both. + +If a refresh was interrupted, first make sure setup has stopped. In `target/wine-cx`, if `lib` is missing and `.gptk-refresh/previous-lib` exists, restore it with `mv .gptk-refresh/previous-lib lib`. Once `lib` is in place, remove the leftover `.gptk-refresh` directory before retrying. + ## CrossOver's Wine is patched `tools/macos/build-crossover-wine.sh` applies the patches in `tools/macos/patches` to CrossOver's source. One of them, `wineserver-view-tree.patch`, is UwUCammie's from fxceless/victory-fork#184 (see #155 and WineHQ bug 60868). Wine's server keeps a process's memory views in a list and walks the list on every map and unmap request. The patch also keeps them in a red-black tree by base address, so those requests take O(log n). The protocol is unchanged. @@ -126,7 +137,9 @@ On an M5 Pro with 20,000 live views, the `wine_views` benchmark from #159 took 1 The other, `ntdll-skip-host-mappings.patch`, is for thread creation. To find room for a new thread's stack, Wine's `try_map_free_area` tries an address and, if something is mapped there already, moves on by one 64 KiB granule. Memory that the host maps outside Wine, such as Metal's, looks free to Wine, so the search stepped through gigabytes of it one granule at a time, with `virtual_mutex` held. Every page fault, `VirtualQuery`, `VirtualProtect` and `GetWriteWatch` of the other threads waits for that lock. On an M3 Max with the Series S profile (`--console series-s`), each thread the title made took about 2.5 s, and the intro ran at 0.1 fps with frames of 7.6 s (#50, runs 65 to 68). Stack dumps showed one thread in `NtCreateThreadEx` → `virtual_alloc_thread_stack` → `map_view` → `try_map_free_area` → `mach_vm_map` in all twelve dumps, and the others waiting for `virtual_mutex`. With the patch, a failed address asks `mach_vm_region` for the mapping in the way and moves past it. Every address it skips overlaps that mapping, so no free area is missed. The same intro then ran at 20 to 30 fps, and the longest wait for the lock fell from 2.5 to 7 s to 27 ms (run 69). World frames with the Series X profile were unchanged (run 70): the title does not make threads there at that rate. -`./setup.sh` compares the selected CrossOver release and patch stamp with `target/wine-cx/.victory-patches`. A release change or an old stamp without a release triggers a full install and reapplies D3DMetal. Within the same release, changes limited to `server/` and `dlls/ntdll/unix/` rebuild just the server, `ntdll.so` and `winebus.so`, preserving the existing D3DMetal overlay. Patches outside those paths trigger a full install. +`./setup.sh` compares the selected CrossOver release and patch stamp with `target/wine-cx/.victory-patches`. Within the same release, changes limited to `server/` and `dlls/ntdll/unix/` rebuild just the server, `ntdll.so` and `winebus.so`, preserving the D3DMetal overlay. + +A release change, missing metadata or patches outside those paths require a full rebuild. Setup stops before changing the installed Wine or toolkit. Once you have a qualifying toolkit disk image, move `target/wine-cx` to a backup and run the `GPTK_DMG` setup command above. Keep the backup until `gpu-check` passes. ## Game controllers @@ -361,15 +374,27 @@ None of these changes the default, except `VICTORY_OUTPUT`, which sets the title | `VICTORY_SILENT_AUDIO=1` | Routes title playback to VIctory's silent spatial-audio endpoint even when the host has an active output device, keeping the title's playback clock running during muted or automated runs. (Hosts without an active render device use the silent endpoint automatically.) | | `VICTORY_UAV_SIZE_LEVEL0=[,]` | Makes a size query on a writable image ask for level 0 in the listed programs (16-digit shader hashes, as the log prints them). D3DMetal answers the undefined level DXC writes with a size of 0, so the shadow min/max program `07f451a14b13fecb` writes one flat value and sun shadows get 16x16-tile edges; `VICTORY_UAV_SIZE_LEVEL0=07f451a14b13fecb` smooths them. `=1` does it in every program, which also gave speckles on skin, so the list is the one to try. | -## An ambient light in place of ray-traced indirect light +## Ray tracing and indirect light + +By default VIctory suppresses dispatches from the title's BVH builder and skips `CS_RaytracingResolve_*` dispatches. Probe activation and other tracing shaders can still run. VIctory estimates indirect diffuse light from the frame and clamps reflections to half the local estimated light. + +For ray-tracing reference and acceptance runs, leave `VICTORY_AMBIENT` and `VICTORY_RAY_SKIP` unset and opt in to the builder when launching. + +```sh +VICTORY_BVH_BUILDER=1 tools/macos/victory.sh run --execute "/path/to/game.exe" +``` + +Only the exact value `1` opts in. The builder runs in frames where all its host pipelines are ready. With the builder opted in, an unset `VICTORY_AMBIENT` leaves the game's lighting in place and an unset `VICTORY_RAY_SKIP` skips no ray passes. Explicit values override these defaults in either mode. An empty value, `0` or `off` disables the corresponding fallback. For `VICTORY_RAY_SKIP`, `resolve` selects the reflection-hit resolves, `activate` selects probe activation and `1` selects both. These skips apply only in frames where the builder is held back. + +### Constant ambient light -`VICTORY_AMBIENT=1` turns on a stand-in from Belobug's fork (`victory-gpu/src/ambient.rs`). It is off by default, and off it changes nothing. The game lights what the sun does not reach with probes it fills by tracing rays. Right after the game's program that resolves those probes (`CS_ScreenProbes_TemporalResolve_*`), a compute pass of VIctory's own replaces that program's output with an ambient light: the same everywhere in a frame, darker in creases and under objects (worked out from the depth image). By default its level and colour follow the sky dome the game draws for its reflections. After the game's last reflection pass (`CS_UpdateHistory`), a second pass of the same shader holds reflections to half of that light. +`VICTORY_AMBIENT=1` turns on a stand-in from Belobug's fork (`victory-gpu/src/ambient.rs`). The game lights what the sun does not reach with probes it fills by tracing rays. Right after the game's program that resolves those probes (`CS_ScreenProbes_TemporalResolve_*`), a compute pass of VIctory's own replaces that program's output with an ambient light: the same everywhere in a frame, darker in creases and under objects (worked out from the depth image). By default its level and colour follow the sky dome the game draws for its reflections. After the game's last reflection pass (`CS_UpdateHistory`), a second pass of the same shader holds reflections to half of that light. VIctory logs one line at start when the switch is on, one line for each program it found by name, and one line the first time each part runs (`ambient light: the first image it writes`, `ambient light follows the sky dome`, `reflections held to the ambient light`). `no ambient light: ...` says why a pass did not run. | Variable | Effect | | --- | --- | -| `VICTORY_AMBIENT=1` | Turns the stand-in on. Unset, empty, `0` and `off` leave the game's own output. | +| `VICTORY_AMBIENT=1` | Selects the constant stand-in. Empty, `0` and `off` leave the game's own output. | | `VICTORY_AMBIENT_SKY=off` or `gain,least,power` | `off` keeps a constant level. Otherwise the level is `gain * mean^power + least` of the sky dome's mean (0.36, 0.05, 0.4). | | `VICTORY_AMBIENT_LEVEL=` | The constant level (0.6), used while the light does not follow the sky. | | `VICTORY_AMBIENT_TINT=r,g,b` | The constant light's colour (1, 0.98, 0.94). | @@ -383,7 +408,7 @@ The pass is compiled at run time, so under Wine its shader keeps to what Wine's ### The estimate: `VICTORY_AMBIENT=estimate` -`VICTORY_AMBIENT=estimate` (or `estimate:`) turns on another stand-in in the same place, from avatarmanz's fork (`victory-gpu/src/ambient_estimate.rs`). Every other value of the variable means what it meant before, and the constant stand-in above is unchanged. The constant one gives the whole picture one light. The estimate works the light out from the frame, so it follows the hour, the room and its lamps by itself: +`VICTORY_AMBIENT=estimate` (or `estimate:`) selects the stand-in from avatarmanz's fork (`victory-gpu/src/ambient_estimate.rs`). An unset `VICTORY_AMBIENT` selects the estimate when the BVH builder is disabled. The estimate works the light out from the frame, so it follows the hour, the room and its lamps by itself: - The game keeps the light its visible surfaces send out, for its own screen traces (`CS_CacheScreenSpaceRadiance`, an R11G11B10 image of half the picture's size). Right after that program, in the same host list, VIctory averages the image in 64x36 cells of a buffer of its own, and moves a slow mean of all cells toward this frame's. - Right after the program that resolves the screen probes, in the next frame, VIctory places the cells in space by the depth image the resolve reads. At 160x90 points of the picture it sums the cells' light, each cell weighted by the share of the point's surroundings it covers, as a mean and a direction per colour. Every texel of the resolve's light image then gets what lies between the four points around it (those at its own depth first), turned by its normal, a fifth of it the slow mean, darker in creases. diff --git a/docs/superpowers/plans/2026-11-27-direct-metal.md b/docs/superpowers/plans/2026-11-27-direct-metal.md new file mode 100644 index 000000000..89ad167c6 --- /dev/null +++ b/docs/superpowers/plans/2026-11-27-direct-metal.md @@ -0,0 +1,187 @@ +# Direct Metal Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement the prerequisite tasks in order. Use superpowers:subagent-driven-development only if delegated execution is subsequently selected. Steps use checkbox syntax for tracking. + +**Goal:** Deliver the approved direct Metal GPU path after fixing its shared correctness and tooling prerequisites. + +**Architecture:** Retain the loader, HLE runtime, Rosetta, and Xbox-to-DXIL translator. Introduce direct Metal through a Wine Unix bridge, starting with shared memory and compute. Keep D3DMetal available for comparison throughout. + +**Tech Stack:** Existing Rust workspace, CrossOver Wine, Rosetta, Objective-C/C Metal bridge where required, Apple Metal Shader Converter, synthetic native and Wine GPU tests. + +**Spec:** [Direct Metal with prerequisites first](../specs/2026-11-27-direct-metal-design.md). + +## Global Constraints + +- Retain the current loader, console runtime, and Rosetta CPU execution. +- Keep D3D12/D3DMetal available as the reference backend throughout migration. +- Keep all game files, derived shaders, dumps, captures, and Apple redistributables outside the repository. +- Commit only original source, synthetic tests, build identities, and aggregate measurements allowed by `docs/asset-policy.md`. +- Use the existing Rust workspace and local Apple/Wine toolchain; add dependencies only when a required capability is unavailable locally. +- The existing macOS baseline is Apple Silicon and macOS 15 or newer. Report any higher requirement discovered for the selected Metal Shader Converter explicitly. +- Use D3DMetal 4.0 beta 3 or newer for the comparison baseline; never replace a working runtime with an unverified or partial installation. +- Keep backend selection explicit during development; an explicitly requested Metal backend must report unavailable capabilities instead of silently switching to D3DMetal. +- Missing graphics operations must fail visibly or remain counted as unsupported; they must not become successful no-ops. +- Preserve saves and original game files. Use isolated external cache/data directories for controlled game checks and record the backend and shader options with each measurement. + +## Review Focus + +1. Divergent lanes, upper-half-only activity, partial groups, and early exits must preserve first-active-lane behavior without deadlocking: Task 3. +2. Diagnostics, runtime overrides, and cache/library identities must choose compatible shader semantics: Task 1. +3. Missing, older, malformed, or partially copied toolkit installations must leave the previous runtime intact: Task 2. +4. Aliased or remapped memory still referenced by a GPU submission must remain valid and coherent: Milestone B's required tests. +5. Compiler failures, device limits, unsupported stages, and GPU timeouts must remain observable and must not be reported as correct rendering: Tasks 3–4 and Milestones C–E. + +## Delivery structure + +Tasks 1–4 are the first work package. Later milestones define the approved destination, dependencies, owned files, and acceptance gates. Write their executable task plans after the preceding hardware gate establishes the required interfaces; do not invent a bridge ABI or promise timings before that evidence exists. This is sequencing, not a reduction of the Direct Metal goal. + +Execute inline by default, preserving a small reviewable change per semantic fix. A commit is an integration boundary after its checks pass; no push, merge, or publication is part of this plan. Avoid unrelated formatting and do not repeat full suites after every small edit without a reason. + +Before the first source edit, record the current revision/configuration and run both baseline suites from the verification section. Label results from the inherited beta-1 runtime accordingly; Task 2 establishes the qualifying comparison baseline. Preserve unrelated local changes and use the repository's isolation workflow when implementation starts. + +## File map + +| Area | Existing files to reuse or modify | Responsibility | +| --- | --- | --- | +| Shader options/diagnostics | `crates/victory-gpu/src/shader_cache.rs`, `apps/victory/src/translate.rs`, `apps/victory/tests/translate.rs` | One option policy and accurate diagnostic outcomes | +| Cache consumers | `crates/victory-gpu/src/pipeline.rs`, `crates/victory-gpu/src/pipeline/library.rs` | Preserve linked-shader behavior and cache compatibility | +| Runtime setup | `setup.sh`, `tools/macos/victory.sh`, `docs/macos.md` | Version checks and safe toolkit refresh | +| Wave64 correctness | `crates/victory-shader/src/emit/lower/halves.rs`, `lower/meet.rs`, `lower.rs`, `emit/mod.rs`, `emit/halves_tests.rs` | Correct lane communication and control flow | +| Other shader gaps | `crates/victory-shader/src/native.rs`, `resource.rs`, `emit/mod.rs`, `emit/lower.rs`, existing stage/instruction tests | Stage selection, operands, descriptors, and instructions | +| Builder integrity | `crates/victory-gpu/src/pipeline/builder.rs`, `pipeline/host.rs`, `draw.rs` | Preserve complete-builder gating and visible failures | +| Memory/backend | `crates/victory-gpu/src/backend.rs`, `host.rs`, `alias.rs`, `inplace_probe.rs`, `shadow.rs`, `memory.rs`; `crates/victory-hle/src/modules/xmem.rs` | Minimal backend boundary, allocation identity, aliases, lifetime | +| Rendering | `crates/victory-gpu/src/descriptor/`, `pipeline/`, `texture.rs`, `draw.rs`, `list.rs`, `queue.rs`, `dxgi.rs` | Binding, graphics commands, synchronization, presentation | + +Potential bridge files are scoped to `tools/macos/metal/` for the Wine/native build and `crates/victory-gpu/src/metal/` for Rust integration. Create only the files needed by Milestone B's approved probe; choose the exact module split from its ABI and existing build conventions. + +## Task 1: Make diagnostics use runtime shader choices + +**Files:** modify `crates/victory-gpu/src/shader_cache.rs` and `apps/victory/src/translate.rs`; extend their unit tests and `apps/victory/tests/translate.rs`. Read all `runtime_options()` consumers in `pipeline.rs` and `pipeline/library.rs` before changing shared construction. For the baseline, reuse diagnostics in `draw.rs`, `pipeline.rs`, and `pipeline/builder.rs`; modify those only if the required attempted-work evidence is currently missing. + +**Interfaces:** retain the existing `runtime_options() -> victory_shader::emit::Options` contract for pipeline consumers. Expose one shared entry point `pub fn translation_options(container: &[u8], host_wave32: bool) -> victory_shader::emit::Options` for runtime translation and CLI diagnostics. The supplied wave capability must avoid requiring a GPU merely to perform an offline scan. Move common option assembly into shared code; do not copy its field list into the CLI. Apply existing per-container overrides in this entry point. + +- [ ] Establish the repeatable acceptance sequence and isolated data before fixes: prologue through first controllable movement/camera response. Capture the furthest reachable checkpoint, requested settings, and attempted work, including refused/dropped pipelines, indirect work, and BVH gate decisions. Reuse existing diagnostics; add only missing pre-drop counters needed to distinguish attempted work from successfully executed work. Store detailed traces outside the repository. +- [ ] Add `diagnostic_options_match_runtime_translation`: for identical container, host capability, and environment, compare the complete `Options`, including rendezvous, image-atomic settings, narrow waves, literal halves, and selective UAV-size behavior. Run environment-dependent cases in child processes to avoid `OnceLock` state leaking across cases. +- [ ] Add a synthetic divergent-wave regression that exposes the current diagnostic/runtime difference and a test that `--wave32` analysis works without an available GPU. +- [ ] Run the new tests before the change and record the failure showing the mismatch. +- [ ] Route `host_shader` and diagnostic emission through the shared entry point. Preserve linked mesh/pixel overrides and the current cache/library key inputs; add key-invalidation coverage for every newly shared setting that changes emitted bytes. +- [ ] Add `same_payload_containers_keep_distinct_overrides`: construct two original synthetic containers with the same DXIL/ACCC payload and different full-container hashes, target one with a selective override, and assert that each retains its own option/result. Compare using the full length-bounded container hash and the runtime-selected native program (`emit::prepare`), rather than the diagnostic's payload-only deduplication. Cover a container with multiple native programs and one containing no supported runtime stage; keep extra diagnostic programs separately counted. +- [ ] Keep program counts and distinct-container counts explicitly separate. A successful IR build must not be presented as successful host shader execution. Preserve named refusal reporting through `translate --list`. +- [ ] Run `cargo test -p victory -p victory-gpu --locked` for native coverage, then `tools/macos/test-wine.sh -p victory --test translate -- --nocapture` with D3DMetal overrides as described below. Run the affected shader-cache/library tests under Wine. +- [ ] Repeat the owned-file diagnostic and runtime-cache scans with identical options and a cold external cache. Reconcile outcomes for the same containers/stages, not only total counts. Record aggregate results outside the repository. +- [ ] Review the change and commit the option/diagnostic fix as one unit after checks pass. + +**Done:** identical requested translation semantics no longer depend on which CLI path was used; cache identities and offline analysis behavior remain correct. + +## Task 2: Establish a versioned, recoverable reference runtime + +**Files:** modify `setup.sh`, `tools/macos/victory.sh`, and `docs/macos.md`. Create a small reusable version helper at `tools/macos/gptk-version.sh` and its assert-based shell check at `tools/macos/tests/gptk-version.sh` if sharing the parser between setup and launcher requires it. + +**Interfaces:** a shell function `gptk_version_supported VERSION` returns success for recognized versions at or above `4.0b3`, failure for older or malformed versions. Read the installed framework's version with `plutil`. Keep `GPTK_DMG` as the existing explicit input for refresh; do not add another installer configuration mechanism. + +- [ ] Add cases rejecting `3.0`, `4.0b1`, `4.0b2`, empty and malformed values; accepting `4.0b3`, `4.0b10`, `4.0`, and `4.1`. Verify an unknown spelling produces an actionable error rather than an optimistic success. +- [ ] Demonstrate the current issue with a synthetic existing framework marked `4.0b1`: setup must not call that version satisfactory simply because the directory exists. +- [ ] Make setup report the installed version and refresh from an explicitly selected valid toolkit. Stage and validate the replacement redistributable set before replacing installed components; preserve the previous set on extraction, validation, or copy failure. Keep cache and save directories untouched. +- [ ] Test a failed staged copy, an older input toolkit, and a repeat run on an accepted installation using temporary synthetic directory trees. Assert the installed sentinel files remain unchanged on failure and no Wine rebuild occurs on a normal accepted repeat. +- [ ] Run `zsh -n setup.sh`, `sh -n tools/macos/victory.sh`, and `sh tools/macos/tests/gptk-version.sh`; run the staging failure checks. Do not redistribute or commit Apple files. +- [ ] With a user-supplied qualifying toolkit available, refresh locally, inspect the installed version, and run `tools/macos/victory.sh gpu-check`. If the download requires Apple sign-in, record that concrete external dependency and continue source work that does not require it. +- [ ] Establish both native and Wine suite baselines using the commands below. Record every skip and any existing failure separately from regressions. +- [ ] Review and commit setup, tests, and documentation together. + +**Done:** the comparison runtime meets the documented version floor, setup detects stale installations, and failed refreshes preserve the previous runtime. Source work can proceed while a licensed download is unavailable; hardware comparison claims cannot. + +## Task 3: Fix the three BVH translation blockers + +**Files:** start in `crates/victory-shader/src/emit/lower/halves.rs`, `lower/meet.rs`, `lower.rs`, and `emit/halves_tests.rs`. Change `emit/mod.rs` or `crates/victory-gpu/src/pipeline/builder.rs` only when the traced defect requires it. Keep all owned shader inputs and detailed disassembly outside the repository. + +**Interfaces:** preserve `emit::translate_with(container: &[u8], options: Options) -> Result`, `Lower::first_lane_across`, and the builder's all-created-pipelines-ready contract. Reuse `readfirstlane_in_branch` and the existing synthetic GPU comparison helpers rather than introducing another harness. + +- [ ] Reproduce the three refusals through Task 1's shared runtime options and identify their control-flow shapes. Search callers of the lowering operation before editing it. +- [ ] Add original synthetic cases named `bvh_first_lane_shapes_lower` and `bvh_first_lane_shapes_match_console_on_gpu`. Assertions: the first active lane across the whole console wave wins; upper-half-only activity reads the upper half; inactive lanes do not supply values; different waves/groups do not exchange values. +- [ ] Exercise group sizes 32, 64, 96, and 128; active lanes at 0, 31, 32, and 63; divergence, unequal loop progress, early exits, and empty masks. Use an explicit CPU oracle for each case and run GPU cases in a bounded child process so a deadlock fails the test. +- [ ] Verify the synthetic regressions fail for the same reason before the fix. Implement the smallest sound change to uniformity analysis, exchange placement, or rendezvous handling supported by that evidence. Do not weaken a refusal without establishing the required lane semantics. +- [ ] Run `cargo test -p victory-shader halves_tests --locked`, then `tools/macos/test-wine.sh -p victory-shader halves_tests -- --nocapture` with D3DMetal overrides. A skipped hardware test is not a semantic pass. +- [ ] Run the owned BVH container scan and GPU pipeline creation check: require 52/52 emitted and 52/52 pipelines accepted. Validate emitted DXIL when a compatible validator is installed; record absence rather than counting it as success. +- [ ] In the controlled acceptance sequence using isolated external data, require a positive observation of the title's own builder pipelines becoming ready and an actual dispatch passing the builder gate. Standalone CLI pipelines use different creation state and cannot substitute for this evidence. Keep the whole-builder gate and its negative test: a refused pipeline must still hold it back. +- [ ] Review and commit each independently testable semantic fix with its regression. + +**Done:** all 52 builder shaders translate and create standalone host pipelines; synthetic behavior is correct on the GPU; the title's own builder reaches ready state and dispatches in the controlled run; builder integrity checks remain enforced. This gate alone does not prove correct lighting throughout the game. + +## Task 4: Close the remaining required shader gaps + +**Files:** use the file map and the refusal's existing module. Reuse `emit/flow_tests.rs`, `emit/halves_tests.rs`, `emit/valu_tests.rs`, `emit/semantics_tests.rs`, and resource/stage tests as appropriate. Avoid a new generic shader subsystem. + +**Interfaces:** preserve the translator's `Result` boundary and named failure categories. Extend stage representation and GPU pipeline consumers together when adding a stage; a translator-only success is incomplete. + +- [ ] Rebuild the refusal inventory after Tasks 1–3. The original 266 includes the three BVH failures, so do not add them twice. Separate unsupported stages (195 initially) from cross-wave/mask/control-flow, floating-point conversion, gather-level, and descriptor failures (71 initially). +- [ ] Record which stage families and semantic shapes are present and which are attempted by the acceptance sequence established in Task 1. Include suppressed, refused, indirect, and builder-gated work. Assign each family a status: observed/required, excluded by identified profile or stage selection, or not yet observed. Incomplete traces cannot prove a shader unused. Keep unobserved families and remaining uncertainty visible without making all future game paths a prerequisite to the Metal memory probe. +- [ ] Before implementing each family, write a small task with its exact failing synthetic case, affected caller/pipeline paths, and expected CPU or console-calibrated output. Check that test fails first. Avoid prescribing a floating-point or synchronization algorithm before identifying the required console semantics. +- [ ] Implement required families in this order: shared BVH/lighting wave behavior, masks and loops, descriptors, conversions/gathers, then required additional stages. Change dependent formats, exports, cache keys, and pipeline creation together. +- [ ] Validate integers exactly. For floating-point cases, specify NaN, infinity, signed-zero, rounding, and tolerance behavior from the existing hardware-calibrated conventions; do not select tolerances merely to make results pass. +- [ ] Run focused native and Wine GPU tests per family. Re-run the runtime scan from a cold external cache at integration boundaries, with count and reason changes recorded. +- [ ] Finish Gate A: all 52 standalone BVH pipelines accepted and positive title-builder dispatch evidence recorded; known shared blockers in the observed workload resolved; every remaining refusal classified; both complete suites checked. Carry unobserved/unexecuted paths forward explicitly to game acceptance. Preserve visible failure behavior for still-unsupported inputs. +- [ ] Review and commit each family independently. Update the milestone record with measured coverage and remaining limitations. + +**Done:** missing shared functionality needed for the planned Metal workload is fixed and tested. Reaching zero refusals without correct execution does not satisfy this task. + +## Milestone B: Backend boundary and shared Metal memory + +**Depends on:** Gate A. **Approved steps:** 1 and 2. + +- [ ] Read `backend.rs`, `HostList`, `alias.rs`, `inplace_probe.rs`, and XMem mapping lifetimes together; trace all affected callers before defining the bridge ABI. +- [ ] Write the executable memory-slice plan with exact Rust/native interfaces and ownership rules. Match the actual Wine host architecture/ABI and test packing/calling conventions across the bridge. Reuse the existing alias/probe findings; move only copies, barriers, and resource lifetime operations needed by this slice. +- [ ] Implement an end-to-end Wine bridge probe over eligible game-style allocations. Required tests: page alignment, overflow and device limits, CPU/GPU round trip, two CPU aliases of one physical region, canonical GPU identity, remap/unmap during queued work, rejected mappings, allocation failure, and repeated create/submit/release cycles. +- [ ] Compare equal workloads against D3DMetal, including existing alias support. Require wall-clock submission-to-completion and CPU submission/wait timings, bytes copied, and live allocations. Report GPU execution time only from a validated source; known zero D3DMetal timestamps mean unavailable. Do not infer savings from API names. +- [ ] Pass Gate B before expanding the abstraction or committing to an ABI for the rest of the renderer. + +## Milestone C: Direct Metal compute + +**Depends on:** Gate B. **Approved step:** 3. + +- [ ] Write the executable compute-slice plan using the proven bridge ABI and locally verified converter capabilities. +- [ ] Integrate DXIL-to-Metal conversion, minimal bindings/root layout, residency, submission, and completion for the same synthetic programs used in the reference tests. +- [ ] Test compile/link failure, invalid bindings, cross-wave behavior, required atomic operations, cold/warm caches, compiler/options changes, and buffer visibility after completion. +- [ ] Require correct output written back to the original shared allocation through the Windows-to-Metal path. Count and reject accidental D3DMetal execution for selected Metal work. +- [ ] Pass Gate C; record copied bytes and time relative to the same D3DMetal workloads. Only then expand beyond compute. + +## Milestone D: Direct Metal rendering + +**Depends on:** Gate C. **Approved step:** 4. + +- [ ] Split implementation into independently verifiable binding, texture, graphics/mesh, indirect-command, synchronization, and presentation tasks using the existing file map. +- [ ] Reuse existing texture-layout conversion and shader translation. Test mip/array formats, resource aliasing, read/write transitions, depth/stencil/blend, actual mesh-output limits, indirect bounds, and query/fence semantics. +- [ ] Add explicit backend selection through existing CLI/configuration surfaces and capability reporting. An unavailable Metal request must fail clearly, and its caches must not collide with D3DMetal artifacts. +- [ ] Exercise resource exhaustion, compiler errors, command-buffer failure, resize/close, and teardown with in-flight work. Preserve diagnostic causes and avoid silent dropped work. +- [ ] Pass synthetic render comparisons and present a real game frame using Metal for the complete GPU path. Continue to Gate E before calling the goal achieved. + +## Milestone E: Game acceptance + +**Depends on:** Gate D. **Approved step:** 4, completion. + +- [ ] Reuse the prologue scene/input sequence established in Task 1 and isolated save/data directories. Complete any previously unexecuted portion and revisit its unobserved shader families. Use equal resolution/settings and separate cold/warm measurements for each backend. +- [ ] Verify first controllable movement and camera response, geometry, lighting/reflections, UI, and audio/input continuity. Test save/reload when reachable; preserve original saves. +- [ ] Complete a 20-minute warm-cache run with no hang or GPU reset and no unbounded memory growth. Record dropped work, refusal counts, peak memory, copied bytes, and wall-clock frame-time median/tails. GPU timings remain separately labeled with their measurement source or unavailable status. +- [ ] Report visual discrepancies and practical playability with the results. If a required defect remains, keep the goal open and prioritize the measured blocker. +- [ ] Run the integrated checks, review the complete change, and update backend/setup documentation with only verified support and limitations. + +## Verification commands and evidence + +Use focused tests while changing one behavior. At the baseline and integrated milestone gates, use the repository's documented commands: + +```sh +cargo test --workspace --locked +WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" tools/macos/test-wine.sh --workspace --no-fail-fast --locked +cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm --locked -- -D warnings +cargo clippy --workspace --all-targets --all-features --target x86_64-pc-windows-gnullvm --locked -- -D warnings +cargo xtask policy +``` + +For focused Wine commands in tasks above, use the same `WINEDLLOVERRIDES` setting. Add the helper DXC environment from `tools/macos/victory.sh` if the build requires it. Format changed code only; do not reformat unrelated files. + +Owned-file checks use `VICTORY_GAME_DIR` or explicit paths from the user's configuration. Set `VICTORY_CACHE_DIR` and `VICTORY_DATA_DIR` to canonical locations outside the repository before scans or game execution, including when using Wine drive mappings. Use the existing `translate --list`, `translate --pipelines`, and `translate --cache` commands; retain counts, options, and version metadata outside the repository. A cache hit on a previous refusal is not a newly tested translation. + +Distinguish these evidence levels in every milestone: IR construction, host shader emission, validator acceptance, pipeline creation, GPU execution with known expected output, and game behavior. Each level proves only its own result. + +## Plan status + +The four architectural steps are approved. This document records the prerequisite-first order and the implementation gates. No product code or runtime upgrade has been performed as part of writing the plan. No completion date or FPS target is asserted before the prerequisite and memory measurements exist. diff --git a/docs/superpowers/specs/2026-11-27-direct-metal-design.md b/docs/superpowers/specs/2026-11-27-direct-metal-design.md new file mode 100644 index 000000000..07dd5c442 --- /dev/null +++ b/docs/superpowers/specs/2026-11-27-direct-metal-design.md @@ -0,0 +1,109 @@ +# Direct Metal with prerequisites first + +## Intent and approved direction + +Deliver a direct Metal GPU backend for VIctory on Apple Silicon. First address the missing shared functionality that would otherwise follow the project into the new backend. Keep the existing executable loader, console runtime, Rosetta CPU execution, and shader translator. Reach Metal from the Windows process through a Wine Unix bridge. + +The user approved these four steps on 2026-11-27: + +1. Keep the existing loader, console runtime, and shader translator. +2. Prove correct Metal access to game memory, including aliases and remapping. +3. Execute translated compute through DXIL, Metal Shader Converter, and Metal. +4. Extend to rendering while retaining D3DMetal for comparison. + +The current deliverable is the plan. The approved direction does not require another architecture-selection discussion. Implementation proceeds with the prerequisites first; later details are settled from the hardware evidence described below. + +## Current evidence + +Baseline checkout: `1fcc386`. Counts describe the audit on this checkout, not permanent regression-test expectations. + +| Area | Observed baseline | +| --- | --- | +| Owned game package | All 104 manifest-listed files present; 22 RPF headers valid | +| Executable | Recognized Series 1.0.2.1 build | +| Static binding | 587 executable imports resolved; four initially loaded title DLLs have no unresolved imports | +| Host capabilities | Mesh shaders and shader model 6.6 reported supported | +| Installed D3DMetal | 4.0 beta 1; repository documentation asks for 4.0 beta 3 or newer | +| Native tests | 727 passed, 18 ignored; full Wine suite was not run in the audit | +| Runtime shader translation | 25,941 distinct containers: 25,675 emitted, 266 refused | +| Refusal classes | 195 unsupported-stage containers; 71 other refusals | +| BVH builder | 49 of 52 compute containers emitted; three cross-half first-lane reads refused | + +Emission was measured with the runtime cache path and its actual options in a separate, cold cache. It did not validate DXIL, create every host pipeline, or establish correct GPU results. The separate diagnostic command has different option construction and different counting units; its counts must not be substituted for this baseline. + +## Approach and tradeoffs + +The chosen approach is shared correctness work followed by an incremental direct Metal backend. It makes shader fixes useful to both backends and preserves a comparison implementation while the new backend grows. + +Continuing only with D3DMetal offers a shorter route to individual fixes but retains its translation and memory constraints. A complete native CPU/runtime rewrite would expand the scope beyond the approved GPU work. Those alternatives are not part of this effort. + +D3DMetal is a comparison path, not a semantic oracle: known differences must be checked against synthetic CPU expectations and existing console-calibrated tests. Direct Metal is not assumed to make the GPU execute Xbox wave64 instructions correctly or to understand the game's acceleration-structure representation automatically. + +## Constraints + +- Retain the current loader, console runtime, and Rosetta CPU execution. +- Keep D3D12/D3DMetal available as the reference backend throughout migration. +- Keep all game files, derived shaders, dumps, captures, and Apple redistributables outside the repository. +- Commit only original source, synthetic tests, build identities, and aggregate measurements allowed by `docs/asset-policy.md`. +- Use the existing Rust workspace and local Apple/Wine toolchain; add dependencies only when a required capability is unavailable locally. +- The existing macOS baseline is Apple Silicon and macOS 15 or newer. Report any higher requirement discovered for the selected Metal Shader Converter explicitly. +- Use D3DMetal 4.0 beta 3 or newer for the comparison baseline; never replace a working runtime with an unverified or partial installation. +- Keep backend selection explicit during development; an explicitly requested Metal backend must report unavailable capabilities instead of silently switching to D3DMetal. +- Missing graphics operations must fail visibly or remain counted as unsupported; they must not become successful no-ops. +- Preserve saves and original game files. Use isolated external cache/data directories for controlled game checks and record the backend and shader options with each measurement. + +## Work order and gates + +### A. Trustworthy baseline and missing shared functionality + +First establish the acceptance workload: the prologue through first controllable movement/camera response, with a repeatable input sequence, settings, and isolated data. Initially record the furthest reachable checkpoint and repeat after fixes; a shader omitted by a refused pipeline or a held builder is not evidence of an unused shader. Trace attempted work before it is dropped, including indirect work, and keep hashes and detailed traces outside the repository. + +Unify shader option selection between diagnostics and runtime, including cross-half synchronization, image atomics, narrow waves, and per-container overrides. Comparisons must also use the same identity: the length-bounded full container and the native program selected by the runtime. The diagnostic's extra program analysis remains separately labeled. Make setup detect the installed toolkit version and support a safe refresh from a user-supplied toolkit. Run the native and Wine suites and preserve the original baseline when upgrading. + +Then reproduce the three BVH failures with original synthetic programs. Correct the first-lane semantics for active lanes in both halves, upper-half-only activity, divergence, early exits, loops, and partial groups. Keep the existing all-or-nothing builder gate: it prevents partial builds from damaging title memory. + +Classify the other refusals by semantic family and by attempted use in the agreed game acceptance workload. Implement required stages/instructions and verify numerical behavior. A packaged shader is not proof that the selected workload executes it. Label coverage as observed/required, excluded by identified profile or stage selection, or not yet observed; absence from an incomplete run proves nothing beyond that recorded prefix. A deferred family stays in the coverage inventory with its evidence and uncertainty, never counted as implemented. Resolve known shared blockers before the Metal slice; do not require proving every future game path unused before starting the memory probe. + +**Gate A:** diagnostic and runtime choices agree for identical inputs; reference runtime is version-checked; all 52 BVH containers emit and their standalone host pipelines can be made; synthetic semantic tests execute correctly; the title's own builder pipelines become ready and at least one actual builder dispatch passes its gate in the controlled run. Every refusal family has a coverage status, and known shared blockers in the observed acceptance workload are resolved. Unobserved package coverage and unexecuted paths remain explicit follow-up work for game acceptance. + +### B. Minimal backend boundary and shared memory + +Reuse `HostGpu`, `HostMemory`, `alias.rs`, `inplace_probe.rs`, and the XMem mapping tests. Inventory concrete D3D12 types at their callers. Move copies, barriers, and lifetime handling behind the minimum boundary needed by the memory/compute slice, preserving existing behavior. Avoid moving all roughly 200 command sites before there is a working slice. + +Build the Wine-to-Metal bridge and test a Metal buffer over eligible owned memory. The in-process bridge must match the running Wine process's architecture and calling convention; an ARM64-only library cannot simply be loaded into its x86-64 host. Shader conversion may use a separate native command-line tool without moving title-memory operations out of process. Eligibility includes actual host-page alignment, one valid VM region, checked sizes, stable ownership, and device limits. Unsupported mappings must have an explicit outcome and a valid copying fallback where the slice supports one. Do not claim zero-copy for ineligible memory. + +Aliases of the same physical pages must resolve to one canonical GPU buffer with offsets. The existing roadmap reports that separate GPU aliases are not necessarily coherent within a submission. Remapping and release must wait for in-flight GPU use; no stale pointers or resource destruction before completion. + +**Gate B:** deterministic CPU-to-GPU-to-CPU results, aliases, remapping, unmapping, allocation failure, and repeated lifetime tests pass through the real Wine bridge on this Mac. Report bytes copied, wall-clock submission-to-completion time, and live allocation totals against D3DMetal. GPU execution timings are optional evidence only when a validated timing source exists; D3DMetal timestamps that remain zero are unavailable measurements, not zero GPU cost. A standalone native Metal demo does not satisfy this gate. + +### C. One complete Metal compute path + +Reuse VIctory's emitted DXIL and compile it with the locally installed Metal Shader Converter. Implement only the bindings, descriptors, pipeline creation, residency, command submission, and synchronization required by an existing synthetic compute workload. Keep converter-generated data outside the repository. + +Test ordinary buffers first, then cross-wave and atomic operations required by the BVH shaders. Associate compiled artifacts with backend, translator options/build, converter version, and applicable device/OS identity so incompatible caches cannot be reused. + +**Gate C:** the Windows process invokes Metal directly; an existing translated compute workload writes the correct bytes into the shared title allocation; repeat runs and cache reloads agree; required BVH pipelines compile and controlled semantic probes execute. D3DMetal must not execute the selected Metal compute work. + +### D. Rendering through Metal + +Extend the proven slice in testable units: resource bindings, texture formats and detiling, graphics/mesh pipelines, indirect work, depth/blend state, fences and queries, then presentation. Preserve the console behavior already encoded in `draw.rs`, `descriptor/`, `memory.rs`, `texture.rs`, and the shader translator. Query actual device limits and keep unsupported cases visible. + +Integrate explicit backend selection into the existing launcher/configuration and capability checks. Validate that all GPU work for a Metal game run reaches Metal, while the CPU side continues through the retained runtime. + +**Gate D:** synthetic render cases pass with CPU/reference expectations where available; resource lifetime and failure recovery remain correct; Metal presents a game frame with its backend and dropped-work counters visible. First frame is a milestone, not final acceptance. + +### E. Game correctness and performance acceptance + +Reuse the workload established in A with the owned Series 1.0.2.1 build and a separate save/data location. Compare equal resolution, settings, camera path, shader options, and cold/warm cache conditions. Record hardware, OS, runtime/compiler versions, translation refusals, dropped commands, GPU faults, wall-clock frame and submission/completion times, copied bytes, and peak memory. Report GPU execution time only when measurable with a validated source. + +Start with the prologue through first controllable movement and camera response. Verify representative geometry, lighting, reflections, UI, and audio/input continuity. Test save/reload against the isolated data location when the game reaches that functionality. Require a 20-minute warm-cache run without a hang, GPU reset, or unbounded memory growth; identify any known visual deviation rather than hiding it in a performance number. + +**Goal complete:** Direct Metal is selectable and handles the full GPU workload for the defined scene; required correctness checks pass; measured performance and memory costs are reported against D3DMetal. If gameplay remains impractically slow, report that limitation and keep performance work open. No FPS promise is made before the baseline is measured. + +## Decisions left to implementation evidence + +Bridge ABI and the smallest command abstraction are chosen after the memory probe, using the Wine build already present. Converter version and hardware-specific capability floors are verified locally before integration. Exact instruction-lowering changes follow synthetic reproductions of the real refusal shapes. These are engineering decisions within the approved direction, not reasons to repeat architecture approval. + +## Explicit exclusions + +This effort does not replace Wine/Rosetta for CPU execution, implement online services, redistribute game/toolkit material, add a launcher UI, or undertake unrelated repository refactoring. It does not require spending time optimizing D3DMetal paths that the new backend will remove unless they are needed for a reliable comparison or reveal shared correctness defects. diff --git a/setup.sh b/setup.sh index 9aba82e84..d15b77921 100755 --- a/setup.sh +++ b/setup.sh @@ -16,6 +16,7 @@ case "$dmg" in *) dmg="$PWD/$dmg" ;; esac cd "$ROOT" +. tools/macos/gptk-version.sh say() { print -P "%F{cyan}==>%f $*"; } die() { print -P "%F{red}error:%f $*" >&2; exit 1; } @@ -60,61 +61,82 @@ rustup target add x86_64-pc-windows-gnullvm > /dev/null # too): the build goes through it, and tools/macos/victory.sh and # test-wine.sh take this checkout's own target/wine-cx first. ALIAS="$HOME/Library/Caches/victory-macos" -mkdir -p "$ALIAS" "$ROOT/target" -ln -sfn "$ROOT/target" "$ALIAS/target" -WINE_DIR="$ALIAS/target/wine-cx" - -# 4. x86_64 libraries for Wine. -say "building the x86_64 libraries Wine needs (about 10 minutes the first time)" -tools/macos/build-deps.sh "$ALIAS/target/deps-x86" +WINE_DIR="$ROOT/target/wine-cx" -# 5. CrossOver Wine, with the patches in tools/macos/patches and SDL2 for game -# controllers. The builder decides whether it can update just the affected -# libraries or needs to reinstall the full release. -if [[ -x $WINE_DIR/bin/wine && -f $WINE_DIR/.victory-patches && -f $WINE_DIR/.victory-patch-paths && "$(cat "$WINE_DIR/.victory-patches" 2> /dev/null)" == "$(tools/macos/build-crossover-wine.sh --stamp)" ]]; then - say "Wine already built" -elif [[ -x $WINE_DIR/bin/wine ]]; then - say "updating the installed CrossOver Wine" - DEPS="$ALIAS/target/deps-x86" tools/macos/build-crossover-wine.sh -else - say "building CrossOver Wine (about 30 minutes the first time)" - DEPS="$ALIAS/target/deps-x86" tools/macos/build-crossover-wine.sh -fi +# Validate the candidate before rebuilding an existing Wine or touching its lib. +validate_gptk() { + local lib=${1:A} description=$2 version component file + for component in external/D3DMetal.framework/Resources/Info.plist \ + external/D3DMetal.framework/D3DMetal external/libd3dshared.dylib \ + wine/x86_64-windows/d3d12.dll wine/x86_64-windows/dxgi.dll; do + file="$lib/$component" + [[ -f $file && -s $file ]] \ + || die "$description is missing $component. Check that GPTK_DMG points to Apple's Game Porting Toolkit .dmg" + [[ ${file:A} == "$lib"/* ]] \ + || die "$component in $description resolves outside its library tree. Check the selected GPTK_DMG" + done + version=$(gptk_framework_version "$lib/external/D3DMetal.framework") \ + || die "could not read D3DMetal's version in $description. Set GPTK_DMG to a Game Porting Toolkit .dmg with D3DMetal 4.0b3 or newer" + gptk_version_supported "$version" \ + || die "$description has unsupported D3DMetal version '$version'; set GPTK_DMG to a .dmg with D3DMetal 4.0b3 or newer" + print -r -- "$version" +} -# 6. D3DMetal from Apple's Game Porting Toolkit. -if [[ -d $WINE_DIR/lib/external/D3DMetal.framework ]]; then - say "D3DMetal already added" -else - if [[ -z $dmg ]]; then +setup_gptk() ( + lib="$WINE_DIR/lib" + framework="$lib/external/D3DMetal.framework" + stage="$WINE_DIR/.gptk-refresh" + [[ ! -e $stage ]] || die "a D3DMetal refresh is in progress or was interrupted at $stage. See docs/macos.md for recovery" + if [[ -e $framework || -L $framework ]]; then + if installed=$(gptk_framework_version "$framework"); then + say "installed D3DMetal version $installed" + if gptk_version_supported "$installed" && [[ -z $dmg ]]; then + validate_gptk "$lib" "the installed D3DMetal runtime" > /dev/null + return + fi + else + say "could not read the installed D3DMetal version from $framework/Resources/Info.plist" + fi + [[ -n $dmg ]] || die "set GPTK_DMG to the path of a Game Porting Toolkit .dmg with D3DMetal 4.0b3 or newer, then run ./setup.sh" + elif [[ -z $dmg ]]; then # (N) keeps zsh quiet when nothing matches, (om) puts the newest first. downloads=("$HOME"/Downloads/Game_Porting_Toolkit*.dmg(Nom)) dmg="${downloads[1]:-}" - elif [[ ! -f $dmg ]]; then - printf 'GPTK_DMG does not point to a file: %s\n' "$dmg" >&2 - exit 1 fi - if [[ -z $dmg || ! -f $dmg ]]; then + if [[ -z $dmg ]]; then print - print -P "%F{yellow}One manual step is left.%f Apple only gives D3DMetal to people who sign in, so you have to download it yourself:" + print -P "%F{yellow}One manual step is left.%f Apple requires a sign-in to download D3DMetal:" print " 1. Open https://developer.apple.com/download/all/?q=game%20porting%20toolkit" - print " 2. Sign in with any Apple account (a free one works) and download the newest Game Porting Toolkit .dmg" + print " 2. Sign in and download a Game Porting Toolkit .dmg with D3DMetal 4.0b3 or newer" print " 3. Leave it in your Downloads folder and run ./setup.sh again" exit 1 fi - say "adding D3DMetal from ${dmg:t}" - outer="$(mktemp -d)"; inner="$(mktemp -d)" - # Detach both images however this step ends, so a failed run does not leave - # the toolkit mounted for the next one. - unmount() { - hdiutil detach -quiet "$inner" 2> /dev/null || true - hdiutil detach -quiet "$outer" 2> /dev/null || true - rmdir "$inner" "$outer" 2> /dev/null || true + [[ -f $dmg ]] || die "GPTK_DMG does not name a file: $dmg" + [[ -d $lib && ! -L $lib ]] || die "expected Wine's library directory at $lib; reinstall Wine before refreshing D3DMetal" + say "checking D3DMetal from ${dmg:t}" + mkdir "$stage" || die "could not start a D3DMetal refresh at $stage" + outer= inner= + cleanup_gptk() { + local restored=1 + if [[ -d $stage/previous-lib && ! -e $lib ]] && ! mv -f "$stage/previous-lib" "$lib"; then + print -r -- "Could not restore Wine's library directory. The previous set is at $stage/previous-lib" >&2 + restored=0 + fi + if [[ -n $inner ]]; then + hdiutil detach -quiet "$inner" 2> /dev/null || true + rmdir "$inner" 2> /dev/null || true + fi + if [[ -n $outer ]]; then + hdiutil detach -quiet "$outer" 2> /dev/null || true + rmdir "$outer" 2> /dev/null || true + fi + (( restored )) && rm -rf "$stage" } - trap unmount EXIT + trap cleanup_gptk EXIT + trap 'exit 1' HUP INT TERM + outer="$(mktemp -d)" + inner="$(mktemp -d)" if ! hdiutil attach -quiet -nobrowse -readonly -mountpoint "$outer" "$dmg"; then - # An intact download that macOS would not mount is not fixed by - # downloading it again: a sandboxed shell, such as an AI agent's, failed - # with "Device not configured" while the disk-image service was not running. if hdiutil verify -quiet "$dmg" 2> /dev/null; then die "macOS could not mount ${dmg:t}, though the file is intact. Run ./setup.sh again; if an AI agent or another sandboxed shell runs it and it fails again, run it from your own Terminal" fi @@ -124,19 +146,59 @@ else (( ${#eval_dmg} )) || die "${dmg:t} has no Evaluation .dmg inside. Check that it is Apple's Game Porting Toolkit" hdiutil attach -quiet -nobrowse -readonly -mountpoint "$inner" "$eval_dmg[1]" \ || die "could not open ${eval_dmg[1]:t} inside ${dmg:t}" - [[ -d $inner/redist/lib/external/D3DMetal.framework ]] \ - || die "${dmg:t} has no D3DMetal.framework where setup expects it (redist/lib/external). Download the newest Game Porting Toolkit and run ./setup.sh again" - # A half-copied framework would make the next run skip this step, so remove - # it if the copy fails. - ditto "$inner/redist/lib/" "$WINE_DIR/lib/" || { - rm -rf "$WINE_DIR/lib/external/D3DMetal.framework" - die "copying D3DMetal into Wine failed. Check the free space on this disk and run ./setup.sh again" - } - unmount - trap - EXIT + candidate=$(validate_gptk "$inner/redist/lib" "${dmg:t}") + + # Clone on APFS and overlay in staging so neither Wine nor the old toolkit + # is modified if the copy runs out of disk space or a component is missing. + cp -cRp "$lib" "$stage/new-lib" \ + || die "could not copy Wine's library directory for staging. Check the disk's free space" + [[ ! -L $stage/new-lib/external ]] \ + || die "Wine's external library directory is a symlink. Reinstall Wine before refreshing D3DMetal" + rm -rf "$stage/new-lib/external/D3DMetal.framework" + ditto "$inner/redist/lib/" "$stage/new-lib/" \ + || die "could not copy the D3DMetal redistributables to staging. Check the disk's free space" + staged=$(validate_gptk "$stage/new-lib" "the staged D3DMetal copy") + [[ $staged == $candidate ]] || die "the staged D3DMetal version is '$staged'; expected '$candidate'" + # Both renames stay on the Wine volume. The exit trap restores the previous + # library directory if the second rename fails. + mv -f "$lib" "$stage/previous-lib" && mv -f "$stage/new-lib" "$lib" \ + || die "could not activate the staged D3DMetal $candidate" + say "installed D3DMetal $candidate" +) + +# Protect any existing runtime before deciding whether setup can rebuild Wine. +wine_existing=0 +wine_current=0 +framework="$WINE_DIR/lib/external/D3DMetal.framework" +if [[ -x $WINE_DIR/bin/wine || -e $framework || -L $framework ]]; then + wine_existing=1 + if [[ -x $WINE_DIR/bin/wine && -f $WINE_DIR/.victory-patches && -f $WINE_DIR/.victory-patch-paths && "$(cat "$WINE_DIR/.victory-patches" 2> /dev/null)" == "$(tools/macos/build-crossover-wine.sh --stamp)" ]]; then + wine_current=1 + elif ! tools/macos/build-crossover-wine.sh --can-update-in-place; then + die "this installation needs a full Wine rebuild. Move $WINE_DIR to a backup, then set GPTK_DMG to a qualifying toolkit .dmg and run ./setup.sh. See docs/macos.md" + fi + setup_gptk +fi + +# 4. x86_64 libraries for Wine. +mkdir -p "$ALIAS" "$ROOT/target" +ln -sfn "$ROOT/target" "$ALIAS/target" +say "building the x86_64 libraries Wine needs (about 10 minutes the first time)" +tools/macos/build-deps.sh "$ALIAS/target/deps-x86" + +# 5. CrossOver Wine with the patches in tools/macos/patches and SDL2. +if (( wine_current )); then + say "Wine already built" +elif (( wine_existing )); then + say "rebuilding Wine's server, ntdll and HID bus (a few minutes)" + DEPS="$ALIAS/target/deps-x86" tools/macos/build-crossover-wine.sh --incremental-only +else + say "building CrossOver Wine (about 30 minutes the first time)" + DEPS="$ALIAS/target/deps-x86" tools/macos/build-crossover-wine.sh + setup_gptk fi -# 7. VIctory itself. +# 6. VIctory itself. say "building VIctory" [[ -f victory.toml ]] || cp victory.example.toml victory.toml # victory.sh owns the single release build: it sets VICTORY_HELPER_DXC when diff --git a/tools/macos/build-crossover-wine.sh b/tools/macos/build-crossover-wine.sh index fb151ca17..34041f275 100755 --- a/tools/macos/build-crossover-wine.sh +++ b/tools/macos/build-crossover-wine.sh @@ -24,6 +24,48 @@ stamp() { } build_stamp="$(stamp)" if [[ ${1-} == --stamp ]]; then print -r -- "$build_stamp"; exit 0; fi + +# The sorted paths the patches touch. +patch_paths() { grep -h '^+++ ' "$@" /dev/null | awk '{sub(/^b\//, "", $2); print $2}' | sort -u; } + +# An installed Wine has D3DMetal's DLLs copied over Wine's own, and make +# install would put Wine's back. So it gets only its server, ntdll's Unix +# library and the HID bus's (winebus.so, where SDL2 support lives) rebuilt, +# which D3DMetal does not replace. That is enough only while neither the +# patches baked into the installed Wine nor the current ones change anything +# but the server and ntdll, and the installed release matches. The paths of +# the applied patches are recorded next to the install stamp. +prefix="$ROOT/target/wine-cx" +installed=0 +release_changed=0 +outside= +if [[ -x $prefix/bin/wine && -f $prefix/.victory-patches && -r $prefix/.victory-patches && + -f $prefix/.victory-patch-paths && -r $prefix/.victory-patch-paths ]]; then + if [[ "$(< "$prefix/.victory-patches")" == "$VERSION:"* ]]; then + outside=$( { patch_paths "${PATCHES[@]}"; cat "$prefix/.victory-patch-paths"; } | + grep -v -e '^server/' -e '^dlls/ntdll/unix/' -e '^$' | sort -u) + [[ -n $outside ]] || installed=1 + else + release_changed=1 + fi +fi + +if [[ ${1-} == --can-update-in-place ]]; then + (( installed )) && exit 0 + exit 1 +fi +if (( ! installed )) && [[ ${1-} == --incremental-only ]]; then + echo "Wine needs a full rebuild. See docs/macos.md to back up the existing build first." >&2 + exit 1 +fi +if [[ -n $outside ]]; then + echo "the patches change ${outside//$'\n'/ }: reinstalling Wine fully" +elif (( release_changed )); then + echo "the installed CrossOver release changed or was not recorded: reinstalling Wine fully" +elif (( ! installed )) && [[ -x $prefix/bin/wine ]]; then + echo "the installed Wine metadata is incomplete: reinstalling it fully" +fi + DEPS_REAL="${DEPS:?set DEPS to an x86_64 prefix with FreeType, GnuTLS and SDL2}" # Wine's build splits flags at spaces, and both the project and the deps # can live under folders with spaces in their names. Space-free links to @@ -120,32 +162,7 @@ if ! grep -q 'victory-macos fallback' "$VK"; then mv "$VK.new" "$VK" fi -# The sorted paths the patches touch. -patch_paths() { grep -h '^+++ ' "$@" /dev/null | awk '{sub(/^b\//, "", $2); print $2}' | sort -u; } - -# An installed Wine has D3DMetal's DLLs copied over Wine's own, and make -# install would put Wine's back. So it gets only its server, ntdll's Unix -# library and the HID bus's (winebus.so, where SDL2 support lives) rebuilt, -# which D3DMetal does not replace. That is enough only while neither the -# patches baked into the installed Wine nor the current ones change anything -# but the server and ntdll, and the installed release matches. The paths of -# the applied patches are recorded next to the install stamp. -installed=0 PATCH_PATHS="$PREFIX/.victory-patch-paths" -if [[ -x $PREFIX/bin/wine && -f $PREFIX/.victory-patches && -f $PATCH_PATHS ]]; then - if [[ "$(< "$PREFIX/.victory-patches")" != "$VERSION:"* ]]; then - echo "the installed CrossOver release changed or was not recorded: reinstalling Wine fully" - else - outside=($( { patch_paths "${PATCHES[@]}"; cat "$PATCH_PATHS"; } | grep -v -e '^server/' -e '^dlls/ntdll/unix/' -e '^$' | sort -u || true)) - if (( ${#outside} > 0 )); then - echo "the patches change ${outside[*]}: reinstalling Wine fully" - else - installed=1 - fi - fi -elif [[ -x $PREFIX/bin/wine ]]; then - echo "the installed Wine metadata is incomplete: reinstalling it fully" -fi # Each patch goes in once: one that already reverses cleanly is in. A patch # is applied only after a dry run shows all of it applies, and one that diff --git a/tools/macos/gptk-version.sh b/tools/macos/gptk-version.sh new file mode 100644 index 000000000..fede3475c --- /dev/null +++ b/tools/macos/gptk-version.sh @@ -0,0 +1,22 @@ +# Shared by setup.sh and the macOS launcher. +gptk_framework_version() ( + # The suffix preserves any trailing newline in the plist value for rejection. + version=$(/usr/bin/plutil -extract CFBundleShortVersionString raw -expect string -n -o - \ + "$1/Resources/Info.plist" 2>/dev/null && printf '.') || exit 1 + case "$version" in + *' +'*) exit 1 ;; + esac + printf '%s\n' "${version%.}" +) + +gptk_version_supported() { + case "${1-}" in + ''|*[!0-9.b]*) return 1 ;; + esac + printf '%s\n' "$1" | LC_ALL=C awk -F '[.b]' ' + /^[0-9]+\.[0-9]+(\.[0-9]+|b[1-9][0-9]*)?$/ { + supported = $1 > 4 || ($1 == 4 && ($2 > 0 || $0 !~ /b/ || $3 >= 3)) + } + END { exit !supported }' +} diff --git a/tools/macos/tests/gptk-setup.sh b/tools/macos/tests/gptk-setup.sh new file mode 100644 index 000000000..8c9a0fa8b --- /dev/null +++ b/tools/macos/tests/gptk-setup.sh @@ -0,0 +1,342 @@ +#!/bin/sh +# Exercise setup with a complete synthetic Wine tree and disk-image fixtures. +set -eu +root=$(cd "$(dirname "$0")/../../.." && pwd) +tmp=$(cd "$(mktemp -d)" && pwd -P) +trap 'rm -rf "$tmp"' EXIT +export HOME="$tmp/home" FAKE_BREW="$tmp/brew" FAKE_OUTER="$tmp/outer" FAKE_INNER="$tmp/inner" +export PATH="$tmp/bin:$PATH" +unset DEPS GPTK_DMG +export CROSSOVER_VERSION=26.0.1 + +work="$tmp/checkout" +wine="$work/target/wine-cx" +installed="$wine/lib" +redist="$FAKE_INNER/redist/lib" +mkdir -p "$HOME" "$tmp/bin" "$work/tools/macos" "$wine/bin" "$FAKE_OUTER" "$FAKE_INNER" \ + "$work/cache" "$work/saves" +cp "$root/setup.sh" "$root/victory.example.toml" "$work/" +cp "$root/tools/macos"/gptk-*.sh "$work/tools/macos/" 2>/dev/null || true +cp "$root/tools/macos/victory.sh" "$tmp/launcher.sh" +builder="$work/tools/macos/build-crossover-real.sh" +cp "$root/tools/macos/build-crossover-wine.sh" "$builder" +current_stamp=$(/bin/zsh "$builder" --stamp) +stale_stamp="$CROSSOVER_VERSION:stale-stamp" +export FULL_REBUILD_MARKER="$tmp/full-rebuild" +touch "$FAKE_OUTER/Evaluation test.dmg" "$tmp/Selected Toolkit.dmg" +printf '%s\n' "$current_stamp" > "$wine/.victory-patches" +touch "$wine/.victory-patch-paths" +printf 'cache\n' > "$work/cache/sentinel" +printf 'save\n' > "$work/saves/sentinel" + +# Only platform/build boundaries are stubbed. plutil, the file operations, +# and setup itself operate on real fixtures. +cat > "$tmp/bin/uname" <<'STUB' +#!/bin/sh +echo arm64 +STUB +cat > "$tmp/bin/sw_vers" <<'STUB' +#!/bin/sh +echo 15.0 +STUB +cat > "$tmp/bin/brew" <<'STUB' +#!/bin/sh +case "$1" in + --prefix) echo "$FAKE_BREW" ;; + list) ;; + *) exit 99 ;; +esac +STUB +cat > "$tmp/bin/hdiutil" <<'STUB' +#!/bin/sh +set -eu +case "$1" in + attach) + [ "$5" = -mountpoint ] + case "$7" in + */Selected\ Toolkit.dmg) + [ "${FAIL_EXTRACT:-0}" = 0 ] + [ "${FAIL_AFTER_FULL_REBUILD:-0}" = 0 ] || [ ! -f "$FULL_REBUILD_MARKER" ] + ln -s "$FAKE_OUTER/Evaluation test.dmg" "$6/Evaluation test.dmg" + ;; + */Evaluation\ test.dmg) + case "${LINK_FRAMEWORK:-0}" in + 0) ln -s "$FAKE_INNER/redist" "$6/redist" ;; + outside|absolute) + cp -Rp "$FAKE_INNER/redist" "$6/redist" + framework="$6/redist/lib/external/D3DMetal.framework" + destination="$6/Mounted.framework" + [ "$LINK_FRAMEWORK" != absolute ] || destination="$6/redist/lib/external/Mounted.framework" + /bin/mv "$framework" "$destination" + ln -s "$destination" "$framework" + ;; + esac + ;; + *) exit 99 ;; + esac + ;; + detach) + rm -rf "$3/Evaluation test.dmg" "$3/redist" "$3/Mounted.framework" + ;; + verify) ;; + *) exit 99 ;; +esac +STUB +cat > "$tmp/bin/ditto" <<'STUB' +#!/bin/sh +set -eu +case "$1" in + */redist/lib/) + if [ "${FAIL_COPY:-0}" = 1 ]; then + mkdir -p "$2/wine/x86_64-windows" + printf 'partial copy\n' > "$2/wine/x86_64-windows/d3d12.dll" + exit 1 + fi + ;; +esac +exec /usr/bin/ditto "$@" +STUB +cat > "$tmp/bin/mv" <<'STUB' +#!/bin/sh +set -eu +case "$*" in + *new-lib*" $TEST_WINE_DIR/lib") + if [ "${FAIL_ACTIVATE:-0}" = 1 ]; then exit 1; fi + ;; +esac +exec /bin/mv "$@" +STUB +export TEST_WINE_DIR="$wine" +for command in arch xcode-select rustup; do + ln -s /usr/bin/true "$tmp/bin/$command" +done +for script in "$wine/bin/wine" "$work/tools/macos/build-deps.sh"; do + cp /usr/bin/true "$script" +done +cp /usr/bin/true "$work/tools/macos/victory.sh" +cat > "$work/tools/macos/build-crossover-wine.sh" <<'STUB' +#!/bin/sh +builder="$(dirname "$0")/build-crossover-real.sh" +case "${1:-}" in + --stamp|--can-update-in-place) exec /bin/zsh "$builder" "$@" ;; + --incremental-only) /bin/zsh "$builder" --stamp > "$TEST_WINE_DIR/.victory-patches" ;; + *) + if [ ! -f "$TEST_WINE_DIR/.victory-patch-paths" ]; then + touch "$FULL_REBUILD_MARKER" + rm -rf "$TEST_WINE_DIR/lib/external/D3DMetal.framework" + else + echo "unexpected Wine rebuild" >&2 + exit 99 + fi + ;; +esac +STUB +chmod +x "$tmp/bin/"* "$work/tools/macos/build-crossover-wine.sh" + +fail() { echo "FAIL: $*" >&2; cat "$tmp/output" >&2; exit 1; } +write_redist() { + lib=$1 version=$2 label=$3 + framework="$lib/external/D3DMetal.framework" + mkdir -p "$framework/Versions/A/Resources" "$lib/wine/x86_64-windows" + ln -sfn A "$framework/Versions/Current" + ln -sfn Versions/Current/Resources "$framework/Resources" + ln -sfn Versions/Current/D3DMetal "$framework/D3DMetal" + cat > "$framework/Resources/Info.plist" < + +CFBundleShortVersionString$version + +PLIST + for path in external/libd3dshared.dylib external/D3DMetal.framework/Versions/A/D3DMetal \ + wine/x86_64-windows/d3d12.dll wine/x86_64-windows/dxgi.dll; do + printf '%s\n' "$label" > "$lib/$path" + done +} + +setup() (cd "$tmp" && env "$@" /bin/zsh "$work/setup.sh" > "$tmp/output" 2>&1) +run_builder() { /bin/zsh "$builder" "$@" > "$tmp/output" 2>&1; } +assert_output() { grep -F -- "$1" "$tmp/output" >/dev/null || fail "missing diagnostic $1"; } +assert_preserved() { + diff -r --no-dereference "$tmp/original-lib" "$installed" >/dev/null || fail "failed setup modified the installed Wine library tree" + [ "$(cat "$work/cache/sentinel")" = cache ] && [ "$(cat "$work/saves/sentinel")" = save ] || + fail "failed setup modified cache or saves" +} + +write_redist "$installed" 4.0b1 old +printf 'Wine library\n' > "$installed/wine/x86_64-windows/other.dll" +touch "$installed/external/D3DMetal.framework/obsolete" +cp -Rp "$installed" "$tmp/original-lib" + +if setup; then fail "setup accepted an existing 4.0b1 framework"; fi +assert_output '4.0b1' +assert_output 'GPTK_DMG' +assert_preserved + +cp "$tmp/launcher.sh" "$work/tools/macos/launcher.sh" +if WINE="$wine/bin/wine" sh "$work/tools/macos/launcher.sh" --version > "$tmp/output" 2>&1; then + fail "launcher accepted an existing 4.0b1 framework" +fi +assert_output '4.0b1' +assert_output 'GPTK_DMG' + +export GPTK_DMG="$tmp/Selected Toolkit.dmg" +write_redist "$redist" 4.0b2 candidate +printf '%s\n' "$stale_stamp" > "$wine/.victory-patches" +if setup; then fail "setup accepted an older toolkit"; fi +assert_output '4.0b2' +assert_output '4.0b3' +assert_preserved +printf '%s\n' "$current_stamp" > "$wine/.victory-patches" + +write_redist "$redist" '4.0beta3' candidate +if setup; then fail "setup accepted unknown toolkit spelling"; fi +assert_output '4.0beta3' +assert_output 'GPTK_DMG' +assert_preserved + +write_redist "$redist" "4.0b3 +" candidate +if setup; then fail "setup accepted a newline in the toolkit version"; fi +assert_output "GPTK_DMG" +assert_preserved + +write_redist "$redist" 4.0b3 candidate +if setup FAIL_EXTRACT=1; then fail "setup accepted a failed extraction"; fi +assert_output 'could not mount' +assert_preserved + +rm "$redist/wine/x86_64-windows/dxgi.dll" +if setup; then fail "setup accepted an incomplete toolkit"; fi +assert_output 'dxgi.dll' +assert_preserved +write_redist "$redist" 4.0b3 candidate + +if setup FAIL_COPY=1; then fail "setup accepted an incomplete staged copy"; fi +assert_output 'copy' +assert_preserved + +if setup FAIL_ACTIVATE=1; then fail "setup accepted a failed activation"; fi +assert_output 'activate' +assert_preserved + +case "${1:-all}" in + all|relative) + setup GPTK_DMG='Selected Toolkit.dmg' || fail "setup rejected an image relative to its caller" + ;; + *) setup || fail "setup rejected a complete 4.0b3 toolkit" ;; +esac +assert_output '4.0b3' +for path in external/libd3dshared.dylib external/D3DMetal.framework/D3DMetal \ + wine/x86_64-windows/d3d12.dll wine/x86_64-windows/dxgi.dll; do + [ "$(cat "$installed/$path")" = candidate ] || fail "refresh did not update $path" +done +[ ! -e "$installed/external/D3DMetal.framework/obsolete" ] || fail "refresh retained an obsolete framework file" +[ "$(cat "$installed/wine/x86_64-windows/other.dll")" = 'Wine library' ] || fail "refresh replaced an unrelated Wine library" + +unset GPTK_DMG +setup || fail "setup rejected a repeat with an accepted installation" +assert_output 'Wine already built' +assert_output '4.0b3' +[ "$(cat "$work/cache/sentinel")" = cache ] && [ "$(cat "$work/saves/sentinel")" = save ] || + fail "successful setup modified cache or saves" +case "${1:-all}" in + all|rebuild-no-image|rebuild-image) + rm "$wine/.victory-patch-paths" + cp -Rp "$wine" "$tmp/original-wine" + for case_name in rebuild-no-image rebuild-image; do + [ "${1:-all}" = all ] || [ "$1" = "$case_name" ] || continue + if [ "$case_name" = rebuild-image ]; then + write_redist "$redist" 4.0b10 candidate + export GPTK_DMG="$tmp/Selected Toolkit.dmg" + fi + if setup FAIL_AFTER_FULL_REBUILD=1; then fail "$case_name unexpectedly ran a full rebuild"; fi + diff -r --no-dereference "$tmp/original-wine" "$wine" >/dev/null || + fail "$case_name lost the original Wine tree" + [ ! -e "$FULL_REBUILD_MARKER" ] || fail "$case_name started the full rebuild" + assert_output 'full Wine rebuild' + assert_output 'backup' + assert_output 'GPTK_DMG' + done + touch "$wine/.victory-patch-paths" + unset GPTK_DMG + ;; +esac + +case "${1:-all}" in + all|framework-link|framework-staged-link) + rm -rf "$tmp/original-lib" + cp -Rp "$installed" "$tmp/original-lib" + write_redist "$redist" 4.0b10 candidate + export GPTK_DMG="$tmp/Selected Toolkit.dmg" + for link_mode in outside absolute; do + [ "${1:-all}" = all ] || + [ "$1:$link_mode" = framework-link:outside ] || + [ "$1:$link_mode" = framework-staged-link:absolute ] || continue + if setup LINK_FRAMEWORK="$link_mode"; then fail "setup accepted a framework linked to the mounted image ($link_mode)"; fi + assert_output 'resolves outside' + assert_preserved + done + unset GPTK_DMG + ;; +esac + +case "${1:-all}" in + all|incremental) + printf '%s\n' "$stale_stamp" > "$wine/.victory-patches" + setup || fail "setup rejected an incremental Wine rebuild" + assert_output "rebuilding Wine's server" + [ "$(cat "$wine/.victory-patches")" = "$current_stamp" ] || fail "setup did not invoke the incremental builder" + ;; +esac + +case "${1:-all}" in + all|classifier) + printf 'server/fd.c\ndlls/ntdll/unix/virtual.c\n' > "$wine/.victory-patch-paths" + run_builder --can-update-in-place || fail "classifier rejected Wine's server and ntdll patches" + # Without DEPS, the real builder stops once it has accepted a partial build. + if run_builder --incremental-only; then fail "incremental builder ran without DEPS"; fi + assert_output 'set DEPS to an x86_64 prefix' + printf 'dlls/win32u/main.c\n' > "$wine/.victory-patch-paths" + if run_builder --can-update-in-place; then fail "classifier accepted a previously installed patch that needs a full rebuild"; fi + mkdir -p "$work/tools/macos/patches" + printf '+++ b/dlls/win32u/main.c\n' > "$work/tools/macos/patches/full.patch" + : > "$wine/.victory-patch-paths" + if run_builder --can-update-in-place; then fail "classifier accepted an incoming patch that needs a full rebuild"; fi + rm "$work/tools/macos/patches/full.patch" "$wine/.victory-patch-paths" + if run_builder --can-update-in-place; then fail "classifier accepted missing Wine metadata"; fi + if run_builder --incremental-only; then + fail "incremental-only Wine builder accepted a full rebuild" + fi + assert_output 'full rebuild' + touch "$wine/.victory-patch-paths" + ;; +esac + +case "${1:-all}" in + all|release) + cp -Rp "$wine" "$tmp/release-wine" + write_redist "$redist" 4.0b10 candidate + export CROSSOVER_VERSION=26.0.2 + if run_builder --can-update-in-place; then fail "classifier accepted a different CrossOver release"; fi + if run_builder --incremental-only; then fail "incremental builder accepted a different CrossOver release"; fi + assert_output 'full rebuild' + if setup GPTK_DMG="$tmp/Selected Toolkit.dmg"; then fail "setup accepted a different CrossOver release"; fi + assert_output 'full Wine rebuild' + diff -r --no-dereference "$tmp/release-wine" "$wine" >/dev/null || + fail "the release change modified the installed Wine tree" + [ ! -e "$FULL_REBUILD_MARKER" ] || fail "the release change started a full rebuild" + export CROSSOVER_VERSION=26.0.1 + + printf '%s\n' "${current_stamp#*:}" > "$wine/.victory-patches" + if run_builder --can-update-in-place; then fail "classifier accepted an unversioned CrossOver stamp"; fi + if run_builder --incremental-only; then fail "incremental builder accepted an unversioned CrossOver stamp"; fi + assert_output 'full rebuild' + printf '%s\n' "$current_stamp" > "$wine/.victory-patches" + ;; +esac + +rm "$installed/wine/x86_64-windows/dxgi.dll" +if setup; then fail "setup accepted an installed library tree with a missing DLL"; fi +assert_output "dxgi.dll" +assert_output "GPTK_DMG" +echo "GPTK setup checks passed" diff --git a/tools/macos/tests/gptk-version.sh b/tools/macos/tests/gptk-version.sh new file mode 100644 index 000000000..5d5741421 --- /dev/null +++ b/tools/macos/tests/gptk-version.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu +tool_dir=$(cd "$(dirname "$0")/.." && pwd) +[ -f "$tool_dir/gptk-version.sh" ] || { echo "FAIL: no shared GPTK version check" >&2; exit 1; } +. "$tool_dir/gptk-version.sh" + +for version in 3.0 4.0b1 4.0b2 '' 4 4.0b 4.0b0 4.1b0 4.0beta3 '4.0 beta 3' '4\0560' '4.0b3+' '4.0 +4.1' 3.99b99; do + if gptk_version_supported "$version"; then + printf 'FAIL: accepted <%s>\n' "$version" >&2 + exit 1 + fi +done +for version in 4.0b3 4.0b10 4.0 4.1 4.1b1 4.0.1 5.0b1; do + gptk_version_supported "$version" || { echo "FAIL: rejected $version" >&2; exit 1; } +done +echo "GPTK version checks passed" diff --git a/tools/macos/victory.sh b/tools/macos/victory.sh index 2ef7dcd58..af991b0c0 100755 --- a/tools/macos/victory.sh +++ b/tools/macos/victory.sh @@ -25,14 +25,23 @@ if [ -z "${WINE:-}" ]; then [ -x "$WINE" ] || WINE="$HOME/Library/Caches/victory-macos/target/wine-cx/bin/wine" fi [ -x "$WINE" ] || { echo "no Wine at $WINE: run tools/macos/build-crossover-wine.sh first" >&2; exit 1; } -[ -d "$(dirname "$WINE")/../lib/external/D3DMetal.framework" ] || { - echo "D3DMetal is missing: copy the redist/lib folder of Apple's evaluation environment over $(dirname "$WINE")/../lib" >&2 +. tools/macos/gptk-version.sh +FRAMEWORK="$(dirname "$WINE")/../lib/external/D3DMetal.framework" +if [ ! -d "$FRAMEWORK" ]; then + echo "D3DMetal is missing at $FRAMEWORK. Run ./setup.sh with Apple's Game Porting Toolkit." >&2 exit 1 -} +fi +if ! version=$(gptk_framework_version "$FRAMEWORK"); then + version="unreadable ($FRAMEWORK/Resources/Info.plist)" +fi +if ! gptk_version_supported "$version"; then + echo "D3DMetal version $version is unsupported. Set GPTK_DMG to an Apple Game Porting Toolkit .dmg with D3DMetal 4.0b3 or newer and run ./setup.sh." >&2 + exit 1 +fi # The 64-thread argument clamp is compiled at build time with the DXC that # D3DMetal ships: CrossOver's own compiler refuses it, and without it the # one-thread form runs instead. A VICTORY_HELPER_DXC already set wins. -DXC_LIB="$(dirname "$WINE")/../lib/external/D3DMetal.framework/Versions/A/Resources/libdxcompiler.dylib" +DXC_LIB="$FRAMEWORK/Versions/A/Resources/libdxcompiler.dylib" if [ -z "${VICTORY_HELPER_DXC:-}" ] && [ -f "$DXC_LIB" ]; then # A build product of this checkout, as its target/ holds them. helper="$ROOT/target/dxc-d3dmetal"