diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index 05a3bac9..e9f6da5d 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -38,6 +38,8 @@ windows = { workspace = true, features = [ "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", + "Win32_Security", + "Win32_System_Threading", ] } [lints] diff --git a/crates/victory-shader/src/emit/first_lane_bench.rs b/crates/victory-shader/src/emit/first_lane_bench.rs new file mode 100644 index 00000000..7a0cfe82 --- /dev/null +++ b/crates/victory-shader/src/emit/first_lane_bench.rs @@ -0,0 +1,169 @@ +//! Matched GPU completion-time workloads for the embedded CODE first-lane proof. + +use super::halves_tests::{ + PROLOGUE, S_ENDPGM, compute_container, lower_halves_limited, native, store, +}; +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::{Options, translate_with}; +use crate::native::{NativeProgram, StageIo}; + +const THREADS: u32 = 128; +const GROUPS: u32 = 8192; +const WARMUP: usize = 3; +const SAMPLES: usize = 15; +const READS: u32 = 8; + +#[derive(Clone, Copy, Debug)] +enum Workload { + Embedded, + EightReads, + ScalarControl, + VaryingSource, +} + +fn program(workload: Workload) -> NativeProgram { + let mut words = PROLOGUE.to_vec(); + words.extend([ + 0x8F02_8701, // s_lshl_b32 s2, s1 (group id X), 7 + 0x4A22_0002, // v_add_nc_u32 v17, s2, v0 (global id) + 0x3420_2282, // v_lshlrev_b32 v16, 2, v17 (output byte address) + ]); + let pc = words.len(); + words.extend([ + 0xBEA0_1F00, // s_getpc_b64 s[32:33] + 0xF404_0390, // s_load_dwordx2 s[14:15], s[32:33], embedded data + 0xFA00_0000, + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + ]); + if matches!(workload, Workload::EightReads) { + words.extend([ + 0x7E02_0300, // v_mov_b32 v1, v0 + 0x7E08_0280, // v_mov_b32 v4, 0 + ]); + // Each read feeds a scalar branch and each taken edge contributes + // to the result. The source grows by the loaded dword at each site. + for site in 1..=READS { + words.extend([ + 0x4A08_080F, // v_add_nc_u32 v4, s15, v4 + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0xBF06_FF0C, // s_cmp_eq_u32 s12, literal + 16 * site, + 0xBF84_0001, // s_cbranch_scc0 next + 0x4A02_020C, // v_add_nc_u32 v1, s12, v1 + ]); + } + } else { + words.extend([ + 0x7E08_020F, // v_mov_b32 v4, s15 + match workload { + Workload::ScalarControl => 0xBE8C_030F, // s_mov_b32 s12, s15 + Workload::VaryingSource => 0x7E18_0500, // v_readfirstlane_b32 s12, v0 + _ => 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + }, + 0x7E02_020C, // v_mov_b32 v1, s12 + 0xBF06_900C, // s_cmp_eq_u32 s12, 16 + 0xBF84_0001, // s_cbranch_scc0 past + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + ]); + } + words.extend(store(1, 0)); + words.push(S_ENDPGM); + words[pc + 2] |= ((words.len() - pc - 1) * 4) as u32; + words.extend([0xABCD_0123, 16]); + let mut program = native(&words, true, THREADS, 0); + let StageIo::Cs(cs) = &mut program.io else { + unreachable!("compute fixture"); + }; + cs.rsrc2 |= 1 << 7; + program +} + +fn expected(workload: Workload, lane: u32) -> u32 { + match workload { + Workload::Embedded | Workload::ScalarControl => 17, + Workload::EightReads => lane + 16 * (1..=READS).sum::(), + Workload::VaryingSource => lane / 64 * 64, + } +} + +#[test] +#[ignore = "hardware GPU completion benchmark; run serially with the D3DMetal Wine runtime"] +fn embedded_code_first_lane_gpu_completion() { + assert!( + super::host::under_wine(), + "requires the D3DMetal Wine runtime" + ); + let hosts = Host::each_hardware(); + let (adapter, host) = hosts.first().expect("no hardware D3D12 device with SM 6.6"); + for workload in [ + Workload::Embedded, + Workload::EightReads, + Workload::ScalarControl, + Workload::VaryingSource, + ] { + let program = program(workload); + let bytes = compute_container(&program); + let lowered = + lower_halves_limited(&program, true, true, true, false).expect("lowering statistics"); + let translation_start = std::time::Instant::now(); + let shader = translate_with( + &bytes, + Options { + host_wave32: true, + narrow_waves: true, + halves_rendezvous: true, + ..Default::default() + }, + ) + .expect("production translation"); + let translation_us = translation_start.elapsed().as_micros(); + let (root, pso) = host + .compute_pipeline(&shader) + .expect("GPU pipeline creation"); + eprintln!( + "setup {workload:?} adapter={adapter:?} wave_size={:?} half_mask={} group_barriers={} dxil_bytes={} translation_us={translation_us}", + lowered.wave_size, + lowered.has_half_wave_mask, + lowered.barriers, + shader.dxil.len(), + ); + let bindings = Dispatch { + roots: vec![( + 0, + Root::Constants(vec![0; shader.user_data_dwords() as usize]), + )], + views: &[ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(GROUPS * THREADS), + ], + samplers: &[], + groups: [GROUPS, 1, 1], + }; + for sample in 0..WARMUP + SAMPLES { + let (outputs, duration) = host + .dispatch_timed(&root, &pso, &bindings) + .unwrap_or_else(|error| panic!("{workload:?} sample {sample}: {error}")); + assert_eq!(outputs.len(), 1, "{workload:?} UAV count"); + let output = &outputs[0]; + assert_eq!(output.len(), (GROUPS * THREADS) as usize); + for (thread, &word) in output.iter().enumerate() { + assert_eq!( + word, + expected(workload, thread as u32 % THREADS), + "{workload:?} sample {sample}, thread {thread}", + ); + } + if sample >= WARMUP { + eprintln!( + "sample {workload:?} {} {}", + sample - WARMUP, + duration.as_nanos(), + ); + } + } + } +} diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index d85a3593..8c775bd9 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -22,12 +22,12 @@ use crate::native::{ }; use crate::{gfx10, io, ir, resource, structure}; -const S_ENDPGM: u32 = 0xBF81_0000; +pub(super) const S_ENDPGM: u32 = 0xBF81_0000; const S_WAITCNT_LGKM: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) /// `s[40:43]`: the raw UAV at table dword 16 (s0 is the table's address). -const PROLOGUE: [u32; 5] = [ +pub(super) const PROLOGUE: [u32; 5] = [ 0xBE84_0300, // s_mov_b32 s4, s0 0xBE85_0380, // s_mov_b32 s5, 0 0xF408_0A02, @@ -36,7 +36,7 @@ const PROLOGUE: [u32; 5] = [ ]; /// `buffer_store_dword v, v16, s[40:43], 0 offen offset:`. -const fn store(vdata: u8, offset: u32) -> [u32; 2] { +pub(super) const fn store(vdata: u8, offset: u32) -> [u32; 2] { [0xE070_1000 | offset, 0x800A_0010 | (vdata as u32) << 8] } @@ -95,7 +95,7 @@ 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 { let range = |kind, table_offset_dwords, dwords| UsedResource { kind, root: RootType::Table, @@ -177,7 +177,7 @@ fn lower_halves( /// `limits` the program goes through the translation's own entry, where /// `literal` retries a refusal in whole-wave halves; without, `literal` /// takes a 64-thread wave64 program straight to the whole-wave translation. -fn lower_halves_limited( +pub(super) fn lower_halves_limited( native: &NativeProgram, host_wave32: bool, narrow_waves: bool, @@ -1221,6 +1221,214 @@ fn first_lane_of_a_buffer_load(offset: u32) -> Vec { w } +#[derive(Clone, Copy, Debug)] +enum ScalarFirstLane { + Code, + ShortTable, + Mutable, + Guarded, +} + +const SCALAR_FIRST_VALUE: u32 = 42; + +/// Read the second dword of an embedded scalar load, then use the first +/// lane in a scalar branch. Store the selected value under a mask, restore +/// EXEC, and repeat the store at the next dword for all lanes. +fn scalar_first_lane(mask: &[u32], source: ScalarFirstLane) -> Vec { + let mut words = PROLOGUE.to_vec(); + let pc = words.len(); + if matches!(source, ScalarFirstLane::Mutable) { + words.extend([ + 0xF408_0B02, + 0xFA00_0020, // s_load_dwordx4 s[44:47], s[4:5], 0x20 + S_WAITCNT_LGKM, + 0xF420_03D6, + 0xFA00_0000, // s_buffer_load_dword s15, s[44:47], 0 + ]); + } else { + words.extend([ + 0xBEA0_1F00, // s_getpc_b64 s[32:33] + 0xF404_0390, + 0xFA00_0000, // s_load_dwordx2 s[14:15], s[32:33], + ]); + } + words.extend([ + S_WAITCNT_LGKM, + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + ]); + if matches!(source, ScalarFirstLane::Guarded) { + words.push(0x7E08_0287); // v_mov_b32 v4, 7 (inactive lanes retain this) + words.extend(MASK_LANES_40_41); + words.extend([ + 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc + 0x7E08_020F, // v_mov_b32 v4, s15 + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + ]); + } else { + words.push(0x7E08_020F); // v_mov_b32 v4, s15 + } + words.extend(mask); + words.extend([ + 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + 0x7E0A_020C, // v_mov_b32 v5, s12 + 0x7E0C_020C, // v_mov_b32 v6, s12 (raw result) + 0xBF06_AA0C, // s_cmp_eq_u32 s12, 42 + 0xBF85_0001, // s_cbranch_scc1 (skip replacing v5) + 0x7E0A_0288, // v_mov_b32 v5, 8 + 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc + ]); + words.extend(store(5, 0)); + words.push(0xBEFE_0400); // s_mov_b64 exec, s[0:1] + words.extend(store(5, 4)); + words.extend(store(6, 8)); + words.push(S_ENDPGM); + if !matches!(source, ScalarFirstLane::Mutable) { + words[pc + 2] |= ((words.len() - pc - 1) * 4) as u32; + words.push(71); + if !matches!(source, ScalarFirstLane::ShortTable) { + words.push(SCALAR_FIRST_VALUE); + } + } + words +} + +pub(super) fn compute_container(program: &NativeProgram) -> Vec { + let part = crate::native::tests::compute_part(program); + super::container::build(&[(b"DXIL", &part)]) +} + +#[test] +fn bounded_code_scalar_load_removes_only_the_proven_exchange() { + for threads in [64, 96, 128] { + for (source, wave_size) in [ + (ScalarFirstLane::Code, None), + (ScalarFirstLane::ShortTable, Some(32)), + (ScalarFirstLane::Mutable, Some(32)), + (ScalarFirstLane::Guarded, Some(32)), + ] { + let n = native( + &scalar_first_lane(&MASK_LANES_12_44, source), + true, + threads, + 0, + ); + let l = lowered_with(&n, true, true).expect("translated"); + assert_eq!(l.wave_size, wave_size, "{source:?}, {threads} threads"); + assert_eq!( + l.barriers == 0, + wave_size.is_none(), + "{source:?}, {threads} threads" + ); + let shader = super::translate_with(&compute_container(&n), scalar_first_lane_options()) + .expect("production translation"); + let dxil = crate::dxbc::Container::parse(&shader.dxil).expect("emitted container"); + let psv = dxil.part(crate::dxbc::FourCC::PSV0).expect("compute runtime info"); + // The runtime-info size prefix occupies the first four bytes. + let min_wave = u32::from_le_bytes(psv.data[20..24].try_into().unwrap()); + let max_wave = u32::from_le_bytes(psv.data[24..28].try_into().unwrap()); + assert_eq!( + (min_wave, max_wave), + wave_size.map_or((0, u32::MAX), |width| (width, width)), + "{source:?}, {threads} threads" + ); + } + } +} + +fn scalar_first_lane_options() -> super::Options { + super::Options { + host_wave32: true, + narrow_waves: true, + halves_rendezvous: true, + ..super::Options::default() + } +} + +/// Explicit hardware acceptance. Missing devices, pipelines and readbacks +/// all fail this test. Fixture outputs are derived from console lane order. +#[test] +#[ignore = "requires a D3D12 hardware device with 32-lane waves"] +#[cfg(windows)] +fn bounded_code_scalar_first_lane_gpu() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let host = Host::new(false).expect("D3D12 hardware device"); + assert!( + host.wave32().expect("hardware wave width"), + "requires wave32 hardware" + ); + let mut dispatches = 0; + let mut checked = 0; + for threads in [64u32, 96, 128] { + for (mask, active) in [ + (&MASK_LANES_8_9, (|t| t >> 1 == 4) as fn(u32) -> bool), + (&MASK_LANES_40_41, |t| t >> 1 == 20), + (&MASK_LANES_12_44, |t| t & 31 == 12), + (&MASK_EMPTY, |_| false), + ] { + for source in [ + ScalarFirstLane::Code, + ScalarFirstLane::Mutable, + ScalarFirstLane::Guarded, + ] { + let n = native(&scalar_first_lane(mask, source), true, threads, 0); + let shader = + super::translate_with(&compute_container(&n), scalar_first_lane_options()) + .expect("production translation"); + let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline"); + let input = [SCALAR_FIRST_VALUE, 0, 0, 0]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![( + 0, + Root::Constants(vec![0; shader.user_data_dwords().max(1) as usize]), + )], + views: &[ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &input, + stride: Stride::Structured(16), + }, + View::RawUav(threads * 8), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch and readback"); + let mut expected = Vec::new(); + for t in 0..threads { + let wave_start = t & !63; + let first = (wave_start..(wave_start + 64).min(threads)) + .find(|&lane| active(lane)) + .unwrap_or(wave_start); + let raw = if matches!(source, ScalarFirstLane::Guarded) && first >> 1 != 20 { + 7 + } else { + SCALAR_FIRST_VALUE + }; + let value = if raw == SCALAR_FIRST_VALUE { raw } else { 8 }; + expected.extend([if active(t) { value } else { 0 }, value, raw, 0, 0, 0, 0, 0]); + } + assert_eq!( + out, + [expected], + "{source:?}, {threads} threads, mask {mask:x?}" + ); + dispatches += 1; + checked += threads * 8; + } + } + } + eprintln!("{dispatches} hardware dispatches, {checked} checked dwords"); +} + /// Per thread `l` of a group of 128 (two console wave64s), two dwords at /// `l * 32`: the first lane of `l >> 6` (one value per console wave, the /// same in both its halves) and the lane `v_mbcnt` counts. diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index caa907fa..60154167 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1562,6 +1562,28 @@ impl Host { pso: &ID3D12PipelineState, d: &Dispatch, ) -> Result>, String> { + self.dispatch_with_timing(root, pso, d, false).map(|(out, _)| out) + } + + /// Measures command-list submission through fence completion. The list + /// includes upload/clear commands and UAV copies. Pipeline creation, + /// command-list recording and CPU readback are outside this interval. + pub fn dispatch_timed( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Dispatch, + ) -> Result<(Vec>, std::time::Duration), String> { + self.dispatch_with_timing(root, pso, d, true) + } + + fn dispatch_with_timing( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Dispatch, + event_wait: bool, + ) -> Result<(Vec>, std::time::Duration), String> { let _guard = self.lock_warp(); let dev = &self.device; // SAFETY: D3D12 calls with descriptions that outlive them; resources @@ -2163,13 +2185,19 @@ impl Host { } } list.Close().map_err(err)?; - let submitted = std::time::Instant::now(); - queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let commands = [Some(list.cast().map_err(err)?)]; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; - queue.Signal(&fence, 1).map_err(err)?; - wait_done(dev, &fence)?; - if std::env::var_os("VICTORY_NARROW_EXEC_TIMING").is_some() { - eprintln!("NARROW_EXEC_SAMPLE_NS {}", submitted.elapsed().as_nanos()); + let narrow_timing = std::env::var_os("VICTORY_NARROW_EXEC_TIMING").is_some(); + let completion = if event_wait || narrow_timing { + submit_and_time(dev, &queue, &commands, &fence)? + } else { + queue.ExecuteCommandLists(&commands); + queue.Signal(&fence, 1).map_err(err)?; + wait_done(dev, &fence)?; + std::time::Duration::ZERO + }; + if narrow_timing { + eprintln!("NARROW_EXEC_SAMPLE_NS {}", completion.as_nanos()); } let mut out = Vec::new(); for (_, size, n, rb) in &uavs { @@ -2195,11 +2223,44 @@ impl Host { out.push(words); } drop(keep); - Ok(out) + Ok((out, completion)) } } } +/// Use a fence event for timing rather than yield-polling the fence, which +/// can add scheduler delays after the GPU has completed. +#[cfg(test)] +fn submit_and_time( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + commands: &[Option], + fence: &ID3D12Fence, +) -> Result { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + // SAFETY: the event and command objects live through fence completion. + unsafe { + let event = CreateEventW(None, false, false, None).map_err(err)?; + let result = (|| { + fence.SetEventOnCompletion(1, event).map_err(err)?; + let start = std::time::Instant::now(); + queue.ExecuteCommandLists(commands); + queue.Signal(fence, 1).map_err(err)?; + let wake = WaitForSingleObject(event, GPU_DEADLINE.as_millis() as u32); + let duration = start.elapsed(); + dev.GetDeviceRemovedReason().map_err(err)?; + if wake != WAIT_OBJECT_0 || fence.GetCompletedValue() < 1 { + return Err(format!("GPU completion wait failed: {wake:?}")); + } + Ok(duration) + })(); + let _ = CloseHandle(event); + result + } +} + /// How long a test's GPU work may take before it counts as never done. const GPU_DEADLINE: std::time::Duration = std::time::Duration::from_secs(60); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ceb84533..e04fc197 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5595,14 +5595,7 @@ impl<'a> Lower<'a> { else { return Err("a scalar load"); }; - let count = match inst.name().strip_prefix("s_load_dword") { - Some("") => 1u32, - Some("x2") => 2, - Some("x4") => 4, - Some("x8") => 8, - Some("x16") => 16, - _ => return Err("a scalar load from the code"), - }; + let count = smem_dwords(inst.name()).ok_or("a scalar load from the code")?; let c = self.cur; let mut addr = self.s.m.i32(a.offset); if let Some(d) = a.dynamic { diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 3e41df40..a927c90e 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -1012,7 +1012,7 @@ pub(super) fn lane_uniform(x: &Parts) -> HashSet { let per_lane = |v: Value| x.res.waterfall.reads.contains(&v); // Scalar SSA values the same in every lane of a console wave, proven the // same way: a root parameter's dword on entry (a root constant, a user - // SGPR), grown by [`SCALAR_ALOP`] over such values in the fixed point. + // SGPR), fixed code-table loads, and [`SCALAR_ALOP`] over such values. let mut same_s: HashSet = x.res.params.iter().map(|&(v, _, _)| v).collect(); // Whether any instruction writes memory a `global_load_dword*` can read // (a global, flat, buffer or image store or atomic, or a scalar store, @@ -1065,6 +1065,33 @@ pub(super) fn lane_uniform(x: &Parts) -> HashSet { // title-memory address, so a root descriptor is not one. Every dword a // `global_load_dword*` at that address loads is covered by the table. let is_code = |site: Site| matches!(addr_of.get(&site), Some(Address { param: CODE, .. })); + // Fixed loads from the private code table are independent of all + // title-memory stores. Require the entire load to fit: code_dword's + // out-of-range clamping does not establish the console's value. + let fixed_code_load = |inst: &Inst, site: Site| { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return false; + }; + let Some(Address { + param: CODE, + offset, + dynamic: None, + }) = addr_of.get(&site) + else { + return false; + }; + offset.is_multiple_of(4) + && smem_dwords(inst.name()).is_some_and(|count| { + u32::from(code) + count <= u32::from(VCC) + && offset + .checked_add(4 * count) + .is_some_and(|end| end as usize <= x.native.code.len()) + }) + }; let mut tid_aliases: HashSet = wave_tid.into_iter().collect(); for block in &p.blocks { for inst in &block.insts { @@ -1318,6 +1345,14 @@ pub(super) fn lane_uniform(x: &Parts) -> HashSet { if writes_global && !pure_ok { continue; } + // The fixed address needs no input equality. The load still + // needs to run together in both halves before its SSA result + // can feed the scalar and vector uniformity rules. + if st.guards[b][i].is_none() && pure_wave_all[b] && fixed_code_load(inst, (b, i)) { + next_s.extend(inst.writes.iter().filter_map(|&(r, v)| { + matches!(r, Reg::S(code) if code < VCC).then_some(v) + })); + } // A whitelisted scalar op over values every lane holds alike // (and constants) writes a scalar every lane holds alike. A // missing read or an unwhitelisted def is unknown, not alike: diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs index 14263785..896f94fd 100644 --- a/crates/victory-shader/src/emit/lower/tests.rs +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -3910,6 +3910,32 @@ fn a_global_load_from_the_code_table_stays_uniform_with_a_store_present() { ); } +#[test] +fn a_fixed_code_smem_load_avoids_halves_only_when_the_whole_load_is_in_bounds() { + let mut w = vec![0xBE80_1F00]; // s_getpc_b64 s[0:1] (PC = byte 4) + w.extend(smem(1, 4, 0, 44, None)); // s_load_dwordx2 s[4:5], s[0:1], 44 + w.extend([ + 0xBF8C_0000, // s_waitcnt lgkmcnt(0) + 0x7E02_0205, // v_mov_b32 v1, s5 (the second dword) + 0x7E0C_0501, // v_readfirstlane_b32 s6, v1 + 0xBF06_8006, // s_cmp_eq_u32 s6, 0 + 0xBF85_0003, // s_cbranch_scc1 to s_endpgm + V_LSHLREV_V1_2_V0, + ]); + w.extend(global_store(0, 1, 2, 0)); // global_store_dword v0, v1, s[2:3], 0 + w.push(S_ENDPGM); + assert_eq!(w.len() * 4, 48, "the scalar load starts at the table"); + w.extend([0x1111_1111, 0x2222_2222]); + let in_bounds = lower_halves(&w).expect("a bounded code-table load lowers"); + assert_eq!(in_bounds.wave_size, None); + assert_eq!(in_bounds.shape.barriers, 0); + + w.pop(); // same starting address, but the second dword falls past the code + let out_of_bounds = lower_halves(&w).expect("the existing code-table clamp still lowers"); + assert_eq!(out_of_bounds.wave_size, Some(32)); + assert!(out_of_bounds.shape.barriers > 0); +} + /// Where the shader also stores (here a `global_store_dword`), a /// `buffer_load_dword` result is not lane-uniform: the console wave's two /// host waves can observe the store to the loaded buffer at different times diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index dba7eb70..03ccf8d6 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -252,6 +252,8 @@ mod crosslane_tests; #[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] +mod first_lane_bench; +#[cfg(all(test, windows))] mod flow_tests; #[cfg(all(test, windows))] mod halves_tests; diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 2a16ac1d..b227b5a9 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -892,6 +892,82 @@ pub(crate) mod tests { out } + /// DXIL part carrying an original compute program for end-to-end translator tests. + #[cfg(windows)] + pub(crate) fn compute_part(program: &NativeProgram) -> Vec { + assert_eq!(program.stage, HwStage::Cs); + let StageIo::Cs(io) = &program.io else { + panic!("expected compute inputs"); + }; + let mut blob = fssm(&[(HwStage::Cs, &program.code)]); + let stage = stage_data_at(&blob, HwStage::Cs); + let record = stage - RECORD_SIZE as usize; + let set_u32 = |blob: &mut [u8], at: usize, value: u32| { + blob[at..at + 4].copy_from_slice(&value.to_le_bytes()); + }; + let set_u64 = |blob: &mut [u8], at: usize, value: u64| { + blob[at..at + 8].copy_from_slice(&value.to_le_bytes()); + }; + set_u32(&mut blob, record + RECORD_REGS, u32::from(program.vgprs)); + set_u32( + &mut blob, + record + RECORD_FLAGS, + if program.wave64 { 0 } else { FLAG_WAVE32 }, + ); + set_u32(&mut blob, stage + CS_RSRC2, io.rsrc2); + for (i, &n) in io.threads.iter().enumerate() { + set_u32(&mut blob, stage + CS_THREADS + 4 * i, n); + } + let root_kind = |kind: RootType| match kind { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 3, + _ => panic!("unsupported test root kind {kind:?}"), + }; + let layout = (blob.len() - FSSM_HEADER) as u64; + for entry in &program.layout { + for word in [ + u32::from(root_kind(entry.root)), + entry.table_offset_dwords, + entry.sgprs, + entry.base_register, + ] { + blob.extend(word.to_le_bytes()); + } + blob.extend([entry.user_data, entry.slot, 0, 0]); + } + let used = (blob.len() - FSSM_HEADER) as u64; + for entry in &program.used { + let kind = match entry.kind { + ResourceType::Srv => 0, + ResourceType::Sampler => 1, + ResourceType::Cbv => 2, + ResourceType::Uav => 3, + ResourceType::Other(n) => n, + }; + blob.extend([kind, root_kind(entry.root), 0, 0]); + for word in [entry.table_offset_dwords, entry.lower_bound, entry.stride] { + blob.extend(word.to_le_bytes()); + } + blob.extend([entry.dwords, entry.user_data, entry.slot, 0]); + } + let payload = (blob.len() - FSSM_HEADER) as u64; + set_u64(&mut blob, 8, payload); + set_u64(&mut blob, record + RECORD_LAYOUT, layout); + set_u64(&mut blob, record + RECORD_USED, used); + set_u32( + &mut blob, + record + RECORD_COUNTS, + program.layout.len() as u32, + ); + set_u32( + &mut blob, + record + RECORD_COUNTS + 4, + program.used.len() as u32, + ); + part(&[(KIND_NATIVE, &xbch(&blob))]) + } + #[test] fn finds_graphics_programs() { let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]));