diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..04893416e3 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,46 @@ +# A pull request with no activity for 3 days gets the `stale` label and a comment, and is closed +# 4 days later (a week in all, as in CONTRIBUTING.md) unless something happens on it. Issues are +# left alone. PRs labelled `goal:world-load` or `keep-open` are never touched. +name: Stale PRs + +on: + schedule: + - cron: "17 */6 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Only log what would be done + type: boolean + default: true + +permissions: + actions: write # where the last run stopped is kept in the cache + issues: read + pull-requests: write + +concurrency: + group: stale + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 + with: + days-before-issue-stale: -1 + days-before-issue-close: -1 + days-before-pr-stale: 3 + days-before-pr-close: 4 + stale-pr-label: stale + exempt-pr-labels: goal:world-load,keep-open + sort-by: updated + ascending: true + operations-per-run: 300 + debug-only: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} + stale-pr-message: >- + Nothing has happened on this PR for 3 days, so it is marked `stale` and will be closed in + 4 days. A push or a comment takes the mark off: rebase it onto `main` if it conflicts, and + say in one line what it still fixes. If it only waits for a maintainer, a comment saying so is enough. + close-pr-message: >- + Closed after a week with no activity. This is not a verdict on the code: if it still applies to + `main`, rebase it, say so here and it can be reopened. diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index caf2ef4c7e..64a6b08bd3 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -20,6 +20,16 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/xbox.rs", ]; +/// The per-lane form's sources (`XCL_PER_LANE`): part of only its own cache entries' identity, +/// so editing them does not invalidate the HLSL path's. +const PER_LANE_SOURCES: &[&str] = &[ + "src/gpu/recomp/lane_masks.rs", + "src/gpu/recomp/lower.rs", + "src/gpu/recomp/lower/wave.rs", + "src/gpu/recomp/lower_dxil.rs", + "src/gpu/recomp/ssa.rs", +]; + fn add(h: &mut u64, bytes: &[u8]) { for &byte in bytes { *h ^= byte as u64; @@ -48,4 +58,13 @@ fn main() { add(&mut h, &[0]); } println!("cargo:rustc-env=XCL_TRANSLATOR_SOURCE_ID={h:016x}"); + let mut p = 0xcbf2_9ce4_8422_2325u64; + for relative in PER_LANE_SOURCES { + println!("cargo:rerun-if-changed={relative}"); + add(&mut p, relative.as_bytes()); + add(&mut p, &[0]); + add(&mut p, &std::fs::read(root.join(relative)).expect("read per-lane source")); + add(&mut p, &[0]); + } + println!("cargo:rustc-env=XCL_PER_LANE_SOURCE_ID={p:016x}"); } diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a754a072a5..9e872ccaba 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -279,3 +279,107 @@ fn graphics_stages_with_a_branch_before_their_exports() { assert_eq!(draw(&dvs, &dps, 0), cleared, "branch not taken"); assert_eq!(draw(&dvs, &dps, 1), kept, "branch taken"); } + +/// Exhaustive bit-exact check of the IEEE-754 bit-manipulation formula used by +/// `lower_mem::uf_small_bits` for all 10-bit (mb=5) and 11-bit (mb=6) float inputs. +#[test] +fn uf_small_ieee_bit_math_matches_exact_formula() { + for mb in [5u32, 6u32] { + let p = 1u32 << mb; + let mmask = p - 1; + let mshift = 23 - mb; + let den_scale = f32::from_bits(if mb == 6 { 0x3580_0000 } else { 0x3600_0000 }); + for v in 0..(1u32 << (mb + 5)) { + let e = v >> mb; + let m = v & mmask; + // Reference formula (matching HLSL `uf_small`) + let fm = (m as f32) / (p as f32); + let ref_f = if e == 31 { + f32::from_bits(if m != 0 { 0x7FC0_0000 } else { 0x7F80_0000 }) + } else if e == 0 { + fm * (-14.0f32).exp2() + } else { + ((e as f32) - 15.0).exp2() * (1.0 + fm) + }; + // Exact IEEE bit math + let got_bits = if e == 31 { + if m != 0 { 0x7FC0_0000 } else { 0x7F80_0000 } + } else if e == 0 { + ((m as f32) * den_scale).to_bits() + } else { + ((e + 112) << 23) | (m << mshift) + }; + assert_eq!(got_bits, ref_f.to_bits(), "mb={mb} v={v:#x} (e={e} m={m})"); + } + } +} + +/// Multi-window switch dispatch, vector rawBufferLoad/Store, hoisted FormatLoad +/// descriptors, single/multi-component FormatLoad, and hoisted BVH loads all pass +/// DXIL validation across 1..=4 memory windows and wave configurations. +#[test] +fn multi_window_mem_format_and_bvh_validate() { + let code = prog(&[ + // Load descriptor s[12:15] once, then reuse across repeated BUFFER_LOAD_FORMAT_X + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 0), ("OFFSET", 0x40), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16), ("SBASE", 0), ("OFFSET", 0x80), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 12), ("OFFSET", 0x10), ("SOFFSET", 125)], None), + // Divergent EXEC so lane guards are active (non-constant `act`) + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + // Repeated single-component format loads sharing s[12:15] (exercises hoisted FmtComp1 + Load2) + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 5), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + // Sub-4 and full-4 component format loads + D16 + static MTBUF + small byte load + ("BUFFER_LOAD_FORMAT_XY", "ENC_MUBUF", &[("VDATA", 6), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 8), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 12), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_HI_X", "ENC_MUBUF", &[("VDATA", 12), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("TBUFFER_LOAD_FORMAT_X", "ENC_MTBUF", &[("VDATA", 13), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("FORMAT", 28), ("IDXEN", 1)], None), + ("BUFFER_LOAD_UBYTE", "ENC_MUBUF", &[("VDATA", 14), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + // Vector MUBUF & FLAT loads/stores + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_STORE_DWORDX4", "ENC_MUBUF", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("GLOBAL_LOAD_DWORDX4", "ENC_FLAT_GLBL", &[("VDST", 20), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("DATA", 20), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 16)], None), + ("GLOBAL_LOAD_USHORT", "ENC_FLAT_GLBL", &[("VDST", 24), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 4)], None), + // BVH node intersection (box32 / box16 / tri hoisted vector loads) + ("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 28), ("VADDR", 0), ("SRSRC", 3), ("DMASK", 0xF)], None), + ]); + for windows in [1u32, 2, 3, 4] { + for (wave64, split) in [(true, false), (false, false)] { + translate(&code, KernelOptions { wave64, split, mem_windows: windows, sampler_base: 0 }) + .unwrap_or_else(|e| panic!("w={windows} wave64={wave64}: {}", &e[..e.len().min(800)])); + if windows > 1 { + translate(&code, KernelOptions { wave64, split, mem_windows: windows | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) + .unwrap_or_else(|e| panic!("heap w={windows} wave64={wave64}: {}", &e[..e.len().min(800)])); + } + } + } +} + +/// `image_get_lod` with a static sampler (an S# built from constants in the code) translates +/// to `CalculateLevelOfDetail` on the sampler bound at `s, space1`, shared with a sample of +/// the same S#, and validates. +#[test] +fn ps_get_lod_with_a_static_sampler() { + use crate::gpu::recomp::{Mode, PsInterface}; + let clamp = 2 | 2 << 3 | 2 << 6; + let linear = [clamp, 0x00FF_F000u32, 1 << 20 | 1 << 22, 0]; + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, &w) in linear.iter().enumerate() { + list.push(if w == 0 { ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 24 + k as u64), ("SSRC0", 128)], None) } else { ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 24 + k as u64), ("SSRC0", 255)], Some(w)) }); + } + // uv = (I, J) of the first barycentric pair (v0, v1); T# s[16:23], S# s[24:27] + list.push(("IMAGE_GET_LOD", "ENC_MIMG", vec![("VDATA", 4), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x3), ("DIM", 1)], None)); + list.push(("IMAGE_SAMPLE", "ENC_MIMG", vec![("VDATA", 6), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x3), ("DIM", 1)], None)); + list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); + if crate::gpu::recomp::dxc::location().is_ok() { + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + } +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 62c7a84ec7..f1aa9b2db5 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -123,12 +123,23 @@ pub struct Report { pub times_us: Vec, /// (direct DXIL bytes, HLSL-path DXIL bytes) for programs both paths produced pub sizes: Vec<(usize, usize)>, + /// the slowest programs: (microseconds, program), slowest first, at most [`SLOWEST`] + pub slowest: Vec<(u64, String)>, } +/// How many of the slowest programs a [`Report`] keeps. +pub const SLOWEST: usize = 10; + impl Report { pub fn add(&mut self, name: &str, s: &Sample) { let c = self.stages.entry(s.stage).or_default(); - self.times_us.push(s.time.as_micros() as u64); + let us = s.time.as_micros() as u64; + self.times_us.push(us); + if self.slowest.len() < SLOWEST || self.slowest.last().is_some_and(|l| l.0 < us) { + let at = self.slowest.partition_point(|l| l.0 >= us); + self.slowest.insert(at, (us, name.to_string())); + self.slowest.truncate(SLOWEST); + } match &s.result { Ok(size) => { c.translated += 1; @@ -186,6 +197,10 @@ impl Report { row(&mut s, "all", &self.total()); let (p50, p95, max) = self.time_percentiles(); s.push_str(&format!(" translation time per program: p50 {:.2} ms, p95 {:.2} ms, max {:.2} ms\n", p50 as f64 / 1e3, p95 as f64 / 1e3, max as f64 / 1e3)); + for (us, name) in &self.slowest { + s.push_str(&format!(" slow: {:>9.2} ms {name} +", *us as f64 / 1e3)); + } if !self.sizes.is_empty() { let (d, h): (usize, usize) = self.sizes.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); s.push_str(&format!(" DXIL size, {} programs: direct {} B, HLSL+DXC {} B (direct/HLSL {:.2})\n", self.sizes.len(), d, h, d as f64 / h.max(1) as f64)); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index efcf15a00c..2b8d3e44cd 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -17,6 +17,7 @@ use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR use super::module::{Block, Pred, Value}; use super::shader::{RawUav, Shader}; use super::ssa::Ssa; +use crate::gpu::rdna2::Decoded; use crate::gpu::recomp::{CsInterface, MsInterface, PsInterface, VsInterface, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; #[derive(Debug, Clone, Copy)] @@ -36,7 +37,7 @@ pub struct KernelOptions { /// Version of the direct translator's output, part of the on-disk translation cache's /// identity (`recomp::pso`): bump it on any change that alters the emitted containers /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 5; +pub const TRANSLATOR_VERSION: u32 = 6; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. @@ -87,7 +88,7 @@ pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Resul /// The entry ABI. #[derive(Clone)] -enum Entry { +pub enum Entry { Kernel, Compute(CsInterface), Mesh(MsInterface), @@ -132,120 +133,14 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Result { let cfg = Cfg::build(code)?; - let split = o.wave64 && o.split; let kernel = matches!(entry, Entry::Kernel); - let cs = match &entry { - Entry::Compute(cs) => Some(cs.clone()), - _ => None, - }; - let ms = match &entry { - Entry::Mesh(ms) => Some(ms.clone()), - _ => None, - }; let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); - let split = split && !gfx; - let stage = match &entry { - Entry::Vertex(_) => Stage::Vertex, - Entry::Pixel(_) => Stage::Pixel, - _ => Stage::Compute, - }; - let mut s = Shader::new(stage, (6, 6)); - let io = s.raw_uav(0, 0); - let res = if kernel || ms.is_some() { Some(s.raw_uav(1, 0)) } else { None }; - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); - let i32 = s.m.i32(); - let z = s.m.i32c(0); - let mut lw = Lw { - s, - ssa: Ssa::new(i32), - init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, - wave64: o.wave64, - split, - lane: z, - lane31: z, - upper: z, - half: z, - mems, - heap_mem, - res, - fmt_table: None, - ntmp: 0, - scratch: None, - static_samplers: Default::default(), - static_used: Vec::new(), - sampler_base: o.sampler_base, - dyn_rm: false, - has_f64_round_op: false, - exec_cache: HashMap::new(), - xs: None, - xw: None, - xc: None, - waves: 1, - cw: z, - xn: z, - xslot: 1, - lds: None, - lds_top: 8191, - dpp_enable: None, - partner: Partner::Present, - mesh: None, - gfx: None, - gfx_half: None, - whole_live: Default::default(), - guard_override: None, - mask_override: None, - exchange_error: None, - pc: 0, - }; - { - let Lw { s, ssa, init, .. } = &mut lw; - ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); - } - // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, - // 32 for ds_bpermute), as the HLSL kernel sizes them - let mut uses_lds = false; - let mut slot = 1u32; - for d in &cfg.insts { - let n = d.inst.name; - if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { - uses_lds = true; - } - if n == "DS_BPERMUTE_B32" { - slot = slot.max(32); - } - if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { - let w = match n.rsplit('_').next().unwrap_or("") { - "DWORDX2" => 2, - "DWORDX4" => 4, - "DWORDX8" => 8, - "DWORDX16" => 16, - _ => 1, - }; - slot = slot.max(w); - } - } + let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); - lw.static_samplers = crate::gpu::recomp::constant_samplers(&cfg.insts, &leaders); - let group_threads: Option = match &entry { - Entry::Vertex(_) | Entry::Pixel(_) => None, - Entry::Kernel => None, - Entry::Compute(cs) => Some(cs.threads.iter().product()), - Entry::Mesh(ms) => Some(ms.threads), - }; - if let (Some(t), true) = (group_threads, split) { - lw.waves = t.div_ceil(64).max(1); - } - if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { - lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(&cfg.insts, kernel); - } - lw.setup_storage(uses_lds, if split { slot } else { 1 }); - if let (Some(t), true) = (group_threads, split) { - lw.partner = match t { - 0..=32 => Partner::Missing, - 33..=64 => Partner::Present, - _ => Partner::Spin, - }; - } + let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + let uses_lds = lw.lds.is_some(); + let res = lw.res; + let io = lw.init.io.expect("the I/O buffer"); let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -361,25 +256,162 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu lw.s.m.ret(); lw.s.m.set_block(Block(0)); lw.s.m.br(h0); - if let Some(e) = lw.exchange_error.take() { - return Err(e); - } let hw = if split || !o.wave64 { 32 } else { 64 }; - let c = if gfx { - let g = lw.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; - lw.s.try_finish_graphics(g.io, info) - } else { - lw.s.try_finish(numthreads, Some(hw)) + lw.finish(numthreads, hw) +} + +impl Lw { + /// The translator's state for a program (`insts`, its blocks starting at `leaders`) at + /// `entry`: the shader with its buffers, + /// the SSA's entry block, the program's LDS and the split form's exchange storage and + /// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the + /// program's blocks, branches from `Block(0)` to the first of them and ends with + /// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's + /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. + pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry) -> Lw { + let split = o.wave64 && o.split; + let kernel = matches!(entry, Entry::Kernel); + let cs = match entry { + Entry::Compute(cs) => Some(cs.clone()), + _ => None, + }; + let ms = match entry { + Entry::Mesh(ms) => Some(ms.clone()), + _ => None, + }; + let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + let split = split && !gfx; + let stage = match entry { + Entry::Vertex(_) => Stage::Vertex, + Entry::Pixel(_) => Stage::Pixel, + _ => Stage::Compute, + }; + let mut s = Shader::new(stage, (6, 6)); + let io = s.raw_uav(0, 0); + let res = if kernel || ms.is_some() { Some(s.raw_uav(1, 0)) } else { None }; + let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); + let i32 = s.m.i32(); + let z = s.m.i32c(0); + let mut lw = Lw { + s, + ssa: Ssa::new(i32), + init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, + wave64: o.wave64, + split, + lane: z, + lane31: z, + upper: z, + half: z, + mems, + heap_mem, + res, + fmt_table: None, + fmt_desc_cache: HashMap::new(), + fmt_comp1_cache: HashMap::new(), + uma_base_val: None, + ntmp: 0, + scratch: None, + static_samplers: Default::default(), + static_used: Vec::new(), + sampler_base: o.sampler_base, + dyn_rm: false, + has_f64_round_op: false, + exec_cache: HashMap::new(), + xs: None, + xw: None, + xc: None, + waves: 1, + cw: z, + xn: z, + xslot: 1, + lds: None, + lds_top: 8191, + dpp_enable: None, + partner: Partner::Present, + mesh: None, + gfx: None, + gfx_half: None, + whole_live: Default::default(), + guard_override: None, + mask_override: None, + exchange_error: None, + pc: 0, + }; + { + let Lw { s, ssa, init, .. } = &mut lw; + ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); + } + // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, + // 32 for ds_bpermute), as the HLSL kernel sizes them + let mut uses_lds = false; + let mut slot = 1u32; + for d in insts { + let n = d.inst.name; + if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { + uses_lds = true; + } + if n == "DS_BPERMUTE_B32" { + slot = slot.max(32); + } + if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { + let w = match n.rsplit('_').next().unwrap_or("") { + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => 1, + }; + slot = slot.max(w); + } + } + lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders); + let group_threads: Option = match entry { + Entry::Vertex(_) | Entry::Pixel(_) => None, + Entry::Kernel => None, + Entry::Compute(cs) => Some(cs.threads.iter().product()), + Entry::Mesh(ms) => Some(ms.threads), + }; + if let (Some(t), true) = (group_threads, split) { + lw.waves = t.div_ceil(64).max(1); + } + if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { + lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); + } + lw.setup_storage(uses_lds, if split { slot } else { 1 }); + if let (Some(t), true) = (group_threads, split) { + lw.partner = match t { + 0..=32 => Partner::Missing, + 33..=64 => Partner::Present, + _ => Partner::Spin, + }; + } + lw } - .map_err(|e| format!("direct DXIL builder error: {e}"))?; - if cfg!(any(test, debug_assertions)) { - if let Err(e) = super::validate::validate(&c) { - let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); - return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + + /// The finished container and the static samplers the program bound, once every block + /// is closed: `numthreads` and the hardware wave size `hw` for a compute-like entry, the + /// stage's I/O for a VS / PS. + pub fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + if let Some(e) = self.exchange_error.take() { + return Err(e); + } + let stage = self.s.stage; + let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { + let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + self.s.try_finish_graphics(g.io, info) + } else { + self.s.try_finish(numthreads, Some(hw)) + } + .map_err(|e| format!("direct DXIL builder error: {e}"))?; + if cfg!(any(test, debug_assertions)) { + if let Err(e) = super::validate::validate(&c) { + let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); + return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + } } + Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } - Ok(Kernel { dxil: c, static_samplers: lw.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } /// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. @@ -412,7 +444,7 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { @@ -450,7 +482,7 @@ fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the /// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot, /// other VGPRs 0; and the record slots. -fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { +pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { let lanes: u32 = if lw.wave64 { 64 } else { 32 }; let l = lw.c(lanes); let wave = lw.bin(super::module::BinOp::UDiv, tid, l); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index cbb17b93bd..6f60192dc2 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -151,6 +151,12 @@ pub struct Lw { pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, + /// cached decoded format descriptors hoisted to `d3`'s defining block + pub fmt_desc_cache: HashMap<(Value, Option), super::lower_mem::FmtDesc>, + /// cached single-component format decode parameters hoisted to `d3`'s defining block + pub fmt_comp1_cache: HashMap<(Value, Option), super::lower_mem::FmtComp1>, + /// cached `IO_UMA_BASE_HI` loaded once in the entry block for multi-window address math + pub uma_base_val: Option, /// temporaries handed out (`lower_mem::VAR_TMP`) pub ntmp: u32, /// the lane's scratch array (an alloca in the entry block) diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index dc37a95569..9acee38a69 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -12,6 +12,28 @@ use super::ops_core::op; use crate::gpu::rdna2::{self, Decoded}; impl Lw { + /// The sampler of the MIMG at `pc`: a static sampler (bound at `s, space1` in order of + /// first use) when the console bound one there, else the heap sampler the S# indexes. + fn mimg_sampler(&mut self, pc: u64, has_c: bool, s3: Value) -> Sampler { + match self.static_samplers.get(&pc).copied() { + Some(w) => match self.static_used.iter().find(|u| u.0 == w && u.1 == has_c) { + Some(u) => u.2, + None => { + let k = self.static_used.len() as u32; + let cur = self.cur(); + self.s.m.set_block(self.init.entry); + let h = self.s.sampler(self.sampler_base + k, 1, has_c); + self.s.m.set_block(cur); + self.static_used.push((w, has_c, h)); + h + } + }, + None => { + let si = self.andc(s3, 0xFFF); + self.s.heap_sampler(si, has_c, true) + } + } + } fn f3(&mut self, a: [Value; 3], b: [Value; 3], op: fn(&mut Lw, Value, Value) -> Value) -> [Value; 3] { [op(self, a[0], b[0]), op(self, a[1], b[1]), op(self, a[2], b[2])] } @@ -32,15 +54,6 @@ impl Lw { let f32 = self.s.m.f32(); self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) } - fn load3f(&mut self, at: Value) -> [Value; 3] { - let mut r = [at; 3]; - for (k, slot) in r.iter_mut().enumerate() { - let a = self.addc(at, 4 * k as u32); - let v = self.mem_ld(a); - *slot = self.f(v); - } - r - } /// `bvh_intersect`: one BVH node → 4 result dwords (written to temporaries). #[allow(clippy::too_many_arguments)] @@ -52,27 +65,34 @@ impl Lw { for box32 in [true, false] { let is = self.cmpc(Pred::Eq, ty, if box32 { 5 } else { 4 }); self.guarded(is, &mut |lw| { - let mut child = [ones; 4]; - for (k, c) in child.iter_mut().enumerate() { - let a = lw.addc(at, 4 * k as u32); - *c = lw.mem_ld(a); - } + // Box32 is 28 contiguous dwords (4 children + 4×6 box floats); + // Box16 is 16 contiguous dwords (4 children + 4×3 packed f16 pairs). + // Load the whole node in one window switch using 4-dword rawBufferLoads. + let at_al = lw.andc(at, !3); + let chunks = if box32 { 7usize } else { 4usize }; + let words = lw.with_mem_i32s(None, chunks * 4, &mut |lw, m| { + let mut out = Vec::with_capacity(chunks * 4); + for j in 0..chunks { + let a = lw.addc(at_al, 16 * j as u32); + out.extend(lw.s.raw_load(m, a, 0xF)); + } + out + }); + let child = [words[0], words[1], words[2], words[3]]; let ninf = lw.s.m.f32c(0xFF80_0000); let pinf = lw.s.m.f32c(0x7F80_0000); let mut tn = [pinf; 4]; let mut id = [ones; 4]; - for k in 0..4u32 { + for k in 0..4usize { let (mn, mx) = if box32 { - let a = lw.addc(at, 16 + 24 * k); - let b = lw.addc(at, 28 + 24 * k); - (lw.load3f(a), lw.load3f(b)) + let b = 4 + 6 * k; + ( + [lw.f(words[b]), lw.f(words[b + 1]), lw.f(words[b + 2])], + [lw.f(words[b + 3]), lw.f(words[b + 4]), lw.f(words[b + 5])], + ) } else { - let a = lw.addc(at, 16 + 12 * k); - let mut h = [ones; 3]; - for (j, slot) in h.iter_mut().enumerate() { - let x = lw.addc(a, 4 * j as u32); - *slot = lw.mem_ld(x); - } + let b = 4 + 3 * k; + let h = [words[b], words[b + 1], words[b + 2]]; let hx16 = lw.lshrc(h[0], 16); let hy16 = lw.lshrc(h[1], 16); let hz16 = lw.lshrc(h[2], 16); @@ -102,7 +122,7 @@ impl Lw { let a = lw.fmax(a, lo[2]); let b = lw.fmin(hi[0], hi[1]); let b = lw.fmin(b, hi[2]); - let cv = lw.cmpc(Pred::Ne, child[k as usize], u32::MAX); + let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); let mut all = cv; for c in 0..3 { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); @@ -115,8 +135,8 @@ impl Lw { let hit = lw.land(all, ab); let x = lw.land(b0, at_); let hit = lw.land(hit, x); - tn[k as usize] = lw.sel(hit, a, pinf); - id[k as usize] = lw.sel(hit, child[k as usize], ones); + tn[k] = lw.sel(hit, a, pinf); + id[k] = lw.sel(hit, child[k], ones); } for (i, j) in [(0usize, 1usize), (2, 3), (0, 2), (1, 3), (1, 2)] { let lt = lw.fcmp(Pred::FOLt, tn[j], tn[i]); @@ -145,9 +165,20 @@ impl Lw { let p0 = lw.add(at, a0); let p1 = lw.add(at, a1); let p2 = lw.addc(at, 24); - let v0 = lw.load3f(p0); - let v1 = lw.load3f(p1); - let v2 = lw.load3f(p2); + let p60 = lw.addc(at, 60); + let (p0, p1, p2, p60) = (lw.andc(p0, !3), lw.andc(p1, !3), lw.andc(p2, !3), lw.andc(p60, !3)); + let words = lw.with_mem_i32s(None, 10, &mut |lw, m| { + let mut out = Vec::with_capacity(10); + out.extend(lw.s.raw_load(m, p0, 0x7)); + out.extend(lw.s.raw_load(m, p1, 0x7)); + out.extend(lw.s.raw_load(m, p2, 0x7)); + out.push(lw.s.raw_load(m, p60, 0x1)[0]); + out + }); + let v0 = [lw.f(words[0]), lw.f(words[1]), lw.f(words[2])]; + let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; + let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; + let tw = words[9]; let e1 = lw.f3(v1, v0, Lw::fsub); let e2 = lw.f3(v2, v0, Lw::fsub); let p = lw.cross(dir, e2); @@ -176,8 +207,6 @@ impl Lw { let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; - let p60 = lw.addc(at, 60); - let tw = lw.mem_ld(p60); let sh = lw.shlc(ty, 3); let tid = lw.shr_masked(tw, sh); let s0 = lw.andc(tid, 3); @@ -459,25 +488,7 @@ impl Lw { let ps = self.gfx.as_ref().is_some_and(|g| g.ps.is_some()); let spatial: Vec = coords[..kind.grads().min(coords.len())].to_vec(); let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); - let smp: Sampler = match self.static_samplers.get(&d.pc).copied() { - // the console's static samplers: bound at s, space1 in order of first use - Some(w) => match self.static_used.iter().find(|u| u.0 == w && u.1 == has_c) { - Some(u) => u.2, - None => { - let k = self.static_used.len() as u32; - let cur = self.cur(); - self.s.m.set_block(self.init.entry); - let h = self.s.sampler(self.sampler_base + k, 1, has_c); - self.s.m.set_block(cur); - self.static_used.push((w, has_c, h)); - h - } - }, - None => { - let si = self.andc(s3, 0xFFF); - self.s.heap_sampler(si, has_c, true) - } - }; + let smp: Sampler = self.mimg_sampler(d.pc, has_c, s3); if let Some(o) = ovgpr { // texel offset / size of the sampled mip (0 for lz / gather; else the LOD given, else 0) let level = match (&lod, has_lz || gather) { @@ -613,9 +624,6 @@ impl Lw { if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { return err(d, "image_get_lod outside PS"); } - if self.static_samplers.contains_key(&d.pc) { - return err(d, "image_get_lod with a static sampler"); - } let coords: Vec = (0..body as usize).map(|k| compf(self, i_body + k)).collect(); let spatial: Vec = match dim { 3 => self.cube_dir(coords[0], coords[1], coords[2]).to_vec(), @@ -623,8 +631,7 @@ impl Lw { }; let s3 = self.sreg(ssamp + 3); let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); - let si = self.andc(s3, 0xFFF); - let smp = self.s.heap_sampler(si, false, true); + let smp = self.mimg_sampler(d.pc, false, s3); let a = self.s.calculate_lod(tex, smp, &spatial, true); let b = self.s.calculate_lod(tex, smp, &spatial, false); let z = self.c(0); diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 97c0e3bd7f..609d1c7a2b 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -114,84 +114,271 @@ enum At { Lds(Value), } +/// Hoisted descriptor-level format info for `FormatLoad` / `FormatStore`. +#[derive(Clone, Copy)] +pub struct FmtDesc { + pub info: Value, + pub n: Value, + pub ty: Value, + pub isint: Value, + pub nb: Value, + pub has: Value, + pub t: [Value; 6], +} + +/// Hoisted single-component format decode parameters for `BUFFER_LOAD_FORMAT_X` +/// (and 1-component `d16` format loads), computed once in `d3`'s defining block. +#[derive(Clone, Copy)] +pub struct FmtComp1 { + pub desc: FmtDesc, + pub s0: Value, + pub s1: Value, + pub one_val: Value, + pub off_bytes: Value, + pub off_bits: Value, + pub big: Value, + pub sh: Value, + pub mu: Value, + pub maxu: Value, + pub maxs: Value, + pub w16: Value, + pub w32: Value, + pub mb: Value, + pub mmask: Value, + pub mshift: Value, + pub den_scale: Value, + pub cge: Value, + pub dflt: Value, +} + impl Lw { - /// Runs `f` on the memory window the last `window` selected (`mem`, `mem1`.. at u2..): - /// a switch over the windows when the program may address several, as the HLSL kernel's - /// `xcl_m*` accessors; returns `f`'s value (i32 or i64). - fn with_mem(&mut self, f: &mut dyn FnMut(&mut Lw, RawUav) -> Option) -> Option { + /// Runs `f` on the active memory window (`mem`, `mem1`.. at u2.., or descriptor heap + /// when `self.heap_mem` is set via `XCL_HEAP_WINDOWS`), returning `out_tys.len()` values + /// merged across the window arms via a single `switch` (or single guarded heap lookup) + /// and direct phis (`f` must not write SSA variables). Out-of-range windows (`w >= n`) + /// jump to `join` (reads 0, stores and atomics dropped), matching `#1693` semantics. + pub(crate) fn with_mem_many_tys( + &mut self, + mut guard: Option, + out_tys: &[super::module::Ty], + f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, + ) -> Vec { + if let Some(c) = guard { + match self.s.m.const_u64(c) { + Some(1) => guard = None, + Some(0) => return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(), + _ => {} + } + } + // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup + // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. if let Some(coherent) = self.heap_mem { - return self.with_heap_mem(coherent, f); + let windows = self.mems.len() as u32; + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, windows); + let cond = match guard { + Some(g) => self.and(g, inside), + None => inside, + }; + if self.s.m.const_u64(cond) == Some(0) { + return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(); + } + if self.s.m.const_u64(cond) == Some(1) { + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), out_tys.len()); + return vals; + } + let from = self.cur(); + let then = self.block(None); + let join = self.block(None); + self.cond_br(cond, then, join); + self.seal(then); + self.s.m.set_block(then); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + let end = self.cur(); + self.s.m.br(join); + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let z = self.s.m.const_int(ty, 0); + let phi = self.s.m.phi(ty); + self.s.m.add_incoming(phi, z, from); + self.s.m.add_incoming(phi, vals[j], end); + out.push(phi); + } + return out; } - if self.mems.len() <= 1 { - let m = self.mems[0]; - return f(self, m); + // Single window, or window known at translation time: at most one branch for `guard`. + let fixed_mem = if self.mems.len() <= 1 { + Some(self.mems[0]) + } else { + let w = self.rd(super::lower::VAR_WIN); + if let Some(k) = self.s.m.const_u64(w) { + if (k as usize) < self.mems.len() { + Some(self.mems[k as usize]) + } else { + return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(); + } + } else { + None + } + }; + if let Some(m) = fixed_mem { + let Some(cond) = guard else { + let vals = f(self, m); + debug_assert_eq!(vals.len(), out_tys.len()); + return vals; + }; + let from = self.cur(); + let then = self.block(None); + let join = self.block(None); + self.cond_br(cond, then, join); + self.seal(then); + self.s.m.set_block(then); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + let end = self.cur(); + self.s.m.br(join); + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let z = self.s.m.const_int(ty, 0); + let phi = self.s.m.phi(ty); + self.s.m.add_incoming(phi, z, from); + self.s.m.add_incoming(phi, vals[j], end); + out.push(phi); + } + return out; } + // Multi-window dispatch via a single LLVM `switch` (default -> `join` for out-of-range + // or inactive lane, matching `#1693` window semantics). let w = self.rd(super::lower::VAR_WIN); - let (tl, th) = (self.tmp_var(), self.tmp_var()); - let z = self.c(0); - self.wr(tl, z); - self.wr(th, z); - let mut kind = 0u8; // 0 none, 1 i32, 2 i64 let mems = self.mems.clone(); + let n = mems.len(); + let from = self.cur(); + let arms: Vec = (0..n).map(|_| self.block(None)).collect(); + let join = self.block(None); + let w_eff = if let Some(cond) = guard { + let skip = self.c(n as u32); + self.sel(cond, w, skip) + } else { + w + }; + let cases: Vec<(Value, super::module::Block)> = (0..n).map(|k| (self.c(k as u32), arms[k])).collect(); + self.s.m.switch(w_eff, join, &cases); + for &arm in &arms { + self.edge(from, arm); + self.seal(arm); + } + let mut arm_vals: Vec> = Vec::with_capacity(n); + let mut arm_ends: Vec = Vec::with_capacity(n); for (k, &m) in mems.iter().enumerate() { - // a window outside them matches none (the `switch` default: reads 0, stores - // and atomics dropped) - let is = self.cmpc(Pred::Eq, w, k as u32); - let _ = self.guarded(is, &mut |lw| { - if let Some(v) = f(lw, m) { - let t = lw.s.m.type_of(v); - if t == lw.s.m.i64() { - let (l, h) = lw.unpack64(v); - lw.wr(tl, l); - lw.wr(th, h); - kind = 2; - } else { - lw.wr(tl, v); - kind = 1; - } - } - Ok(()) - }); + self.s.m.set_block(arms[k]); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + arm_ends.push(self.cur()); + arm_vals.push(vals); + self.s.m.br(join); } - match kind { - 0 => None, - 1 => Some(self.rd(tl)), - _ => { - let (l, h) = (self.rd(tl), self.rd(th)); - Some(self.pack64(l, h)) + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let phi = self.s.m.phi(ty); + let z = self.s.m.const_int(ty, 0); + self.s.m.add_incoming(phi, z, from); + for k in 0..n { + self.s.m.add_incoming(phi, arm_vals[k][j], arm_ends[k]); } + out.push(phi); } + out + } + + pub(crate) fn with_mem_i32s( + &mut self, + guard: Option, + n: usize, + f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, + ) -> Vec { + let i32 = self.s.m.i32(); + let tys = vec![i32; n]; + self.with_mem_many_tys(guard, &tys, f) + } + + pub(crate) fn with_mem_void( + &mut self, + guard: Option, + f: &mut dyn FnMut(&mut Lw, RawUav), + ) { + let _ = self.with_mem_many_tys(guard, &[], &mut |lw, m| { + f(lw, m); + Vec::new() + }); } fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { - self.with_mem(&mut |lw, m| Some(lw.s.raw_atomic(m, op, a, v))).expect("atomic value") + let ty = self.s.m.type_of(v); + self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] } fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { - self.with_mem(&mut |lw, m| Some(lw.s.raw_cmpxchg(m, a, c, n))).expect("cmpxchg value") + let ty = self.s.m.type_of(c); + self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] } /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { let a = self.andc(a, !3); - self.with_mem(&mut |lw, m| Some(lw.s.raw_load(m, a, 1)[0])).expect("load value") + self.with_mem_i32s(None, 1, &mut |lw, m| lw.s.raw_load(m, a, 1))[0] + } + /// `mem.Load2/3/4(a & ~3)` (1..=4 consecutive dwords in one window switch). + pub(crate) fn mem_ld_n(&mut self, guard: Option, a: Value, count: u32) -> Vec { + debug_assert!((1..=4).contains(&count)); + let a = self.andc(a, !3); + let mask = ((1u32 << count) - 1) as u8; + self.with_mem_i32s(guard, count as usize, &mut |lw, m| lw.s.raw_load(m, a, mask)) } /// `mem.Store(a & ~3, v)` pub fn mem_st(&mut self, a: Value, v: Value) { let a = self.andc(a, !3); - self.with_mem(&mut |lw, m| { - lw.s.raw_store(m, a, &[v]); - None - }); + self.with_mem_void(None, &mut |lw, m| lw.s.raw_store(m, a, &[v])); + } + /// `mem.Store1..4(a & ~3, vals)` in one window switch. + fn mem_st_n(&mut self, guard: Option, a: Value, vals: &[Value]) { + debug_assert!((1..=4).contains(&vals.len())); + let a = self.andc(a, !3); + self.with_mem_void(guard, &mut |lw, m| lw.s.raw_store(m, a, vals)); } - /// `ld_raw`: four dwords from an unaligned byte address. - fn ld_raw(&mut self, a: Value) -> [Value; 4] { + /// `ld_raw`: four dwords from an unaligned byte address (one Load4 + one Load1 + /// in a single window switch, optionally combined with a lane guard). + fn ld_raw_guarded(&mut self, guard: Option, a: Value) -> [Value; 4] { let b = self.andc(a, !3); + let b16 = self.addc(b, 16); let s = self.andc(a, 3); let s = self.shlc(s, 3); - let mut w = Vec::new(); - for k in 0..5 { - let at = self.addc(b, 4 * k); - w.push(self.mem_ld(at)); - } + let w = self.with_mem_i32s(guard, 5, &mut |lw, m| { + let mut v = lw.s.raw_load(m, b, 0xF); + v.push(lw.s.raw_load(m, b16, 1)[0]); + v + }); let k32 = self.c(32); let inv = self.sub(k32, s); let inv = self.andc(inv, 31); @@ -205,6 +392,22 @@ impl Lw { } r } + + /// One unaligned dword from byte address `a` (one Load2 in a single window switch). + fn ld_raw_u32_guarded(&mut self, guard: Option, a: Value) -> Value { + let b = self.andc(a, !3); + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let w = self.with_mem_i32s(guard, 2, &mut |lw, m| lw.s.raw_load(m, b, 0x3)); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let sz = self.cmpc(Pred::Eq, s, 0); + let lo = self.bin(BinOp::LShr, w[0], s); + let hi = self.bin(BinOp::Shl, w[1], inv); + let x = self.or(lo, hi); + self.sel(sz, w[0], x) + } /// `st_part`: atomically replace the bits `m` of the dword at `b` by `v`. fn st_part(&mut self, b: Value, m: Value, v: Value) { let nm = self.not(m); @@ -272,8 +475,12 @@ impl Lw { // ------------------------------------------------------------ formats - /// `FMT_INFO[min(fmt, 77)]` (a constant table) for a dynamic format. + /// `FMT_INFO[min(fmt, 77)]` (a constant table) for a dynamic format; constant-folded + /// when `fmt` is known at translation time. pub(crate) fn fmt_info(&mut self, fmt: Value) -> Value { + if let Some(k) = self.s.m.const_u64(fmt) { + return self.c(buf_format_info(k.min(77) as usize)); + } let i32 = self.s.m.i32(); let g = match self.fmt_table { Some(g) => g, @@ -292,6 +499,128 @@ impl Lw { let p = self.s.m.gep(g, &[z, i]); self.s.m.load(p, 4) } + /// Emits pure instructions into `v`'s defining block (before its terminator if already + /// terminated) so every use of `v` can share them without duplicating across branches. + fn in_def_block(&mut self, v: Value, f: impl FnOnce(&mut Lw) -> T) -> T { + let Some(b) = self.s.m.def_block(v) else { + return f(self); + }; + let cur = self.cur(); + if b == cur { + return f(self); + } + let prev_ins = self.s.m.set_insert_before_term(true); + self.s.m.set_block(b); + let r = f(self); + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(prev_ins); + r + } + fn fmt_desc(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtDesc { + let key = (d3, mtbuf_fmt); + if let Some(&cached) = self.fmt_desc_cache.get(&key) { + return cached; + } + let anchor = if mtbuf_fmt.is_some() { self.c(0) } else { d3 }; + let desc = self.in_def_block(anchor, |lw| { + let fmt = match mtbuf_fmt { + Some(k) => lw.c(k), + None => { + let x = lw.lshrc(d3, 12); + lw.andc(x, 0x7F) + } + }; + let info = lw.fmt_info(fmt); + let n = lw.andc(info, 7); + let ty = lw.lshrc(info, 3); + let ty = lw.andc(ty, 7); + let t = [0, 1, 2, 3, 4, 5].map(|k| lw.cmpc(Pred::Eq, ty, k)); + let isint = lw.lor(t[4], t[5]); + let nb = lw.fmt_bytes(info); + let has = lw.nz(n); + FmtDesc { info, n, ty, isint, nb, has, t } + }); + self.fmt_desc_cache.insert(key, desc); + desc + } + fn fmt_comp1(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtComp1 { + let key = (d3, mtbuf_fmt); + if let Some(&cached) = self.fmt_comp1_cache.get(&key) { + return cached; + } + let desc = self.fmt_desc(d3, mtbuf_fmt); + let c1 = self.in_def_block(d3, |lw| { + let sel = lw.andc(d3, 7); + let s0 = lw.cmpc(Pred::Eq, sel, 0); + let s1 = lw.cmpc(Pred::Eq, sel, 1); + let one = lw.c(1); + let onef = lw.c(0x3F80_0000); + let one_val = lw.sel(desc.isint, one, onef); + let k4 = lw.c(4); + let ci = lw.sub(sel, k4); + let ci = lw.andc(ci, 3); + let z = lw.c(0); + let w0 = lw.lshrc(desc.info, 8); + let w0 = lw.andc(w0, 63); + let w1 = lw.lshrc(desc.info, 14); + let w1 = lw.andc(w1, 63); + let w2 = lw.lshrc(desc.info, 20); + let w2 = lw.andc(w2, 63); + let gt0 = lw.cmpc(Pred::UGt, ci, 0); + let gt1 = lw.cmpc(Pred::UGt, ci, 1); + let gt2 = lw.cmpc(Pred::UGt, ci, 2); + let o0 = lw.sel(gt0, w0, z); + let o1 = lw.sel(gt1, w1, z); + let o2 = lw.sel(gt2, w2, z); + let off = lw.add(o0, o1); + let off = lw.add(off, o2); + let off_bytes = lw.lshrc(off, 3); + let off_bits = lw.andc(off, 7); + let k6 = lw.c(6); + let c6 = lw.mul(ci, k6); + let sh_info = lw.addc(c6, 8); + let sh_info = lw.andc(sh_info, 31); + let w = lw.bin(BinOp::LShr, desc.info, sh_info); + let w = lw.andc(w, 63); + let big = lw.cmpc(Pred::UGe, w, 32); + let k32 = lw.c(32); + let sh = lw.sub(k32, w); + let sh = lw.andc(sh, 31); + let w31 = lw.andc(w, 31); + let mu = lw.bin(BinOp::Shl, one, w31); + let mu = lw.sub(mu, one); + let maxu = lw.uitof(mu); + let fmaxu = lw.fc(4294967295.0); + let maxu = lw.sel(big, fmaxu, maxu); + let wm1 = lw.sub(w, one); + let wm1 = lw.andc(wm1, 31); + let ms = lw.bin(BinOp::Shl, one, wm1); + let ms = lw.sub(ms, one); + let maxs = lw.uitof(ms); + let fmaxs = lw.fc(2147483647.0); + let maxs = lw.sel(big, fmaxs, maxs); + let w11 = lw.cmpc(Pred::Eq, w, 11); + let w16 = lw.cmpc(Pred::Eq, w, 16); + let w32 = lw.cmpc(Pred::Eq, w, 32); + let k5 = lw.c(5); + let mb = lw.sel(w11, k6, k5); + let k63 = lw.c(63); + let k31 = lw.c(31); + let mmask = lw.sel(w11, k63, k31); + let k17 = lw.c(17); + let k18 = lw.c(18); + let mshift = lw.sel(w11, k17, k18); + let sc6 = lw.s.m.f32c(0x3580_0000); // 2^-20 + let sc5 = lw.s.m.f32c(0x3600_0000); // 2^-19 + let den_scale = lw.sel(w11, sc6, sc5); + let cge = lw.cmp(Pred::ULe, desc.n, ci); + let is3 = lw.cmpc(Pred::Eq, ci, 3); + let dflt = lw.sel(is3, one_val, z); + FmtComp1 { desc, s0, s1, one_val, off_bytes, off_bits, big, sh, mu, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt } + }); + self.fmt_comp1_cache.insert(key, c1); + c1 + } fn fmt_bytes(&mut self, info: Value) -> Value { let mut t = self.c(0); for sh in [8, 14, 20, 26] { @@ -340,74 +669,48 @@ impl Lw { let big = self.cmpc(Pred::UGe, w, 32); self.sel(big, v, vm) } - fn exp2f(&mut self, x: Value) -> Value { - self.un(super::ops_core::op::EXP, x) - } - fn uf_small(&mut self, v: Value, mb: Value) -> Value { + /// Exact IEEE-754 conversion of 10-bit (mb=5) or 11-bit (mb=6) unsigned float to f32 bits. + fn uf_small_bits(&mut self, v: Value, mb: Value, mmask: Value, mshift: Value, den_scale: Value) -> Value { let e = self.bin(BinOp::LShr, v, mb); - let one = self.c(1); - let p = self.bin(BinOp::Shl, one, mb); - let pm = self.sub(p, one); - let m = self.and(v, pm); - let fm = self.uitof(m); - let fp = self.uitof(p); - let fm = self.fdiv(fm, fp); + let m = self.and(v, mmask); let mnz = self.nz(m); - let qn = self.s.m.f32c(0x7FC0_0000); - let inf = self.s.m.f32c(0x7F80_0000); + let qn = self.c(0x7FC0_0000); + let inf = self.c(0x7F80_0000); let special = self.sel(mnz, qn, inf); - let m14 = self.fc(-14.0); - let p14 = self.exp2f(m14); - let den = self.fmul(fm, p14); - let ef = self.uitof(e); - let k15 = self.fc(15.0); - let eb = self.fsub(ef, k15); - let pe = self.exp2f(eb); - let one_f = self.fc(1.0); - let mant = self.fadd(one_f, fm); - let norm = self.fmul(pe, mant); + let fm = self.uitof(m); + let den = self.fmul(fm, den_scale); + let den = self.bits(den); + let eb = self.addc(e, 112); + let exp_bits = self.shlc(eb, 23); + let mant_bits = self.bin(BinOp::Shl, m, mshift); + let norm = self.or(exp_bits, mant_bits); let e0 = self.cmpc(Pred::Eq, e, 0); let r = self.sel(e0, den, norm); let e31 = self.cmpc(Pred::Eq, e, 31); self.sel(e31, special, r) } - fn fmt_comp(&mut self, r: &[Value; 4], info: Value, c: u32) -> Value { - let n = self.andc(info, 7); - let ty = self.lshrc(info, 3); - let ty = self.andc(ty, 7); - let t4 = self.cmpc(Pred::Eq, ty, 4); - let t5 = self.cmpc(Pred::Eq, ty, 5); - let isint = self.lor(t4, t5); - let mut off = self.c(0); - for k in 0..c { - let w = self.lshrc(info, 8 + 6 * k); - let w = self.andc(w, 63); - off = self.add(off, w); - } - let w = self.lshrc(info, (8 + 6 * c) & 31); - let w = self.andc(w, 63); - let v = self.bits_at(r, off, w); - let k32 = self.c(32); - let sh = self.sub(k32, w); - let sh = self.andc(sh, 31); + /// Decodes raw component bits `v` using pre-computed format parameters. + #[allow(clippy::too_many_arguments)] + fn fmt_decode_val( + &mut self, + v: Value, + desc: &FmtDesc, + big: Value, + sh: Value, + maxu: Value, + maxs: Value, + w16: Value, + w32: Value, + mb: Value, + mmask: Value, + mshift: Value, + den_scale: Value, + cge: Value, + dflt: Value, + ) -> Value { let x = self.bin(BinOp::Shl, v, sh); let x = self.bin(BinOp::AShr, x, sh); - let big = self.cmpc(Pred::UGe, w, 32); let sv = self.sel(big, v, x); - let w31 = self.andc(w, 31); - let one = self.c(1); - let mu = self.bin(BinOp::Shl, one, w31); - let mu = self.sub(mu, one); - let maxu = self.uitof(mu); - let fmaxu = self.fc(4294967295.0); - let maxu = self.sel(big, fmaxu, maxu); - let wm1 = self.sub(w, one); - let wm1 = self.andc(wm1, 31); - let ms = self.bin(BinOp::Shl, one, wm1); - let ms = self.sub(ms, one); - let maxs = self.uitof(ms); - let fmaxs = self.fc(2147483647.0); - let maxs = self.sel(big, fmaxs, maxs); let fv = self.uitof(v); let fsv = self.sitof(sv); let zf = self.fc(0.0); @@ -428,32 +731,133 @@ impl Lw { let f_sn = self.bits(sn); let h = self.s.f16_to_f32(v); let hb = self.bits(h); - let w11 = self.cmpc(Pred::Eq, w, 11); - let k6 = self.c(6); - let k5 = self.c(5); - let mb = self.sel(w11, k6, k5); - let uf = self.uf_small(v, mb); - let ufb = self.bits(uf); - let w16 = self.cmpc(Pred::Eq, w, 16); - let w32 = self.cmpc(Pred::Eq, w, 32); + let ufb = self.uf_small_bits(v, mb, mmask, mshift, den_scale); let flt = self.sel(w16, hb, ufb); let flt = self.sel(w32, v, flt); let fvb = self.bits(fv); let fsvb = self.bits(fsv); let mut res = flt; - for (k, val) in [(5u32, sv), (4, v), (3, fsvb), (2, fvb), (1, f_sn), (0, f_un)] { - let is = self.cmpc(Pred::Eq, ty, k); - res = self.sel(is, val, res); + for (k, val) in [(5usize, sv), (4, v), (3, fsvb), (2, fvb), (1, f_sn), (0, f_un)] { + res = self.sel(desc.t[k], val, res); + } + self.sel(cge, dflt, res) + } + fn fmt_comp(&mut self, r: &[Value; 4], desc: &FmtDesc, c: u32) -> Value { + let mut off = self.c(0); + for k in 0..c { + let w = self.lshrc(desc.info, 8 + 6 * k); + let w = self.andc(w, 63); + off = self.add(off, w); } - let cge = self.cmpc(Pred::ULe, n, c); + let w = self.lshrc(desc.info, (8 + 6 * c) & 31); + let w = self.andc(w, 63); + let v = self.bits_at(r, off, w); + let k32 = self.c(32); + let sh = self.sub(k32, w); + let sh = self.andc(sh, 31); + let big = self.cmpc(Pred::UGe, w, 32); + let w31 = self.andc(w, 31); + let one = self.c(1); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + let w11 = self.cmpc(Pred::Eq, w, 11); + let w16 = self.cmpc(Pred::Eq, w, 16); + let w32 = self.cmpc(Pred::Eq, w, 32); + let k6 = self.c(6); + let k5 = self.c(5); + let mb = self.sel(w11, k6, k5); + let k63 = self.c(63); + let k31 = self.c(31); + let mmask = self.sel(w11, k63, k31); + let k17 = self.c(17); + let k18 = self.c(18); + let mshift = self.sel(w11, k17, k18); + let sc6 = self.s.m.f32c(0x3580_0000); + let sc5 = self.s.m.f32c(0x3600_0000); + let den_scale = self.sel(w11, sc6, sc5); + let cge = self.cmpc(Pred::ULe, desc.n, c); let dflt = if c == 3 { let a = self.c(1); let b = self.c(0x3F80_0000); - self.sel(isint, a, b) + self.sel(desc.isint, a, b) } else { self.c(0) }; - self.sel(cge, dflt, res) + self.fmt_decode_val(v, desc, big, sh, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt) + } + /// Decodes a single dynamically chosen component `ci` (0..3) from `r` (used for + /// 2- and 3-component `FormatLoad`s so unused channels are not decoded). + fn fmt_comp_dyn(&mut self, r: &[Value; 4], desc: &FmtDesc, ci: Value) -> Value { + let z = self.c(0); + let w0 = self.lshrc(desc.info, 8); + let w0 = self.andc(w0, 63); + let w1 = self.lshrc(desc.info, 14); + let w1 = self.andc(w1, 63); + let w2 = self.lshrc(desc.info, 20); + let w2 = self.andc(w2, 63); + let gt0 = self.cmpc(Pred::UGt, ci, 0); + let gt1 = self.cmpc(Pred::UGt, ci, 1); + let gt2 = self.cmpc(Pred::UGt, ci, 2); + let o0 = self.sel(gt0, w0, z); + let o1 = self.sel(gt1, w1, z); + let o2 = self.sel(gt2, w2, z); + let off = self.add(o0, o1); + let off = self.add(off, o2); + let k6 = self.c(6); + let c6 = self.mul(ci, k6); + let sh_info = self.addc(c6, 8); + let sh_info = self.andc(sh_info, 31); + let w = self.bin(BinOp::LShr, desc.info, sh_info); + let w = self.andc(w, 63); + let v = self.bits_at(r, off, w); + let k32 = self.c(32); + let sh = self.sub(k32, w); + let sh = self.andc(sh, 31); + let big = self.cmpc(Pred::UGe, w, 32); + let w31 = self.andc(w, 31); + let one = self.c(1); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + let w11 = self.cmpc(Pred::Eq, w, 11); + let w16 = self.cmpc(Pred::Eq, w, 16); + let w32 = self.cmpc(Pred::Eq, w, 32); + let k5 = self.c(5); + let mb = self.sel(w11, k6, k5); + let k63 = self.c(63); + let k31 = self.c(31); + let mmask = self.sel(w11, k63, k31); + let k17 = self.c(17); + let k18 = self.c(18); + let mshift = self.sel(w11, k17, k18); + let sc6 = self.s.m.f32c(0x3580_0000); + let sc5 = self.s.m.f32c(0x3600_0000); + let den_scale = self.sel(w11, sc6, sc5); + let cge = self.cmp(Pred::ULe, desc.n, ci); + let is3 = self.cmpc(Pred::Eq, ci, 3); + let onef = self.c(0x3F80_0000); + let one_val = self.sel(desc.isint, one, onef); + let dflt = self.sel(is3, one_val, z); + self.fmt_decode_val(v, desc, big, sh, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt) } fn dst_sel(&mut self, c: &[Value; 4], sel: Value, isint: Value) -> Value { let k4 = self.c(4); @@ -645,8 +1049,7 @@ impl Lw { let imm = Self::fv(d, "OFFSET") as u32; let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; - let mut vals = Vec::new(); - if name.starts_with("s_buffer_load") { + let mut vals = if name.starts_with("s_buffer_load") { let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); let k = self.c(imm); let off = self.add(k, soff); @@ -656,14 +1059,28 @@ impl Lw { let sz = self.cmpc(Pred::Eq, st, 0); let lim = self.mul(d2, st); let lim = self.sel(sz, d2, lim); - for i in 0..count { - let o = self.addc(off, 4 * i); - let ok = self.cmp(Pred::ULt, o, lim); - let a = self.add(d0, o); - let v = self.mem_ld(a); - let z = self.c(0); - vals.push(self.sel(ok, v, z)); - } + let base = self.add(d0, off); + let base_aligned = self.andc(base, !3); + let raw = self.with_mem_i32s(None, count as usize, &mut |lw, m| { + let mut out = Vec::with_capacity(count as usize); + let mut done = 0u32; + while done < count { + let chunk = (count - done).min(4); + let at = lw.addc(base_aligned, 4 * done); + let mask = ((1u32 << chunk) - 1) as u8; + out.extend(lw.s.raw_load(m, at, mask)); + done += chunk; + } + out + }); + let z = self.c(0); + (0..count) + .map(|i| { + let o = self.addc(off, 4 * i); + let ok = self.cmp(Pred::ULt, o, lim); + self.sel(ok, raw[i as usize], z) + }) + .collect::>() } else { let imm = ((imm << 11) as i32 >> 11) as u32; let b = self.sreg(sbase); @@ -672,11 +1089,20 @@ impl Lw { self.window_at(hi, b, &[Ea::S(k), Ea::U(soff)], false); let a = self.add(b, k); let a = self.add(a, soff); - for i in 0..count { - let at = self.addc(a, 4 * i); - vals.push(self.mem_ld(at)); - } - } + let base_aligned = self.andc(a, !3); + self.with_mem_i32s(None, count as usize, &mut |lw, m| { + let mut out = Vec::with_capacity(count as usize); + let mut done = 0u32; + while done < count { + let chunk = (count - done).min(4); + let at = lw.addc(base_aligned, 4 * done); + let mask = ((1u32 << chunk) - 1) as u8; + out.extend(lw.s.raw_load(m, at, mask)); + done += chunk; + } + out + }) + }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { // both halves take the lower half's values @@ -752,14 +1178,12 @@ impl Lw { let nv = self.c(n); return self.guarded(c, &mut |lw| lw.st_bytes(a, [data, z, z, z], nv)); } - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let z = lw.c(0); - let raw = lw.sel(ok, r[0], z); - let nv = lw.d16_merge(v, raw, n, signed, half); - lw.vset(vdata, nv); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let z = self.c(0); + let raw = self.sel(ok, r0, z); + let nv = self.d16_merge(v, raw, n, signed, half); + self.write32(&Dst::V(vdata), nv); + return Ok(()); } if let Some((n, signed, store)) = small { let nb = self.c(n); @@ -771,131 +1195,201 @@ impl Lw { let nv = self.c(n); return self.guarded(c, &mut |lw| lw.st_bytes(a, [v, z, z, z], nv)); } - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let bits = 8 * n; - let val = if signed { - let x = lw.shlc(r[0], 32 - bits); - lw.ashrc(x, 32 - bits) - } else { - lw.andc(r[0], ((1u64 << bits) - 1) as u32) - }; - let z = lw.c(0); - let val = lw.sel(ok, val, z); - lw.vset(vdata, val); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let bits = 8 * n; + let val = if signed { + let x = self.shlc(r0, 32 - bits); + self.ashrc(x, 32 - bits) + } else { + self.andc(r0, ((1u64 << bits) - 1) as u32) + }; + let z = self.c(0); + let val = self.sel(ok, val, z); + self.write32(&Dst::V(vdata), val); + return Ok(()); } match kind { BufKind::Load => { - let oks: Vec = (0..count).map(|i| { - let b = self.c(4 * i as u32 + 4); - in_range(self, b) - }).collect(); - self.guarded(act, &mut |lw| { - for i in 0..count { - let at = lw.addc(a, 4 * i as u32); - let v = lw.mem_ld(at); - let z = lw.c(0); - let v = lw.sel(oks[i as usize], v, z); - lw.vset(vdata + i, v); - } - Ok(()) - }) + let oks: Vec = (0..count) + .map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }) + .collect(); + let loaded = self.mem_ld_n(Some(act), a, count as u32); + let z = self.c(0); + for i in 0..count { + let v = self.sel(oks[i as usize], loaded[i as usize], z); + self.write32(&Dst::V(vdata + i), v); + } + Ok(()) } BufKind::Store => { let vals: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); - let oks: Vec = (0..count).map(|i| { - let b = self.c(4 * i as u32 + 4); - in_range(self, b) - }).collect(); - self.guarded(act, &mut |lw| { - for i in 0..count as usize { - let at = lw.addc(a, 4 * i as u32); - let v = vals[i]; - lw.guarded(oks[i], &mut |lw| { - lw.mem_st(at, v); - Ok(()) - })?; - } - Ok(()) - }) + let oks: Vec = (0..count) + .map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }) + .collect(); + for i in 0..count as usize { + let at = self.addc(a, 4 * i as u32); + let c = self.land(act, oks[i]); + self.mem_st_n(Some(c), at, &[vals[i]]); + } + Ok(()) } BufKind::FormatLoad => { - let fmt = if d.enc.name == "ENC_MTBUF" { - self.c(f("FORMAT") as u32) - } else { - let x = self.lshrc(d3, 12); - self.andc(x, 0x7F) + let mtbuf_fmt = (d.enc.name == "ENC_MTBUF").then_some(f("FORMAT") as u32); + let single_comp = match d16_format { + Some((_, components, _)) => components == 1, + None => count == 1, }; - let info = self.fmt_info(fmt); - let ty = self.lshrc(info, 3); - let ty = self.andc(ty, 7); - let t4 = self.cmpc(Pred::Eq, ty, 4); - let t5 = self.cmpc(Pred::Eq, ty, 5); - let isint = self.lor(t4, t5); - let nb = self.fmt_bytes(info); - let rng = in_range(self, nb); - let n7 = self.andc(info, 7); - let has = self.nz(n7); - let ok = self.land(has, rng); - let cur: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); - self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let c = [lw.fmt_comp(&r, info, 0), lw.fmt_comp(&r, info, 1), lw.fmt_comp(&r, info, 2), lw.fmt_comp(&r, info, 3)]; - let z = lw.c(0); - if let Some((_, components, high)) = d16_format { + if single_comp { + let c1 = self.fmt_comp1(d3, mtbuf_fmt); + let rng = in_range(self, c1.desc.nb); + let ok = self.land(c1.desc.has, rng); + let ea = self.add(a, c1.off_bytes); + let eb = self.andc(ea, !3); + let ea3 = self.andc(ea, 3); + let ea3_8 = self.shlc(ea3, 3); + let s = self.or(ea3_8, c1.off_bits); + let w = self.with_mem_i32s(Some(act), 2, &mut |lw, m| lw.s.raw_load(m, eb, 0x3)); + let lo = self.bin(BinOp::LShr, w[0], s); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let hi = self.bin(BinOp::Shl, w[1], inv); + let x = self.or(lo, hi); + let sz = self.cmpc(Pred::Eq, s, 0); + let v_raw = self.sel(sz, w[0], x); + let vm = self.and(v_raw, c1.mu); + let v = self.sel(c1.big, v_raw, vm); + let dec = self.fmt_decode_val( + v, + &c1.desc, + c1.big, + c1.sh, + c1.maxu, + c1.maxs, + c1.w16, + c1.w32, + c1.mb, + c1.mmask, + c1.mshift, + c1.den_scale, + c1.cge, + c1.dflt, + ); + let s_val = self.sel(c1.s1, c1.one_val, dec); + let s_val = self.selc(c1.s0, 0, s_val); + let z = self.c(0); + if let Some((_, _, high)) = d16_format { + let cur0 = self.vreg(vdata); + let lo16 = self.andc(s_val, 0xFFFF); + let sf = self.f(s_val); + let h16 = self.s.f32_to_f16(sf); + let h = self.sel(c1.desc.isint, lo16, h16); + if high { + let h = self.shlc(h, 16); + let h = self.sel(ok, h, z); + let l = self.andc(cur0, 0xFFFF); + let res = self.or(l, h); + self.write32(&Dst::V(vdata), res); + } else { + let res = self.sel(ok, h, z); + self.write32(&Dst::V(vdata), res); + } + } else { + let res = self.sel(ok, s_val, z); + self.write32(&Dst::V(vdata), res); + } + return Ok(()); + } + let desc = self.fmt_desc(d3, mtbuf_fmt); + let rng = in_range(self, desc.nb); + let ok = self.land(desc.has, rng); + let r = self.ld_raw_guarded(Some(act), a); + let z = self.c(0); + let num_comp = d16_format.map_or(count, |(_, components, _)| components); + if num_comp < 4 { + let decode_sel = |lw: &mut Lw, comp: u64| -> Value { + let sel = lw.lshrc(d3, 3 * comp as u32); + let sel = lw.andc(sel, 7); + let k4 = lw.c(4); + let ci = lw.sub(sel, k4); + let ci = lw.andc(ci, 3); + let dec = lw.fmt_comp_dyn(&r, &desc, ci); + let one = lw.c(1); + let onef = lw.c(0x3F80_0000); + let o = lw.sel(desc.isint, one, onef); + let s1 = lw.cmpc(Pred::Eq, sel, 1); + let v = lw.sel(s1, o, dec); + let s0 = lw.cmpc(Pred::Eq, sel, 0); + lw.selc(s0, 0, v) + }; + if let Some((_, components, _)) = d16_format { let half = |lw: &mut Lw, comp: u64| -> Value { - let sel = lw.lshrc(d3, 3 * comp as u32); - let sel = lw.andc(sel, 7); - let s = lw.dst_sel(&c, sel, isint); + let s = decode_sel(lw, comp); let lo = lw.andc(s, 0xFFFF); let sf = lw.f(s); let h = lw.s.f32_to_f16(sf); - lw.sel(isint, lo, h) + lw.sel(desc.isint, lo, h) }; - if high { - let h = half(lw, 0); - let h = lw.shlc(h, 16); - let h = lw.sel(ok, h, z); - let l = lw.andc(cur[0], 0xFFFF); - let v = lw.or(l, h); - lw.vset(vdata, v); - } else { - for i in 0..count { - let lo = half(lw, 2 * i); - let hi = if 2 * i + 1 < components { half(lw, 2 * i + 1) } else { z }; - let hi = lw.shlc(hi, 16); - let v = lw.or(lo, hi); - let v = lw.sel(ok, v, z); - lw.vset(vdata + i, v); - } + for i in 0..count { + let lo = half(self, 2 * i); + let hi = if 2 * i + 1 < components { half(self, 2 * i + 1) } else { z }; + let hi = self.shlc(hi, 16); + let v = self.or(lo, hi); + let v = self.sel(ok, v, z); + self.write32(&Dst::V(vdata + i), v); + } + } else { + for i in 0..count { + let s = decode_sel(self, i); + let v = self.sel(ok, s, z); + self.write32(&Dst::V(vdata + i), v); } - return Ok(()); } - for i in 0..count { - let sel = lw.lshrc(d3, 3 * i as u32); + return Ok(()); + } + let c = [self.fmt_comp(&r, &desc, 0), self.fmt_comp(&r, &desc, 1), self.fmt_comp(&r, &desc, 2), self.fmt_comp(&r, &desc, 3)]; + if let Some((_, components, _)) = d16_format { + let half = |lw: &mut Lw, comp: u64| -> Value { + let sel = lw.lshrc(d3, 3 * comp as u32); let sel = lw.andc(sel, 7); - let s = lw.dst_sel(&c, sel, isint); - let v = lw.sel(ok, s, z); - lw.vset(vdata + i, v); + let s = lw.dst_sel(&c, sel, desc.isint); + let lo = lw.andc(s, 0xFFFF); + let sf = lw.f(s); + let h = lw.s.f32_to_f16(sf); + lw.sel(desc.isint, lo, h) + }; + for i in 0..count { + let lo = half(self, 2 * i); + let hi = if 2 * i + 1 < components { half(self, 2 * i + 1) } else { z }; + let hi = self.shlc(hi, 16); + let v = self.or(lo, hi); + let v = self.sel(ok, v, z); + self.write32(&Dst::V(vdata + i), v); } - Ok(()) - }) + } else { + for i in 0..count { + let sel = self.lshrc(d3, 3 * i as u32); + let sel = self.andc(sel, 7); + let s = self.dst_sel(&c, sel, desc.isint); + let v = self.sel(ok, s, z); + self.write32(&Dst::V(vdata + i), v); + } + } + Ok(()) } BufKind::FormatStore => { - let fmt = if d.enc.name == "ENC_MTBUF" { - self.c(f("FORMAT") as u32) - } else { - let x = self.lshrc(d3, 12); - self.andc(x, 0x7F) - }; - let info = self.fmt_info(fmt); - let nb = self.fmt_bytes(info); + let mtbuf_fmt = (d.enc.name == "ENC_MTBUF").then_some(f("FORMAT") as u32); + let desc = self.fmt_desc(d3, mtbuf_fmt); + let info = desc.info; + let nb = desc.nb; let rng = in_range(self, nb); - let n7 = self.andc(info, 7); - let has = self.nz(n7); - let ok = self.land(has, rng); + let ok = self.land(desc.has, rng); let z = self.c(0); let vals: [Value; 4] = if let Some((_, components, high)) = d16_format { let ty = self.lshrc(info, 3); @@ -1285,12 +1779,10 @@ impl Lw { } let vd = Self::fv(d, "VDST"); let v = self.vreg(vd); - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let nv = lw.d16_merge(v, r[0], n, signed, half); - lw.vset(vd, nv); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let nv = self.d16_merge(v, r0, n, signed, half); + self.write32(&Dst::V(vd), nv); + return Ok(()); } let (store, count) = match op { "load_dword" | "load_dword_addtid" => (false, 1), @@ -1323,23 +1815,15 @@ impl Lw { }; if store { let vals: Vec = (0..count).map(|i| self.vreg(Self::fv(d, "DATA") + i)).collect(); - self.guarded(act, &mut |lw| { - for (i, &v) in vals.iter().enumerate() { - let at = lw.addc(a, 4 * i as u32); - lw.mem_st(at, v); - } - Ok(()) - }) + self.mem_st_n(Some(act), a, &vals); + Ok(()) } else { let vd = Self::fv(d, "VDST"); - self.guarded(act, &mut |lw| { - for i in 0..count { - let at = lw.addc(a, 4 * i as u32); - let v = lw.mem_ld(at); - lw.vset(vd + i, v); - } - Ok(()) - }) + let loaded = self.mem_ld_n(Some(act), a, count as u32); + for i in 0..count { + self.write32(&Dst::V(vd + i), loaded[i as usize]); + } + Ok(()) } } diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 06efbe2f0e..1339aa3d48 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -4,7 +4,6 @@ use super::lower::{Lw, VAR_WIN}; use super::module::{Pred, Value}; -use super::shader::RawUav; use crate::gpu::rdna2::Decoded; /// A term of a 64-bit effective address (`window_at`). @@ -26,11 +25,29 @@ impl Lw { self.mems.len() > 1 } - /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`). + /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`), + /// hoisted to the entry block so multi-window shaders load it once rather than on every + /// memory operation. fn uma_base(&mut self) -> Value { + if let Some(v) = self.uma_base_val { + return v; + } let io = self.init.io.expect("io"); let off = self.c(crate::gpu::recomp::IO_UMA_BASE_HI as u32 * 4); - self.s.raw_load(io, off, 1)[0] + let cur = self.cur(); + let entry = self.init.entry; + let v = if cur == entry { + self.s.raw_load(io, off, 1)[0] + } else { + let prev = self.s.m.set_insert_before_term(true); + self.s.m.set_block(entry); + let v = self.s.raw_load(io, off, 1)[0]; + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(prev); + v + }; + self.uma_base_val = Some(v); + v } /// Selects the window of an access whose 64-bit effective address is `hi:lo` plus @@ -128,47 +145,4 @@ impl Lw { }; self.window_at(hi, lo, &[Ea::U(l4), off], write); } - - /// `with_mem` with the windows in the descriptor heap (`Options::heap_windows`): window - /// `w` is the raw UAV `ResourceDescriptorHeap[NonUniformResourceIndex(MEM_HEAP_BASE + w)]` - /// (`globallycoherent` where the root windows are); a `w` outside the windows does what - /// the HLSL accessor does (reads 0, stores and atomics dropped). - pub(super) fn with_heap_mem( - &mut self, - coherent: bool, - f: &mut dyn FnMut(&mut Lw, RawUav) -> Option, - ) -> Option { - let windows = self.mems.len() as u32; - let w = self.rd(VAR_WIN); - let (tl, th) = (self.tmp_var(), self.tmp_var()); - let z = self.c(0); - self.wr(tl, z); - self.wr(th, z); - let mut kind = 0u8; // 0 none, 1 i32, 2 i64 - let inside = self.cmpc(Pred::ULt, w, windows); - let _ = self.guarded(inside, &mut |lw| { - let i = lw.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); - let m = lw.s.heap_raw_buffer_uav(i, coherent); - if let Some(v) = f(lw, m) { - if lw.s.m.type_of(v) == lw.s.m.i64() { - let (l, h) = lw.unpack64(v); - lw.wr(tl, l); - lw.wr(th, h); - kind = 2; - } else { - lw.wr(tl, v); - kind = 1; - } - } - Ok(()) - }); - match kind { - 0 => None, - 1 => Some(self.rd(tl)), - _ => { - let (l, h) = (self.rd(tl), self.rd(th)); - Some(self.pack64(l, h)) - } - } - } } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 3462ca3610..cc37c4fa74 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -249,8 +249,10 @@ pub struct Module { func_ids: HashMap, globals: Vec, insts: Vec, + def_block: Vec, blocks: Vec>, cur: Block, + insert_before_term: bool, md: Vec, named_md: Vec<(String, Vec)>, md_strings: HashMap, @@ -275,8 +277,10 @@ impl Module { func_ids: HashMap::new(), globals: Vec::new(), insts: Vec::new(), + def_block: Vec::new(), blocks: vec![Vec::new()], cur: Block(0), + insert_before_term: false, md: Vec::new(), named_md: Vec::new(), md_strings: HashMap::new(), @@ -521,6 +525,24 @@ impl Module { pub fn current_block(&self) -> Block { self.cur } + /// Block where `v` is defined (entry block for constants, globals and functions). + pub fn def_block(&self, v: Value) -> Option { + match v { + Value::Inst(i) => { + let b = self.def_block[i as usize]; + (b.0 < self.blocks.len() as u32).then_some(b) + } + _ => Some(Block(0)), + } + } + /// When enabled, emitting into an already-terminated block inserts immediately + /// before its terminator (used for hoisting pure computations to a value's + /// defining block). Returns the previous setting. + pub fn set_insert_before_term(&mut self, on: bool) -> bool { + let prev = self.insert_before_term; + self.insert_before_term = on; + prev + } /// Whether the current block already ends in a terminator. pub fn terminated(&self) -> bool { self.blocks[self.cur.0 as usize].last().is_some_and(|&i| { @@ -529,12 +551,20 @@ impl Module { } fn push(&mut self, op: Op, ty: Ty) -> Value { - if self.terminated() { + let terminated = self.terminated(); + if terminated && !self.insert_before_term { self.fail(format!("instruction after a terminator in block {:?}", self.cur)); } let id = self.insts.len() as u32; self.insts.push(InstDef { op, ty }); - self.blocks[self.cur.0 as usize].push(id); + self.def_block.push(self.cur); + let list = &mut self.blocks[self.cur.0 as usize]; + if terminated && self.insert_before_term { + let at = list.len() - 1; + list.insert(at, id); + } else { + list.push(id); + } Value::Inst(id) } @@ -608,6 +638,7 @@ impl Module { pub fn phi_at(&mut self, b: Block, ty: Ty) -> Value { let id = self.insts.len() as u32; self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + self.def_block.push(b); let list = &mut self.blocks[b.0 as usize]; let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); list.insert(at, id); @@ -618,11 +649,13 @@ impl Module { pub fn detached_phi(&mut self, ty: Ty) -> Value { let id = self.insts.len() as u32; self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + self.def_block.push(Block(u32::MAX)); Value::Inst(id) } /// Puts a [`Module::detached_phi`] after the existing phis of block `b`. pub fn place_phi(&mut self, b: Block, phi: Value) { let Value::Inst(id) = phi else { panic!("not a phi") }; + self.def_block[id as usize] = b; let list = &mut self.blocks[b.0 as usize]; let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); list.insert(at, id); @@ -1077,9 +1110,19 @@ impl Module { /// Replaces every use of `old` by `new` in the entry's instructions and in /// metadata (e.g. to drop a trivial phi). `old` itself stays in its block. pub fn replace_all_uses(&mut self, old: Value, new: Value) { + self.replace_uses(&HashMap::from([(old, new)])); + } + + /// `replace_all_uses` for every `old → new` of `map` in one pass over the module: a use + /// becomes the end of its chain (`a → b`, `b → c`: a use of `a` becomes `c`), as the same + /// calls one at a time in order would leave it. + pub fn replace_uses(&mut self, map: &HashMap) { + if map.is_empty() { + return; + } let r = |v: &mut Value| { - if *v == old { - *v = new; + while let Some(&n) = map.get(v) { + *v = n; } }; for inst in &mut self.insts { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 74153ff4ad..d852d8a413 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; -use super::{FnAttrs, Module, Op, Ty, Value}; +use super::{BinOp, CastOp, FnAttrs, Module, Op, Pred, Ty, Value}; impl Op { /// Calls `f` on every value operand. @@ -84,15 +84,160 @@ impl Module { n.starts_with("dx.op.wave") || n.starts_with("dx.op.quad") } + fn is_const_global_ptr(&self, v: Value) -> bool { + match v { + Value::Global(g) => self.globals[g as usize].constant, + Value::Inst(i) => match &self.insts[i as usize].op { + Op::Gep(base, _) => self.is_const_global_ptr(*base), + _ => false, + }, + _ => false, + } + } + fn cse_kind(&self, op: &Op) -> Cse { match op { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, + Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } } + /// Cheap algebraic & constant simplification on already-resolved operands. + fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { + // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. + if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + return None; + } + match *op { + Op::Select(c, t, f) => { + if t == f { + return Some(t); + } + match self.const_u64(c) { + Some(1) => Some(t), + Some(0) => Some(f), + _ => None, + } + } + Op::Bin(bop, a, b, 0) => { + let w = self.int_width(ty)?; + // avoid dropping 64-bit ops that keep Int64Ops shader flags consistent + if w > 32 { + return None; + } + let mask = (1u64 << w) - 1; + let (ca, cb) = (self.const_u64(a), self.const_u64(b)); + if let (Some(x), Some(y)) = (ca, cb) { + let r = match bop { + BinOp::Add => Some(x.wrapping_add(y)), + BinOp::Sub => Some(x.wrapping_sub(y)), + BinOp::Mul => Some(x.wrapping_mul(y)), + BinOp::And => Some(x & y), + BinOp::Or => Some(x | y), + BinOp::Xor => Some(x ^ y), + BinOp::Shl if y < w as u64 => Some(x << y), + BinOp::LShr if y < w as u64 => Some(x >> y), + BinOp::AShr if y < w as u64 => Some((((x << (64 - w)) as i64) >> (64 - w + y as u32)) as u64), + BinOp::UDiv if y != 0 => Some(x / y), + BinOp::URem if y != 0 => Some(x % y), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r & mask)); + } + } + match (bop, cb) { + (BinOp::Add | BinOp::Sub | BinOp::Or | BinOp::Xor | BinOp::Shl | BinOp::LShr | BinOp::AShr, Some(0)) => return Some(a), + (BinOp::And, Some(m)) if m == mask => return Some(a), + (BinOp::And | BinOp::Mul, Some(0)) => return Some(b), + (BinOp::Mul, Some(1)) => return Some(a), + _ => {} + } + match (bop, ca) { + (BinOp::Add | BinOp::Or | BinOp::Xor, Some(0)) => return Some(b), + (BinOp::And, Some(m)) if m == mask => return Some(b), + (BinOp::And | BinOp::Mul | BinOp::Shl | BinOp::LShr, Some(0)) => return Some(a), + (BinOp::Mul, Some(1)) => return Some(b), + _ => {} + } + if a == b { + match bop { + BinOp::And | BinOp::Or => return Some(a), + BinOp::Sub | BinOp::Xor => return Some(self.const_int(ty, 0)), + _ => {} + } + } + None + } + Op::Cmp(p, a, b) => { + let at = self.value_ty(a); + let w = self.int_width(at)?; + if w > 32 { + return None; + } + if let (Some(x), Some(y)) = (self.const_u64(a), self.const_u64(b)) { + let sx = |v: u64| ((v << (64 - w)) as i64) >> (64 - w); + let r = match p { + Pred::Eq => Some(x == y), + Pred::Ne => Some(x != y), + Pred::UGt => Some(x > y), + Pred::UGe => Some(x >= y), + Pred::ULt => Some(x < y), + Pred::ULe => Some(x <= y), + Pred::SGt => Some(sx(x) > sx(y)), + Pred::SGe => Some(sx(x) >= sx(y)), + Pred::SLt => Some(sx(x) < sx(y)), + Pred::SLe => Some(sx(x) <= sx(y)), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r as u64)); + } + } + if a == b { + let r = match p { + Pred::Eq | Pred::ULe | Pred::UGe | Pred::SLe | Pred::SGe => Some(true), + Pred::Ne | Pred::ULt | Pred::UGt | Pred::SLt | Pred::SGt => Some(false), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r as u64)); + } + } + None + } + Op::Cast(CastOp::BitCast, Value::Inst(j), to) => { + if matches!(self.types[self.insts[j as usize].ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + return None; + } + if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + None + } + Op::Cast(cop @ (CastOp::ZExt | CastOp::SExt | CastOp::Trunc), v, to) => { + let sw = self.int_width(self.value_ty(v))?; + let dw = self.int_width(to)?; + if sw > 32 || dw > 32 { + return None; + } + let x = self.const_u64(v)?; + let r = match cop { + CastOp::ZExt | CastOp::Trunc => x & ((1u64 << dw) - 1), + CastOp::SExt => ((((x << (64 - sw)) as i64) >> (64 - sw)) as u64) & ((1u64 << dw) - 1), + _ => unreachable!(), + }; + Some(self.const_int(to, r)) + } + _ => None, + } + } + /// Whether an unused instruction can go. 64-bit values stay: helpers already set /// the Int64Ops / Doubles / DoubleExtensions flags for them. fn removable(&self, op: &Op, ty: Ty, wide: &[Ty]) -> bool { @@ -284,6 +429,7 @@ impl Module { Leave(usize), } let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let mut cse_replaced = false; while let Some(step) = stack.pop() { let b = match step { Step::Leave(mark) => { @@ -304,16 +450,24 @@ impl Module { let i = self.blocks[b][k] as usize; let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); op.map_operands(|v| resolve(&mut repl, v)); - let kind = self.cse_kind(&op); - if repl[i].is_none() && kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); - let t = if kind == Cse::Dom { &mut table } else { &mut local }; - if let Some(&v) = t.get(&key) { - repl[i] = Some(v); + if repl[i].is_none() { + if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { + repl[i] = Some(s); + cse_replaced = true; } else { - let old = t.insert(key.clone(), Value::Inst(i as u32)); - if kind == Cse::Dom { - undo.push((key, old)); + let kind = self.cse_kind(&op); + if kind != Cse::No { + let key = (op.clone(), self.insts[i].ty); + let t = if kind == Cse::Dom { &mut table } else { &mut local }; + if let Some(&v) = t.get(&key) { + repl[i] = Some(v); + cse_replaced = true; + } else { + let old = t.insert(key.clone(), Value::Inst(i as u32)); + if kind == Cse::Dom { + undo.push((key, old)); + } + } } } } @@ -323,6 +477,42 @@ impl Module { stack.push(Step::Enter(c)); } } + // second trivial-phi fixed point if CSE/simplification collapsed incoming values + if cse_replaced && !skip("phi") { + loop { + let mut changed = false; + for &b in &order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(&mut repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + } // phis may name values defined later (back edges): resolve once more for &b in &order { for k in 0..self.blocks[b as usize].len() { diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs index 67e6baf0dc..af8d2e960e 100644 --- a/crates/xcl/src/gpu/dxil/tests.rs +++ b/crates/xcl/src/gpu/dxil/tests.rs @@ -177,3 +177,42 @@ fn blocks_are_written_in_reverse_post_order() { let want: Vec = (0..64).map(|l| ((l as u32) << 2) + 7 + sgpr[l]).collect(); assert_eq!(&r.raw[..64], &want[..]); } + +/// `replace_uses` makes a whole map of trivial phis in one pass and leaves the module as +/// `replace_all_uses` one at a time in order does, a chain included (`a → b`, then `b → v`, +/// as the SSA construction makes when `b` turns trivial after `a`). +#[test] +fn batched_replacements_match_one_at_a_time() { + let build = |batched: bool| { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = s.raw_uav(1, 0); + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let next = s.m.new_block(); + let x = s.raw_load(io, off, 1)[0]; + s.m.br(next); + let entry = s.m.entry_block(); + s.m.set_block(next); + let i32 = s.m.i32(); + let b = s.m.phi(i32); + s.m.add_incoming(b, x, entry); + let a = s.m.phi(i32); + s.m.add_incoming(a, b, entry); + let sum = s.m.bin(BinOp::Add, a, b); + s.raw_store(res, off, &[sum]); + if batched { + s.m.replace_uses(&std::collections::HashMap::from([(a, b), (b, x)])); + } else { + s.m.replace_all_uses(a, b); + s.m.replace_all_uses(b, x); + } + s.finish([64, 1, 1], None) + }; + let c = build(true); + assert_eq!(c, build(false)); + if let Err(e) = validate::validate(&c) { + panic!("validator rejected the kernel:\n{e}"); + } +} diff --git a/crates/xcl/src/gpu/recomp/dxil/assemble.rs b/crates/xcl/src/gpu/recomp/dxil/assemble.rs new file mode 100644 index 0000000000..490db860aa --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/assemble.rs @@ -0,0 +1,129 @@ +//! A DXIL module as LLVM IR text (or bitcode) to a signed container, through the PC DXC's +//! libraries: `dxcompiler.dll`'s assembler builds the container from the module's `dx.*` +//! metadata, `dxil.dll`'s validator checks and signs it. Neither DXC's HLSL front end nor its +//! optimiser runs: a retail compute program's module (8.6 MB of IR, 1 MB of DXIL) takes 0.75 s, +//! where its HLSL takes 25 s through `dxc::compile`. +//! +//! What a module needs on top of what the validator checks (RX 7800 XT, Windows driver): +//! an `!llvm.ident`. Without one the container validates and signs, but +//! `CreateComputePipelineState` faults inside the AMD driver. + +use std::ffi::c_void; + +use windows::core::{Interface, GUID, HRESULT}; +use windows::Win32::Graphics::Direct3D::Dxc::{ + DxcValidatorFlags_InPlaceEdit, IDxcAssembler, IDxcOperationResult, IDxcUtils, IDxcValidator, CLSID_DxcAssembler, CLSID_DxcUtils, CLSID_DxcValidator, DXC_CP_UTF8, +}; + +type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; + +fn errors(r: &IDxcOperationResult) -> String { + unsafe { r.GetErrorBuffer().map(|b| String::from_utf8_lossy(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize())).into_owned()).unwrap_or_default() } +} + +unsafe fn make(create: CreateInstance, clsid: &GUID) -> Result { + let mut p = std::ptr::null_mut(); + create(clsid, &T::IID, &mut p).ok().map_err(|e| format!("DxcCreateInstance: {e}"))?; + Ok(T::from_raw(p)) +} + +/// The module `ir` as a validated, signed DXIL container; the assembler's or the validator's +/// messages as the error. +pub fn assemble(ir: &str) -> Result, String> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; + let create = super::super::dxc::create_instance().ok_or("dxcompiler.dll not found")?; + unsafe { + let create = std::mem::transmute::(create); + // (`dxc` loaded dxil.dll by its full path, before dxcompiler.dll) + let signer = GetModuleHandleW(crate::util::wide("dxil.dll").as_ptr()); + let sign = (!signer.is_null()).then(|| GetProcAddress(signer, b"DxcCreateInstance\0".as_ptr())).flatten().ok_or("assemble: no dxil.dll to sign with")?; + let utils: IDxcUtils = make(create, &CLSID_DxcUtils)?; + let blob = utils.CreateBlob(ir.as_ptr() as *const c_void, ir.len() as u32, DXC_CP_UTF8).map_err(|e| format!("assemble: {e}"))?; + let asm: IDxcAssembler = make(create, &CLSID_DxcAssembler)?; + let r = asm.AssembleToContainer(&blob).map_err(|e| format!("assemble: {e}"))?; + if r.GetStatus().map_err(|e| format!("assemble: {e}"))?.is_err() { + return Err(format!("assemble: {}", errors(&r))); + } + let container = r.GetResult().map_err(|e| format!("assemble: {e}"))?; + let v: IDxcValidator = make(std::mem::transmute::(sign as usize), &CLSID_DxcValidator)?; + let r = v.Validate(&container, DxcValidatorFlags_InPlaceEdit).map_err(|e| format!("validate: {e}"))?; + if r.GetStatus().map_err(|e| format!("validate: {e}"))?.is_err() { + return Err(format!("validate: {}", errors(&r))); + } + Ok(std::slice::from_raw_parts(container.GetBufferPointer() as *const u8, container.GetBufferSize()).to_vec()) + } +} + +#[cfg(test)] +mod tests { + use super::super::super::runner; + + /// A CS of the ABI root signature, written by hand: `mem[i] = 3 i + 1` through `u2`. + const IR: &str = r#"target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64" +target triple = "dxil-ms-dx" +%dx.types.Handle = type { i8* } +%dx.types.ResBind = type { i32, i32, i32, i8 } +%dx.types.ResourceProperties = type { i32, i32 } +%struct.RWByteAddressBuffer = type { i32 } +define void @main() { + %1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 2, i32 2, i32 0, i8 1 }, i32 2, i1 false) + %2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) + %3 = mul i32 %2, 3 + %4 = add i32 %3, 1 + %5 = shl i32 %2, 2 + %6 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) + call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %6, i32 %5, i32 undef, i32 %4, i32 undef, i32 undef, i32 undef, i8 1, i32 4) + ret void +} +declare i32 @dx.op.threadId.i32(i32, i32) #0 +declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #1 +declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0 +declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0 +attributes #0 = { nounwind readnone } +attributes #1 = { nounwind } +!llvm.ident = !{!0} +!dx.version = !{!1} +!dx.valver = !{!2} +!dx.shaderModel = !{!3} +!dx.resources = !{!4} +!dx.entryPoints = !{!7} +!0 = !{!"xcl"} +!1 = !{i32 1, i32 6} +!2 = !{i32 1, i32 6} +!3 = !{!"cs", i32 6, i32 6} +!4 = !{null, !5, null, null} +!5 = !{!6} +!6 = !{i32 0, %struct.RWByteAddressBuffer* undef, !"", i32 0, i32 2, i32 1, i32 11, i1 false, i1 false, i1 false, null} +!7 = !{void ()* @main, !"main", null, !4, !8} +!8 = !{i32 0, i64 16, i32 4, !9} +!9 = !{i32 64, i32 1, i32 1} +"#; + + /// The text assembles, signs and runs on the GPU; a module the validator rejects (a use + /// before its definition) is an error, not a container. + #[test] + fn ir_text_assembles_signs_and_runs() { + if super::super::super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + // a Windows SDK's `bin\\x64` has dxcompiler.dll without dxil.dll: nothing to sign with + let dxil = match super::assemble(IR) { + Err(e) if e.contains("no dxil.dll") => { + runner::skip_test("no dxil.dll"); + return; + } + r => r.unwrap(), + }; + assert_eq!(&dxil[..4], b"DXBC"); + let bad = super::assemble(&IR.replace("%3 = mul i32 %2, 3", "%3 = mul i32 %4, 3")).unwrap_err(); + assert!(bad.contains("dominate"), "{bad}"); + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; + } + let out = runner::dispatch(&dxil, [1, 1, 1], &[], &[0u32; 64]).unwrap(); + let want: Vec = (0..64).map(|i| 3 * i + 1).collect(); + assert_eq!(&out[..64], &want[..]); + } +} diff --git a/crates/xcl/src/gpu/recomp/dxil/mod.rs b/crates/xcl/src/gpu/recomp/dxil/mod.rs new file mode 100644 index 0000000000..fb1a5dffd8 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/mod.rs @@ -0,0 +1,3 @@ +//! A DXIL module without HLSL: assembled and signed from LLVM IR text (`assemble`). + +pub mod assemble; diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs new file mode 100644 index 0000000000..bdb04fb157 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -0,0 +1,1099 @@ +//! Lane masks as per-lane booleans: what a backend that writes DXIL itself (no HLSL, so no +//! structured control flow) needs in order to run console code without emulating EXEC. +//! +//! The HLSL path keeps EXEC as a wave-uniform value and guards every vector write with the +//! lane's bit of it. With an unstructured CFG each lane can instead branch on its own bit and +//! leave reconvergence to the host driver. Per program this works out: +//! - every lane mask (EXEC, VCC, any SGPR a mask is kept in) as a boolean function of *atoms* – +//! the lane's result of a VALU compare or carry, a wave-uniform SCC, a mask it cannot follow, +//! a join it cannot resolve – as a reduced ordered BDD; +//! - every branch on a mask (`s_cbranch_execz/execnz/vccz/vccnz`, SCC of a mask op) as a branch +//! of each lane on its own bit, and a branch on any other SCC as a uniform one; +//! - for every block, what holds in each lane that reaches it: a forward dataflow over the +//! branch conditions; facts a back edge carries about atoms its loop redefines are dropped; +//! - which vector instructions still need a guard: those where reaching the instruction does +//! not imply the lane's EXEC bit. +//! +//! Branching lane by lane on a mask assumes what compiled code does: it jumps over work that +//! inactive lanes would not change anyway, or it tests a uniform value. A join of a mask is +//! resolved when every lane coming in has it set (or clear) – EXEC restored where the branches +//! meet – and becomes an atom otherwise. A loop head's join is guessed from its forward edges +//! and checked against its back edges; a wrong guess becomes an atom and the analysis restarts. +//! +//! Nothing translates with this yet: `xcl shaders --recomp` reports its counts. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::x64_masks; +use crate::gpu::rdna2::{self, Decoded, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +type R = Result; + +/// A BDD node: 0 = false, 1 = true. +type B = u32; +const FALSE: B = 0; +const TRUE: B = 1; +/// More nodes than this: the program fails with "lane conditions too large". +const MAX_NODES: usize = 1 << 20; +/// New nodes one reach fact may take before it is weakened. +const STEP_NODES: usize = 1 << 9; +/// Passes of the reach fixpoint, restarts after wrong loop-head guesses included. +const MAX_ROUNDS: usize = 256; +const EXEC: usize = 126; +const VCC: usize = 106; +/// The SCC slot of a join. +const SCC: usize = 128; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Op { + And, + Or, + Xor, +} + +struct Bdd { + /// (atom, low, high); the terminals have atom u32::MAX, so atoms created first are on top + nodes: Vec<(u32, B, B)>, + unique: HashMap<(u32, B, B), B>, + memo: HashMap<(Op, B, B), B>, + /// node count `mk` fails at + limit: usize, +} + +impl Bdd { + fn new() -> Self { + Bdd { nodes: vec![(u32::MAX, 0, 0), (u32::MAX, 1, 1)], unique: HashMap::new(), memo: HashMap::new(), limit: MAX_NODES } + } + + /// `f`'s result, or None when it needs more than `STEP_NODES` new nodes (those it made stay: + /// they are valid nodes, and the memo stays right). For results that can be weakened. + fn within(&mut self, f: impl FnOnce(&mut Self) -> R) -> Option { + self.limit = (self.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = f(self); + self.limit = MAX_NODES; + r.ok() + } + + /// The function "atom v", whatever the limits: what a weakened result falls back on. + fn atom(&mut self, v: u32) -> B { + if let Some(&n) = self.unique.get(&(v, FALSE, TRUE)) { + return n; + } + let n = self.nodes.len() as B; + self.nodes.push((v, FALSE, TRUE)); + self.unique.insert((v, FALSE, TRUE), n); + n + } + + fn mk(&mut self, v: u32, lo: B, hi: B) -> R { + if lo == hi { + return Ok(lo); + } + if let Some(&n) = self.unique.get(&(v, lo, hi)) { + return Ok(n); + } + if self.nodes.len() >= self.limit { + return Err("lane conditions too large"); + } + let n = self.nodes.len() as B; + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), n); + Ok(n) + } + + fn apply(&mut self, op: Op, a: B, b: B) -> R { + let (a, b) = (a.min(b), a.max(b)); + match (op, a) { + (Op::And, FALSE) => return Ok(FALSE), + (Op::Or, TRUE) => return Ok(TRUE), + (Op::And, TRUE) | (Op::Or | Op::Xor, FALSE) => return Ok(b), + _ if a == b => return Ok(if op == Op::Xor { FALSE } else { a }), + _ => {} + } + if let Some(&n) = self.memo.get(&(op, a, b)) { + return Ok(n); + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + let lo = self.apply(op, a0, b0)?; + let hi = self.apply(op, a1, b1)?; + let n = self.mk(v, lo, hi)?; + self.memo.insert((op, a, b), n); + Ok(n) + } + + fn and(&mut self, a: B, b: B) -> R { + self.apply(Op::And, a, b) + } + + fn or(&mut self, a: B, b: B) -> R { + self.apply(Op::Or, a, b) + } + + fn not(&mut self, a: B) -> R { + self.apply(Op::Xor, a, TRUE) + } + + /// a → b, without building a ∧ ¬b. + fn implies(&self, a: B, b: B) -> bool { + self.implies_in(a, b, &mut HashSet::new()) + } + + fn implies_in(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == TRUE || a == b { + return true; + } + if a == TRUE && b == FALSE { + return false; + } + if !seen.insert((a, b)) { + return true; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.implies_in(a0, b0, seen) && self.implies_in(a1, b1, seen) + } + + /// a → ¬b, i.e. a ∧ b is false, without building it. + fn disjoint(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == FALSE { + return true; + } + if a == TRUE && b == TRUE { + return false; + } + if a == b || !seen.insert((a, b)) { + return a != b; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.disjoint(a0, b0, seen) && self.disjoint(a1, b1, seen) + } + + /// `a` with the atoms `drop` names quantified away (∃). + fn exists(&mut self, a: B, drop: &dyn Fn(u32) -> bool, memo: &mut HashMap) -> R { + if a <= TRUE { + return Ok(a); + } + if let Some(&n) = memo.get(&a) { + return Ok(n); + } + let (v, lo, hi) = self.nodes[a as usize]; + let (lo, hi) = (self.exists(lo, drop, memo)?, self.exists(hi, drop, memo)?); + let n = if drop(v) { self.or(lo, hi)? } else { self.mk(v, lo, hi)? }; + memo.insert(a, n); + Ok(n) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Atom { + /// the lane's result of the VALU compare / carry at this pc (before EXEC) + Lane(u64), + /// SCC written at this pc: uniform + Scc(u64), + /// a mask the analysis cannot follow, read at this pc from this register + Opaque(u64, usize), + /// an unresolved join of this slot (SGPR, `SCC`) at the start of this block + Join(usize, usize), + /// EXEC at launch, where it need not hold every lane that runs (`LaunchExec::Unknown`) + Launch, +} + +/// EXEC at the program's start, as the analysis takes it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum LaunchExec { + /// every lane that runs is in EXEC: kernel mode (lanes outside it leave at once) and compute + All, + /// unknown per lane: a PS, whose helper lanes start outside EXEC and run on. A vector + /// instruction keeps its guard until EXEC is written. + Unknown, +} + +/// The masks at a program point. `regs[r]`: the lane function of the mask SGPR r holds (wave64: +/// in the pair's first register), None when it holds nothing the analysis knows as a mask. +/// EXEC always has one. `scc`: (lane function, true when it is a mask op's "result has the +/// lane's bit" rather than a uniform value). +#[derive(Clone, PartialEq)] +struct State { + regs: Vec>, + scc: Option<(B, bool)>, +} + +/// How a block's successor is reached: unconditionally, or by its branch taken / not taken. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Edge { + Always, + Taken, + NotTaken, +} + +/// A basic block of the program, as the lowering walks it. +#[derive(Clone, Debug)] +pub struct Block { + /// its instructions: indices into the decoded program + pub insts: std::ops::Range, + pub succ: Vec<(usize, Edge)>, + /// predecessors that the entry reaches, back edges included + pub preds: Vec, + /// it ends in a branch on a lane mask: each lane takes it on its own bit + pub lane_branch: bool, +} + +/// What the analysis found in a program. +#[derive(Debug, Default)] +pub struct Summary { + /// vector instructions (VALU writes, memory, LDS, exports) + pub vector: usize, + /// pcs of those that still need a guard on the lane's EXEC bit + pub guarded: Vec, + /// pcs of the mask-width `s_wqm` whose result is every lane (whole-quad mode of the launch + /// EXEC, `LaunchExec::Unknown`) + pub wqm_all: Vec, + /// conditional branches on a lane mask (each lane decides) and on uniform values + pub lane_branches: usize, + pub uniform_branches: usize, + /// the CFG (block 0 is the entry) and the order to lower it in (reverse postorder of the + /// blocks the entry reaches: every block after its forward predecessors) + pub blocks: Vec, + pub order: Vec, +} + +/// Executed with the lane's EXEC bit (VOPC and the lane reads / writes are mask producers). +fn is_vector(d: &Decoded) -> bool { + let n = d.inst.name; + !n.starts_with("S_") && !n.starts_with("V_CMP") && !matches!(n, "V_READLANE_B32" | "V_READFIRSTLANE_B32" | "V_WRITELANE_B32") +} + +struct Lanes<'a> { + insts: &'a [Decoded], + wave64: bool, + launch: LaunchExec, + bdd: Bdd, + atoms: HashMap, + /// block each atom is born in + born: Vec, + /// block → its instruction index range, successors (block, edge), predecessors (block, + /// index in its successors) + blocks: Vec<(usize, usize)>, + succ: Vec>, + preds: Vec>, + /// reverse postorder, and for each block: Some(blocks of its loop) when it heads one + order: Vec, + body: Vec>>, + /// per instruction: SGPRs it overwrites (`x64_masks::uses`), SGPRs it may change, whether + /// it writes SCC + effects: Vec<(u128, u128, bool)>, +} + +impl<'a> Lanes<'a> { + fn new(insts: &'a [Decoded], wave64: bool, launch: LaunchExec) -> R { + let starts: HashMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut leaders = BTreeSet::from([0usize]); + let mut target = vec![None; insts.len()]; + for (i, d) in insts.iter().enumerate() { + let indirect = d.far_target.is_none() && (d.inst.flags & F_INDIRECT != 0 || matches!(d.inst.name, "S_SETPC_B64" | "S_SWAPPC_B64")); + if indirect { + return Err("indirect jump"); + } + if let Some(t) = rdna2::branch_target(d) { + let &j = starts.get(&t).ok_or("branch into an instruction")?; + if j == 0 { + return Err("branch to the entry"); + } + target[i] = Some(j); + leaders.extend([j, i + 1]); + } else if d.inst.flags & F_TERMINATOR != 0 { + leaders.insert(i + 1); + } + } + leaders.retain(|&i| i < insts.len()); + let firsts: Vec = leaders.into_iter().collect(); + let block_of: HashMap = firsts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); + let blocks: Vec<(usize, usize)> = firsts.iter().enumerate().map(|(b, &i)| (i, firsts.get(b + 1).copied().unwrap_or(insts.len()))).collect(); + let succ: Vec> = blocks + .iter() + .map(|&(_, end)| { + let d = &insts[end - 1]; + let next = block_of.get(&end).copied(); + match target[end - 1] { + Some(t) if d.inst.flags & F_CONDITIONAL != 0 => [Some((block_of[&t], Edge::Taken)), next.map(|n| (n, Edge::NotTaken))].into_iter().flatten().collect(), + Some(t) => vec![(block_of[&t], Edge::Always)], + None if d.inst.flags & F_TERMINATOR != 0 => vec![], + None => next.map(|n| (n, Edge::Always)).into_iter().collect(), + } + }) + .collect(); + let n = blocks.len(); + // reverse postorder of what the entry reaches + let (mut order, mut seen, mut stack) = (Vec::new(), vec![false; n], vec![(0usize, 0usize)]); + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + if let Some(&(s, _)) = succ[b].get(i) { + top.1 += 1; + if !seen[s] { + seen[s] = true; + stack.push((s, 0)); + } + } else { + order.push(b); + stack.pop(); + } + } + order.reverse(); + let mut rpo = vec![usize::MAX; n]; + for (i, &b) in order.iter().enumerate() { + rpo[b] = i; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for (k, &(s, _)) in succ[b].iter().enumerate() { + preds[s].push((b, k)); + } + } + // dominators (Cooper, Harvey, Kennedy) – a retreating edge must go to a dominator + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while rpo[a] > rpo[b] { + a = idom[a]; + } + while rpo[b] > rpo[a] { + b = idom[b]; + } + } + a + }; + loop { + let mut changed = false; + for &b in &order[1..] { + let new = preds[b].iter().map(|p| p.0).filter(|&p| idom[p] != usize::MAX).reduce(|a, p| intersect(&idom, a, p)).unwrap_or(usize::MAX); + changed |= idom[b] != new; + idom[b] = new; + } + if !changed { + break; + } + } + let dominates = |h: usize, mut b: usize| loop { + if b == h { + return true; + } + if b == 0 { + return false; + } + b = idom[b]; + }; + let mut body: Vec>> = vec![None; n]; + for &h in &order { + for &(p, _) in &preds[h] { + if rpo[p] < rpo[h] { + continue; + } + if !dominates(h, p) { + return Err("irreducible control flow"); + } + let inside = body[h].get_or_insert_with(|| vec![false; n]); + inside[h] = true; + let mut work = vec![p]; + while let Some(b) = work.pop() { + if !inside[b] { + inside[b] = true; + work.extend(preds[b].iter().map(|q| q.0)); + } + } + } + } + let effects = insts + .iter() + .map(|d| { + let written = x64_masks::uses(d).1; + let explicit = rdna2::sgpr_uses(d).1.iter().fold(0u128, |m, &r| m | 1 << r); + let kill = if d.inst.name.starts_with("S_MOVREL") { !0 } else { written | explicit }; + (written, kill, d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")) + }) + .collect(); + Ok(Lanes { insts, wave64, launch, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) + } + + fn atom(&mut self, a: Atom, block: usize) -> R { + let fresh = self.born.len() as u32; + let v = *self.atoms.entry(a).or_insert(fresh); + if v == fresh { + self.born.push(block); + } + Ok(self.bdd.atom(v)) + } + + /// `step` within `STEP_NODES` new nodes; past that, what the instruction writes becomes + /// unknown: EXEC and SCC atoms, no mask in the other registers (weaker, still sound). + fn step_bounded(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let mut next = st.clone(); + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.step(&mut next, i, block); + self.bdd.limit = MAX_NODES; + if r.is_ok() { + *st = next; + return Ok(()); + } + let d = &self.insts[i]; + let (_, kill, writes_scc) = self.effects[i]; + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + if st.regs[EXEC].is_none() || d.inst.name.starts_with("V_CMPX") { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = Some((self.atom(Atom::Scc(d.pc), block)?, true)); + } + Ok(()) + } + + /// A scalar source read as a mask: a register's lane function, all lanes, none, or None. + fn mask_src(&self, st: &State, d: &Decoded, code: u64) -> Option { + match code { + 128 => Some(FALSE), + 193 => Some(TRUE), + 255 if d.literal == Some(0) => Some(FALSE), + 255 if d.literal == Some(!0) && !self.wave64 => Some(TRUE), + c if c < 128 => st.regs[c as usize], + _ => None, + } + } + + /// … and an atom where the analysis cannot follow it. + fn need(&mut self, st: &State, d: &Decoded, code: u64, block: usize) -> R { + match self.mask_src(st, d, code) { + Some(v) => Ok(v), + None => self.atom(Atom::Opaque(d.pc, code as usize), block), + } + } + + fn combine(&mut self, op: &str, a: B, b: B) -> R> { + let bdd = &mut self.bdd; + Ok(Some(match op { + "AND" => bdd.and(a, b)?, + "OR" => bdd.or(a, b)?, + "XOR" => bdd.apply(Op::Xor, a, b)?, + "ANDN2" => (bdd.not(b).and_then(|nb| bdd.and(a, nb)))?, + "ORN2" => (bdd.not(b).and_then(|nb| bdd.or(a, nb)))?, + "ANDN1" => (bdd.not(a).and_then(|na| bdd.and(na, b)))?, + "ORN1" => (bdd.not(a).and_then(|na| bdd.or(na, b)))?, + "NAND" => (bdd.and(a, b).and_then(|x| bdd.not(x)))?, + "NOR" => (bdd.or(a, b).and_then(|x| bdd.not(x)))?, + "XNOR" => (bdd.apply(Op::Xor, a, b).and_then(|x| bdd.not(x)))?, + _ => return Ok(None), + })) + } + + /// One instruction's effect on the masks. + fn step(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let d = &self.insts[i]; + let (written, kill, writes_scc) = self.effects[i]; + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let e = st.regs[EXEC].expect("EXEC"); + let mut set: Vec<(usize, B)> = Vec::new(); + let mut scc = None; + if name.starts_with("V_") { + if name.starts_with("V_CMPX") { + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((EXEC, self.bdd.and(l, e)?)); + } else if written != 0 && !matches!(name, "V_READLANE_B32" | "V_READFIRSTLANE_B32") { + // compares and carries: the lane's result, 0 in inactive lanes + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((written.trailing_zeros() as usize, self.bdd.and(l, e)?)); + } + } else if let Some(base) = name.strip_suffix(if self.wave64 { "_B64" } else { "_B32" }) { + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").map(|v| v as usize)); + let op = base.trim_start_matches("S_"); + if let Some(op) = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")) { + let a = self.need(st, d, s0, block)?; + let new = self.combine(op, a, e)?.ok_or("unknown saveexec")?; + set.push((EXEC, new)); + if let Some(sd) = sd.filter(|&r| r < 128) { + set.push((sd, if base.ends_with("_WREXEC") { new } else { e })); + } + scc = Some((new, true)); + } else { + let (a, b) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)); + let value = match (op, a, b) { + ("MOV", Some(a), _) => Some(a), + ("NOT", Some(a), _) => Some(self.bdd.not(a)?), + ("WQM", Some(a), _) => self.wqm(a), + ("CSELECT", Some(a), Some(b)) => match st.scc { + Some((u, false)) => { + let (ua, nu) = (self.bdd.and(u, a)?, self.bdd.not(u)?); + let nub = self.bdd.and(nu, b)?; + Some(self.bdd.or(ua, nub)?) + } + _ => None, + }, + (_, Some(a), Some(b)) => self.combine(op, a, b)?, + _ => None, + }; + if let (Some(v), Some(sd)) = (value, sd.filter(|&r| r < 128)) { + set.push((sd, v)); + if !matches!(op, "MOV" | "CSELECT") { + scc = Some((v, true)); + } + } + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp = if self.wave64 { ("S_CMP_EQ_U64", "S_CMP_LG_U64") } else { ("S_CMP_EQ_U32", "S_CMP_LG_U32") }; + if name == cmp.0 || name == cmp.1 { + let (s0, s1) = (fv("SSRC0").unwrap_or(255), fv("SSRC1").unwrap_or(255)); + if let (Some(a), Some(b)) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)) { + if s0 < 128 || s1 < 128 { + let x = self.bdd.apply(Op::Xor, a, b)?; + scc = Some((if name == cmp.0 { self.bdd.not(x)? } else { x }, true)); + } + } + } + // whatever else the instruction writes is no longer a known mask + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + for (r, v) in set { + self.kill(st, r); + st.regs[r] = Some(v); + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = match scc { + Some(s) => Some(s), + None => Some((self.atom(Atom::Scc(d.pc), block)?, false)), + }; + } + Ok(()) + } + + /// `s_wqm` of a mask: the lanes whose quad has a lane in it. Followed only where that is a + /// mask the analysis knows: none or every lane, and the launch EXEC (`LaunchExec::Unknown`), + /// since a lane that runs outside it is a helper lane of a quad with a lane in it. + fn wqm(&mut self, a: B) -> Option { + if a <= TRUE { + return Some(a); + } + let launch = *self.atoms.get(&Atom::Launch)?; + (a == self.bdd.atom(launch)).then_some(TRUE) + } + + fn kill(&self, st: &mut State, r: usize) { + st.regs[r] = None; + // wave64: the pair starting one register lower + if self.wave64 && r > 0 { + st.regs[r - 1] = None; + } + } + + /// Whether `c` is the same in every lane that reaches with its EXEC bit (`reach` and `e`): + /// then a lane deciding by its own bit decides as the whole wave does. Unknown (too large + /// to build) is no. + fn uniform_over(&mut self, reach: B, e: B, c: B) -> bool { + let Some(re) = self.bdd.within(|bdd| bdd.and(reach, e)) else { return false }; + if self.bdd.implies(re, c) { + return true; + } + match self.bdd.within(|bdd| bdd.not(c)) { + Some(nc) => self.bdd.implies(re, nc), + None => false, + } + } + + /// The condition under which a lane takes the branch ending a block, and whether it is a + /// lane mask's. + fn cond(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + let e = st.regs[EXEC].expect("EXEC"); + let (c, lane, negate) = match d.inst.name { + n @ ("S_CBRANCH_SCC0" | "S_CBRANCH_SCC1") => { + let (c, lane) = match st.scc { + Some(s) => s, + None => (self.atom(Atom::Scc(d.pc), block)?, false), + }; + (c, lane, n == "S_CBRANCH_SCC0") + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let v = match st.regs[VCC] { + Some(v) => v, + None => self.atom(Atom::Opaque(d.pc, VCC), block)?, + }; + (self.bdd.and(v, e)?, true, n == "S_CBRANCH_VCCZ") + } + n @ ("S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ") => (e, true, n == "S_CBRANCH_EXECZ"), + _ => (self.atom(Atom::Scc(d.pc), block)?, false, false), + }; + Ok((if negate { self.bdd.not(c)? } else { c }, lane)) + } + + /// `cond` within `STEP_NODES` new nodes; past that, an unknown per-lane condition. + fn cond_bounded(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.cond(st, d, block); + self.bdd.limit = MAX_NODES; + match r { + Ok(c) => Ok(c), + Err(_) => Ok((self.atom(Atom::Scc(d.pc), block)?, true)), + } + } + + /// Simulates a block from `st`: the facts and states on its outgoing edges. + fn run_block(&mut self, b: usize, reach: B, mut st: State) -> R> { + let (first, end) = self.blocks[b]; + for i in first..end { + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + let mut out = Vec::new(); + for k in 0..self.succ[b].len() { + let fact = match self.succ[b][k].1 { + Edge::Always => reach, + edge => { + // a fact too large to build is left without the branch's condition (weaker) + let (c, _) = self.cond_bounded(&st, last, b)?; + self.bdd + .within(|bdd| { + let c = if edge == Edge::Taken { c } else { bdd.not(c)? }; + bdd.and(reach, c) + }) + .unwrap_or(reach) + } + }; + out.push((fact, st.clone())); + } + Ok(out) + } + + /// Block b's reach and masks from its predecessors' edges. Back edges add their facts + /// with the loop's atoms dropped; their masks only count with `back_masks` (the check of a + /// loop head's guess). + fn join(&mut self, b: usize, outs: &[Vec<(B, State)>], forced: &HashSet<(usize, usize)>, back_masks: bool) -> R<(B, State)> { + let mut reach = FALSE; + let mut edges: Vec<(B, State)> = Vec::new(); + for &(p, k) in &self.preds[b].clone() { + let Some((fact, st)) = outs[p].get(k) else { continue }; + let back = self.body[b].as_ref().is_some_and(|inside| inside[p]); + let carried = if back { + let (inside, born) = (self.body[b].as_ref().unwrap(), &self.born); + self.bdd.within(|bdd| bdd.exists(*fact, &|v| inside[born[v as usize]], &mut HashMap::new())).unwrap_or(TRUE) + } else { + *fact + }; + reach = self.bdd.within(|bdd| bdd.or(reach, carried)).unwrap_or(TRUE); + if *fact != FALSE && (!back || back_masks) { + edges.push((*fact, st.clone())); + } + } + let mut st = State { regs: vec![None; 128], scc: None }; + st.regs[EXEC] = Some(FALSE); + if edges.is_empty() { + return Ok((reach, st)); + } + // an SCC a mask op set on any incoming edge, back edges included (their masks may not + // count here, but a lane's own SCC carried around a loop is still a lane's: thehollowedone, + // #1745) + let scc_lane = self.preds[b].iter().any(|&(p, k)| outs[p].get(k).is_some_and(|(f, s)| *f != FALSE && s.scc.is_some_and(|x| x.1))); + for slot in 0..=SCC { + let get = |s: &State| if slot == SCC { s.scc.map(|x| x.0) } else { s.regs[slot] }; + let lane = scc_lane; + let v = if forced.contains(&(b, slot)) { + Some(self.atom(Atom::Join(b, slot), b)?) + } else if edges.iter().any(|(_, s)| get(s).is_none()) { + None + } else { + let first = get(&edges[0].1).unwrap(); + Some(if edges.iter().all(|(_, s)| get(s) == Some(first)) { + first + } else if edges.iter().all(|(fact, s)| self.bdd.implies(*fact, get(s).unwrap())) { + TRUE + } else if edges.iter().all(|(fact, s)| self.bdd.disjoint(*fact, get(s).unwrap(), &mut HashSet::new())) { + FALSE + } else { + self.atom(Atom::Join(b, slot), b)? + }) + }; + if slot == SCC { + // unknown but a lane's on some edge: an unknown lane condition, not a uniform one + let v = match v { + None if lane => Some(self.atom(Atom::Join(b, SCC), b)?), + v => v, + }; + st.scc = v.map(|v| (v, lane)); + } else { + st.regs[slot] = v; + } + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Join(b, EXEC), b)?); + } + Ok((reach, st)) + } + + fn analyze(mut self) -> R { + let n = self.blocks.len(); + let mut entry = State { regs: vec![None; 128], scc: None }; + entry.regs[EXEC] = Some(match self.launch { + LaunchExec::All => TRUE, + LaunchExec::Unknown => self.atom(Atom::Launch, 0)?, + }); + let mut forced = HashSet::new(); + let mut reach = vec![FALSE; n]; + let mut ins: Vec> = vec![None; n]; + let mut outs: Vec> = vec![Vec::new(); n]; + // blocks to recompute: every block first, then those an incoming edge changed for. Any + // fixpoint of the facts is sound (it is weaker than the least one), so a wrong loop-head + // guess only makes that head recompute instead of restarting from nothing. + let order = self.order.clone(); + let mut dirty = vec![false; n]; + for &b in &order { + dirty[b] = true; + } + let heads: Vec = order.iter().copied().filter(|&h| self.body[h].is_some()).collect(); + let mut rounds = 0; + loop { + while order.iter().any(|&b| dirty[b]) { + rounds += 1; + if rounds > MAX_ROUNDS { + return Err("no fixpoint"); + } + for &b in &order { + if !std::mem::take(&mut dirty[b]) { + continue; + } + let (r, st) = if b == 0 { (TRUE, entry.clone()) } else { self.join(b, &outs, &forced, false)? }; + if ins[b].as_ref() == Some(&st) && reach[b] == r { + continue; + } + reach[b] = r; + ins[b] = Some(st.clone()); + let out = self.run_block(b, r, st)?; + if out != outs[b] { + for &(s, _) in &self.succ[b] { + dirty[s] = true; + } + outs[b] = out; + } + } + } + // loop heads: does the guess from the forward edges hold on the back edges too? + let mut wrong = false; + for &h in &heads { + let (_, full) = self.join(h, &outs, &forced, true)?; + let guess = ins[h].as_ref().unwrap(); + for slot in 0..=SCC { + let (g, f) = if slot == SCC { (guess.scc.map(|x| x.0), full.scc.map(|x| x.0)) } else { (guess.regs[slot], full.regs[slot]) }; + if g != f && forced.insert((h, slot)) { + wrong = true; + dirty[h] = true; + } + } + } + if !wrong { + break; + } + } + let mut sum = Summary::default(); + let mut implied: HashMap<(B, B), bool> = HashMap::new(); + let mut lane_branch = vec![false; self.blocks.len()]; + for &b in &self.order.clone() { + let mut st = ins[b].clone().unwrap(); + let (first, end) = self.blocks[b]; + for i in first..end { + let d = &self.insts[i]; + if is_vector(d) { + sum.vector += 1; + let key = (reach[b], st.regs[EXEC].unwrap()); + let covered = match implied.get(&key) { + Some(&c) => c, + None => *implied.entry(key).or_insert(self.bdd.implies(key.0, key.1)), + }; + if !covered { + sum.guarded.push(d.pc); + } + } + // an SCC a mask op set, read by a scalar instruction: the console reads the whole + // wave's, each lane here its own bit, the same only where it is constant over EXEC + let n = d.inst.name; + if ["S_CSELECT", "S_CMOV", "S_ADDC", "S_SUBB"].iter().any(|p| n.starts_with(p)) { + if let Some((c, true)) = st.scc { + let e = st.regs[EXEC].unwrap(); + if !self.uniform_over(reach[b], e, c) { + return Err("a scalar read of the SCC of a mask op, with lanes in EXEC without its bit"); + } + } + } + if d.inst.name == if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" } { + let s0 = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); + if self.mask_src(&st, d, s0).and_then(|a| self.wqm(a)) == Some(TRUE) { + sum.wqm_all.push(d.pc); + } + } + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + if self.succ[b].iter().any(|s| s.1 != Edge::Always) { + let (c, lane) = self.cond_bounded(&st, last, b)?; + // a lane branch is each lane's only where the condition is constant over the lanes + // in EXEC (`s_and_saveexec` then `s_cbranch_execz`); `s_cbranch_vccz` on a mask some + // lanes in EXEC lack takes the whole wave's way on the console (Kalmarv, #1745) + if lane && !self.uniform_over(reach[b], st.regs[EXEC].unwrap(), c) { + return Err("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit"); + } + let (_, lane) = self.cond_bounded(&st, last, b)?; + if lane { + sum.lane_branches += 1; + } else { + sum.uniform_branches += 1; + } + lane_branch[b] = lane; + } + } + sum.blocks = (0..self.blocks.len()) + .map(|b| Block { + insts: self.blocks[b].0..self.blocks[b].1, + succ: self.succ[b].clone(), + preds: self.preds[b].iter().map(|p| p.0).collect(), + lane_branch: lane_branch[b], + }) + .collect(); + sum.order = self.order.clone(); + Ok(sum) + } +} + +/// Analyses a decoded program (far jumps resolved) that starts with every lane in EXEC. +pub fn analyze(insts: &[Decoded], wave64: bool) -> R { + analyze_launch(insts, wave64, LaunchExec::All) +} + +/// Analyses a decoded program (far jumps resolved) that starts with EXEC as `launch` says. +pub fn analyze_launch(insts: &[Decoded], wave64: bool, launch: LaunchExec) -> R { + if insts.is_empty() { + return Ok(Summary::default()); + } + Lanes::new(insts, wave64, launch)?.analyze() +} + +/// Decodes and analyses a program. +pub fn analyze_code(code: &[u8], wave64: bool) -> R { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { return Err("cannot decode") }; + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze(&insts, wave64) +} + +#[cfg(test)] +mod tests { + use super::*; + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + const MOV2: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]); + const MOV3: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 130)]); + const RESTORE: I = ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]); + + /// Every instruction here is one dword: a branch's SIMM16 is (target − index − 1). + fn run(lines: &[I]) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + assert_eq!(bytes.len(), lines.len() * 4); + analyze_code(&bytes, true) + } + + #[test] + fn implication_tests_agree_with_the_built_formulas() { + let mut bdd = Bdd::new(); + let x: Vec = (0..4).map(|v| bdd.mk(v, FALSE, TRUE).unwrap()).collect(); + let mut fs = vec![FALSE, TRUE]; + for &a in &x { + for &b in &x { + let (and, or, xor) = (bdd.and(a, b).unwrap(), bdd.or(a, b).unwrap(), bdd.apply(Op::Xor, a, b).unwrap()); + let na = bdd.not(a).unwrap(); + fs.extend([a, and, or, xor, na]); + } + } + for &a in &fs { + for &b in &fs { + let nb = bdd.not(b).unwrap(); + let (built_imp, built_dis) = (bdd.and(a, nb).unwrap() == FALSE, bdd.and(a, b).unwrap() == FALSE); + assert_eq!(bdd.implies(a, b), built_imp, "{a} → {b}"); + assert_eq!(bdd.disjoint(a, b, &mut HashSet::new()), built_dis, "{a} ∧ {b}"); + } + } + } + + #[test] + fn a_skipped_if_needs_no_guard() { + // v_cmp; s_and_saveexec s[0:1], vcc; s_cbranch_execz L; v_mov; L: exec |= s[0:1]; v_mov + let s = run(&[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches), (2, 0, 1, 0)); + // the CFG the lowering walks: entry (to the skip), the v_mov, the join + let b = &s.blocks; + assert_eq!(b.iter().map(|b| b.insts.clone()).collect::>(), vec![0..3, 3..4, 4..7]); + assert_eq!(b[0].succ, vec![(2, Edge::Taken), (1, Edge::NotTaken)]); + assert_eq!((b[1].succ.clone(), b[2].preds.clone()), (vec![(2, Edge::Always)], vec![0, 1])); + assert_eq!(b.iter().map(|b| b.lane_branch).collect::>(), vec![true, false, false]); + assert_eq!(s.order, vec![0, 1, 2]); + } + + #[test] + fn an_if_without_its_skip_is_guarded() { + let s = run(&[CMP, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), MOV2, RESTORE, MOV3, ENDPGM]).unwrap(); + assert_eq!(s.vector, 2); + assert_eq!(s.guarded, vec![8], "only the v_mov under the narrowed EXEC"); + } + + #[test] + fn lanes_leaving_a_loop_keep_it_unguarded() { + // s_mov s[0:1], exec; L: v_cmp; v_add; exec &= ~vcc; s_cbranch_execnz L; exec |= s[0:1] + let s = run(&[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + CMP, + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 5)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 0, 1)); + } + + #[test] + fn a_loop_that_narrows_exec_is_found_on_its_back_edge() { + // s4 = 0; L: v_mov; v_cmp; exec &= vcc; s4 += 1; s_cmp_lt s4, 10; s_cbranch_scc1 L; v_mov + // – the head's guess (all lanes) is wrong once the back edge is seen + let s = run(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)]), + MOV2, + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 138)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!(s.guarded, vec![4, 28]); + assert_eq!((s.lane_branches, s.uniform_branches), (0, 1)); + } + + #[test] + fn a_vccz_branch_is_a_lane_branch_only_where_vcc_is_the_exec() { + // v_cmp; s_cbranch_vccz L: the console skips only when no lane in EXEC has the bit, so + // lanes in EXEC without it run the v_mov too; deciding per lane would skip it: refused + let err = run(&[CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).err(); + assert_eq!(err, Some("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit")); + // v_cmp; s_and_saveexec s0, vcc; s_cbranch_vccz L: VCC ∧ EXEC is the new EXEC, the same + // as each lane's bit for every lane in it: a lane branch + let save: I = ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + let s = run(&[CMP, save, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 1, 1)); + } + + #[test] + fn unsupported_control_flow_is_refused() { + // a loop entered at two places + let two_entries = run(&[ + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + MOV3, + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0xFFFD)]), + ENDPGM, + ]); + assert_eq!(two_entries.unwrap_err(), "irreducible control flow"); + assert_eq!(run(&[("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]), ENDPGM]).unwrap_err(), "indirect jump"); + assert_eq!(run(&[MOV2, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFE)]), ENDPGM]).unwrap_err(), "branch to the entry"); + } + + fn run_launch(lines: &[I], launch: LaunchExec) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let mut insts = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze_launch(&insts, true, launch) + } + + #[test] + fn a_lane_outside_exec_at_launch_keeps_its_guard_until_exec_is_written() { + // v_mov (a helper lane must not write); exec = -1; v_mov (every lane writes) + let p = [MOV2, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), MOV3, ENDPGM]; + let all = run_launch(&p, LaunchExec::All).unwrap(); + assert_eq!((all.vector, all.guarded.len()), (2, 0)); + let unknown = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(unknown.guarded, vec![0], "only the v_mov before EXEC is written"); + } + + #[test] + fn a_lane_branch_still_proves_exec_when_the_launch_exec_is_unknown() { + // as `a_skipped_if_needs_no_guard`: inside the if only lanes with their bit run, but the + // restored EXEC after the join is the launch EXEC again + let p = [ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]; + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!((s.vector, s.guarded.clone(), s.lane_branches), (2, vec![20], 1)); + } + + #[test] + fn whole_quad_mode_of_the_launch_exec_is_every_lane() { + // s[0:1] = exec; s_wqm exec, exec; v_mov (helper lanes too); exec &= s[0:1]; v_mov + let wqm: I = ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]); + let p: [I; 6] = [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + wqm, + MOV2, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + MOV3, + ENDPGM, + ]; + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(s.guarded, vec![16], "only the v_mov after EXEC is narrowed to the launch EXEC again"); + assert_eq!(s.wqm_all, vec![4]); + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + // the quads of any other mask are not followed + let s = run_launch(&[CMP, ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), MOV2, ENDPGM], LaunchExec::All).unwrap(); + assert_eq!((s.guarded, s.wqm_all), (vec![8], vec![])); + } +} diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs new file mode 100644 index 0000000000..1b5942dea4 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -0,0 +1,4322 @@ +//! Lowering of console programs to DXIL-shaped IR, for the direct backend (`XCL_RECOMP_DXIL`). +//! +//! The console CFG is kept: blocks become blocks, and every register dword is an SSA value +//! (`ssa`). EXEC is not a number here but each lane's own bit (`i1`): a mask branch +//! (`s_cbranch_execz`, `vccz`, SCC of a mask op) is a branch of each lane on its bit, and a +//! vector instruction keeps a guard (`select(bit, new, old)`) only where `lane_masks` could not +//! prove the bit set. An SGPR therefore has two views: its number (`Var::S`) and, when it holds +//! a mask, the lane's bit of it (`Var::M`). Writing one view leaves a marker in the other – `undef` +//! – so a number read where only a mask was written (or the reverse, across a join) is found once +//! every phi is complete, and the program is refused (it stays on the HLSL path). A bit read where +//! only a number was written is the lane's bit of that number. At the end of the program every +//! lane is back, so a mask stored as a number there is the wave's ballot of the bits. +//! +//! Kernel mode only for now (the ABI of `runner`): registers come from `io` and go back to `res`. +//! The IR is written through `Ir`, the part of the DXIL module builder this needs. + +use std::collections::HashSet; + +use super::lane_masks::{self, Edge, Summary}; +use super::ssa::{Sink, Ssa, Var}; +use super::{KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +mod wave; + +type R = Result; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Bin { + Add, + Sub, + Mul, + And, + Or, + Xor, + Shl, + LShr, + AShr, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Cmp { + Eq, + Ne, + Ult, + Ule, + Ugt, + Uge, + Slt, + Sle, + Sgt, + Sge, +} + +/// What the lowering needs from the DXIL module builder. Blocks are numbered in the order +/// `new_block` creates them, the first being the entry; `And` / `Or` / `Xor` take `i1` or `i32`. +pub trait Ir: Sink { + fn new_block(&mut self) -> usize; + fn at(&mut self, block: usize); + fn int(&mut self, v: u32) -> Self::V; + fn boolean(&mut self, v: bool) -> Self::V; + fn bin(&mut self, op: Bin, a: Self::V, b: Self::V) -> Self::V; + fn icmp(&mut self, c: Cmp, a: Self::V, b: Self::V) -> Self::V; + fn select(&mut self, c: Self::V, a: Self::V, b: Self::V) -> Self::V; + /// `i1` → `i32` (0 / 1) + fn zext(&mut self, b: Self::V) -> Self::V; + /// the console lane of this thread + fn lane(&mut self) -> Self::V; + /// compute: the group's id, component k (x, y, z) + fn group_id(&mut self, k: u32) -> Self::V; + /// compute, a group of `threads`: this thread's console thread (its flat index in the group) + /// and that thread's id (x, y, z). The console forms a wave from consecutive threads, lane l + /// the l-th of them, so the flat index is the wave's first thread plus `lane()`; a PC driver + /// need not, in 2-D / 3-D groups, so the threads are numbered as the waves arrive + fn compute_ids(&mut self, threads: [u32; 3]) -> (Self::V, [Self::V; 3]); + /// the wave's ballot of `c`: lanes 0–31, 32–63 + fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; + /// `ballot` where only the word of this lane's 32-lane half is used (the other may be + /// anything): a wave64 split into two 32-lane hardware waves needs no exchange for it + fn ballot_half(&mut self, c: Self::V) -> [Self::V; 2]; + /// `v` as lane `lane` holds it (`WaveReadLaneAt`); `lane` may differ between lanes and is + /// always one running this instruction too + fn read_lane(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// `read_lane` of a lane in this lane's 32-lane half (DPP, permlane, swizzle) + fn read_lane_half(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// Whether a whole-wave `ballot` / `read_lane` meets another hardware wave (the split form + /// of a wave64 program): then it needs every lane of the console wave where it runs. + fn whole_needs_exchange(&self) -> bool { + false + } + /// the number of bits set in `v` (`countbits`) + fn count_bits(&mut self, v: Self::V) -> Self::V; + /// `d` lowered with another lowering's instruction semantics (#1426's `Lw::inst_guarded`): + /// `inputs` are the registers it reads, `guard` (i1) decides this lane's register writes and + /// memory effects, and the values of `outputs` after it come back in order. Err when there + /// is no such lowering or it refuses `d`. + fn foreign(&mut self, _d: &Decoded, _guard: Self::V, _inputs: &[(Var, Self::V)], _outputs: &[Var]) -> R> { + Err("no foreign lowering".into()) + } + fn io_load(&mut self, dword: Self::V) -> Self::V; + fn res_store(&mut self, dword: Self::V, value: Self::V); + /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of + /// range reads 0 and writes nothing, as D3D12 raw buffers do + fn mem_load(&mut self, addr: Self::V) -> Self::V; + fn mem_store(&mut self, addr: Self::V, value: Self::V); + /// the 4 GiB memory windows the program addresses: with more than one, `mem_load` / + /// `mem_store` (window 0 only) are not used, and memory instructions go to `foreign` + fn mem_windows(&self) -> u32 { + 1 + } + fn br(&mut self, target: usize); + fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); + fn ret(&mut self); + /// VS / PS: the stage's start (in the DXIL adapter #1426's `setup_vertex` / `setup_pixel`), + /// with `vregs` the VGPRs the program names. None: this IR has no graphics entry, and the + /// program is refused. + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let _ = vregs; + None + } + /// … and its end (`finish_gfx`: the outputs, the PS discard), where every lane is back + fn graphics_end(&mut self) {} +} + +/// What a VS / PS starts with (`Ir::graphics_start`). +pub struct GraphicsStart { + /// the registers the stage sets beyond the user SGPRs from `io`: (SGPR, value), (VGPR, + /// value); a VGPR it does not set starts as 0 + pub sgprs: Vec<(u8, V)>, + pub vgprs: Vec<(u16, V)>, + /// the lane's bit of the launch EXEC: false in a PS's helper lanes, which run the program too + pub exec: V, +} + +const EXEC: u8 = 126; +const VCC: u8 = 106; + +/// The program's stage: where its registers come from and go. +#[derive(Clone, Copy)] +pub enum Stage<'a> { + /// `runner`'s ABI: the whole register file from `io`, back to `res` + Kernel, + /// a compute program: user SGPRs from `io`, then the group ids and TG_SIZE it enables, + /// thread ids in v0–v2; it ends without storing registers + Compute(&'a super::CsInterface), + /// a vertex / pixel shader: user SGPRs from `io`, the rest from `Ir::graphics_start`; it ends + /// in `Ir::graphics_end` + Vertex, + Pixel, +} + +struct Lower<'a, I: Ir> { + ir: I, + ssa: Ssa, + sum: &'a Summary, + guarded: HashSet, + wave64: bool, + /// the markers: a number where a mask was written, a bit where a number was + num_marker: I::V, + bit_marker: I::V, + /// values read as numbers / as mask bits, checked once every phi is complete + num_uses: Vec, + bit_uses: Vec, + lane: Option, + /// per IR block: not every lane that reached one of the program's lane branches gets here + /// before they meet again (a loop that lanes leave one by one, an arm some lanes skip) + partial: Vec, + /// stale-value ownership for blocks split by a coalesced run: backbone blocks of console + /// block b (`blk(b)` and its continuations) share `blk(b)` for both defs and uses, while a + /// run's inner block keeps its own `def_owner` (any def there is partial to outside reads) + /// and `blk(b)` as its `use_owner` (reads of earlier defs in the same console block stay valid) + def_owner: Vec, + use_owner: Vec, + /// inside a coalesced guarded run's own block: only lanes with EXEC set enter, so writes + /// need no per-instruction guard + unguarded: bool, + /// the IR block each mask bit was written in, and the mask bits read (block, value) + def_block: std::collections::HashMap, + lane_uses: Vec<(usize, I::V)>, + /// a DPP instruction's first source, read from its source lane, and its write enable + dpp_src: Option, + dpp_en: Option, + /// survey mode (`survey_compute`): every refusal is noted here and the lowering goes on + noted: Option>, + /// a VS / PS (`lower_graphics`): `s_wqm` only of the launch EXEC (its quads' helper lanes) + graphics: bool, +} + +/// A vector memory store: a side effect inactive lanes must not have. +fn is_store(d: &Decoded) -> bool { + let n = d.inst.name; + (n.starts_with("GLOBAL_STORE_") || n.starts_with("FLAT_STORE_")) && matches!(d.enc.name, "ENC_FLAT_GLBL" | "ENC_FLAT") +} + +/// A PS instruction that needs all four lanes of each quad: an image sample or gather with an +/// implicit LOD (no `_L` / `_LZ`, no gradients `_D` / `_CD`), `image_get_lod`, `s_wqm`. The +/// console has them from whole-quad mode; DXIL leaves derivatives undefined where control flow is +/// not uniform over the quad. +fn whole_quad(name: &str) -> bool { + if name == "IMAGE_GET_LOD" || name.starts_with("S_WQM_") { + return true; + } + match name.strip_prefix("IMAGE_SAMPLE").or_else(|| name.strip_prefix("IMAGE_GATHER4")) { + Some(rest) => !rest.split('_').any(|t| matches!(t, "L" | "LZ" | "D" | "CD")), + None => false, + } +} + +/// Cross-lane and wave-level ops stay out of coalesced guarded runs (they need the parent +/// block's lane participation, e.g. fetch-inactive or whole-wave mask reads). +fn is_cross_lane(d: &Decoded) -> bool { + let n = d.inst.name; + matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) + || n.starts_with("V_PERMLANE") + || n.starts_with("V_MBCNT_") + || n.starts_with("V_READLANE") + || n.starts_with("V_READFIRSTLANE") + || n.starts_with("V_WRITELANE") + || n.starts_with("DS_SWIZZLE") + || n.starts_with("DS_BPERMUTE") + || n.starts_with("DS_PERMUTE") +} + +/// Any write to an SGPR, mask (VCC / EXEC / M0), or SCC must run for all lanes outside a +/// coalesced run (inactive lanes clear their bit in a VALU mask write rather than keeping it). +fn writes_scalar_or_scc(d: &Decoded) -> bool { + let (_, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r) & !(1u128 << 125); + writes != 0 + || d.inst.name.starts_with("V_CMPX") + || d.ienc + .operands + .iter() + .any(|o| o.output && matches!(o.ty, "OPR_VCC" | "OPR_EXEC" | "OPR_SDST_EXEC" | "OPR_SDST_M0" | "OPR_SSRC_SPECIAL_SCC")) +} + +/// Pure no-ops in this lowering: allowed inside a coalesced run without breaking it. +fn is_run_noop(d: &Decoded) -> bool { + matches!( + d.inst.name, + "V_NOP" | "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" + ) +} + +/// Guarded instructions with side effects that inactive lanes must not execute even alone. +fn must_branch(d: &Decoded) -> bool { + let n = d.inst.name; + is_store(d) + || n.contains("_STORE_") + || n.starts_with("IMAGE_STORE") + || n.contains("_ATOMIC_") + || (n.starts_with("DS_") && !n.starts_with("DS_READ") && !n.starts_with("DS_NOP")) + || n == "EXP" +} + +fn can_coalesce(d: &Decoded, guarded: &HashSet) -> bool { + guarded.contains(&d.pc) && !is_cross_lane(d) && !whole_quad(d.inst.name) && !writes_scalar_or_scc(d) +} + +/// Exclusive end of a block's non-terminator instructions. +fn block_body_end(insts: &[Decoded], range: &std::ops::Range) -> usize { + let mut end = range.end; + if end > range.start { + let d = &insts[end - 1]; + let name = d.inst.name; + if name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some() { + end -= 1; + } + } + end +} + +/// Straight-line runs of guarded instructions in one console block that benefit from a single +/// per-lane EXEC branch instead of per-write `select`s (or per-store branches): any run with +/// a `must_branch` instruction or at least two guarded instructions. +fn coalesced_runs(insts: &[Decoded], range: &std::ops::Range, guarded: &HashSet) -> Vec> { + let end = block_body_end(insts, range); + let mut runs = Vec::new(); + let mut start: Option = None; + let mut last_end = 0usize; + let mut inst_count = 0usize; + let mut branch = false; + let mut flush = |start: &mut Option, last_end: usize, inst_count: &mut usize, branch: &mut bool| { + if let Some(s) = start.take() { + if *branch || *inst_count >= 2 { + runs.push(s..last_end); + } + *inst_count = 0; + *branch = false; + } + }; + for i in range.start..end { + let d = &insts[i]; + if is_run_noop(d) { + continue; + } + if can_coalesce(d, guarded) { + if start.is_none() { + start = Some(i); + } + last_end = i + 1; + inst_count += 1; + branch |= must_branch(d); + } else { + flush(&mut start, last_end, &mut inst_count, &mut branch); + } + } + flush(&mut start, last_end, &mut inst_count, &mut branch); + runs +} + +/// IR block of analysis block b (block 0 is the prologue). +fn blk(b: usize) -> usize { + b + 1 +} + +impl<'a, I: Ir> Lower<'a, I> { + fn lane(&mut self) -> I::V { + *self.lane.get_or_insert_with(|| self.ir.lane()) + } + + fn read(&mut self, b: usize, var: Var) -> I::V { + self.ssa.read(&mut self.ir, b, var) + } + + fn read_num(&mut self, b: usize, r: u8) -> R { + let v = self.read(b, Var::S(r)); + if self.ssa.resolve_value(v) == self.num_marker { + return Err(format!("s{r}: a mask read as a number")); + } + self.num_uses.push(v); + self.lane_uses.push((b, v)); + Ok(v) + } + + /// The lane's bit of the mask in s (wave64: the pair from s). + fn read_bit(&mut self, b: usize, r: u8) -> R { + let m = self.read(b, Var::M(r)); + if self.ssa.resolve_value(m) != self.bit_marker { + self.bit_uses.push(m); + if r != EXEC { + self.lane_uses.push((b, m)); + } + return Ok(m); + } + // only numbers written: the lane's bit of them + let lane = self.lane(); + let word = if self.wave64 { + let (lo, hi) = (self.read_num(b, r)?, self.read_num(b, r + 1)?); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, hi, lo) + } else { + self.read_num(b, r)? + }; + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let shifted = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let bit = self.ir.bin(Bin::And, shifted, one); + let zero = self.ir.int(0); + Ok(self.ir.icmp(Cmp::Ne, bit, zero)) + } + + /// SCC, written and read like an SGPR number: a lane that skipped the block writing it + /// keeps its own older value (`stale`). + /// `v` as written in block b: in a block some lanes skip, a value made elsewhere (an older + /// mask copied, a shared constant) gets a copy of its own, so `stale` sees the write here. + fn own(&mut self, b: usize, v: I::V, bit: bool) -> I::V { + let v = match self.def_block.get(&v) { + Some(&d) if d != b && self.partial[b] => { + let z = if bit { self.ir.boolean(false) } else { self.ir.int(0) }; + self.ir.bin(Bin::Or, v, z) + } + _ => v, + }; + self.def_block.entry(v).or_insert(b); + v + } + + fn write_scc(&mut self, b: usize, v: I::V) { + let v = self.own(b, v, true); + self.ssa.write(b, Var::Scc, v); + } + + fn read_scc(&mut self, b: usize) -> I::V { + let v = self.read(b, Var::Scc); + self.lane_uses.push((b, v)); + v + } + + fn write_num(&mut self, b: usize, r: u8, v: I::V) { + let v = self.own(b, v, false); + self.ssa.write(b, Var::S(r), v); + self.ssa.write(b, Var::M(r), self.bit_marker); + if self.wave64 && r > 0 { + // a mask in the pair from s is no longer that mask + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + + fn write_bit(&mut self, b: usize, r: u8, bit: I::V) { + let bit = if r != EXEC { self.own(b, bit, true) } else { bit }; + self.ssa.write(b, Var::M(r), bit); + self.ssa.write(b, Var::S(r), self.num_marker); + if self.wave64 { + self.ssa.write(b, Var::S(r + 1), self.num_marker); + self.ssa.write(b, Var::M(r + 1), self.bit_marker); + if r > 0 { + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + } + + /// Whether s holds a mask here (its bit view is not the marker). + fn holds_mask(&mut self, b: usize, r: u8) -> bool { + let m = self.read(b, Var::M(r)); + self.ssa.resolve_value(m) != self.bit_marker + } + + /// A scalar or vector source operand as a number. + fn src(&mut self, b: usize, d: &Decoded, code: u64) -> R { + if let (233 | 234 | 250, Some(v)) = (code, self.dpp_src) { + return Ok(v); + } + Ok(match code { + 0..=105 | 106 | 107 | 124 | 126 | 127 => self.read_num(b, code as u8)?, + 128..=192 => self.ir.int((code - 128) as u32), + 193..=208 => self.ir.int((-((code - 192) as i32)) as u32), + 240..=247 => self.ir.int([0.5f32, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0][(code - 240) as usize].to_bits()), + 248 => self.ir.int(0x3E22_F983), + 253 => { + let s = self.read_scc(b); + self.ir.zext(s) + } + 255 => self.ir.int(d.literal.ok_or("missing literal")?), + 256..=511 => self.read(b, Var::V((code - 256) as u16)), + _ => return Err(format!("source code {code}")), + }) + } + + /// A scalar source operand as a mask's lane bit: a register, all lanes or none. + fn src_bit(&mut self, b: usize, code: u64) -> R { + match code { + 0..=105 | 106 | 107 | 126 | 127 => self.read_bit(b, code as u8), + 128 => Ok(self.ir.boolean(false)), + 193 => Ok(self.ir.boolean(true)), + _ => Err(format!("mask source code {code}")), + } + } + + fn write_v(&mut self, b: usize, d: &Decoded, r: u16, v: I::V) -> R<()> { + let v = match self.dpp_en.take() { + Some(en) => { + let old = self.read(b, Var::V(r)); + self.ir.select(en, v, old) + } + None => v, + }; + let v = if !self.unguarded && self.guarded.contains(&d.pc) { + let old = self.read(b, Var::V(r)); + let e = self.read_bit(b, EXEC)?; + self.ir.select(e, v, old) + } else { + v + }; + self.ssa.write(b, Var::V(r), v); + Ok(()) + } + + fn not(&mut self, a: I::V) -> I::V { + let t = self.ir.boolean(true); + self.ir.bin(Bin::Xor, a, t) + } + + /// A bitwise mask op of SALU / saveexec on lane bits. + fn bit_op(&mut self, op: &str, a: I::V, e: I::V) -> R { + Ok(match op { + "AND" => self.ir.bin(Bin::And, a, e), + "OR" => self.ir.bin(Bin::Or, a, e), + "XOR" => self.ir.bin(Bin::Xor, a, e), + "ANDN2" => { + let ne = self.not(e); + self.ir.bin(Bin::And, a, ne) + } + "ORN2" => { + let ne = self.not(e); + self.ir.bin(Bin::Or, a, ne) + } + "ANDN1" => { + let na = self.not(a); + self.ir.bin(Bin::And, na, e) + } + "ORN1" => { + let na = self.not(a); + self.ir.bin(Bin::Or, na, e) + } + "NAND" | "NOR" | "XNOR" => { + let inner = match op { + "NAND" => Bin::And, + "NOR" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.ir.bin(inner, a, e); + self.not(x) + } + _ => return Err(format!("mask op {op}")), + }) + } + + fn salu(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").unwrap_or(0) as u8); + if self.wave_salu(b, d)? { + return Ok(()); + } + if name == "S_GETPC_B64" { + // the address after it, as the program's offset (#1426's `s_getpc_b64`): read only by + // the far jump `resolve_far_jumps` resolved + let (lo, hi) = (self.ir.int((d.pc + d.len as u64) as u32), self.ir.int(0)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + return Ok(()); + } + let width = if self.wave64 { "_B64" } else { "_B32" }; + // s_wqm: every lane where the analysis found it so (whole-quad mode of the launch EXEC); + // any other mask would need the lanes of the quad + if name.strip_prefix("S_WQM") == Some(width) { + if !self.sum.wqm_all.contains(&d.pc) { + return Err(format!("{name} of a mask other than the launch EXEC")); + } + let t = self.ir.boolean(true); + self.write_bit(b, sd, t); + self.write_scc(b, t); + return Ok(()); + } + // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask + if let Some(base) = name.strip_suffix(width) { + let op = base.trim_start_matches("S_"); + let saveexec = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")); + // SOP1 has no SSRC1: only the sources the encoding has + let srcs: Vec = std::iter::once(s0).chain(d.enc.field("SSRC1").map(|_| s1)).collect(); + let reads_mask = srcs.iter().any(|&c| c <= 127 && c != 124 && self.holds_mask(b, c as u8)); + let bitwise = matches!(op, "MOV" | "NOT" | "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR"); + if let Some(op) = saveexec { + let a = self.src_bit(b, s0)?; + let old = self.read_bit(b, EXEC)?; + let new = self.bit_op(op, a, old)?; + self.write_bit(b, EXEC, new); + if sd != 125 { + self.write_bit(b, sd, if base.ends_with("_WREXEC") { new } else { old }); + } + self.write_scc(b, new); + return Ok(()); + } + if op == "CSELECT" && (sd == EXEC || reads_mask) { + // `s_cselect_b64 s, exec, 0`: the lane's bit of the source SCC picks + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_bit(b, sd, v); + return Ok(()); + } + if bitwise && (sd == EXEC || reads_mask) { + let a = self.src_bit(b, s0)?; + let v = match op { + "MOV" => a, + "NOT" => self.not(a), + _ => { + let c = self.src_bit(b, s1)?; + self.bit_op(op, a, c)? + } + }; + self.write_bit(b, sd, v); + if op != "MOV" { + self.write_scc(b, v); + } + return Ok(()); + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp64 = if self.wave64 { ["S_CMP_EQ_U64", "S_CMP_LG_U64"] } else { ["S_CMP_EQ_U32", "S_CMP_LG_U32"] }; + if cmp64.contains(&name) && [s0, s1].iter().any(|&c| c <= 127 && self.holds_mask(b, c as u8)) { + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let x = self.ir.bin(Bin::Xor, a, c); + let v = if name == cmp64[0] { self.not(x) } else { x }; + self.write_scc(b, v); + return Ok(()); + } + // numbers + let num2 = |l: &mut Self, op: Bin| -> R { + let (a, c) = (l.src(b, d, s0)?, l.src(b, d, s1)?); + Ok(l.ir.bin(op, a, c)) + }; + let nonzero = |l: &mut Self, v: I::V| { + let z = l.ir.int(0); + l.ir.icmp(Cmp::Ne, v, z) + }; + match name { + "S_MOV_B32" => { + let v = self.src(b, d, s0)?; + self.write_num(b, sd, v); + } + "S_MOVK_I32" => { + let v = self.ir.int(fv("SIMM16").unwrap_or(0) as u16 as i16 as i32 as u32); + self.write_num(b, sd, v); + } + "S_MOV_B64" => { + let (lo, hi) = self.src64(b, d, s0)?; + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } + "S_ADD_U32" | "S_SUB_U32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let (op, carry) = if name == "S_ADD_U32" { (Bin::Add, true) } else { (Bin::Sub, false) }; + let v = self.ir.bin(op, a, c); + // carry out: the sum wrapped below a; borrow: a < b + let scc = if carry { self.ir.icmp(Cmp::Ult, v, a) } else { self.ir.icmp(Cmp::Ult, a, c) }; + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_CSELECT_B32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_num(b, sd, v); + } + "S_CSELECT_B64" => { + let ((al, ah), (cl, ch)) = (self.src64(b, d, s0)?, self.src64(b, d, s1)?); + let scc = self.read_scc(b); + let (lo, hi) = (self.ir.select(scc, al, cl), self.ir.select(scc, ah, ch)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } + "S_ADDC_U32" | "S_SUBB_U32" => { + // with SCC as the carry in / borrow in, and the carry / borrow out in SCC + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let cin = self.read_scc(b); + let cin = self.ir.zext(cin); + let (v, out) = if name == "S_ADDC_U32" { + let t = self.ir.bin(Bin::Add, a, c); + let v = self.ir.bin(Bin::Add, t, cin); + let (c1, c2) = (self.ir.icmp(Cmp::Ult, t, a), self.ir.icmp(Cmp::Ult, v, t)); + (v, self.ir.bin(Bin::Or, c1, c2)) + } else { + let t = self.ir.bin(Bin::Sub, a, c); + let v = self.ir.bin(Bin::Sub, t, cin); + let (b1, b2) = (self.ir.icmp(Cmp::Ult, a, c), self.ir.icmp(Cmp::Ult, t, cin)); + (v, self.ir.bin(Bin::Or, b1, b2)) + }; + self.write_num(b, sd, v); + self.write_scc(b, out); + } + "S_ADD_I32" | "S_SUB_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let op = if name == "S_ADD_I32" { Bin::Add } else { Bin::Sub }; + let v = self.ir.bin(op, a, c); + // signed overflow: the operands' signs agree (add) / differ (sub) and the result's differs + let (av, cv) = (self.ir.bin(Bin::Xor, a, v), self.ir.bin(Bin::Xor, c, v)); + let both = if op == Bin::Add { + self.ir.bin(Bin::And, av, cv) + } else { + let ac = self.ir.bin(Bin::Xor, a, c); + self.ir.bin(Bin::And, ac, av) + }; + let z = self.ir.int(0); + let scc = self.ir.icmp(Cmp::Slt, both, z); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_MUL_I32" => { + let v = num2(self, Bin::Mul)?; + self.write_num(b, sd, v); + } + "S_AND_B32" | "S_OR_B32" | "S_XOR_B32" => { + let op = match name { + "S_AND_B32" => Bin::And, + "S_OR_B32" => Bin::Or, + _ => Bin::Xor, + }; + let v = num2(self, op)?; + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, c, c31); + let op = match name { + "S_LSHL_B32" => Bin::Shl, + "S_LSHR_B32" => Bin::LShr, + _ => Bin::AShr, + }; + let v = self.ir.bin(op, a, sh); + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + n if n.starts_with("S_CMP_") && (n.ends_with("_U32") || n.ends_with("_I32")) => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let signed = n.ends_with("_I32"); + let p = match &n[6..8] { + "EQ" => Cmp::Eq, + "LG" => Cmp::Ne, + "GT" => if signed { Cmp::Sgt } else { Cmp::Ugt }, + "GE" => if signed { Cmp::Sge } else { Cmp::Uge }, + "LT" => if signed { Cmp::Slt } else { Cmp::Ult }, + "LE" => if signed { Cmp::Sle } else { Cmp::Ule }, + _ => return Err(format!("unsupported {n}")), + }; + let v = self.ir.icmp(p, a, c); + self.write_scc(b, v); + } + "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} + "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { + let s = fv("SIMM16").unwrap_or(0); + return Err(format!("unsupported {name} hwreg {} offset {} size {}", s & 0x3F, (s >> 6) & 0x1F, ((s >> 11) & 0x1F) + 1)); + } + n => return Err(format!("unsupported {n}")), + } + Ok(()) + } + + /// A 64-bit scalar source: a register pair or a constant. + fn src64(&mut self, b: usize, d: &Decoded, code: u64) -> R<(I::V, I::V)> { + Ok(match code { + 0..=105 | 106 | 126 => (self.read_num(b, code as u8)?, self.read_num(b, code as u8 + 1)?), + 128..=192 => (self.ir.int((code - 128) as u32), self.ir.int(0)), + 193..=208 => (self.ir.int((-((code - 192) as i32)) as u32), self.ir.int(u32::MAX)), + 255 => (self.ir.int(d.literal.ok_or("missing literal")?), self.ir.int(0)), + _ => return Err(format!("64-bit source code {code}")), + }) + } + + fn valu(&mut self, b: usize, d: &Decoded) -> R<()> { + if d.inst.name == "V_NOP" { + return Ok(()); + } + if matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) { + self.dpp(b, d)?; + } + let r = self.valu_op(b, d); + (self.dpp_src, self.dpp_en) = (None, None); + r + } + + fn valu_op(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if d.variant == Variant::Sdwa { + return Err(format!("unsupported {name}: SDWA")); + } + if self.wave_valu(b, d)? { + return Ok(()); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OP_SEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { + return Err(format!("unsupported {name}: VOP3 modifiers")); + } + // sources: VOP1 / VOP2 / VOPC put src1 in VSRC1 (a VGPR); VOP3 in SRC1 + let s0 = fv("SRC0").unwrap_or(0); + let s1 = if vop3 { fv("SRC1").unwrap_or(0) } else { fv("VSRC1").map(|v| v + 256).unwrap_or(0) }; + let vdst = fv("VDST").unwrap_or(0); + if let Some(rest) = name.strip_prefix("V_CMP") { + let (x, cond) = match rest.strip_prefix("X_") { + Some(c) => (true, c), + None => (false, rest.trim_start_matches('_')), + }; + let (pred, ty) = cond.split_once('_').ok_or_else(|| format!("unsupported {name}"))?; + let signed = match ty { + "U32" => false, + "I32" => true, + _ => return Err(format!("unsupported {name}")), + }; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c = match pred { + "EQ" => self.ir.icmp(Cmp::Eq, a, c), + "NE" => self.ir.icmp(Cmp::Ne, a, c), + "GT" => self.ir.icmp(if signed { Cmp::Sgt } else { Cmp::Ugt }, a, c), + "GE" => self.ir.icmp(if signed { Cmp::Sge } else { Cmp::Uge }, a, c), + "LT" => self.ir.icmp(if signed { Cmp::Slt } else { Cmp::Ult }, a, c), + "LE" => self.ir.icmp(if signed { Cmp::Sle } else { Cmp::Ule }, a, c), + "F" => self.ir.boolean(false), + "T" => self.ir.boolean(true), + _ => return Err(format!("unsupported {name}")), + }; + // the lane's result, 0 in inactive lanes + let e = self.read_bit(b, EXEC)?; + let bit = self.ir.bin(Bin::And, c, e); + let dst = if x { EXEC } else if vop3 { vdst as u8 } else { VCC }; + self.write_bit(b, dst, bit); + return Ok(()); + } + let v = match name { + "V_MOV_B32" => self.src(b, d, s0)?, + "V_CNDMASK_B32" => { + let sel = if vop3 { fv("SRC2").unwrap_or(0) } else { VCC as u64 }; + let m = self.src_bit(b, sel)?; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + self.ir.select(m, c, a) + } + _ => { + // the opcode first: an unsupported VOP1 has no SRC1, which would read as s0 + const TWO_SOURCE: &[&str] = &[ + "V_ADD_NC_U32", "V_ADD_U32", "V_SUB_NC_U32", "V_SUB_U32", "V_SUBREV_NC_U32", "V_SUBREV_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", + "V_MUL_LO_U32", "V_LSHL_ADD_U32", "V_ADD_LSHL_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XOR3_B32", "V_ADD3_U32", + "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", + ]; + if !TWO_SOURCE.contains(&name) { + return Err(format!("unsupported {name}")); + } + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + match name { + "V_ADD_NC_U32" | "V_ADD_U32" => self.ir.bin(Bin::Add, a, c), + "V_SUB_NC_U32" | "V_SUB_U32" => self.ir.bin(Bin::Sub, a, c), + "V_SUBREV_NC_U32" | "V_SUBREV_U32" => self.ir.bin(Bin::Sub, c, a), + "V_AND_B32" => self.ir.bin(Bin::And, a, c), + "V_OR_B32" => self.ir.bin(Bin::Or, a, c), + "V_XOR_B32" => self.ir.bin(Bin::Xor, a, c), + "V_MUL_LO_U32" => self.ir.bin(Bin::Mul, a, c), + // three-source integer ops (VOP3): shifts take the low 5 bits of their amount + "V_LSHL_ADD_U32" | "V_ADD_LSHL_U32" | "V_LSHL_OR_B32" | "V_AND_OR_B32" | "V_OR3_B32" | "V_XOR3_B32" | "V_ADD3_U32" => { + let e = self.src(b, d, fv("SRC2").unwrap_or(0))?; + match name { + "V_LSHL_ADD_U32" | "V_LSHL_OR_B32" => { + let sh = self.ir.bin(Bin::And, c, c31); + let x = self.ir.bin(Bin::Shl, a, sh); + self.ir.bin(if name == "V_LSHL_ADD_U32" { Bin::Add } else { Bin::Or }, x, e) + } + "V_ADD_LSHL_U32" => { + let x = self.ir.bin(Bin::Add, a, c); + let sh = self.ir.bin(Bin::And, e, c31); + self.ir.bin(Bin::Shl, x, sh) + } + "V_AND_OR_B32" => { + let x = self.ir.bin(Bin::And, a, c); + self.ir.bin(Bin::Or, x, e) + } + _ => { + let op = match name { + "V_OR3_B32" => Bin::Or, + "V_XOR3_B32" => Bin::Xor, + _ => Bin::Add, + }; + let x = self.ir.bin(op, a, c); + self.ir.bin(op, x, e) + } + } + } + "V_LSHLREV_B32" | "V_LSHRREV_B32" | "V_ASHRREV_I32" => { + let sh = self.ir.bin(Bin::And, a, c31); + let op = match name { + "V_LSHLREV_B32" => Bin::Shl, + "V_LSHRREV_B32" => Bin::LShr, + _ => Bin::AShr, + }; + self.ir.bin(op, c, sh) + } + n => return Err(format!("unsupported {n}")), + } + } + }; + self.write_v(b, d, vdst as u16, v) + } + + /// `s_load_dword{,x2,x4,x8,x16}`: dwords of the flat memory into SGPRs, from + /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). + fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } + let count = match name.strip_prefix("S_LOAD_") { + Some("DWORD") => 1, + Some("DWORDX2") => 2, + Some("DWORDX4") => 4, + Some("DWORDX8") => 8, + Some("DWORDX16") => 16, + _ => return Err(format!("unsupported {name}")), + }; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + let (sdata, sbase) = (fv("SDATA") as u8, fv("SBASE") as u8); + let imm = (((fv("OFFSET") as u32) << 11) as i32 >> 11) as u32; // 21-bit signed + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let base = self.read_num(b, sbase)?; + let imm = self.ir.int(imm); + let mut a = self.ir.bin(Bin::Add, base, imm); + if soff != 125 { + let s = self.src(b, d, soff)?; + a = self.ir.bin(Bin::Add, a, s); + } + let m = self.ir.int(!3); + let a = self.ir.bin(Bin::And, a, m); + let vals: Vec = (0..count) + .map(|i| { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + self.ir.mem_load(ai) + }) + .collect(); + for (i, v) in vals.into_iter().enumerate() { + self.write_num(b, sdata + i as u8, v); + } + Ok(()) + } + + /// `global_` / `flat_` `load` / `store_dword{,x2,x3,x4}` on the flat memory. A standalone + /// guarded load keeps the old register in lanes without their EXEC bit (`write_v`); guarded + /// stores and coalesced runs are lowered unguarded in a block only those lanes enter (`splits`). + fn vmem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } + let op = name.trim_start_matches("GLOBAL_").trim_start_matches("FLAT_"); + let (store, count) = match op { + "LOAD_DWORD" => (false, 1), + "LOAD_DWORDX2" => (false, 2), + "LOAD_DWORDX3" => (false, 3), + "LOAD_DWORDX4" => (false, 4), + "STORE_DWORD" => (true, 1), + "STORE_DWORDX2" => (true, 2), + "STORE_DWORDX3" => (true, 3), + "STORE_DWORDX4" => (true, 4), + _ => return Err(format!("unsupported {name}")), + }; + let global = d.enc.name == "ENC_FLAT_GLBL"; + if !global && d.enc.name != "ENC_FLAT" { + return Err(format!("{name}: {}", d.enc.name)); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let raw = fv("OFFSET") as u32; + let off = if global { ((raw << 20) as i32 >> 20) as u32 } else { raw }; + let saddr = fv("SADDR"); + let mut a = self.read(b, Var::V(fv("ADDR") as u16)); + if global && saddr != 0x7D && saddr != 0x7F { + let s = self.read_num(b, saddr as u8)?; + a = self.ir.bin(Bin::Add, s, a); + } + let off = self.ir.int(off); + let a = self.ir.bin(Bin::Add, a, off); + for i in 0..count { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + let m = self.ir.int(!3); + let ai = self.ir.bin(Bin::And, ai, m); + if store { + let v = self.read(b, Var::V(fv("DATA") as u16 + i as u16)); + self.ir.mem_store(ai, v); + } else { + let v = self.ir.mem_load(ai); + self.write_v(b, d, fv("VDST") as u16 + i as u16, v)?; + } + } + Ok(()) + } + + /// The condition under which a lane takes the branch ending block b. + fn cond(&mut self, b: usize, d: &Decoded) -> R { + Ok(match d.inst.name { + "S_CBRANCH_SCC1" => self.read_scc(b), + "S_CBRANCH_SCC0" => { + let s = self.read_scc(b); + self.not(s) + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let (v, e) = (self.read_bit(b, VCC)?, self.read_bit(b, EXEC)?); + let c = self.ir.bin(Bin::And, v, e); + if n == "S_CBRANCH_VCCZ" { + self.not(c) + } else { + c + } + } + "S_CBRANCH_EXECNZ" => self.read_bit(b, EXEC)?, + "S_CBRANCH_EXECZ" => { + let e = self.read_bit(b, EXEC)?; + self.not(e) + } + n => return Err(format!("unsupported branch {n}")), + }) + } + + /// Whether a lane reading mask bit v in block c may see its own stale bit: v (or a phi + /// operand reaching it) was written in another block that not every lane passed through. + /// The hardware's whole-wave write left the absent lanes' bits 0 there; this lane kept its + /// own older one. EXEC is not concerned: an absent lane's bit is 0 in both. + fn stale(&self, c: usize, v: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if !seen.insert(v) { + continue; + } + match self.ssa.phi_operands(v) { + Some(ops) => work.extend_from_slice(ops), + None => { + if let Some(&b) = self.def_block.get(&v) { + if self.def_owner[b] != self.use_owner[c] && self.partial[b] { + return true; + } + } + } + } + } + false + } + + /// Whether v is (or is a phi reaching) `marker`. + fn reaches(&self, v: I::V, marker: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if v == marker { + return true; + } + if seen.insert(v) { + if let Some(ops) = self.ssa.phi_operands(v) { + work.extend_from_slice(ops); + } + } + } + false + } +} + +/// Per analysis block: whether some lane that reached a lane branch may not pass through it +/// before the lanes meet again – it is reachable from the branch but does not post-dominate +/// both of its successors (lanes that take the other one never get there; a loop's own latch +/// counts: the lanes that leave do not come back to it). +fn partial_blocks(sum: &Summary) -> Vec { + let n = sum.blocks.len(); + let words = (n + 1).div_ceil(64); + // post-dominators over the blocks the entry reaches, with a virtual exit n + let full = vec![!0u64; words]; + let mut pdom: Vec> = vec![full; n + 1]; + pdom[n] = vec![0u64; words]; + pdom[n][n / 64] |= 1 << (n % 64); + let mut changed = true; + while changed { + changed = false; + for &b in sum.order.iter().rev() { + let succ: Vec = if sum.blocks[b].succ.is_empty() { vec![n] } else { sum.blocks[b].succ.iter().map(|s| s.0).collect() }; + let mut new = vec![!0u64; words]; + for s in succ { + for (w, x) in new.iter_mut().zip(&pdom[s]) { + *w &= x; + } + } + new[b / 64] |= 1 << (b % 64); + if new != pdom[b] { + pdom[b] = new; + changed = true; + } + } + } + let mut partial = vec![false; n]; + for &x in &sum.order { + if !sum.blocks[x].lane_branch { + continue; + } + let mut seen = vec![false; n]; + let mut work: Vec = sum.blocks[x].succ.iter().map(|s| s.0).collect(); + while let Some(b) = work.pop() { + if std::mem::replace(&mut seen[b], true) { + continue; + } + if sum.blocks[x].succ.iter().any(|&(s, _)| pdom[s][b / 64] >> (b % 64) & 1 == 0) { + partial[b] = true; + } + work.extend(sum.blocks[b].succ.iter().map(|s| s.0)); + } + } + partial +} + +/// Lowers a kernel-mode program (far jumps resolved) into `ir`, which gets it complete, with +/// the mask registers whose value at the end may differ from the console's: written in a block +/// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads +/// them in the program (that would be refused); only the kernel ABI's store of every register. +pub fn lower_kernel(insts: &[Decoded], wave64: bool, ir: I) -> R<(I, Vec)> { + lower(insts, Stage::Kernel, wave64, ir) +} + +/// Lowers a compute program (far jumps resolved) into `ir`. +pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> R { + Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) +} + +/// Lowers a vertex or pixel shader (`pixel`; far jumps resolved) into `ir`. `lanes32`: a wave64 +/// program runs in 32-lane hardware waves (NVIDIA), as the HLSL path runs it with `upper_lanes`; +/// the per-lane form takes such a program only where it reads no lane 32–63 that holds anything. +pub fn lower_graphics(insts: &[Decoded], pixel: bool, wave64: bool, lanes32: bool, ir: I) -> R { + if wave64 && lanes32 && super::upper_lanes::analyze(insts).reads.values().any(|&r| r != super::upper_lanes::Read::Native) { + return Err("wave64 VS / PS in 32-lane waves: a read of lanes 32–63".into()); + } + Ok(lower(insts, if pixel { Stage::Pixel } else { Stage::Vertex }, wave64, ir)?.0) +} + +fn lower(insts: &[Decoded], stage: Stage, wave64: bool, ir: I) -> R<(I, Vec)> { + lower_with(insts, stage, wave64, ir, false).map(|(ir, stale, _)| (ir, stale)) +} + +/// Survey: every reason the per-lane form refuses a compute program, not only the first. An +/// instruction it refuses is left out and the lowering goes on, so a later reason may follow +/// from an earlier one; a program the lane-mask analysis refuses gives that one reason. +pub fn survey_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> Vec { + match lower_with(insts, Stage::Compute(cs), wave64, ir, true) { + Ok((_, _, noted)) => noted, + Err(e) => vec![e], + } +} + +fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec, Vec)> { + let kernel = matches!(stage, Stage::Kernel); + let graphics = matches!(stage, Stage::Vertex | Stage::Pixel); + // a PS: lanes may run outside the launch EXEC (its helper lanes); a VS has none, each D3D + // vertex invocation being one lane + let pixel = matches!(stage, Stage::Pixel); + let launch = if pixel { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All }; + let sum = lane_masks::analyze_launch(insts, wave64, launch).map_err(|e| e.to_string())?; + let n = sum.blocks.len(); + if n == 0 { + return Err("empty program".into()); + } + // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, + // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch, + // then for every coalesced guarded run (only the lanes with their EXEC bit enter): the run's + // block and the one the rest of its block continues in. `tail[b]`: the IR block the + // program's block b ends in. + let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + let mut splits: Vec, usize, usize)>> = vec![Vec::new(); n]; // (run, body, cont) + let mut count = n + 5; + for (b, block) in sum.blocks.iter().enumerate() { + for run in coalesced_runs(insts, &block.insts, &guarded) { + splits[b].push((run, count, count + 1)); + count += 2; + } + } + let tail: Vec = (0..n).map(|b| splits[b].last().map_or(blk(b), |s| s.2)).collect(); + let mut partial = vec![false; count]; + let mut def_owner: Vec = (0..count).collect(); + let mut use_owner: Vec = (0..count).collect(); + for (b, p) in partial_blocks(&sum).into_iter().enumerate() { + partial[blk(b)] = p; + for &(_, s, c) in &splits[b] { + partial[s] = true; + partial[c] = p; + def_owner[s] = s; + use_owner[s] = blk(b); + def_owner[c] = blk(b); + use_owner[c] = blk(b); + } + } + let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); + let mut preds = vec![Vec::new(); count]; + preds[blk(0)] = vec![0]; + for &b in &sum.order { + let mut seen = Vec::new(); + for &(s, _) in &sum.blocks[b].succ { + if !seen.contains(&s) { + seen.push(s); + preds[blk(s)].push(tail[b]); + } + } + let mut prev = blk(b); + for &(_, s, c) in &splits[b] { + preds[s] = vec![prev]; + preds[c] = vec![prev, s]; + prev = c; + } + } + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and + // store blocks are left unreachable (a bare `ret`) + if kernel { + preds[skip] = vec![0]; + preds[sstore] = vec![exit]; + preds[vstore] = vec![exit, sstore]; + } + preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); + for i in 0..count { + let id = ir.new_block(); + debug_assert_eq!(id, i); + } + let num_marker = ir.undef(Var::S(0)); + let bit_marker = ir.undef(Var::M(0)); + let mut l = Lower { + ssa: Ssa::new(preds.clone()), + ir, + + sum: &sum, + guarded, + wave64, + num_marker, + bit_marker, + num_uses: Vec::new(), + bit_uses: Vec::new(), + lane: None, + partial, + def_owner, + use_owner, + unguarded: false, + def_block: std::collections::HashMap::new(), + lane_uses: Vec::new(), + dpp_src: None, + dpp_en: None, + noted: survey.then(Vec::new), + graphics, + }; + // the registers the program names, and the ones the runner reads back + let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; + let mut vregs: Vec = Vec::new(); + for d in insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as u8)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as u16)); + } + sregs.retain(|&r| (r as usize) < KERNEL_SGPRS && r != 125); + sregs.sort_unstable(); + sregs.dedup(); + vregs.sort_unstable(); + vregs.dedup(); + + // prologue: the SGPRs from `io` (kernel: the whole register file; compute: the user data) + l.ir.at(0); + l.ssa.seal(&mut l.ir, 0); + let lane = l.lane(); + for &r in &sregs { + let a = l.ir.int(r as u32); + let v = l.ir.io_load(a); + l.write_num(0, r, v); + } + let mut row = None; + match stage { + Stage::Kernel => { + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let scc = l.ir.io_load(a); + let z = l.ir.int(0); + let scc = l.ir.icmp(Cmp::Ne, scc, z); + l.ssa.write(0, Var::Scc, scc); + let (base, stride) = (l.ir.int(KERNEL_SGPRS as u32), l.ir.int(KERNEL_VGPRS as u32)); + let r = l.ir.bin(Bin::Mul, lane, stride); + let r = l.ir.bin(Bin::Add, base, r); + for &v in &vregs { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, r, o); + let x = l.ir.io_load(a); + l.ssa.write(0, Var::V(v), x); + } + row = Some(r); + // lanes outside EXEC go straight to the end + let active = l.read_bit(0, EXEC)?; + l.write_bit(0, EXEC, active); + l.ir.br_if(active, blk(0), skip); + // … with their bits of every mask 0, as a whole-wave write leaves them + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + let f = l.ir.boolean(false); + for &r in &sregs { + l.ssa.write(skip, Var::M(r), f); + } + l.ir.br(exit); + } + Stage::Compute(cs) => { + let (flat, tid) = l.ir.compute_ids(cs.threads); + // system SGPRs after the user data: the enabled group ids, then TG_SIZE + let mut next = cs.user_sgprs as u8; + for k in 0..3 { + if cs.tgid[k as usize] { + let g = l.ir.group_id(k); + l.write_num(0, next, g); + next += 1; + } + } + if cs.tg_size { + // waves in the group (a last partial one counts) | this wave's index << 6 + let lanes = if wave64 { 64 } else { 32 }; + let waves = l.ir.int(cs.threads.iter().product::().div_ceil(lanes)); + let sh = l.ir.int(lanes.trailing_zeros()); + let w = l.ir.bin(Bin::LShr, flat, sh); + let six = l.ir.int(6); + let w = l.ir.bin(Bin::Shl, w, six); + let v = l.ir.bin(Bin::Or, waves, w); + l.write_num(0, next, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match v { + 0 => tid[0], + 1 if cs.tid_components >= 2 => tid[1], + 2 if cs.tid_components >= 3 => tid[2], + _ => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane that runs is in EXEC + let t = l.ir.boolean(true); + l.write_bit(0, EXEC, t); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } + Stage::Vertex | Stage::Pixel => { + let Some(start) = l.ir.graphics_start(&vregs) else { + return Err("VS / PS: this IR has no graphics entry".into()); + }; + for &(r, v) in &start.sgprs { + l.write_num(0, r, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match start.vgprs.iter().find(|x| x.0 == v) { + Some(&(_, x)) => x, + None => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane runs the program: a PS's helper lanes with their EXEC bit clear (the + // kernel's way out for lanes outside EXEC would leave their quads short) + l.write_bit(0, EXEC, start.exec); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } + } + + // the program, in reverse postorder; a block is sealed once all its predecessors are in + let mut done = vec![false; count]; + done[0] = true; + done[skip] = true; + let seal_ready = |l: &mut Lower, done: &[bool], b: usize| { + if preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + true + } else { + false + } + }; + let mut sealed = vec![false; count]; + sealed[0] = true; + for &b in &sum.order.clone() { + let ib = blk(b); + l.ir.at(ib); + if !sealed[ib] { + sealed[ib] = seal_ready(&mut l, &done, ib); + } + if b == 0 && !pixel { + // the analysis takes the lanes that start the program as its EXEC (a PS keeps the + // launch EXEC from its start: there the analysis does not know it) + let t = l.ir.boolean(true); + l.write_bit(ib, EXEC, t); + } + let block = &sum.blocks[b]; + let last = block.insts.end - 1; + let body_end = block_body_end(insts, &block.insts); + let mut cur = ib; + let mut split = splits[b].iter().peekable(); + let mut i = block.insts.start; + while i < body_end { + if let Some(&(ref run, s, c)) = split.next_if(|x| x.0.start == i) { + // a coalesced guarded run: only the lanes with their EXEC bit enter `s`, + // lowered unguarded; updated registers merge through SSA phis at `c` + let e = l.read_bit(cur, EXEC)?; + l.ir.br_if(e, s, c); + done[cur] = true; + l.ir.at(s); + l.ssa.seal(&mut l.ir, s); + l.unguarded = true; + for j in run.clone() { + let r = l.lower_inst(s, &insts[j]); + l.note_inst(r, s, &insts[j])?; + } + l.unguarded = false; + l.ir.br(c); + done[s] = true; + l.ir.at(c); + l.ssa.seal(&mut l.ir, c); + cur = c; + i = run.end; + } else { + let name = insts[i].inst.name; + if matches!(stage, Stage::Pixel) && whole_quad(name) && l.partial[cur] { + l.note_inst(Err(format!("{name}: needs whole quads, in a block not every lane reaches")), cur, &insts[i])?; + i += 1; + continue; + } + let r = l.lower_inst(cur, &insts[i]); + l.note_inst(r, cur, &insts[i])?; + i += 1; + } + } + match block.succ.as_slice() { + [] => l.ir.br(exit), + [(t, Edge::Always)] => l.ir.br(blk(*t)), + [(t, _), (f, _)] if t == f => l.ir.br(blk(*t)), + [(t, Edge::Taken), (f, Edge::NotTaken)] => match l.cond(cur, &insts[last]) { + Ok(c) => l.ir.br_if(c, blk(*t), blk(*f)), + Err(e) => { + l.note(Err(e))?; + let c = l.ir.boolean(true); + l.ir.br_if(c, blk(*t), blk(*f)); + } + }, + s => { + l.note(Err(format!("block {b}: successors {s:?}")))?; + l.ir.br(blk(s[0].0)); + } + } + done[cur] = true; + for &(s, _) in &block.succ { + let is = blk(s); + if !sealed[is] && l.sum.order.contains(&s) { + // the successor's own code comes later; sealing it early is fine once its + // predecessors are all in + if preds[is].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, is); + sealed[is] = true; + } + } + } + } + for b in 1..=n { + if !sealed[b] && preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + sealed[b] = true; + } + } + + l.ir.at(exit); + l.ssa.seal(&mut l.ir, exit); + let mut stale: Vec = Vec::new(); + let Some(row) = row else { + // compute: nothing to store; a VS / PS: its end + if graphics { + l.ir.graphics_end(); + } + l.ir.ret(); + for b in [sstore, vstore] { + l.ir.at(b); + l.ssa.seal(&mut l.ir, b); + l.ir.ret(); + } + return l.finish(stale); + }; + // kernel exit: every lane is here; masks the runner reads as numbers are the wave's ballots + let mut sval: Vec<(u8, I::V)> = Vec::new(); + let mut i = 0; + while i < sregs.len() { + let r = sregs[i]; + i += 1; + let s = l.read(exit, Var::S(r)); + if l.ssa.resolve_value(s) != l.num_marker && !l.reaches(s, l.num_marker) { + l.num_uses.push(s); + if l.stale(exit, s) { + stale.push(r); + } + sval.push((r, s)); + continue; + } + if !l.holds_mask(exit, r) { + if l.wave64 && r > 0 && sval.iter().any(|&(x, _)| x == r) { + continue; // the upper half of a mask stored with its pair + } + return Err(format!("s{r}: neither a number nor a mask at the end")); + } + // read directly: a stale bit here is reported, not refused (only the ABI's store sees it) + let m = l.read(exit, Var::M(r)); + if r != EXEC && l.stale(exit, m) { + stale.push(r); + if l.wave64 { + stale.push(r + 1); // the upper half comes from the same mask + } + } + let [lo, hi] = l.ir.ballot(m); + sval.push((r, lo)); + if l.wave64 { + sval.retain(|&(x, _)| x != r + 1); + sval.push((r + 1, hi)); + if sregs.get(i) == Some(&(r + 1)) { + i += 1; + } + } + } + let scc = l.read(exit, Var::Scc); + if l.stale(exit, scc) { + stale.push(KERNEL_SCC_SLOT as u8); + } + let vval: Vec<(u16, I::V)> = vregs.iter().map(|&v| (v, l.read(exit, Var::V(v)))).collect(); + let z = l.ir.int(0); + let first = l.ir.icmp(Cmp::Eq, lane, z); + l.ir.br_if(first, sstore, vstore); + l.ir.at(sstore); + l.ssa.seal(&mut l.ir, sstore); + for &(r, v) in &sval { + let a = l.ir.int(r as u32); + l.ir.res_store(a, v); + } + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let s = l.ir.zext(scc); + l.ir.res_store(a, s); + l.ir.br(vstore); + l.ir.at(vstore); + l.ssa.seal(&mut l.ir, vstore); + for &(v, x) in &vval { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, row, o); + l.ir.res_store(a, x); + } + l.ir.ret(); + l.finish(stale) +} + +impl Lower<'_, I> { + /// Every phi is complete: no number may come from a mask, nor a mask bit from a number, nor + /// a lane read a mask bit it kept from before a write it skipped. + fn finish(mut self, mut stale: Vec) -> R<(I, Vec, Vec)> { + if self.num_uses.iter().any(|&v| self.reaches(v, self.num_marker)) { + self.note(Err("a mask read as a number (through a join)".into()))?; + } + if self.bit_uses.iter().any(|&v| self.reaches(v, self.bit_marker)) { + self.note(Err("a number read as a mask (through a join)".into()))?; + } + if self.lane_uses.iter().any(|&(c, v)| self.stale(c, v)) { + self.note(Err("a value written while some lanes were elsewhere, read after they met again".into()))?; + } + stale.sort_unstable(); + stale.dedup(); + Ok((self.ir, stale, self.noted.unwrap_or_default())) + } + + /// A refused instruction in block b: as `note`, and in survey mode the SGPRs (and, for a + /// scalar instruction, SCC) it writes are left as 0 in both views (number and mask bit), + /// so that a later read does not report a refusal that only follows from this one. + /// An instruction this lowering has no semantics of, through `Ir::foreign` (#1426's + /// per-instruction lowering) with the lane-mask analysis's guard: `true` where EXEC is proven + /// (or inside a coalesced guarded run's block, `in_guarded_run`), else the lane's EXEC bit. Its SGPR + /// operands are read as numbers (a mask read whole is refused, as everywhere), the mask a + /// VALU reads lane by lane (`v_cndmask_b32`'s selector, a carry-in) as a number holding only + /// this lane's bit, and a mask it writes (a compare, a carry-out) comes back as this lane's + /// bit of the ballot it makes. Of the instructions writing EXEC, only `v_cmpx_*` is taken. + fn bridge(&mut self, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { + let name = d.inst.name; + let (whole, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r); + // `v_cmpx_*`: EXEC goes in as this lane's bit and comes back as its bit of the result + let cmpx = name.starts_with("V_CMPX"); + if writes & (3 << 126) != 0 && !cmpx { + return Err("writes EXEC".into()); + } + if name == "S_BARRIER" && self.partial[b] { + return Err("a barrier where some lanes are elsewhere".into()); + } + // instructions whose #1426 semantics are known to differ from the HLSL path and the + // console (each reported on #1426): left to the fallback until fixed there + const DIFFERS_ON_1426: &[&str] = &[ + // f32 → f16 of a value below the smallest f16 denormal: 0 instead of rounding to it + "V_CVT_F16_F32", + // f16 products round toward zero (`LegacyF32ToF16`) where the console rounds to + // nearest even (vladbondarenko97's f16 programs; itsSio is fixing it on `main`) + "V_MUL_F16", + "V_PK_MUL_F16", + ]; + if DIFFERS_ON_1426.contains(&name) { + return Err("its #1426 semantics differ from the console's".into()); + } + let operand = |input: bool, ty: &str| d.ienc.operands.iter().any(|o| o.input == input && o.output != input && o.ty == ty); + let mut inputs: Vec<(Var, I::V)> = Vec::new(); + // SGPRs read whole: numbers (EXEC included, which holds a mask here: refused) + for r in (0..128u8).filter(|&r| whole >> r & 1 != 0 && r != 125 && !(cmpx && r >= EXEC)) { + let v = self.read_num(b, r)?; + inputs.push((Var::S(r), v)); + } + // a mask read lane by lane: a number with only this lane's bit + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + let lane_mask = if cmpx { + Some(EXEC as u64) + } else if matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + Some(if vop3 { rdna2::field_value(d.enc, &d.words, "SRC2").unwrap_or(0) } else { VCC as u64 }) + } else { + None + }; + if let Some(m) = lane_mask { + if m > 127 { + return Err(format!("{name}: mask operand {m}")); + } + let bit = self.src_bit(b, m)?; + let lane = self.lane(); + let one = self.ir.zext(bit); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let own = self.ir.bin(Bin::Shl, one, sh); + if self.wave64 { + let (c32, z) = (self.ir.int(32), self.ir.int(0)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let (lo, hi) = (self.ir.select(upper, z, own), self.ir.select(upper, own, z)); + inputs.push((Var::S(m as u8), lo)); + inputs.push((Var::S(m as u8 + 1), hi)); + } else { + // #1426 reads the mask as an SGPR pair in wave32 too: the upper one is 0 + let z = self.ir.int(0); + inputs.push((Var::S(m as u8), own)); + inputs.push((Var::S(m as u8 + 1), z)); + } + } + if operand(true, "OPR_SSRC_SPECIAL_SCC") { + let s = self.read_scc(b); + let s = self.ir.zext(s); + inputs.push((Var::Scc, s)); + } + // VGPRs read, and the ones written (a write keeps the old value where the guard is off) + let (vr, vw) = rdna2::vgpr_uses(d); + let mut vregs: Vec = vr.iter().chain(&vw).map(|&v| v as u16).collect(); + vregs.sort_unstable(); + vregs.dedup(); + for &v in &vregs { + let x = self.read(b, Var::V(v)); + inputs.push((Var::V(v), x)); + } + // outputs: VGPRs, SGPRs (their current values seeded too, so an output the instruction + // leaves alone reads back unchanged), SCC + let sw: Vec = (0..128u8).filter(|&r| writes >> r & 1 != 0 && r != 125).collect(); + for &r in &sw { + if !inputs.iter().any(|&(v, _)| v == Var::S(r)) { + let x = self.read(b, Var::S(r)); + inputs.push((Var::S(r), x)); + } + } + let writes_scc = operand(false, "OPR_SSRC_SPECIAL_SCC"); + let mut outputs: Vec = vw.iter().map(|&v| Var::V(v as u16)).collect(); + outputs.extend(sw.iter().map(|&r| Var::S(r))); + if writes_scc { + outputs.push(Var::Scc); + } + let guard = if cmpx || in_guarded_run || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; + let vals = self.ir.foreign(d, guard, &inputs, &outputs)?; + for (&var, &v) in outputs.iter().zip(&vals) { + match var { + Var::V(_) => self.ssa.write(b, var, v), + Var::Scc => { + let z = self.ir.int(0); + let s = self.ir.icmp(Cmp::Ne, v, z); + self.write_scc(b, s); + } + Var::S(_) | Var::M(_) => {} + } + } + if name.starts_with("V_") && !sw.is_empty() { + // a mask (a compare, a carry-out): this lane's bit of the ballot the instruction made + let base = sw[0]; + let lo = vals[outputs.iter().position(|&v| v == Var::S(base)).unwrap()]; + let word = match (self.wave64, outputs.iter().position(|&v| v == Var::S(base + 1))) { + (true, Some(k)) => { + let lane = self.lane(); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, vals[k], lo) + } + _ => lo, + }; + let lane = self.lane(); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let x = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let x = self.ir.bin(Bin::And, x, one); + let z = self.ir.int(0); + let bit = self.ir.icmp(Cmp::Ne, x, z); + self.write_bit(b, base, bit); + } else { + for (&var, &v) in outputs.iter().zip(&vals) { + if let Var::S(r) = var { + self.write_num(b, r, v); + } + } + } + Ok(()) + } + + /// Lowers one non-terminator instruction in block `b`, falling back to `bridge`. + fn lower_inst(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { + self.smem(b, d) + } else if name.starts_with("S_") { + self.salu(b, d) + } else if name.starts_with("V_") { + self.valu(b, d) + } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { + self.vmem(b, d) + } else if name == "DS_SWIZZLE_B32" { + self.swizzle(b, d) + } else { + Err(format!("unsupported {name}")) + }; + self.or_bridge(r, b, d, self.unguarded) + } + + /// `r`, or an instruction it calls unsupported lowered through `bridge`. + fn or_bridge(&mut self, r: R<()>, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { + match r { + Err(e) if e.starts_with("unsupported ") => match self.bridge(b, d, in_guarded_run) { + Ok(()) => Ok(()), + Err(f) if f == "no foreign lowering" => Err(e), + Err(f) => Err(format!("{e} ({f})")), + }, + r => r, + } + } + + fn note_inst(&mut self, r: R<()>, b: usize, d: &Decoded) -> R<()> { + if r.is_err() && self.noted.is_some() { + let (z, f) = (self.ir.int(0), self.ir.boolean(false)); + for s in rdna2::sgpr_uses(d).1 { + if s < KERNEL_SGPRS as u64 && s != 125 { + self.ssa.write(b, Var::S(s as u8), z); + self.ssa.write(b, Var::M(s as u8), f); + } + } + if d.inst.name.starts_with("S_") { + self.ssa.write(b, Var::Scc, f); + } + } + self.note(r) + } + + /// A refusal: the error, or in survey mode noted and passed over. + fn note(&mut self, r: R<()>) -> R<()> { + match (r, &mut self.noted) { + (Err(e), Some(n)) => { + n.push(e); + Ok(()) + } + (r, _) => r, + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::collections::HashMap; + + /// The IR as a small program, run lane by lane on the CPU: what the lowering means, + /// without a DXIL writer or a GPU. + #[derive(Clone, Debug)] + enum Ins { + Int(u32), + Bool(bool), + Bin(Bin, u32, u32), + Icmp(Cmp, u32, u32), + Select(u32, u32, u32), + Zext(u32), + Lane, + GroupId(u32), + /// the flat thread index in the group: the wave's first thread + lane + Flat, + /// component k of a flat index `v` in a group whose x, y sizes are given + ThreadId(u32, u32, [u32; 2]), + Ballot(u32, usize), + ReadLane(u32, u32), + /// as `Ballot` and `ReadLane`, but the lowering may use only its own 32-lane half's part + BallotHalf(u32, usize), + ReadLaneHalf(u32, u32), + CountBits(u32), + IoLoad(u32), + ResStore(u32, u32), + MemLoad(u32), + MemStore(u32, u32), + Phi(Vec<(u32, usize)>), + /// a VS / PS start: VGPR v from the lane's row of `io` (as in kernel mode), and the + /// lane's bit of the launch EXEC from `io[126..=127]` + GfxVgpr(u16), + GfxExec, + } + + #[derive(Clone, Debug)] + enum Term { + None, + Br(usize), + BrIf(u32, usize, usize), + Ret, + } + + #[derive(Default)] + struct Interp { + /// per block: (value id, instruction) in order, and the terminator + blocks: Vec<(Vec<(u32, Ins)>, Term)>, + cur: usize, + next: u32, + forward: HashMap, + undef: HashMap, + phi_block: HashMap, + } + + impl Interp { + fn push(&mut self, ins: Ins) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[self.cur].0.push((v, ins)); + v + } + fn res(&self, mut v: u32) -> u32 { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + fn selects(&self) -> usize { + self.blocks.iter().map(|(ins, _)| ins.iter().filter(|(_, op)| matches!(op, Ins::Select(..))).count()).sum() + } + fn br_ifs(&self) -> usize { + self.blocks.iter().filter(|(_, t)| matches!(t, Term::BrIf(..))).count() + } + } + + impl Sink for Interp { + type V = u32; + fn phi(&mut self, block: usize, _: Var) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[block].0.insert(0, (v, Ins::Phi(Vec::new()))); + self.phi_block.insert(v, block); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + let b = self.phi_block[&phi]; + for (id, ins) in &mut self.blocks[b].0 { + if *id == phi { + if let Ins::Phi(ops) = ins { + ops.push((value, pred)); + } + } + } + } + fn replace(&mut self, old: u32, new: u32) { + self.forward.insert(old, new); + let b = self.phi_block[&old]; + self.blocks[b].0.retain(|(id, _)| *id != old); + } + fn undef(&mut self, var: Var) -> u32 { + let bit = matches!(var, Var::M(_) | Var::Scc); + if let Some(&v) = self.undef.get(&bit) { + return v; + } + self.next += 1; + let v = self.next; + self.undef.insert(bit, v); + v + } + } + + impl Ir for Interp { + fn new_block(&mut self) -> usize { + self.blocks.push((Vec::new(), Term::None)); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.cur = block; + } + fn int(&mut self, v: u32) -> u32 { + self.push(Ins::Int(v)) + } + fn boolean(&mut self, v: bool) -> u32 { + self.push(Ins::Bool(v)) + } + fn bin(&mut self, op: Bin, a: u32, b: u32) -> u32 { + self.push(Ins::Bin(op, a, b)) + } + fn icmp(&mut self, c: Cmp, a: u32, b: u32) -> u32 { + self.push(Ins::Icmp(c, a, b)) + } + fn select(&mut self, c: u32, a: u32, b: u32) -> u32 { + self.push(Ins::Select(c, a, b)) + } + fn zext(&mut self, b: u32) -> u32 { + self.push(Ins::Zext(b)) + } + fn lane(&mut self) -> u32 { + self.push(Ins::Lane) + } + fn group_id(&mut self, k: u32) -> u32 { + self.push(Ins::GroupId(k)) + } + fn compute_ids(&mut self, threads: [u32; 3]) -> (u32, [u32; 3]) { + let flat = self.push(Ins::Flat); + let xy = [threads[0], threads[1]]; + (flat, [0, 1, 2].map(|k| self.push(Ins::ThreadId(k, flat, xy)))) + } + fn ballot(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] + } + fn ballot_half(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::BallotHalf(c, 0)), self.push(Ins::BallotHalf(c, 1))] + } + fn read_lane(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLane(v, lane)) + } + fn read_lane_half(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLaneHalf(v, lane)) + } + fn count_bits(&mut self, v: u32) -> u32 { + self.push(Ins::CountBits(v)) + } + fn io_load(&mut self, dword: u32) -> u32 { + self.push(Ins::IoLoad(dword)) + } + fn res_store(&mut self, dword: u32, value: u32) { + self.push(Ins::ResStore(dword, value)); + } + fn mem_load(&mut self, addr: u32) -> u32 { + self.push(Ins::MemLoad(addr)) + } + fn mem_store(&mut self, addr: u32, value: u32) { + self.push(Ins::MemStore(addr, value)); + } + fn br(&mut self, target: usize) { + self.blocks[self.cur].1 = Term::Br(target); + } + fn br_if(&mut self, c: u32, then: usize, otherwise: usize) { + self.blocks[self.cur].1 = Term::BrIf(c, then, otherwise); + } + fn ret(&mut self) { + self.blocks[self.cur].1 = Term::Ret; + } + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let vgprs = vregs.iter().map(|&v| (v, self.push(Ins::GfxVgpr(v)))).collect(); + let exec = self.push(Ins::GfxExec); + Some(GraphicsStart { sgprs: Vec::new(), vgprs, exec }) + } + } + + /// One lane's position: block, instruction index, the block it came from, its values. + struct LaneState { + block: usize, + at: usize, + from: usize, + env: HashMap, + done: bool, + } + + impl Interp { + /// A value in a lane: what it computed, or 0 for `undef` (a marker of the lowering). + fn value(&self, env: &HashMap, v: u32) -> u32 { + let v = self.res(v); + if self.undef.values().any(|&u| u == v) { + return 0; + } + *env.get(&v).unwrap_or_else(|| panic!("value {v} not defined")) + } + } + + impl Interp { + /// Runs the program over `lanes` lanes; `io` in, `res` out. Ballots wait for every lane. + fn run(&self, lanes: usize, io: &[u32], res: &mut [u32], mem: &mut [u32]) { + self.run_with(lanes, 0, [0; 3], io, res, mem) + } + + /// One wave of a compute group: its first thread `base`, the group `group`. + fn run_with(&self, lanes: usize, base: u32, group: [u32; 3], io: &[u32], res: &mut [u32], mem: &mut [u32]) { + let mut ls: Vec = (0..lanes).map(|_| LaneState { block: 0, at: 0, from: 0, env: HashMap::new(), done: false }).collect(); + let mut steps = 0usize; + loop { + // run every lane up to a ballot or its end + for (lane, s) in ls.iter_mut().enumerate() { + while !s.done { + steps += 1; + assert!(steps < 10_000_000, "runaway program"); + let (ins, term) = &self.blocks[s.block]; + if s.at == 0 { + // phis read their operands from the edge taken, all at once + let vals: Vec<(u32, u32)> = ins + .iter() + .filter_map(|(id, i)| match i { + Ins::Phi(ops) => { + let (v, _) = ops.iter().find(|(_, p)| *p == s.from).unwrap_or_else(|| panic!("phi {id} in block {} has no operand from {}", s.block, s.from)); + Some((*id, self.value(&s.env, *v))) + } + _ => None, + }) + .collect(); + s.env.extend(vals); + } + if s.at < ins.len() { + let (id, i) = &ins[s.at]; + let g = |v: &u32| self.value(&s.env, *v); + let r = match i { + Ins::Phi(_) => None, + Ins::Int(x) => Some(*x), + Ins::Bool(x) => Some(*x as u32), + Ins::Bin(op, a, b) => { + let (a, b) = (g(a), g(b)); + Some(match op { + Bin::Add => a.wrapping_add(b), + Bin::Sub => a.wrapping_sub(b), + Bin::Mul => a.wrapping_mul(b), + Bin::And => a & b, + Bin::Or => a | b, + Bin::Xor => a ^ b, + Bin::Shl => a << (b & 31), + Bin::LShr => a >> (b & 31), + Bin::AShr => ((a as i32) >> (b & 31)) as u32, + }) + } + Ins::Icmp(c, a, b) => { + let (a, b) = (g(a), g(b)); + let (sa, sb) = (a as i32, b as i32); + Some(match c { + Cmp::Eq => a == b, + Cmp::Ne => a != b, + Cmp::Ult => a < b, + Cmp::Ule => a <= b, + Cmp::Ugt => a > b, + Cmp::Uge => a >= b, + Cmp::Slt => sa < sb, + Cmp::Sle => sa <= sb, + Cmp::Sgt => sa > sb, + Cmp::Sge => sa >= sb, + } as u32) + } + Ins::Select(c, a, b) => Some(if g(c) != 0 { g(a) } else { g(b) }), + Ins::Zext(b) => Some(g(b)), + Ins::Lane => Some(lane as u32), + Ins::GroupId(k) => Some(group[*k as usize]), + Ins::Flat => Some(base + lane as u32), + Ins::ThreadId(k, v, [x, y]) => Some(match k { + 0 => g(v) % x, + 1 => g(v) / x % y, + _ => g(v) / (x * y), + }), + Ins::Ballot(..) | Ins::BallotHalf(..) | Ins::ReadLane(..) | Ins::ReadLaneHalf(..) => break, + Ins::CountBits(v) => Some(g(v).count_ones()), + Ins::IoLoad(a) => Some(io[g(a) as usize]), + Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), + Ins::MemStore(a, v) => { + let (a, v) = (g(a), g(v)); + if let Some(w) = mem.get_mut((a / 4) as usize) { + *w = v; + } + None + } + Ins::ResStore(a, v) => { + res[g(a) as usize] = g(v); + None + } + Ins::GfxVgpr(v) => Some(io[KERNEL_SGPRS + lane * KERNEL_VGPRS + *v as usize]), + Ins::GfxExec => Some(io[EXEC as usize + lane / 32] >> (lane % 32) & 1), + }; + if let Some(r) = r { + s.env.insert(*id, r); + } + s.at += 1; + continue; + } + match term { + Term::Br(t) => { + s.from = s.block; + s.block = *t; + } + Term::BrIf(c, t, f) => { + s.from = s.block; + s.block = if s.env[&self.res(*c)] != 0 { *t } else { *f }; + } + Term::Ret => s.done = true, + Term::None => panic!("block {} has no terminator", s.block), + } + s.at = 0; + } + } + if ls.iter().all(|s| s.done) { + return; + } + // the lanes waiting at the first wave operation (in block order: a loop's body + // before what follows it) run it together, as the lanes active there + let (b, at) = ls.iter().filter(|s| !s.done).map(|s| (s.block, s.at)).min().unwrap(); + let group: Vec = (0..ls.len()).filter(|&l| !ls[l].done && (ls[l].block, ls[l].at) == (b, at)).collect(); + let (id, ins) = &self.blocks[b].0[at]; + let out: Vec = match ins { + Ins::Ballot(c, half) | Ins::BallotHalf(c, half) => { + let mut bits = 0u64; + for &l in &group { + if self.value(&ls[l].env, *c) != 0 { + bits |= 1 << l; + } + } + let word = (bits >> (32 * half)) as u32; + // the half-local form: the other half's word is garbage, so a lowering + // that reads it gets a wrong result here + let local = matches!(ins, Ins::BallotHalf(..)); + group.iter().map(|&l| if local && l / 32 != *half { 0xA5A5_0000 | l as u32 } else { word }).collect() + } + Ins::ReadLane(v, from) | Ins::ReadLaneHalf(v, from) => group + .iter() + .map(|&l| { + let src = self.value(&ls[l].env, *from) as usize; + assert!(group.contains(&src), "lane {l} reads lane {src}, which is elsewhere"); + if matches!(ins, Ins::ReadLaneHalf(..)) { + assert_eq!(src / 32, l / 32, "lane {l} reads lane {src} of the other half"); + } + self.value(&ls[src].env, *v) + }) + .collect(), + _ => unreachable!(), + }; + for (&l, x) in group.iter().zip(out) { + ls[l].env.insert(*id, x); + ls[l].at += 1; + } + } + } + } + + pub(crate) type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + /// A GPU that runs `[WaveSize(32)]` programs, as the per-lane tests need (WARP, the CI + /// adapter, has neither 32 nor 64: skipped, as `recomp::tests::gpu_ready` does). + pub(crate) fn gpu_waves() -> bool { + use super::super::runner; + runner::adapter().is_ok() && runner::wave32_supported() == Ok(true) + } + + pub(crate) const V: u64 = 256; + pub(crate) const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + + // wave32 programs shared by the CPU tests and the comparison with the HLSL path + pub(crate) const STRAIGHT: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ENDPGM, + ]; + /// v_cmp_gt_u32 vcc, 16, v0; s_and_saveexec s0, vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or exec, exec, s0; v_add v2, v1, 1 + pub(crate) const SKIPPED_IF: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov s0, exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; exec &= ~vcc; + /// s_cbranch_execnz L; exec |= s0 → v1 = max(1, lane) + pub(crate) const LEAVING_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// s1 = 0; L: s1 += 3; v1 += 1; s_cmp_lt_u32 s1, 12; s_cbranch_scc1 L + pub(crate) const UNIFORM_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 140)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ENDPGM, + ]; + + /// v1 = 4·lane; s[4:5] = mem[2..4]; v2 = mem[lane] + s4; then lanes below 16 store v2 at + /// mem[64 + lane] (a guarded store: no skip branch), and every lane stores v0 at mem[128 + lane] + pub(crate) const MEMORY: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + /// A compute program: 64 threads, user SGPRs s0–s1, the group id x in s2; + /// mem[64·group + thread] = 3·thread + s0 + group + pub(crate) const COMPUTE: &[I] = &[ + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 1), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 1)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + + // f32 programs: the per-lane form refuses f32 so far, and `lower_dxil`'s + // `f32_programs_on_the_gpu` runs them on the HLSL path, checks its registers with the + // `check_f32_*` below (32 lanes) and compares the per-lane form with it where it lowers them + + /// f32 VOP2 / VOP3 arithmetic on v1 = 2^lane and v2 = 2^lane · (1 + lane / 64), with the + /// VOP3 modifiers, and v19 = NaN (0x7FFFFFFF) into min / max / clamp. Every product is exact, + /// so `FMad` gives the same fused or not. + pub(crate) const F32_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 145), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + // 0.5 + x, x - p, x - (-4), x · x, min / max(2, x) + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 240), ("VSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_SUBREV_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 247), ("VSRC1", 2)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 2), ("VSRC1", 2)]), + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 244), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 244), ("VSRC1", 2)]), + // fma(x, -2, p), mad(x, 0.5, v3); mac v11 = 4 · x + p, fmac v12 = -0.5 · x + v3 + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 245), ("SRC2", V + 1)]), + ("V_MAD_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 240), ("SRC2", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)]), + ("V_MAC_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 246), ("VSRC1", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 3)]), + ("V_FMAC_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 241), ("VSRC1", 2)]), + // -|x| · |-4| (abs before neg); omod 0.5, 2, 4 (with neg on src2); clamp at 1 and at 0 + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 3), ("NEG", 1)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 1), ("OMOD", 3)]), + ("V_SUB_F32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OMOD", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", V + 2), ("NEG", 4), ("OMOD", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", 240), ("CLAMP", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", 243), ("SRC2", 244), ("CLAMP", 1)]), + // min(NaN, x), max(x, -NaN), clamp(NaN · 1); VOP3 fmac v23 = |-0.5| · x + p + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V + 19), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", V + 19), ("NEG", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 19), ("SRC1", 242), ("CLAMP", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_FMAC_F32", "ENC_VOP3", &[("VDST", 23), ("SRC0", 241), ("SRC1", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// f32 compares of a = v3 (NaN in every fourth lane, 2^lane in the others) with 4.0: all 16 + /// predicates into s[2k], two with VOP3 abs / neg, then VOPC into VCC and a cndmask of it, + /// and v_cmpx narrowing EXEC for a v_mov. + pub(crate) const F32_COMPARES: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V + 1), ("VSRC1", 19)]), + ("V_CMP_F_F32", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LT_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LE_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GT_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LG_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GE_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_O_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_U_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGE_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLG_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLE_F32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NEQ_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLT_F32", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_TRU_F32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 3), ("SRC1", 246)]), + // -|a| == -4; !(|-2| > -a) + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 3), ("SRC1", 247), ("ABS", 1), ("NEG", 1)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 34), ("SRC0", 245), ("SRC1", V + 3), ("ABS", 1), ("NEG", 2)]), + // vcc = a < 4, v6 = vcc ? p : 0; exec = a >= 4, v7 = 1.0 there + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 246)]), + ("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 128), ("VSRC1", 1)]), + ("V_CMPX_GE_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)]), + ENDPGM, + ]; + + /// f32 ↔ i32 / u32 / f16 conversions: v2 = lane − 16, v4 = (lane << 26 | lane) rounded, + /// v6 = (lane − 16) / 4 into the f32 → integer ones, v11 = v4² (out of range) and v19 = NaN + /// into the saturating ones; binary16 in and out (denormals, ties to even, overflow, NaN), + /// with OP_SEL halves, omod and clamp. + pub(crate) const F32_CONVERSIONS: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 154), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CVT_F32_I32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 1), ("OMOD", 3), ("CLAMP", 1)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 240), ("OMOD", 3)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + ("V_CVT_RPI_I32_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + ("V_CVT_FLR_I32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 6)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 4), ("VSRC1", 4)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 11)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + ("V_CVT_I32_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 11), ("NEG", 1)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 19)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V + 19)]), + // v17 = f16 (lane & 31) << 9 | (lane & 31), the lane in the high half; v20 = it in the + // high half, the lane in the low one + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 23), ("VSRC1", 17)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 144), ("VSRC1", 17)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V), ("VSRC1", 20)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 144), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 18), ("VSRC1", 17)]), + ("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 21), ("SRC0", V + 17)]), + ("V_CVT_F32_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 20), ("OP_SEL", 1)]), + // v24 = 1 + (lane & 31) · 2^-14: f16 ties at lanes 8 and 24; into v25's low half + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3F80_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 20)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 24)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 6), ("OP_SEL", 8)]), + // f16 denormals (· 2^-20), below the smallest one (· 2^-25), NaN, overflow, clamp + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3580_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 28)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3300_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 28)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 30), ("SRC0", V + 19)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 31), ("SRC0", V + 11)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 6), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// floor / ceil / trunc / rndne / fract of v3 = (lane − 16) / 8 (ties, signed zeros), fract + /// of −2^-30 (just below 1.0), and two with VOP3 modifiers. + pub(crate) const F32_ROUNDING: &[I] = &[ + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 2), ("LITERAL", 0x3E00_0000)]), + ("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CEIL_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 3)]), + ("V_TRUNC_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)]), + ("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0xB080_0000)]), + ("V_FLOOR_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("NEG", 1), ("OMOD", 1)]), + ("V_FRACT_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 3), ("ABS", 1), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// rcp / rsq / sqrt / log of v1 = 1 + (lane & 31) / 32, exp / sin / cos of v2 = v1 − 1.5, + /// and three with VOP3 modifiers (log2 |0| = −∞ at lane 16). The GPU's are approximate. + pub(crate) const F32_TRANSCENDENTALS: &[I] = &[ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 146), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 1), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 243)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 241), ("VSRC1", 2)]), + ("V_RCP_F32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)]), + ("V_RCP_IFLAG_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 1)]), + ("V_RSQ_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)]), + ("V_SQRT_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + ("V_EXP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 2)]), + ("V_LOG_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 1)]), + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 2)]), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)]), + ("V_EXP_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("NEG", 1), ("OMOD", 1)]), + ("V_SIN_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("CLAMP", 1)]), + ("V_LOG_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// v_fmamk / fmaak / madmk / madak (products exact) and min3 / max3 / med3 of a = the lane + /// (NaN in every fourth lane), b = lane − 16 and 4.0, one with VOP3 abs / neg. + pub(crate) const F32_THREE_SOURCE: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 19)]), + ("V_FMAMK_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_FMAAK_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MADMK_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_MADAK_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MIN3_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MAX3_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", V + 5), ("SRC2", 246), ("ABS", 1), ("NEG", 2)]), + ENDPGM, + ]; + + // f16 and packed programs, as the f32 ones: `lower_dxil`'s `f16_programs_on_the_gpu` checks + // the HLSL path's registers with the `check_f16_*` below and compares the per-lane form with it + + /// f16 VOP1 / VOP2 / VOP3 on x = 1 + lane · 2^-10 (v1, and v6's low half; v6's high half is + /// −2 − lane · 2^-9): ties to even, denormal results and their ties, overflow, a fused fma + /// just below a tie (lane 1), NaN into min / max / med3, OP_SEL halves, omod and clamp, and + /// f16 ↔ i16 / u16. + pub(crate) const F16_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 6), ("SRC1", 144), ("SRC2", V + 1)]), + // v2 = 2^-11, v3 = 2^-15 (a denormal), v4 = 65504, v5 = NaN, v7 = 2^-11 · (1 − 2^-10) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x0200)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 255), ("LITERAL", 0x7BFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE)]), + // x + 2^-11, 2^-11 − x (ties), x · 2^-15 (denormal ties), x · 65504 (∞ from lane 1), + // fma(x, v7, x) + ("V_ADD_F16", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_F16", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 1), ("VSRC1", 3)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 1), ("VSRC1", 4)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1)]), + // min(NaN, x), max(x, −NaN); v15's high half = v6's + x, its low half kept + ("V_MIN_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 5), ("VSRC1", 1)]), + ("V_MAX_F16", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 5), ("NEG", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V)]), + ("V_ADD_F16", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 6), ("SRC1", V + 1), ("OP_SEL", 9)]), + // omod: (x · 0.5) · 2, (x · x − 1) · 4; clamp of 65504 · 2 + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", 240), ("OMOD", 1)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", 243), ("OMOD", 2)]), + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 4), ("SRC1", 244), ("CLAMP", 1)]), + // ldexp(x, −lane): denormals and their ties from lane 15, 0 from lane 26 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 128), ("VSRC1", 0)]), + ("V_LDEXP_F16", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 1), ("VSRC1", 20)]), + // fract of v6's high half; q = (lane − 16) / 2 into rndne (ties, −0 at lane 15), i16, u16; + // u16 2049 · lane into f16 (a tie at lane 16) + ("V_FRACT_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 6), ("OP_SEL", 1)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 25), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F16_I16", "ENC_VOP1", &[("VDST", 24), ("SRC0", V + 25)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 26), ("SRC0", 240), ("VSRC1", 24)]), + ("V_RNDNE_F16", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 26)]), + ("V_CVT_I16_F16", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 26)]), + ("V_CVT_U16_F16", "ENC_VOP1", &[("VDST", 28), ("SRC0", V + 26)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_CVT_F16_U16", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 30)]), + // med3(NaN, x, 2); fmac v32 = x · 2^-11 + x + ("V_MED3_F16", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 5), ("SRC1", V + 1), ("SRC2", 244)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 32), ("SRC0", V + 1)]), + ("V_FMAC_F16", "ENC_VOP2", &[("VDST", 32), ("SRC0", V + 1), ("VSRC1", 2)]), + ENDPGM, + ]; + + /// VOP3P packed math on v1 = x | y << 16 (x, y as in `F16_ARITHMETIC`), v2 = 2^-11 | 2^-15 << 16, + /// v3 = NaN | 65504 << 16 and the u16 / i16 pairs v4 = 2049 · lane | (0xFFFF − lane) << 16, + /// v5 = (0x8000 + lane << 10) | (0x7FF0 + lane) << 16: OP_SEL / OP_SEL_HI picking swapped and + /// broadcast halves, NEG / NEG_HI, clamp (f16, and saturating u16 / i16), and + /// v_cvt_pkrtz_f16_f32 (toward zero, 65504 for the out-of-range ones). + pub(crate) const F16_PACKED: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V + 9), ("SRC1", 144), ("SRC2", V + 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x0200_1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x7BFF_7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE_0FFE)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xFFFF)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 11), ("SRC1", 144), ("SRC2", V + 10)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 138), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12), ("LITERAL", 0x8000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FF0)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 13), ("SRC1", 144), ("SRC2", V + 12)]), + // v1 + v2; v1.hi · v2.lo | v1.lo · v2.hi; fma(v1, v7, v1) (v7 as in `F16_ARITHMETIC`) + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL", 1), ("OP_SEL_HI", 2)]), + ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // min(v3, v1), max(v1, −v3), v1 + (−lo | hi of v1's high half), clamp(v3.hi · v1) + ("V_PK_MIN_F16", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL_HI", 3)]), + ("V_PK_MAX_F16", "ENC_VOP3P", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V + 3), ("OP_SEL_HI", 3), ("NEG", 2), ("NEG_HI", 2)]), + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("NEG_HI", 1)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL", 1), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + // u16 / i16: wrapping, saturating (clamp), v4.lo · v5.hi | v4.hi · v5.hi, v4 · v4 + v5 + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 21), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_U16", "ENC_VOP3P", &[("VDST", 23), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_ADD_I16", "ENC_VOP3P", &[("VDST", 24), ("SRC0", V + 5), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_I16", "ENC_VOP3P", &[("VDST", 25), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL", 2), ("OP_SEL_HI", 3)]), + ("V_PK_MAD_U16", "ENC_VOP3P", &[("VDST", 27), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // pkrtz of 1 + lane · 2^-11 and of 65520 + 16 · lane (f32) + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 31), ("SRC0", 140), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 29), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x477F_F000)]), + ("V_CVT_PKRTZ_F16_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", V + 29), ("VSRC1", 30)]), + ENDPGM, + ]; + + /// binary16 of an f64 (exact: an f16 sum or product), rounded to nearest even: denormals, + /// and ∞ past 65504 + pub(crate) fn f16_bits(x: f64) -> u32 { + let s = (x.is_sign_negative() as u32) << 15; + let a = x.abs(); + if a.is_infinite() { + return s | 0x7C00; + } + let e = ((a.to_bits() >> 52) as i32 - 1023).max(-14); + let q = (a * 2f64.powi(10 - e)).round_ties_even() as u32; + s | ((e + 14) as u32 * 1024 + q).min(0x7C00) + } + + pub(crate) fn check_f16_arithmetic(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + for (l, r) in v.iter().enumerate() { + let (x, y) = (0x3C00 + l as u32, 0xC000 + l as u32); + let (fx, fy, q) = (h(x), h(y), (l as f64 - 16.0) / 2.0); + assert_eq!((r[1], r[6]), (x, y << 16 | x), "lane {l}"); + // v8, v9, v12, v17, v19, v29 and v32 round to nearest even on the console (MODE.FP_ROUND + // = 0) and the HLSL path gives them rounded toward zero on NVIDIA (`f32tof16`, whose + // rounding the driver picks), so they are left to the per-lane comparison + let want = [ + (10, f16_bits(fx * p(-15))), + (11, f16_bits(fx * 65504.0)), + (13, x), + (14, x), + (15, f16_bits(fy + fx) << 16 | l as u32), + (16, x), + (18, 0x3C00), + (22, f16_bits(fy - fy.floor())), + (23, f16_bits(q.round_ties_even())), + (24, f16_bits(l as f64 - 16.0)), + (26, f16_bits(q)), + (27, q as i32 as u32 & 0xFFFF), + (28, q as u32), + (31, x), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + + pub(crate) fn check_f16_packed(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + let pk = |lo: u32, hi: u32| lo & 0xFFFF | hi << 16; + let i16s = |a: u32| a as u16 as i16 as i32; + let sat = |a: i32| a.clamp(-32768, 32767) as u32; + for (l, r) in v.iter().enumerate() { + let n = l as u32; + let (x, y) = (0x3C00 + n, 0xC000 + n); + let (fx, fy) = (h(x), h(y)); + let (a0, a1, c0, c1) = (2049 * n, 0xFFFF - n, 0x8000 + (n << 10), 0x7FF0 + n); + assert_eq!((r[1], r[4], r[5]), (pk(x, y), pk(a0, a1), pk(c0, c1)), "lane {l}"); + // v14 and v16 as v8 and v12 of `check_f16_arithmetic` + let want = [ + (15, pk(f16_bits(fy * p(-11)), f16_bits(fx * p(-15)))), + (17, pk(x, y)), + (18, pk(x, y)), + (19, pk(f16_bits(2.0 * fx), 0)), + (20, pk(0x3C00, 0)), + (21, pk(a0 + c0, a1 + c1)), + (22, pk((a0 + c0).min(0xFFFF), (a1 + c1).min(0xFFFF))), + (23, pk(a0.saturating_sub(c0), a1.saturating_sub(c1))), + (24, pk(sat(2 * i16s(c0)), sat(2 * i16s(c1)))), + (25, pk(a0.wrapping_sub(c0), a1.wrapping_sub(c1))), + (26, pk(a0 * c1, a1 * c1)), + (27, pk(a0 * a0 + c0, a1 * a1 + c1)), + (28, pk(0x3C00 + n / 2, 0x7BFF)), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + + pub(crate) fn check_f32_arithmetic(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (p, x) = (f(1), f(2)); + assert_eq!((p, x), (2f32.powi(l as i32), 2f32.powi(l as i32) * (1.0 + l as f32 / 64.0)), "lane {l}"); + let y = x + 0.5; + let want = [y, x - p, x + 4.0, x * x, x.min(2.0), x.max(2.0), x * -2.0 + p, x * 0.5 + y, 4.0 * x + p, -0.5 * x + y, -x * 4.0, (x + p) * 0.5, (p - x) * 2.0, (p * p - x) * 4.0, sat((x - p) * 0.5), sat(2.0 - x)]; + for (i, w) in want.iter().enumerate() { + assert_eq!(f(3 + i).to_bits(), w.to_bits(), "lane {l} v{}: {} against {w}", 3 + i, f(3 + i)); + } + assert_eq!((r[20], r[21], r[22]), (r[2], r[2], 0), "lane {l}: NaN into min, max, clamp"); + assert_eq!(f(23), 0.5 * x + p, "lane {l}: VOP3 fmac"); + } + } + + pub(crate) fn check_f32_compares(s: &[u32], v: &[Vec]) { + let preds: [fn(f32, f32) -> bool; 18] = [ + |_, _| false, + |a, b| a < b, + |a, b| a == b, + |a, b| a <= b, + |a, b| a > b, + |a, b| a < b || a > b, + |a, b| a >= b, + |a, b| !a.is_nan() && !b.is_nan(), + |a, b| a.is_nan() || b.is_nan(), + |a, b| !(a >= b), + |a, b| !(a < b || a > b), + |a, b| !(a > b), + |a, b| !(a <= b), + |a, b| !(a == b), + |a, b| !(a < b), + |_, _| true, + |a, _| -a.abs() == -4.0, + |a, _| !(2.0 > -a), + ]; + let a: Vec = (0..32).map(|l| if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { 2f32.powi(l) }).collect(); + let mask = |p: &dyn Fn(f32) -> bool| (0..32).filter(|&l| p(a[l])).fold(0u32, |m, l| m | 1 << l); + for (k, p) in preds.iter().enumerate() { + assert_eq!(s[2 * k], mask(&|x| p(x, 4.0)), "s{}", 2 * k); + } + assert_eq!(s[106], mask(&|x| x < 4.0), "vcc"); + assert_eq!(s[126], mask(&|x| x >= 4.0), "exec"); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], a[l].to_bits(), "lane {l}"); + assert_eq!(r[6], if a[l] < 4.0 { r[1] } else { 0 }, "lane {l}: cndmask"); + assert_eq!(r[7], if a[l] >= 4.0 { 1f32.to_bits() } else { 0 }, "lane {l}: under v_cmpx"); + } + } + + pub(crate) fn check_f32_conversions(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (li, q) = (l as i32 - 16, (l as i32 - 16) as f32 / 4.0); + assert_eq!(f(2), li as f32, "lane {l}"); + assert_eq!(f(4), ((l as u32) << 26 | l as u32) as f32, "lane {l}: u32 rounded to nearest even"); + assert_eq!(f(5), (li as f32 * 0.5).clamp(0.0, 1.0), "lane {l}: omod and clamp"); + assert_eq!(f(6), q, "lane {l}"); + // the HLSL path's cvt_i32 / cvt_u32 saturate as Rust's `as` does, NaN giving 0 + assert_eq!((r[7], r[8]), (q as i32 as u32, q as u32), "lane {l}: truncated"); + assert_eq!((r[9], r[10]), ((q + 0.5).floor() as i32 as u32, q.floor() as i32 as u32), "lane {l}: rpi, flr"); + assert_eq!((r[12], r[13], r[14]), (f(11) as i32 as u32, f(11) as u32, (-f(11)) as i32 as u32), "lane {l}: out of range"); + assert_eq!((r[15], r[16]), (0, 0), "lane {l}: NaN"); + assert_eq!(f(21), f16_to_f32(r[17] & 0xFFFF), "lane {l}"); + assert_eq!(r[22], r[21], "lane {l}: the high half"); + assert_eq!(r[25] >> 16, r[20] >> 16, "lane {l}: the half kept"); + assert_eq!(r[26] & 0xFFFF, l as u32, "lane {l}: the half kept"); + assert_eq!(r[29], (l != 0) as u32, "lane {l}: below the smallest denormal"); + assert_eq!(r[30], 0x7FFF, "lane {l}: NaN"); + assert_eq!(r[31], if l == 0 { 0 } else { 0x7C00 }, "lane {l}: overflow"); + } + let lo = |l: usize, i: usize| v[l][i] & 0xFFFF; + assert_eq!([lo(0, 21), lo(1, 17), lo(30, 17)], [0, 0x0201, 0x3C1E]); + assert_eq!((f32::from_bits(v[1][21]), f32::from_bits(v[30][21])), (513.0 * 2f32.powi(-24), 1.0 + 30.0 / 1024.0), "f16 in"); + // 1 + k · 2^-14 at k = 1, 8, 16, 24, 31: ties to even at 8 and 24 + assert_eq!([1, 8, 16, 24, 31].map(|l| lo(l, 25)), [0x3C00, 0x3C00, 0x3C01, 0x3C02, 0x3C02]); + assert_eq!([0, 16, 18, 20].map(|l| v[l][26] >> 16), [0xC400, 0, 0x3800, 0x3C00], "f16 into the high half"); + assert_eq!([0, 18, 20, 31].map(|l| lo(l, 32)), [0, 0x3800, 0x3C00, 0x3C00], "clamp"); + assert_eq!(lo(0, 27), 0x0010, "2^-20: an f16 denormal"); + } + + pub(crate) fn check_f32_rounding(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let x = (l as i32 - 16) as f32 / 8.0; + let want = [x.floor(), x.ceil(), x.trunc(), x.round_ties_even(), x - x.floor()]; + for (i, w) in want.iter().enumerate() { + assert_eq!(r[4 + i], w.to_bits(), "lane {l} v{}", 4 + i); + } + assert_eq!(r[9], 0x3F7F_FFFF, "fract(-2^-30): below 1.0"); + assert_eq!(r[10], (2.0 * (-x).floor()).to_bits(), "lane {l} v10"); + assert_eq!(f32::from_bits(r[11]), x.abs() - x.abs().floor(), "lane {l}"); + } + } + + pub(crate) fn check_f32_three_source(_: &[u32], v: &[Vec]) { + let med3 = |a: f32, b: f32, c: f32| a.min(b).max(a.max(b).min(c)); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (x, y) = (l as f32, l as f32 - 16.0); + let a = if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { x }; + assert_eq!([f(6), f(7), f(8), f(9)], [x * 1.5 + y, x * y + 0.25, x * 1.5 + y, x * y + 0.25], "lane {l}"); + assert_eq!([f(10), f(11), f(12)], [a.min(y).min(4.0), a.max(y).max(4.0), med3(a, y, 4.0)], "lane {l}"); + assert_eq!(f(13), med3(y.abs(), -a, 4.0), "lane {l}"); + } + } + + pub(crate) fn check_f32_transcendentals(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let x = 1.0 + (l & 31) as f32 / 32.0; + let y = x - 1.5; + let t = y * 6.283_185_3; + assert_eq!((r[1], r[2]), (x.to_bits(), y.to_bits()), "lane {l}"); + let want = [1.0 / x, 1.0 / x, 1.0 / x.sqrt(), x.sqrt(), y.exp2(), x.log2(), t.sin(), t.cos(), 2.0 * (-y).exp2(), sat(t.sin()), y.abs().log2()]; + for (i, w) in want.iter().enumerate() { + assert!(f32_close(r[3 + i], w.to_bits()), "lane {l} v{}: {} against {w}", 3 + i, f32::from_bits(r[3 + i])); + } + } + } + + /// The same bits, or within `approximate_float_unary_ops_are_within_tolerance`'s tolerance. + pub(crate) fn f32_close(a: u32, b: u32) -> bool { + let (a, b) = (f32::from_bits(a), f32::from_bits(b)); + a.to_bits() == b.to_bits() || (a - b).abs() <= 1e-3f32.max(b.abs() * 1e-5) + } + + /// binary16 in the low 16 bits → f32 (`f16tof32`) + pub(crate) fn f16_to_f32(h: u32) -> f32 { + let (s, e, m) = (h >> 15 & 1, h >> 10 & 0x1F, h & 0x3FF); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 => f32::from_bits(0x7F80_0000 | m << 13), + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -v } else { v } + } + + // integer programs, as the f32 ones: `lower_dxil`'s `integer_programs_on_the_gpu` checks the + // HLSL path's registers with the `check_int_*` below and compares the per-lane form with it + + /// a = lane · 0x9E3779B9 (v1), b = lane − (a >> 13) (v2, negative but at lane 0) and + /// c = 0x7FFFFFF0 + lane (v3, past i32::MAX from lane 16) + const INT_INPUTS: [I; 5] = [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x9E37_79B9)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V + 9)]), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 141), ("VSRC1", 1)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FFF_FFF0)]), + ]; + + /// Integer VALU on a, b, c (`INT_INPUTS`): high products, 24-bit and 16-bit multiplies (OP_SEL + /// halves), bitfields with offset + width past 32 and width 0, align, SAD, min3 / max3 / med3, + /// clamped (saturating) adds, bit counts and scans of 0 and −1, packs that saturate. + pub(crate) const INT_ARITHMETIC: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 12), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_U32_U24", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_I32_I24", "ENC_VOP2", &[("VDST", 14), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_I32_I24", "ENC_VOP2", &[("VDST", 15), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAD_I32_I24", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // bfe(a, lane, 8) unsigned and signed, bfe(a, 4, lane), bfi, bfm(lane, 4) + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 132), ("SRC2", V)]), + ("V_BFI_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_BFM_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 132)]), + ("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 23), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_ALIGNBYTE_B32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_XAD_U32", "ENC_VOP3", &[("VDST", 25), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U8", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_HI_U8", "ENC_VOP3", &[("VDST", 27), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U16", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U32", "ENC_VOP3", &[("VDST", 29), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MSAD_U8", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_U32", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_I32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_I32", "ENC_VOP3", &[("VDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_I32", "ENC_VOP3", &[("VDST", 35), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_U32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // clamp: a + b + c, a + b, b − a (u32); a + c, b − c (i32); a + c without + ("V_ADD3_U32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 38), ("SRC0", V + 1), ("SRC1", V + 2), ("CLAMP", 1)]), + ("V_SUB_NC_U32", "ENC_VOP3", &[("VDST", 39), ("SRC0", V + 2), ("SRC1", V + 1), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 40), ("SRC0", V + 1), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_SUB_NC_I32", "ENC_VOP3", &[("VDST", 41), ("SRC0", V + 2), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 42), ("SRC0", V + 1), ("SRC1", V + 3)]), + // bcnt(a) + lane, ffbh / ffbl / ffbh_i32 (0 and −1 at lane 0), bfrev, not, xnor + ("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 43), ("SRC0", V + 1), ("SRC1", V)]), + ("V_FFBH_U32", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 1)]), + ("V_FFBL_B32", "ENC_VOP1", &[("VDST", 45), ("SRC0", V + 2)]), + ("V_FFBH_I32", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 2)]), + ("V_BFREV_B32", "ENC_VOP1", &[("VDST", 47), ("SRC0", V + 1)]), + ("V_NOT_B32", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 2)]), + ("V_XNOR_B32", "ENC_VOP2", &[("VDST", 49), ("SRC0", V + 1), ("VSRC1", 2)]), + // packs of (a, b) to u16 and (b, c) to i16; 16-bit mads of a.hi · b.lo, a.lo · b.hi + ("V_CVT_PK_U16_U32", "ENC_VOP3", &[("VDST", 50), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_CVT_PK_I16_I32", "ENC_VOP3", &[("VDST", 51), ("SRC0", V + 2), ("SRC1", V + 3)]), + ("V_MAD_U32_U16", "ENC_VOP3", &[("VDST", 52), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 1)]), + ("V_MAD_I32_I16", "ENC_VOP3", &[("VDST", 53), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 2)]), + ("V_MIN_I32", "ENC_VOP2", &[("VDST", 54), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAX_U32", "ENC_VOP2", &[("VDST", 55), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 56), ("SRC0", V + 1), ("SRC1", V), ("SRC2", V + 3)]), + ("V_ADD_LSHL_U32", "ENC_VOP3", &[("VDST", 57), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ENDPGM, + ]; + + /// Carries on a, b, c (`INT_INPUTS`): VOP3 carry-outs into s20..s30 and carry-ins from them, + /// a VOP2 chain through VCC, a VOP3 cndmask on s22, v_mad_u64_u32 / v_mad_i64_i32 with their + /// carry-outs (s32, s34) and the 64-bit shifts by 2 · lane + 3 (65 at lane 31: 1). + pub(crate) const INT_CARRIES: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 10), ("SDST", 20), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 11), ("SDST", 22), ("SRC0", V + 1), ("SRC1", V + 3), ("SRC2", 20)]), + ("V_SUB_CO_U32", "VOP3_SDST_ENC", &[("VDST", 12), ("SDST", 24), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 13), ("SDST", 26), ("SRC0", V + 3), ("SRC1", V + 2), ("SRC2", 24)]), + ("V_SUBREV_CO_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 28), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 15), ("SDST", 30), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", 28)]), + // vcc = a > b; a + b + vcc, c − a − vcc, a − c − vcc, each into vcc + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 2)]), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 16), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_CO_CI_U32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_SUBREV_CO_CI_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 22)]), + // v[20:21] = a · b + (c | a << 32), v[24:25] the same signed; shifts of them and of v[22:23] + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 20), ("SDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_MAD_I64_I32", "VOP3_SDST_ENC", &[("VDST", 24), ("SDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 129), ("SRC2", 131)]), + ("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 20)]), + ("V_LSHRREV_B64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 4), ("SRC1", V + 22)]), + ("V_ASHRREV_I64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 4), ("SRC1", V + 24)]), + ENDPGM, + ]; + + /// `INT_INPUTS`' a, b, c of a lane + fn int_inputs(l: usize) -> (u32, u32, u32) { + let a = (l as u32).wrapping_mul(0x9E37_79B9); + (a, (l as u32).wrapping_sub(a >> 13), 0x7FFF_FFF0 + l as u32) + } + + pub(crate) fn check_int_arithmetic(_: &[u32], v: &[Vec]) { + let (u24, i24) = (|x: u32| (x & 0xFF_FFFF) as u64, |x: u32| ((x << 8) as i32 >> 8) as i64); + let i16s = |x: u32| x as u16 as i16 as i32; + let bytes = |x: u32| x.to_le_bytes().map(|b| b as i32); + let first = |n: u32, x: u32| if x == 0 { u32::MAX } else { n }; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let n = l as u32; + let (ai, bi, ci) = (a as i32, b as i32, c as i32); + assert_eq!((r[1], r[2], r[3]), (a, b, c), "lane {l}"); + let mask = |w: u32| ((1u64 << w) - 1) as u32; + let sext = |x: u32, w: u32| if w == 0 { 0 } else { ((x << (32 - w)) as i32 >> (32 - w)) as u32 }; + let (ba, bb) = (bytes(a), bytes(b)); + let sad8: i32 = (0..4).map(|k| (ba[k] - bb[k]).abs()).sum(); + let msad8: i32 = (0..4).filter(|&k| bb[k] != 0).map(|k| (ba[k] - bb[k]).abs()).sum(); + let sad16 = (i16s(a) as u16 as i32 - b as u16 as i32).abs() + ((a >> 16) as i32 - (b >> 16) as i32).abs(); + let med3 = |x: u32, y: u32, z: u32| x.min(y).max(x.max(y).min(z)); + let med3i = |x: i32, y: i32, z: i32| x.min(y).max(x.max(y).min(z)); + let ffbh_i = |x: u32| if x == 0 || x == u32::MAX { u32::MAX } else { (x ^ (x as i32 >> 31) as u32).leading_zeros() }; + let want = [ + ((a as u64 * b as u64) >> 32) as u32, + ((ai as i64 * bi as i64) >> 32) as u32, + (u24(a) * u24(b)) as u32, + ((u24(a) * u24(b)) >> 32) as u32, + (i24(a) * i24(b)) as u32, + ((i24(a) * i24(b)) >> 32) as u32, + ((u24(a) * u24(b)) as u32).wrapping_add(c), + ((i24(a) * i24(b)) as u32).wrapping_add(c), + a >> (n & 31) & mask(8), + sext((ai >> (n & 31)) as u32 & mask(8), 8), + a >> 4 & mask(n & 31), + a & b | !a & c, + mask(n & 31) << 4, + (((a as u64) << 32 | b as u64) >> (n & 31)) as u32, + (((a as u64) << 32 | b as u64) >> (8 * (n & 3))) as u32, + (a ^ b).wrapping_add(c), + (sad8 as u32).wrapping_add(c), + ((sad8 as u32) << 16).wrapping_add(c), + (sad16 as u32).wrapping_add(c), + a.abs_diff(b).wrapping_add(c), + (msad8 as u32).wrapping_add(c), + a.min(b).min(c), + ai.max(bi).max(ci) as u32, + med3(a, b, c), + med3i(ai, bi, ci) as u32, + ai.min(bi).min(ci) as u32, + a.max(b).max(c), + (a as u64 + b as u64 + c as u64).min(u32::MAX as u64) as u32, + a.saturating_add(b), + b.saturating_sub(a), + ai.saturating_add(ci) as u32, + bi.saturating_sub(ci) as u32, + a.wrapping_add(c), + a.count_ones() + n, + first(a.leading_zeros(), a), + first(b.trailing_zeros(), b), + ffbh_i(b), + a.reverse_bits(), + !b, + !(a ^ b), + a.min(0xFFFF) | b.min(0xFFFF) << 16, + bi.clamp(-32768, 32767) as u32 & 0xFFFF | (ci.clamp(-32768, 32767) as u32) << 16, + (a >> 16).wrapping_mul(b & 0xFFFF).wrapping_add(c), + (i16s(a) * i16s(b >> 16)).wrapping_add(ci) as u32, + ai.min(bi) as u32, + a.max(b), + (a << (n & 31)).wrapping_add(c), + a.wrapping_add(b) << (n & 31), + ]; + for (k, w) in want.iter().enumerate() { + assert_eq!(r[10 + k], *w, "lane {l} v{}: {:#x} against {w:#x}", 10 + k, r[10 + k]); + } + } + } + + pub(crate) fn check_int_carries(s: &[u32], v: &[Vec]) { + let mut masks = [0u32; 8]; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let (a64, b64, c64) = (a as u64, b as u64, c as u64); + let bit = |m: u32| (m >> l & 1) as u64; + let carry = [a64 + b64 > u32::MAX as u64, a64 + c64 + bit(s[20]) > u32::MAX as u64, b > a, b64 + bit(s[24]) > c64, a > b, b64 + bit(s[28]) > c64]; + let want = [a.wrapping_add(b), (a64 + c64 + bit(s[20])) as u32, a.wrapping_sub(b), (c64.wrapping_sub(b64 + bit(s[24]))) as u32, b.wrapping_sub(a), (c64.wrapping_sub(b64 + bit(s[28]))) as u32]; + for k in 0..6 { + assert_eq!(r[10 + k], want[k], "lane {l} v{}", 10 + k); + masks[k] |= (carry[k] as u32) << l; + } + // the VCC chain + let v0 = (a > b) as u64; + let w16 = a64 + b64 + v0; + let v1 = (w16 >> 32) as u64; + let v2 = (a64 + v1 > c64) as u64; + let v3 = (c64 + v2 > a64) as u64; + assert_eq!([r[16], r[17], r[18]], [w16 as u32, c64.wrapping_sub(a64 + v1) as u32, a64.wrapping_sub(c64 + v2) as u32], "lane {l}: through vcc"); + masks[6] |= (v3 as u32) << l; + assert_eq!(r[19], if bit(s[22]) == 1 { b } else { a }, "lane {l}: cndmask"); + let addend = c64 | a64 << 32; + let (wu, cu) = (a64 * b64).overflowing_add(addend); + let wi = ((a as i32 as i64 * b as i32 as i64) as u64).wrapping_add(addend); + masks[7] |= (cu as u32) << l; + let sh = (2 * l as u32 + 3) & 63; + let pair = |i: usize| r[i] as u64 | (r[i + 1] as u64) << 32; + assert_eq!([pair(20), pair(22), pair(24)], [wu, addend, wi], "lane {l}: mads"); + assert_eq!([pair(26), pair(28), pair(30)], [wu << sh, addend >> sh, ((wi as i64) >> sh) as u64], "lane {l}: 64-bit shifts"); + } + let got = [s[20], s[22], s[24], s[26], s[28], s[30], s[106], s[32]]; + assert_eq!(got, masks, "carry-outs s20..s30, vcc, s32"); + } + + pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + } + + /// A compute program run on the CPU over `groups` groups (wave32): the memory after. + pub(crate) fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + run_compute_waves(lines, cs, false, groups, sgprs, mem) + } + + /// … in wave32 or wave64: each wave takes the next `lanes` threads of its group, as on the + /// console (the last one fewer). + pub(crate) fn run_compute_waves(lines: &[I], cs: &crate::gpu::recomp::CsInterface, wave64: bool, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + let ir = lower_compute(&decode(lines), cs, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; + let mut io = vec![0u32; KERNEL_SGPRS]; + io[..sgprs.len()].copy_from_slice(sgprs); + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + let threads: u32 = cs.threads.iter().product(); + for g in 0..groups { + for w in (0..threads).step_by(lanes as usize) { + ir.run_with(lanes.min(threads - w) as usize, w, [g, 0, 0], &io, &mut res, &mut mem); + } + } + mem + } + + /// 2-D and 3-D groups of 64 threads. + pub(crate) const ID_SHAPES: [[u32; 3]; 2] = [[8, 8, 1], [4, 4, 4]]; + + /// Each thread of a 64-thread group of an `ID_SHAPES` shape stores its ids and its lane + /// (`mbcnt` of EXEC) as `x | y << 8 | z << 16 | lane << 24` at word `group * 64 + flat index`. + pub(crate) fn ids_program(threads: [u32; 3], wave64: bool) -> Vec { + let mut p: Vec = vec![("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)])]; + // v4 = flat index: (y << 3) + x, or (z << 4) + (y << 2) + x + if threads[2] == 1 { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 131), ("SRC2", V)])); + } else { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 130), ("SRC2", V)])); + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 2), ("SRC1", 132), ("SRC2", V + 4)])); + } + // v[8:9] = (group * 64 + flat) * 4; v5 = lane + p.extend_from_slice(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 4)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ]); + if wave64 { + p.push(("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)])); + } + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 1), ("SRC1", 136), ("SRC2", V)])); + if threads[2] > 1 { + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 144), ("SRC2", V + 7)])); + } + p.extend_from_slice(&[ + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 152), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]); + p + } + + pub(crate) fn ids_cs(threads: [u32; 3]) -> crate::gpu::recomp::CsInterface { + let tid_components = if threads[2] > 1 { 3 } else { 2 }; + crate::gpu::recomp::CsInterface { threads, tid_components, ..compute_cs() } + } + + pub(crate) fn memory_image() -> Vec { + (0..256).map(|i| 1000 + i).collect() + } + + // f64 programs, as the f32 ones: `lower_dxil`'s `f64_programs_on_the_gpu` checks the HLSL + // path's registers with `check_f64` and compares the per-lane form with it + + /// f64 on x = 1 + lane / 32 + lane · 2^-52 (v[2:3]): x + 2^-53 (ties to even), x · 2^-1040 + /// (a denormal in and out), x · f64::MAX (∞ from lane 1), fma(x, x, −x · x) (the rounding + /// error: nonzero only fused), NaN into min / max, VOP3 abs / neg / omod / clamp; floor / ceil + /// / trunc / rndne / fract / frexp of q = (lane − 16) / 4 (ties, −0 at lane 15); f64 ↔ f32 / + /// i32 / u32 (a tie, overflow, saturation, NaN); rcp / rsq / sqrt. + pub(crate) const F64_ARITHMETIC: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 143), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 3), ("LITERAL", 0x3FF0_0000)]), + // v[4:5] = 2^-53, v[6:7] = 2^-1040, v[8:9] = f64::MAX, v[10:11] = NaN + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x3CA0_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 132)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x7FEF_FFFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 129)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 255), ("LITERAL", 0x7FF8_0000)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", V + 4)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 6)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 2), ("SRC1", V + 8)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", V + 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 18), ("NEG", 4)]), + ("V_MIN_F64", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 10), ("SRC1", V + 2)]), + ("V_MAX_F64", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 2), ("SRC1", V + 10), ("NEG", 2)]), + // −x · |−4|, (x − 1) · 4, clamp(fma(x, x, −1)) + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 2), ("NEG", 1)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 2), ("SRC1", 243), ("OMOD", 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", 243), ("CLAMP", 1)]), + // q = ldexp(lane − 16, −2) + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F64_I32", "ENC_VOP1", &[("VDST", 34), ("SRC0", V + 32)]), + ("V_LDEXP_F64", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 34), ("SRC1", 194)]), + ("V_FLOOR_F64", "ENC_VOP1", &[("VDST", 38), ("SRC0", V + 36)]), + ("V_CEIL_F64", "ENC_VOP1", &[("VDST", 40), ("SRC0", V + 36)]), + ("V_TRUNC_F64", "ENC_VOP1", &[("VDST", 42), ("SRC0", V + 36)]), + ("V_RNDNE_F64", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 36)]), + ("V_FRACT_F64", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 36)]), + ("V_FREXP_MANT_F64", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 36)]), + ("V_FREXP_EXP_I32_F64", "ENC_VOP1", &[("VDST", 50), ("SRC0", V + 36)]), + // f32 of z = 1 + 2^-24 + lane · 2^-52 (a tie at lane 0) and of f64::MAX; i32 of −4x, of + // x · f64::MAX and of NaN, u32 of −4x and of NaN + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 52), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x1000_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 53), ("SRC0", 255), ("LITERAL", 0x3FF0_0000)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 51), ("SRC0", V + 52)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 54), ("SRC0", V + 8)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 55), ("SRC0", V + 26)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 56), ("SRC0", V + 16)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 57), ("SRC0", V + 10)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 58), ("SRC0", V + 26)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 59), ("SRC0", V + 10)]), + // f64 of u32::MAX − lane and of the f32 at v51 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 193), ("VSRC1", 0)]), + ("V_CVT_F64_U32", "ENC_VOP1", &[("VDST", 60), ("SRC0", V + 1)]), + ("V_CVT_F64_F32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 51)]), + ("V_RCP_F64", "ENC_VOP1", &[("VDST", 64), ("SRC0", V + 2)]), + ("V_RSQ_F64", "ENC_VOP1", &[("VDST", 66), ("SRC0", V + 2)]), + ("V_SQRT_F64", "ENC_VOP1", &[("VDST", 68), ("SRC0", V + 2)]), + ENDPGM, + ]; + + pub(crate) fn check_f64(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f64::from_bits(r[i] as u64 | (r[i + 1] as u64) << 32); + let x = 1.0 + l as f64 / 32.0 + l as f64 * 2f64.powi(-52); + let q = (l as f64 - 16.0) / 4.0; + assert_eq!(f(2).to_bits(), x.to_bits(), "lane {l}"); + let p = x * x; + let e = if q == 0.0 { 0 } else { (q.abs().to_bits() >> 52) as i32 - 1022 }; + let want = [ + x + 2f64.powi(-53), + x * 2f64.powi(-1040), + x * f64::MAX, + p, + x.mul_add(x, -p), + x, + x, + -4.0 * x, + (x - 1.0) * 4.0, + x.mul_add(x, -1.0).clamp(0.0, 1.0), + (l as f64 - 16.0), + q, + q.floor(), + q.ceil(), + q.trunc(), + q.round_ties_even(), + q - q.floor(), + q / 2f64.powi(e), + ]; + for (k, w) in want.iter().enumerate() { + let i = 12 + 2 * k + if k >= 10 { 2 } else { 0 }; + assert_eq!(f(i).to_bits(), w.to_bits(), "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + assert_eq!(r[50], e as u32, "lane {l}: frexp_exp"); + let z = 1.0 + 2f64.powi(-24) + l as f64 * 2f64.powi(-52); + assert_eq!([r[51], r[54]], [(z as f32).to_bits(), f32::INFINITY.to_bits()], "lane {l}: f32 of f64"); + assert_eq!([r[55], r[56], r[57], r[58], r[59]], [(-4.0 * x) as i32 as u32, i32::MAX as u32, 0, 0, 0], "lane {l}: i32 / u32 of f64"); + assert_eq!([f(60), f(62)], [(u32::MAX - l as u32) as f64, z as f32 as f64], "lane {l}: f64 of u32, f32"); + // the GPU's rcp / rsq / sqrt are close, not exact + for (i, w) in [(64, 1.0 / x), (66, 1.0 / x.sqrt()), (68, x.sqrt())] { + assert!((f(i) - w).abs() <= w * 1e-12, "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + } + } + + /// A line's bytes; a `("LITERAL", k)` field is the instruction's literal dword. + pub(crate) fn encode_line((n, e, f): &I) -> Vec { + let lit = f.iter().find(|(k, _)| *k == "LITERAL").map(|&(_, v)| v as u32); + let f: Vec<(&str, u64)> = f.iter().copied().filter(|(k, _)| *k != "LITERAL").collect(); + rdna2::encode(n, e, &f, lit).unwrap() + } + + pub(crate) fn decode(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let mut out = Vec::new(); + let mut off = 0; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + rdna2::resolve_far_jumps(&mut out); + out + } + + /// A branch or a scalar select on whether any lane of a mask is set decides for the whole + /// wave on the console: with lanes in EXEC that lack the bit (VCC = lanes 0–15, EXEC = all), + /// each lane deciding by its own bit would differ in lanes 16–31, so the program is refused + /// (Kalmarv's five programs on #1745); where the mask is constant over EXEC it is taken. + #[test] + fn a_whole_wave_decision_on_a_mask_some_lanes_lack_is_refused() { + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]); + const MOV7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]); + const AND: I = ("S_AND_B32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 106), ("SSRC1", 126)]); + let programs: [(&str, Vec); 5] = [ + ("vccnz", vec![CMP, ("S_CBRANCH_VCCNZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("vccz", vec![CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + scc1", vec![CMP, AND, ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("cmp_lg + scc1", vec![CMP, ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 106), ("SSRC1", 128)]), ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + cselect", vec![CMP, AND, ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), ENDPGM]), + ]; + for (name, p) in programs { + let err = lower_kernel(&decode(&p), false, Interp::default()).err().unwrap_or_else(|| panic!("{name}: taken")); + assert!(err.contains("any lane of a mask") || err.contains("SCC of a mask op"), "{name}: {err}"); + } + // the mask op's SCC reaching the `s_cselect` only around the loop's back edge + // (thehollowedone's program on #1745: 7 where the console gives 5 in lanes 16–31) + let around: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 130)]), + CMP, + ("S_CMP_GT_U32", "ENC_SOPC", &[("SSRC0", 129), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 128)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)]), + AND, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + let err = lower_kernel(&decode(&around), false, Interp::default()).err().expect("around the loop: taken"); + assert!(err.contains("SCC of a mask op") || err.contains("any lane of a mask"), "around the loop: {err}"); + // VCC = EXEC: the same in every lane in EXEC, so each lane decides as the wave does + let uniform: [I; 4] = [("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 126)]), ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]; + let (s, v) = state(32); + let (_, v) = run(&uniform, false, &s, &v); + assert!(v.iter().all(|r| r[1] == 7)); + } + + /// A cross-lane scalar op on s0 holding a number takes the number path (the check for the + /// upper dword of a mask pair at s must not compute r - 1 for s0: nobodyttk, #1269). + #[test] + fn a_wave_op_on_s0_holding_a_number() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xF0F0)]), + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 0)]), + ENDPGM, + ]; + // the CPU lowering has no number form of it (DXIL takes it from #1426): refused, no panic + let err = lower_kernel(&decode(lines), false, Interp::default()).err().expect("refused"); + assert_eq!(err, "unsupported S_BCNT1_I32_B32"); + } + + /// `s_wqm` of a mask sets every lane of a quad with a bit; `s_cselect` picks a mask or a + /// number by SCC. + #[test] + fn whole_quad_mode_and_conditional_selects() { + let lines: &[I] = &[ + // vcc = lane 5 only; s0 = wqm(vcc) = lanes 4–7 + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 133), ("VSRC1", 0)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128), ("SRC1", 129), ("SRC2", 0)]), + // scc = (0 == 0): s1 = s0 (a mask), s2 = 5 + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 128), ("SRC1", 129), ("SRC2", 1)]), + // scc = (0 == 1): s3 = 7, s4 = no lanes + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 129)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 133), ("SSRC1", 135)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 0), ("SSRC1", 128)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(lines, false, &s, &v); + assert_eq!((s[2], s[3]), (5, 7)); + for (l, regs) in v.iter().enumerate() { + let quad = (4..8).contains(&l) as u32; + assert_eq!((regs[1], regs[2], regs[3]), (quad, quad, 0), "lane {l}"); + } + } + + /// `s_addc_u32` / `s_subb_u32` take SCC as the carry / borrow in and leave theirs in SCC. + #[test] + fn add_with_carry_and_subtract_with_borrow() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xFFFF_FFFF)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 129)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 128), ("SSRC1", 128)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 128), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 133), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 133), ("SSRC1", 129)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, _) = run(lines, false, &s, &v); + // 0xFFFFFFFF + 1 = 0 carry 1; 0 + 0 + 1 = 1; 0xFFFFFFFF + 0 + 0 = 0xFFFFFFFF + assert_eq!((s[1], s[2], s[5]), (0, 1, 0xFFFF_FFFF)); + // 0 - 1 = 0xFFFFFFFF borrow 1; 5 - 1 - 1 = 3; 5 - 1 - 0 = 4 + assert_eq!((s[3], s[4], s[6]), (0xFFFF_FFFF, 3, 4)); + } + + /// A far jump (`s_getpc_b64`, a constant added, `s_setpc_b64`, as a retail program jumps + /// over a long `then` block) is a plain jump: the lanes skip the instructions it jumps over. + #[test] + fn a_far_jump_skips_what_it_jumps_over() { + let far: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 2)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 255), ("LITERAL", 32)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 128)]), + ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 136)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 138)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 139)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(far, false, &s, &v); + // the address it computed: after `s_getpc_b64` (8) plus 32, past the four moves + assert_eq!((s[2], s[3]), (40, 0)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (7, 7 + l as u32), "lane {l}"); + } + } + + /// The kernel run on the CPU: initial (sgpr, vgpr[lane]) → final ones. + fn run(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec]) -> (Vec, Vec>) { + let (s, v, _) = run_mem(lines, wave64, sgpr, vgpr, &[]); + (s, v) + } + + /// … with the flat memory too: (sgpr, vgpr[lane], memory after). + pub(crate) fn run_mem(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec], mem: &[u32]) -> (Vec, Vec>, Vec) { + let insts = decode(lines); + let (ir, _) = lower_kernel(&insts, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[..sgpr.len()].copy_from_slice(sgpr); + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = io.clone(); + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); + let v = (0..lanes).map(|l| res[KERNEL_SGPRS + l * KERNEL_VGPRS..][..KERNEL_VGPRS].to_vec()).collect(); + (res[..KERNEL_SGPRS].to_vec(), v, mem) + } + + pub(crate) fn state(lanes: usize) -> (Vec, Vec>) { + let mut s = vec![0u32; KERNEL_SGPRS]; + s[126] = u32::MAX; + s[127] = u32::MAX; + // v0 = the lane, v1 = 0 + (s, (0..lanes).map(|l| { let mut v = vec![0u32; 8]; v[0] = l as u32; v }).collect()) + } + + #[test] + fn straight_line_scalar_and_vector_arithmetic() { + let (s, v) = state(32); + let (s, v) = run(STRAIGHT, false, &s, &v); + assert_eq!((s[0], s[1]), (5, 10)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (10, 10 + l as u32), "lane {l}"); + } + } + + /// The survey goes on past a refused instruction: both are reported, and a program the + /// lowering takes gives none. + #[test] + fn the_survey_reports_every_refusal() { + let mut lines = STRAIGHT.to_vec(); + lines.insert(2, ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)])); + lines.insert(4, ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)])); + let cs = compute_cs(); + assert!(lower_compute(&decode(&lines), &cs, false, Interp::default()).is_err()); + assert_eq!(survey_compute(&decode(&lines), &cs, false, Interp::default()), ["unsupported V_ADD_F32", "unsupported V_MUL_F32"]); + assert!(survey_compute(&decode(STRAIGHT), &cs, false, Interp::default()).is_empty()); + } + + #[test] + fn a_skipped_if_runs_only_its_lanes() { + let (s, v) = state(32); + let (s, v) = run(SKIPPED_IF, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + let want = if l < 16 { 7 } else { 0 }; + assert_eq!((regs[1], regs[2]), (want, want + 1), "lane {l}"); + } + assert_eq!(s[106], 0xFFFF, "vcc: the lanes below 16"); + assert_eq!((s[0], s[126]), (u32::MAX, u32::MAX), "saved and restored EXEC"); + } + + #[test] + fn lanes_leave_a_loop_one_by_one() { + let (s, v) = state(32); + let (s, v) = run(LEAVING_LOOP, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], (l as u32).max(1), "lane {l}"); + } + assert_eq!(s[126], u32::MAX); + } + + #[test] + fn a_uniform_loop_with_a_scalar_counter() { + let (s, v) = state(32); + let (s, v) = run(UNIFORM_LOOP, false, &s, &v); + assert_eq!(s[1], 12); + assert!(v.iter().all(|r| r[1] == 4)); + } + + #[test] + fn lanes_outside_exec_at_launch_keep_their_registers() { + let (mut s, v) = state(32); + s[126] = 0x0000_00FF; + let (s, v) = run(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), ENDPGM], false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], if l < 8 { 9 } else { 0 }, "lane {l}"); + } + assert_eq!(s[126], 0xFF); + } + + /// A VS / PS run on the CPU in one wave of `lanes` lanes (a wave64 one in 32 lanes: in + /// 32-lane waves): `launch` its launch EXEC, `vgpr[lane]` the registers it starts with. The + /// memory after. + fn run_graphics(lines: &[I], pixel: bool, wave64: bool, lanes: usize, launch: u64, vgpr: &[Vec], mem: &[u32]) -> Vec { + let ir = lower_graphics(&decode(lines), pixel, wave64, wave64 && lanes == 32, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[EXEC as usize] = launch as u32; + io[EXEC as usize + 1] = (launch >> 32) as u32; + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); + mem + } + + /// v7 = 9, stored at v[8:9] (the lane's address: 4 × lane) + const SET_V7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 137)]); + const STORE_V7: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]); + + fn store_rows() -> Vec> { + (0..64).map(|l| { let mut v = vec![0u32; 10]; v[0] = l; v[1] = 15; v[8] = 4 * l; v }).collect() + } + + #[test] + fn a_ps_helper_lane_runs_the_program_but_does_not_store() { + // even lanes covered, odd lanes helper lanes + let launch = 0x5555_5555u64; + let want: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 && l % 2 == 0 { 9 } else { m }).collect(); + let exact = run_graphics(&[SET_V7, STORE_V7, ENDPGM], true, false, 32, launch, &store_rows(), &memory_image()); + assert_eq!(exact, want, "before EXEC is written, the store keeps its guard"); + // whole-quad mode, then back to the launch EXEC before the store (as compiled PSs do) + let wqm32: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm32, true, false, 32, launch, &store_rows(), &memory_image()), want); + // the same in wave64, run in 32-lane waves + let wqm64: Vec = vec![ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm64, true, true, 32, launch, &store_rows(), &memory_image()), want); + // a VS: each D3D vertex invocation is one lane, so every lane that runs is in EXEC at + // launch and stores, whatever bit its start gives it + let all: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 { 9 } else { m }).collect(); + assert_eq!(run_graphics(&[SET_V7, STORE_V7, ENDPGM], false, false, 32, launch, &store_rows(), &memory_image()), all); + // … so its store keeps no guard (no block of its own), where a PS's does + let blocks = |pixel: bool| lower_graphics(&decode(&[SET_V7, STORE_V7, ENDPGM]), pixel, false, false, Interp::default()).unwrap().blocks.len(); + assert_eq!(blocks(false) + 2, blocks(true), "a guarded store adds two blocks: the PS's only"); + } + + #[test] + fn whole_quad_instructions_need_every_lane_of_the_quad() { + // v_cmp (lanes above 15); s_and_saveexec s0; s_cbranch_execz L; s_wqm exec, s0; v_mov; + // L: exec |= s0 – the s_wqm of the launch EXEC, in a block only some lanes reach + let p: Vec = vec![ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + SET_V7, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let e = lower_graphics(&decode(&p), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32: needs whole quads, in a block not every lane reaches")); + // s_wqm of another mask: the lanes of the quad are not read + let other: Vec = vec![("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), SET_V7, ENDPGM]; + let e = lower_graphics(&decode(&other), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32 of a mask other than the launch EXEC")); + for (name, quad) in [ + ("IMAGE_SAMPLE", true), + ("IMAGE_SAMPLE_B_CL", true), + ("IMAGE_GATHER4_C", true), + ("IMAGE_GET_LOD", true), + ("S_WQM_B64", true), + ("IMAGE_SAMPLE_L", false), + ("IMAGE_SAMPLE_C_LZ_O", false), + ("IMAGE_SAMPLE_D_G16", false), + ("IMAGE_SAMPLE_CD", false), + ("IMAGE_GATHER4_LZ", false), + ("IMAGE_LOAD", false), + ] { + assert_eq!(whole_quad(name), quad, "{name}"); + } + } + + #[test] + fn a_wave64_vs_in_32_lane_waves_that_reads_upper_lanes_is_refused() { + // whole-wave code writes lanes 32–63 (v6 = 5), then v_readlane of lane 32 + let p: Vec = vec![ + ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 133)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]), + ENDPGM, + ]; + let insts = decode(&p); + assert_eq!(super::super::upper_lanes::analyze(&insts).reads.values().copied().collect::>(), vec![super::super::upper_lanes::Read::Const(5)]); + let e = lower_graphics(&insts, false, true, true, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("wave64 VS / PS in 32-lane waves: a read of lanes 32–63")); + assert!(lower_graphics(&insts, false, true, false, Interp::default()).is_ok(), "in 64-lane waves the lanes are there"); + } + + #[test] + fn wave64_masks_span_both_words() { + // v_cmp_gt_u32 vcc, 40, v0 over 64 lanes: lanes 0–39 + let (s, v) = state(64); + let (s, _) = run(&[("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), ENDPGM], true, &s, &v); + assert_eq!((s[106], s[107]), (u32::MAX, 0xFF)); + } + + /// The lowering run on the CPU and the HLSL path run on the GPU give the same registers. + #[test] + fn the_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let insts = decode(lines); + // masks some lanes kept their own older bits of (`lower_kernel`'s `stale`): only the + // kernel ABI's final store sees them + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + // wave64 versions of the programs above: 64-bit EXEC / VCC / saved masks, and thresholds + // past lane 32 so that both words of every mask matter + /// v_cmp_gt_u32 vcc, 40, v0; s_and_saveexec_b64 s[0:1], vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or_b64 exec, exec, s[0:1]; v_add v2, v1, 1 + const SKIPPED_IF_W64: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov_b64 s[0:1], exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; + /// exec &= ~vcc (b64); s_cbranch_execnz L; exec |= s[0:1] → v1 = max(1, lane), 64 lanes + const LEAVING_LOOP_W64: &[I] = &[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// `MEMORY` over 64 lanes: lanes below 40 take the guarded store + const MEMORY_W64: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + #[test] + fn a_wave64_mask_left_behind_is_reported_in_both_halves() { + // VCC from the loop's last v_cmp: lanes that left earlier kept their own bits in both words + let (_, stale) = lower_kernel(&decode(LEAVING_LOOP_W64), true, Interp::default()).unwrap(); + assert_eq!(stale, vec![106, 107]); + } + + /// The wave64 lowering run on the CPU and the HLSL path's native wave64 form run on a GPU + /// with 64-lane waves give the same registers and memory. + #[test] + fn the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: true, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, true, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + /// The split form (two hardware wave32s per console wave64, `lower_dxil::kernel_split`) run + /// on the GPU gives the registers and memory of the wave64 lowering run on the CPU: masks + /// across both halves, lane reads through the exchange (readfirstlane, readlane, the counts + /// of EXEC as numbers, mbcnt), and the reads that stay in their half (DPP, permlanex16, + /// ds_swizzle). A whole-wave read where lanes leave one by one is refused. + #[test] + fn the_split_form_agrees_with_the_wave64_lowering_on_the_gpu() { + use super::super::{lower_dxil, runner}; + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); + return; + } + let reads = lane_reads(true); + // reads across the halves both ways: readlane of lane 41 (the lower half needs the + // upper's), readfirstlane with EXEC from lane 40 up (the first lane is in the upper + // half), and a 64-bit compare mask counted as a number + const ACROSS: &[I] = &[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 169)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", 131)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 106)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 168)]), + ("V_CMPX_LE_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 126)]), + ENDPGM, + ]; + for (name, lines) in [ + ("across the halves", ACROSS), + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ("lane reads", &reads[..]), + ] { + let insts = decode(lines); + let (dxil, stale) = lower_dxil::kernel_split(&insts).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + // compute mode: a 64-thread group as two hardware wave32s, threads numbered by arrival + let cs = compute_cs(); + let dxil = lower_dxil::compute_split(&decode(COMPUTE), &cs).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..], "compute"); + // two console waves per group: their halves pair up through #1426's arrival counters + // and meet in its spin loop. Each thread stores its lane (`mbcnt` of EXEC: the mask + // words exchanged), its thread id and its console wave's first thread + // (`readfirstlane`: a lane of the other half for the upper one) + const TWO_WAVES: &[I] = &[ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 135)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 136), ("SRC2", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 10), ("SRC1", 144), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + let big = crate::gpu::recomp::CsInterface { threads: [128, 1, 1], ..compute_cs() }; + let dxil = lower_dxil::compute_split(&decode(TWO_WAVES), &big).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(TWO_WAVES, &big, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..256], &cpu[..256], "two console waves per group"); + assert!(cpu[..256].iter().any(|&w| w >> 16 == 64), "the CPU run's second wave starts at thread 64"); + // the waterfall's readfirstlane is in a block lanes leave one by one: native wave64 + // takes it, the split form cannot meet the other half there + let insts = decode(&waterfall(true)); + assert!(lower_kernel(&insts, true, Interp::default()).is_ok()); + let e = lower_dxil::kernel_split(&insts).unwrap_err(); + assert!(e.contains("split form"), "{e}"); + } + + #[test] + fn scalar_and_vector_memory_with_a_guarded_store() { + let (s, v) = state(32); + let (s, v, mem) = run_mem(MEMORY, false, &s, &v, &memory_image()); + assert_eq!((s[4], s[5]), (1002, 1003)); + for l in 0..32 { + assert_eq!(v[l][2], 2002 + l as u32, "lane {l}"); + assert_eq!(mem[64 + l], if l < 16 { 2002 + l as u32 } else { 1064 + l as u32 }, "guarded store, lane {l}"); + assert_eq!(mem[128 + l], l as u32, "store, lane {l}"); + } + // the store under the narrowed EXEC is the guarded one + let insts = decode(MEMORY); + let sum = lane_masks::analyze(&insts, false).unwrap(); + assert_eq!(sum.guarded.iter().filter(|&&pc| insts.iter().any(|d| d.pc == pc && is_store(d))).count(), 1); + } + + #[test] + fn a_compute_program_takes_its_group_and_thread_ids() { + let mem = run_compute(COMPUTE, &compute_cs(), 3, &[100, 0], &vec![0u32; 256]); + for g in 0..3u32 { + for t in 0..64u32 { + assert_eq!(mem[(64 * g + t) as usize], 3 * t + 100 + g, "group {g} thread {t}"); + } + } + } + + #[test] + fn a_2d_or_3d_group_numbers_its_threads_as_the_console_does() { + // a wave takes consecutive threads, lane l the l-th: x fastest, then y, then z + for threads in ID_SHAPES { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let mem = run_compute_waves(&ids_program(threads, wave64), &ids_cs(threads), wave64, 2, &[100, 0], &[0u32; 256]); + for g in 0..2u32 { + for t in 0..64u32 { + let (x, y, z) = (t % threads[0], t / threads[0] % threads[1], t / (threads[0] * threads[1])); + let want = x | y << 8 | z << 16 | (t % lanes) << 24; + assert_eq!(mem[(64 * g + t) as usize], want, "{threads:?} wave64 {wave64}: group {g} thread {t}"); + } + } + } + } + } + + /// The same through the HLSL path on the GPU, which numbers the threads by arrival. + #[test] + fn a_2d_or_3d_group_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } + } + + /// The compute program through the HLSL path on the GPU and through the lowering on the CPU. + #[test] + fn a_compute_program_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let cs = compute_cs(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + } + + #[test] + fn a_mask_left_behind_by_lanes_that_skipped_its_write() { + // VCC written inside the loop that lanes leave one by one: the console's last write left + // the earlier leavers' bits 0, each lane here kept its own. Stored at the end: reported. + let insts = decode(LEAVING_LOOP); + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + assert_eq!(stale, vec![106]); + // read after the loop (v_cndmask on VCC): refused + let mut lines = LEAVING_LOOP.to_vec(); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128), ("VSRC1", 0)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + // a mask written before the lanes split is read after they meet: fine + let insts = decode(SKIPPED_IF); + assert_eq!(lower_kernel(&insts, false, Interp::default()).unwrap().1, Vec::::new()); + // an older mask copied in the arm some lanes skip (s_mov s4, s0), read after they meet: + // the copy is the arm's write, not the older value's (found by MiguelMachado-dev) + let mut lines = SKIPPED_IF.to_vec(); + lines[2] = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]); + lines.insert(3, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 0)])); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)])); + // (s4 holds a mask before the lanes split, so the join is mask against mask) + lines.insert(1, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn a_scalar_counted_in_a_loop_lanes_leave_is_not_each_lanes_own() { + // s_add_u32 s1, s1, 1 in the loop lanes leave one by one: the console counts the wave's + // passes, each lane here only its own (a waterfall loop's key is the same case) + // s_mov s0, exec; s1 = 0; L: v_add v1, v1, 1; s1 += 1; v_cmp_ge vcc, v1, v0; + // exec &= ~vcc; s_cbranch_execnz L; exec |= s0 + let mut lines: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let (_, stale) = lower_kernel(&decode(&lines), false, Interp::default()).unwrap(); + assert!(stale.contains(&1), "{stale:?}"); + // read after the loop: refused + lines.insert(8, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 1)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn vop3_operand_selects_are_refused() { + let op_sel: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("OP_SEL", 1)]), ENDPGM]; + let err = lower_kernel(&decode(op_sel), false, Interp::default()).err().expect("refused"); + assert!(err.contains("modifiers"), "{err}"); + let plain: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V)]), ENDPGM]; + assert!(lower_kernel(&decode(plain), false, Interp::default()).is_ok()); + } + + #[test] + fn a_mask_read_as_a_number_is_refused() { + // s_bcnt1-like use: s_add_u32 s2, vcc_lo, 0 after a v_cmp + let insts = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 128)]), + ENDPGM, + ]); + assert!(lower_kernel(&insts, false, Interp::default()).is_err()); + } + + /// Cross-lane reads with EXEC narrowed to the lanes above 4 (`v_cmpx`): readfirstlane, + /// the counts of EXEC as a number, mbcnt, readlane / writelane, DPP16 / DPP8 sources, + /// permlanex16 and ds_swizzle. + fn lane_reads(wave64: bool) -> Vec { + let mut p: Vec = vec![ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 132)]), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 126), ("SRC1", 128)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 4), ("SRC1", 137)]), + ("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 2), ("SRC1", 130)]), + // row_shr:1 with bound_ctrl; quad_perm [3,2,1,0] on rows 1 and 3; DPP8 reversed, added + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 7), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x1B), ("ROW_MASK", 0xA), ("BANK_MASK", 0xF)]), + ("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 8), ("SRC0", 0xE9), ("VSRC0", 4), ("VSRC1", 0), ("LANE_SEL_0", 7), ("LANE_SEL_1", 6), ("LANE_SEL_2", 5), ("LANE_SEL_3", 4), ("LANE_SEL_4", 3), ("LANE_SEL_5", 2), ("LANE_SEL_6", 1), ("LANE_SEL_7", 0)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 5), ("SIMM16", 0x3210)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 6), ("SIMM16", 0x7F54)]), + ("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 5), ("SRC2", 6)]), + // xor 1 (and 0x1F, or 0, xor 1); quad mode [3,2,1,0] + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 4), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 4), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + ]; + if wave64 { + p.extend_from_slice(&[ + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 127), ("SRC1", V + 3)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } else { + p.extend_from_slice(&[ + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } + p.push(ENDPGM); + p + } + + /// A waterfall loop: each pass takes the first lane's key (readfirstlane), the lanes with + /// that key do the work and leave; the readfirstlane is in a block lanes leave one by one. + fn waterfall(wave64: bool) -> Vec { + let w: [I; 4] = if wave64 { + [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + } else { + [ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + }; + vec![ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + w[0], + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 2)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 2), ("VSRC1", 2)]), + w[1], + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 3)]), + w[2], + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + w[3], + ENDPGM, + ] + } + + /// The lowering (on the CPU) and the HLSL path (on the GPU) give the same registers. + fn agrees_with_hlsl(name: &str, lines: &[I], wave64: bool, skip: &[usize]) { + use super::super::{dxc, runner, translate, Options}; + let lanes = if wave64 { 64 } else { 32 }; + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let gpu = runner::run(&dxil, &st, &[]).unwrap(); + let (cs, cv) = run(lines, wave64, &s, &v); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if wave64 { + sregs.extend([107, 127]); + } + // (a stale wave64 mask is reported by its first register; the pair's second is stale too) + let stale_at = |r: usize| stale.contains(&(r as u8)) || (wave64 && r > 0 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r) && !skip.contains(&r)) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + + #[test] + fn cross_lane_reads_on_the_cpu() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (s, v) = run(&lane_reads(wave64), wave64, &s, &v); + assert_eq!(s[2], 5, "readfirstlane: the first lane in EXEC"); + assert_eq!(s[3], lanes as u32 - 5, "s_bcnt1 of EXEC"); + assert_eq!(s[4], 27, "readlane 9 of 3 * lane"); + assert_eq!(s[7], 5, "s_ff1 of EXEC"); + for (l, r) in v.iter().enumerate() { + let (l32, active) = (l as u32, l > 4); + assert_eq!(r[3], if active { l32 - 5 } else { 0 }, "lane {l}: mbcnt"); + assert_eq!(r[5], if l == 2 { 5 } else { 0 }, "lane {l}: writelane, whatever EXEC holds"); + // row_shr:1, bound_ctrl: 0 at a row's first lane or from a lane outside EXEC + let want = if !active || l % 16 == 0 || l - 1 <= 4 { 0 } else { 3 * (l32 - 1) }; + assert_eq!(r[6], want, "lane {l}: DPP16 row_shr"); + let rev = (l32 & !7) | (7 - (l32 & 7)); + let want = if active { l32 + if rev > 4 { 3 * rev } else { 0 } } else { 0 }; + assert_eq!(r[8], want, "lane {l}: DPP8"); + let x = l32 ^ 1; + assert_eq!(r[10], if active && x > 4 { 3 * x } else { 0 }, "lane {l}: ds_swizzle xor 1"); + } + } + } + + #[test] + fn a_waterfall_loop_reads_the_first_lane_of_each_pass() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (_, v) = run(&waterfall(wave64), wave64, &s, &v); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], l as u32 & 3, "lane {l}"); + } + } + // a lane of any lane, where some lanes have left: refused + let mut lines = waterfall(false); + lines.insert(3, ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 129)])); + lines[8] = ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFF8)]); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes are elsewhere"), "{err}"); + } + + #[test] + fn cross_lane_reads_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + agrees_with_hlsl("lane reads, wave32", &lane_reads(false), false, &[]); + // s2 and the saved EXEC s4 after the loop: the last pass's on the console; each lane's own + // last pass's in the lowering (written where lanes leave one by one; not refused yet) + agrees_with_hlsl("waterfall, wave32", &waterfall(false), false, &[2, 4]); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + agrees_with_hlsl("lane reads, wave64", &lane_reads(true), true, &[]); + agrees_with_hlsl("waterfall, wave64", &waterfall(true), true, &[2, 4, 5]); + } + + /// Guarded straight-line run under narrowed EXEC (no skip branch): VALU ops, a guarded load, + /// `s_waitcnt`, and two guarded stores all coalesce into one per-lane branch with 0 selects. + pub(crate) fn coalesced_run(wave64: bool) -> Vec { + let (cmp, save, restore): (&'static [(&'static str, u64)], &str, &str) = if wave64 { + (&[("SRC0", 168), ("VSRC1", 0)], "S_AND_SAVEEXEC_B64", "S_OR_B64") + } else { + (&[("SRC0", 144), ("VSRC1", 0)], "S_AND_SAVEEXEC_B32", "S_OR_B32") + }; + vec![ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", cmp), + (save, "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 138), ("VSRC1", 0)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 131)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 0)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 8), ("SADDR", 125), ("OFFSET", 0)]), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 5), ("VSRC1", 2)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 4), ("SADDR", 125), ("OFFSET", 0x100)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 6), ("SADDR", 125), ("OFFSET", 0x200)]), + (restore, "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + ENDPGM, + ] + } + + /// Guarded runs separated by a scalar write, a `v_cmp`, and a cross-lane `v_readlane`, plus + /// `v_cndmask` and a twice-written VGPR inside coalesced runs. + pub(crate) const COALESCED_BREAKS: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 133)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 135), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 1)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 136), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 4)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 3), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 7)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + + /// Two coalesced runs separated by a scalar write inside an already-`partial` block (arm of a + /// skipped `if`), reading SGPR `s2` and `vcc` written earlier in that same console block. + pub(crate) const COALESCED_IN_PARTIAL: &[I] = &[ + ("S_AND_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 126), ("SSRC1", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 152), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 10)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 139)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 140), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 2), ("VSRC1", 4)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ENDPGM, + ]; + + /// A 4-iteration uniform loop whose body narrows EXEC (no skip branch) around a coalesced run. + pub(crate) const COALESCED_IN_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 2), ("SSRC1", 132)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + + /// Guarded run of f32 instructions lowered through `Ir::foreign` (`Lw::inst_guarded`). + pub(crate) const COALESCED_F32_RUN: &[I] = &[ + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 242), ("VSRC1", 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 244), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 240), ("SRC2", 242)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 242), ("VSRC1", 4)]), + ENDPGM, + ]; + + #[test] + fn guarded_run_coalesces_into_one_branch_with_no_selects() { + for (wave64, lanes, cut) in [(false, 32usize, 16usize), (true, 64usize, 40usize)] { + let lines = coalesced_run(wave64); + let insts = decode(&lines); + let sum = lane_masks::analyze(&insts, wave64).unwrap(); + assert_eq!(sum.guarded.len(), 7, "wave64={wave64}"); + let (ir, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + // wave64 has 1 prologue select to pick EXEC's lo/hi dword; 0 per-write selects in either mode + assert_eq!(ir.selects(), usize::from(wave64), "wave64={wave64}: coalesced run removes all per-write selects"); + assert_eq!(ir.br_ifs(), 3, "wave64={wave64}: entry + 1 coalesced run + exit"); + + let (s, v) = state(lanes); + let (s, v, mem) = run_mem(&lines, wave64, &s, &v, &memory_image()); + assert_eq!(s[126], u32::MAX); + if wave64 { + assert_eq!(s[127], u32::MAX); + } + for l in 0..lanes { + let l32 = l as u32; + if l < cut { + let (v2, v5) = (l32 + 10, 1000 + l32); + let (v3, v6) = (v2 * 3, v5 + v2); + let v4 = v3 ^ l32; + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (v2, v3, v4, v5, v6, v4 + v6), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (v4, v6), "wave64={wave64} lane {l} mem"); + } else { + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (0, 0, 0, 0, 0, 0), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (1064 + l32, 1128 + l32), "wave64={wave64} lane {l} mem"); + } + } + } + + // a single guarded VALU or load keeps its select rather than adding a branch + for single_op in [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)][..]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 125), ("OFFSET", 0)][..]), + ] { + let single = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + single_op, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]); + let (ir, _) = lower_kernel(&single, false, Interp::default()).unwrap(); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 2), "{}", single_op.0); + } + } + + #[test] + fn guard_coalescing_breaks_at_scalar_compare_and_cross_lane_ops() { + let (ir, stale) = lower_kernel(&decode(COALESCED_BREAKS), false, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 6)); // only v_cndmask's select; 4 runs + entry/exit + let (s, v) = state(32); + let (s, v) = run(COALESCED_BREAKS, false, &s, &v); + assert_eq!((s[2], s[3], s[106], s[126]), (8, 10, 0xFF, u32::MAX)); + for l in 0..32usize { + let l32 = l as u32; + let want = if l < 16 { + let (v1, v3) = (l32 + 7, l32 + 15); + let v4 = v3 ^ (v1 + l32); + (v1, v4, 10 + (if l < 8 { v4 } else { v3 }) + 3) + } else { + (0, 0, 0) + }; + assert_eq!((v[l][1], v[l][4], v[l][7]), want, "lane {l}"); + } + + // two coalesced runs inside a partial block (with a scalar write in between) stay non-stale + let (s, v) = state(32); + let (_, v) = run(COALESCED_IN_PARTIAL, false, &s, &v); + for l in 0..32usize { + let l32 = l as u32; + let v4 = if l < 12 { l32 + 24 } else { 0 }; + let v5 = if l < 24 { 12 + v4 } else { 0 }; + assert_eq!((v[l][4], v[l][5], v[l][6]), (v4, v5, v5 + 1), "partial lane {l}"); + } + + // coalesced run inside a loop: 0 selects, SSA phis carry loop values cleanly + let (ir, _) = lower_kernel(&decode(COALESCED_IN_LOOP), false, Interp::default()).unwrap(); + assert_eq!(ir.selects(), 0); + let (s, v) = state(32); + let (s, v) = run(COALESCED_IN_LOOP, false, &s, &v); + assert_eq!((s[2], s[126]), (4, u32::MAX)); + for l in 0..32 { + assert_eq!((v[l][1], v[l][2]), if l < 16 { (4, 10) } else { (0, 0) }, "loop lane {l}"); + } + + // guarded VALU carry-out (VOP3_SDST_ENC) and cross-lane ds_swizzle split runs + let cs = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 1)]), + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 106), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 130), ("VSRC1", 4)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 5), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 129), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 7)]), + ENDPGM, + ]); + let sum = lane_masks::analyze(&cs, false).unwrap(); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + assert_eq!(coalesced_runs(&cs, &sum.blocks[0].insts, &guarded), vec![2..4, 5..7, 8..10]); + } + + #[test] + fn coalesced_guarded_runs_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + agrees_with_hlsl("coalesced breaks, wave32", COALESCED_BREAKS, false, &[]); + agrees_with_hlsl("coalesced in partial, wave32", COALESCED_IN_PARTIAL, false, &[]); + agrees_with_hlsl("coalesced in loop, wave32", COALESCED_IN_LOOP, false, &[]); + let check_mem = |wave64: bool| { + let (lines, lanes) = (coalesced_run(wave64), if wave64 { 64 } else { 32 }); + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(&lines, wave64, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "wave64={wave64}: memory"); + for l in 0..lanes { + for r in 0..8 { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "wave64={wave64}: lane {l} v{r}"); + } + } + assert_eq!(cs[126], gpu.sgpr[126]); + if wave64 { + assert_eq!(cs[127], gpu.sgpr[127]); + } + }; + check_mem(false); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + check_mem(true); + } +} diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs new file mode 100644 index 0000000000..7d3ceceb77 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -0,0 +1,472 @@ +//! Cross-lane operations of the lowering: `v_readlane`, `v_readfirstlane`, `v_writelane`, +//! DPP16 / DPP8 sources, `v_permlane(x)16`, `ds_swizzle_b32`, `v_mbcnt`, and the counts of a +//! mask as a number (`s_bcnt1`, `s_ff1`). +//! +//! A lane reads another through `Ir::read_lane` (`WaveReadLaneAt`), which needs that lane to +//! be running the same instruction. Here a lane is where the console has it except across a +//! lane branch: the lanes that went the other way are elsewhere. So: +//! - a read of a lane in EXEC is always fine: that lane is here (readfirstlane, and DPP, +//! permlane and swizzle without fetch-inactive, whose source outside EXEC reads 0 or keeps +//! the destination); +//! - a read of any lane (readlane, writelane, fetch-inactive) needs every lane here, so it is +//! refused in a block not every lane reaches (`partial`), and the program stays on HLSL; +//! - a mask as a number is the ballot of its bits, which counts the lanes that are here: exact +//! for EXEC (a lane elsewhere is outside it), and for any mask where every lane is here. +//! +//! DPP, permlane(x)16, ds_swizzle and `v_mbcnt_hi` only need this lane's 32-lane half, so they +//! use `Ir::read_lane_half` / `Ir::ballot_half`; readfirstlane, readlane, writelane, `v_mbcnt_lo` +//! and a mask as a number need the whole wave (`read_lane`, `ballot`). With one hardware wave per +//! console wave they are the same; a wave64 split into two 32-lane hardware waves exchanges data +//! between the halves only for the whole-wave forms. +//! +//! Lanes outside EXEC when a kernel-mode program starts leave at once (`lower_kernel`), so a +//! read of one of those is not the console's; compute waves start with every lane in EXEC. + +use super::{Bin, Cmp, Ir, Lower, Var, EXEC, R}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +impl Lower<'_, I> { + fn all_lanes(&self, b: usize, what: &str) -> R<()> { + if self.partial[b] { + Err(format!("{what} where some lanes are elsewhere")) + } else { + Ok(()) + } + } + + /// Whether operand `code` names a register holding a mask here, and the pair's register. + fn mask_reg(&mut self, b: usize, code: u64) -> Option<(u8, bool)> { + if code > 127 || code == 124 || code == 125 { + return None; + } + let r = code as u8; + if self.holds_mask(b, r) { + return Some((r, false)); + } + // the upper dword of a wave64 mask pair + (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then(|| (r - 1, true)) + } + + /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits; with `half`, + /// only this lane's half of it is right (`Ir::ballot_half`). + fn mask_words(&mut self, b: usize, r: u8, half: bool) -> R<[I::V; 2]> { + if r != EXEC || (!half && self.ir.whole_needs_exchange()) { + self.all_lanes(b, "a mask read as a number")?; + } + let bit = self.read_bit(b, r)?; + let [lo, hi] = if half { self.ir.ballot_half(bit) } else { self.ir.ballot(bit) }; + Ok(if self.wave64 { [lo, hi] } else { [lo, self.ir.int(0)] }) + } + + /// A 32-bit scalar operand as a number, also where it holds (half of) a mask. + fn word(&mut self, b: usize, d: &Decoded, code: u64) -> R { + self.word_in(b, d, code, false) + } + + /// `word`; with `half`, a mask's word is only right for the lanes of the half it covers. + fn word_in(&mut self, b: usize, d: &Decoded, code: u64, half: bool) -> R { + match self.mask_reg(b, code) { + Some((r, hi)) => Ok(self.mask_words(b, r, half)?[hi as usize]), + None => self.src(b, d, code), + } + } + + /// A 64-bit scalar operand as numbers, also where it holds a mask. + fn words(&mut self, b: usize, d: &Decoded, code: u64) -> R<[I::V; 2]> { + match self.mask_reg(b, code) { + Some((r, false)) => self.mask_words(b, r, false), + Some((_, true)) => Err("a 64-bit operand across two masks".into()), + None => { + let (lo, hi) = self.src64(b, d, code)?; + Ok([lo, hi]) + } + } + } + + /// The lowest set bit of x, 32 if none. + fn ctz(&mut self, x: I::V) -> I::V { + let (z, one) = (self.ir.int(0), self.ir.int(1)); + let neg = self.ir.bin(Bin::Sub, z, x); + let low = self.ir.bin(Bin::And, x, neg); + let below = self.ir.bin(Bin::Sub, low, one); + self.ir.count_bits(below) + } + + /// The lowest set bit of the 64-bit (lo, hi), `none` if none. + fn first_set(&mut self, [lo, hi]: [I::V; 2], none: u32) -> I::V { + let z = self.ir.int(0); + let (cl, ch) = (self.ctz(lo), self.ctz(hi)); + let c32 = self.ir.int(32); + let ch = self.ir.bin(Bin::Add, ch, c32); + let none = self.ir.int(none); + let hz = self.ir.icmp(Cmp::Eq, hi, z); + let h = self.ir.select(hz, none, ch); + let lz = self.ir.icmp(Cmp::Eq, lo, z); + self.ir.select(lz, h, cl) + } + + /// Bit `l` of the 64-bit (lo, hi). + fn bit_at(&mut self, [lo, hi]: [I::V; 2], l: I::V) -> I::V { + let (c31, c32, one, z) = (self.ir.int(31), self.ir.int(32), self.ir.int(1), self.ir.int(0)); + let low = self.ir.icmp(Cmp::Ult, l, c32); + let w = self.ir.select(low, lo, hi); + let sh = self.ir.bin(Bin::And, l, c31); + let w = self.ir.bin(Bin::LShr, w, sh); + let w = self.ir.bin(Bin::And, w, one); + self.ir.icmp(Cmp::Ne, w, z) + } + + /// The lanes in EXEC, as numbers; with `half`, only this lane's half is right. + fn exec_words(&mut self, b: usize, half: bool) -> R<[I::V; 2]> { + // split: the other half's word comes through an exchange, which both halves must reach + if !half && self.ir.whole_needs_exchange() { + self.all_lanes(b, "EXEC as a number in the split form")?; + } + let e = self.read_bit(b, EXEC)?; + let [lo, hi] = if half { self.ir.ballot_half(e) } else { self.ir.ballot(e) }; + Ok([lo, if self.wave64 { hi } else { self.ir.int(0) }]) + } + + /// `v` of lane `l` (in this lane's 32-lane half) if that lane is in EXEC (or + /// `inactive_too`); whether it was. + fn read_from(&mut self, b: usize, v: I::V, l: I::V, inactive_too: bool, what: &str) -> R<(I::V, I::V)> { + let ok = if inactive_too { + self.all_lanes(b, what)?; + self.ir.boolean(true) + } else { + let e = self.exec_words(b, true)?; + self.bit_at(e, l) + }; + // a lane outside EXEC may be elsewhere: read this lane's own value instead, unused + let me = self.lane(); + let at = self.ir.select(ok, l, me); + Ok((self.ir.read_lane_half(v, at), ok)) + } + + fn c(&mut self, v: u32) -> I::V { + self.ir.int(v) + } + + /// `(lane & !keep) | x` + fn lane_with(&mut self, keep_not: u32, x: I::V) -> I::V { + let me = self.lane(); + let k = self.c(!keep_not); + let hi = self.ir.bin(Bin::And, me, k); + self.ir.bin(Bin::Or, hi, x) + } + + /// `(k >> (bits * (lane & group))) & field`: a lane's entry of a packed selector. + fn packed(&mut self, k: I::V, bits: u32, group: u32, field: u32) -> I::V { + let me = self.lane(); + let (g, w, f) = (self.c(group), self.c(bits), self.c(field)); + let i = self.ir.bin(Bin::And, me, g); + let sh = self.ir.bin(Bin::Mul, i, w); + let x = self.ir.bin(Bin::LShr, k, sh); + self.ir.bin(Bin::And, x, f) + } + + /// The source lane of DPP16 control `ctrl`, and whether it is inside the row. + fn dpp16_lane(&mut self, ctrl: u64) -> R<(I::V, I::V)> { + let me = self.lane(); + let n = (ctrl & 15) as u32; + let t = self.ir.boolean(true); + let row = |l: &mut Self| { + let c = l.c(15); + l.ir.bin(Bin::And, me, c) + }; + Ok(match ctrl { + 0x000..=0x0FF => { + let k = self.c(ctrl as u32); + let x = self.packed(k, 2, 3, 3); + (self.lane_with(3, x), t) + } + 0x101..=0x10F => { + let (r, cn, c16) = (row(self), self.c(n), self.c(16)); + let to = self.ir.bin(Bin::Add, r, cn); + let ok = self.ir.icmp(Cmp::Ult, to, c16); + (self.ir.bin(Bin::Add, me, cn), ok) + } + 0x111..=0x11F => { + let (r, cn) = (row(self), self.c(n)); + let ok = self.ir.icmp(Cmp::Uge, r, cn); + (self.ir.bin(Bin::Sub, me, cn), ok) + } + 0x121..=0x12F => { + let (r, cn, c15) = (row(self), self.c(n), self.c(15)); + let x = self.ir.bin(Bin::Sub, r, cn); + let x = self.ir.bin(Bin::And, x, c15); + (self.lane_with(15, x), t) + } + 0x140 => { + let (r, c15) = (row(self), self.c(15)); + let x = self.ir.bin(Bin::Sub, c15, r); + (self.lane_with(15, x), t) + } + 0x141 => { + let (c7, c8) = (self.c(7), self.c(8)); + let x = self.ir.bin(Bin::And, me, c7); + let x = self.ir.bin(Bin::Sub, c7, x); + let h = self.ir.bin(Bin::And, me, c8); + let x = self.ir.bin(Bin::Or, x, h); + (self.lane_with(15, x), t) + } + 0x150..=0x15F => { + let x = self.c(n); + (self.lane_with(15, x), t) + } + 0x160..=0x16F => { + let cn = self.c(n); + (self.ir.bin(Bin::Xor, me, cn), t) + } + _ => return Err(format!("DPP_CTRL {ctrl:#x}")), + }) + } + + /// A DPP instruction's first source, read from its source lane, and its write enable + /// (`dpp_src`, `dpp_en`, taken by `src` and `write_v`). + pub(super) fn dpp(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if name.starts_with("V_CMP") { + return Err(format!("{name}: DPP compare")); + } + let e = super::super::emit::ext_encoding(d).ok_or("DPP encoding")?; + let f = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if ["SRC0_ABS", "SRC0_NEG", "SRC1_ABS", "SRC1_NEG"].iter().any(|m| f(m) != 0) { + return Err(format!("{name}: DPP modifiers")); + } + let v = self.read(b, Var::V(f("VSRC0") as u16)); + let (val, en) = if d.variant == Variant::Dpp16 { + let (l, inside) = self.dpp16_lane(f("DPP_CTRL"))?; + // outside the row: this lane's own, unused (the lane number may be out of range) + let me = self.lane(); + let l = self.ir.select(inside, l, me); + let (val, ok) = self.read_from(b, v, l, f("FI") == 1, "DPP fetch-inactive")?; + let ok = self.ir.bin(Bin::And, ok, inside); + let z = self.c(0); + let mut en = None; + let val = if f("BOUND_CTRL") == 1 { + self.ir.select(ok, val, z) + } else { + en = Some(ok); + val + }; + let (rm, bm) = (f("ROW_MASK") as u32, f("BANK_MASK") as u32); + if rm != 0xF || bm != 0xF { + let me = self.lane(); + let (k, s4, s2, c3) = (self.c(rm), self.c(4), self.c(2), self.c(3)); + let r = self.ir.bin(Bin::LShr, me, s4); + let r = self.ir.bin(Bin::LShr, k, r); + let k = self.c(bm); + let q = self.ir.bin(Bin::LShr, me, s2); + let q = self.ir.bin(Bin::And, q, c3); + let q = self.ir.bin(Bin::LShr, k, q); + let both = self.ir.bin(Bin::And, r, q); + let one = self.c(1); + let both = self.ir.bin(Bin::And, both, one); + let on = self.ir.icmp(Cmp::Ne, both, z); + en = Some(match en { + Some(ok) => self.ir.bin(Bin::And, ok, on), + None => on, + }); + } + (val, en) + } else { + let sel: u64 = (0..8).map(|i| f(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); + let fi = rdna2::field_value(d.enc, &d.words, "SRC0") == Some(0xEA); + let k = self.c(sel as u32); + let x = self.packed(k, 3, 7, 7); + let l = self.lane_with(7, x); + let (val, ok) = self.read_from(b, v, l, fi, "DPP8 fetch-inactive")?; + let z = self.c(0); + (self.ir.select(ok, val, z), None) + }; + self.dpp_src = Some(val); + self.dpp_en = en; + Ok(()) + } + + /// The cross-lane VALU instructions; `false` for any other. + pub(super) fn wave_valu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, s1, vdst) = (fv("SRC0"), fv("SRC1"), fv("VDST")); + let wmask = if self.wave64 { 63 } else { 31 }; + match name { + "V_READFIRSTLANE_B32" => { + let v = self.src(b, d, s0)?; + let r = if s0 >= 256 { + let e = self.exec_words(b, false)?; + let l = self.first_set(e, 0); + self.ir.read_lane(v, l) + } else { + v + }; + self.write_num(b, vdst as u8, r); + } + "V_READLANE_B32" => { + self.all_lanes(b, "v_readlane")?; + let (v, sel) = (self.src(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let r = self.ir.read_lane(v, l); + self.write_num(b, vdst as u8, r); + } + "V_WRITELANE_B32" => { + // whatever EXEC holds + self.all_lanes(b, "v_writelane")?; + let (a, sel) = (self.word(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let me = self.lane(); + let hit = self.ir.icmp(Cmp::Eq, me, l); + let old = self.read(b, Var::V(vdst as u16)); + let v = self.ir.select(hit, a, old); + self.ssa.write(b, Var::V(vdst as u16), v); + } + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => { + // mbcnt_hi counts the upper lanes' own half only (0 below lane 32); mbcnt_lo + // gives the upper lanes all of the lower half + let hi_half = name == "V_MBCNT_HI_U32_B32"; + let (m, add) = (self.word_in(b, d, s0, hi_half)?, self.src(b, d, s1)?); + // the lanes below this one, in this half of the mask + let me = self.lane(); + let (c31, c32, one, z, all) = (self.c(31), self.c(32), self.c(1), self.c(0), self.c(u32::MAX)); + let sh = self.ir.bin(Bin::And, me, c31); + let below = self.ir.bin(Bin::Shl, one, sh); + let below = self.ir.bin(Bin::Sub, below, one); + let upper = self.ir.icmp(Cmp::Uge, me, c32); + let lt = if name == "V_MBCNT_LO_U32_B32" { self.ir.select(upper, all, below) } else { self.ir.select(upper, below, z) }; + let x = self.ir.bin(Bin::And, m, lt); + let n = self.ir.count_bits(x); + let r = self.ir.bin(Bin::Add, n, add); + self.write_v(b, d, vdst as u16, r)?; + } + "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" => { + let op_sel = fv("OP_SEL"); + if ["ABS", "NEG", "CLAMP", "OMOD"].iter().any(|f| fv(f) != 0) || op_sel & !3 != 0 { + return Err(format!("{name}: VOP3 modifiers")); + } + let (fi, bound) = (op_sel & 1 == 1, op_sel & 2 == 2); + let v = self.src(b, d, s0)?; + let (lo, hi) = (self.word(b, d, s1)?, self.word(b, d, fv("SRC2"))?); + let me = self.lane(); + let (c8, c15, c16) = (self.c(8), self.c(15), self.c(16)); + let r = self.ir.bin(Bin::And, me, c15); + let first8 = self.ir.icmp(Cmp::Ult, r, c8); + let k = self.ir.select(first8, lo, hi); + let n = self.packed(k, 4, 7, 15); + // the same row (permlane16) or the other row of the 32-lane half + let row = self.ir.bin(Bin::And, me, c16); + let row = if name == "V_PERMLANEX16_B32" { self.ir.bin(Bin::Xor, row, c16) } else { row }; + let x = self.ir.bin(Bin::Or, row, n); + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, fi, "v_permlane fetch-inactive")?; + let other = if bound { self.c(0) } else { self.read(b, Var::V(vdst as u16)) }; + let r = self.ir.select(ok, val, other); + self.write_v(b, d, vdst as u16, r)?; + } + _ => return Ok(false), + } + Ok(true) + } + + /// `ds_swizzle_b32`: a lane reads another of its 32-lane half (`emit::swizzle_lane`). + pub(super) fn swizzle(&mut self, b: usize, d: &Decoded) -> R<()> { + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let off = fv("OFFSET0") | fv("OFFSET1") << 8; + let v = self.read(b, Var::V(fv("ADDR") as u16)); + let me = self.lane(); + let c31 = self.c(31); + let i = self.ir.bin(Bin::And, me, c31); + let x = if off >= 0xE000 { + return Err("ds_swizzle FFT mode".into()); + } else if off >= 0xC000 { + // rotate by offset[9:5] lanes, left or right (offset[10]); masked bits stay + let mask = (off & 0x1F) as u32; + let r = ((off >> 5) & 0x1F) as u32; + let r = if off & 0x400 != 0 { r.wrapping_neg() } else { r }; + let (cm, cn, cr) = (self.c(mask), self.c(!mask & 31), self.c(r)); + let kept = self.ir.bin(Bin::And, i, cm); + let moved = self.ir.bin(Bin::Add, i, cr); + let moved = self.ir.bin(Bin::And, moved, cn); + self.ir.bin(Bin::Or, kept, moved) + } else if off & 0x8000 != 0 { + let k = self.c(off as u32); + let q = self.packed(k, 2, 3, 3); + let c28 = self.c(28); + let base = self.ir.bin(Bin::And, i, c28); + self.ir.bin(Bin::Or, base, q) + } else { + let (and, or, xor) = (self.c((off & 0x1F) as u32), self.c(((off >> 5) & 0x1F) as u32), self.c(((off >> 10) & 0x1F) as u32)); + let x = self.ir.bin(Bin::And, i, and); + let x = self.ir.bin(Bin::Or, x, or); + self.ir.bin(Bin::Xor, x, xor) + }; + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, false, "")?; + let z = self.c(0); + let r = self.ir.select(ok, val, z); + self.write_v(b, d, fv("VDST") as u16, r) + } + + /// Scalar counts of a mask; `false` for any other instruction. + pub(super) fn wave_salu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, sd) = (fv("SSRC0"), fv("SDST") as u8); + // `s_wqm` of a mask (`s_wqm_b64 exec, exec`): a lane's bit is set when any lane of its + // quad has its bit; the quad is in the lane's own half of the mask + // (the launch EXEC's, and any in a VS / PS, are `salu`'s) + let wqm = if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" }; + if name == wqm && !self.graphics && !self.sum.wqm_all.contains(&d.pc) { + let Some((r, false)) = self.mask_reg(b, s0) else { return Err(format!("unsupported {name} of a number")) }; + let [lo, hi] = self.mask_words(b, r, true)?; + let lane = self.lane(); + let (c32, c28, f) = (self.c(32), self.c(28), self.c(0xF)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let w = self.ir.select(upper, hi, lo); + let q = self.ir.bin(Bin::And, lane, c28); + let w = self.ir.bin(Bin::LShr, w, q); + let w = self.ir.bin(Bin::And, w, f); + let z = self.c(0); + let bit = self.ir.icmp(Cmp::Ne, w, z); + self.write_bit(b, sd, bit); + self.write_scc(b, bit); + return Ok(true); + } + let (ones, count) = match name { + "S_BCNT1_I32_B32" | "S_BCNT1_I32_B64" => (true, true), + "S_BCNT0_I32_B32" | "S_BCNT0_I32_B64" => (false, true), + "S_FF1_I32_B32" | "S_FF1_I32_B64" => (true, false), + _ => return Ok(false), + }; + // only where the source is a mask: numbers take the usual path + if self.mask_reg(b, s0).is_none() { + return Ok(false); + } + let w = if name.ends_with("_B64") { + self.words(b, d, s0)? + } else { + [self.word(b, d, s0)?, self.c(0)] + }; + let w = if ones { + w + } else { + let all = self.c(u32::MAX); + let hi = if name.ends_with("_B64") { self.ir.bin(Bin::Xor, w[1], all) } else { w[1] }; + [self.ir.bin(Bin::Xor, w[0], all), hi] + }; + let r = if count { + let (lo, hi) = (self.ir.count_bits(w[0]), self.ir.count_bits(w[1])); + let r = self.ir.bin(Bin::Add, lo, hi); + let z = self.c(0); + let c = self.ir.icmp(Cmp::Ne, r, z); + self.ssa.write(b, Var::Scc, c); + r + } else { + self.first_set(w, u32::MAX) + }; + self.write_num(b, sd, r); + Ok(true) + } +} diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs new file mode 100644 index 0000000000..7107e53854 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -0,0 +1,771 @@ +//! The direct lowering (`lower`) written into a DXIL module through `gpu::dxil`'s builder: +//! the per-lane form of a program as a signed container, with no HLSL and no DXC. +//! +//! `Ir` maps one to one onto the builder: blocks, phis (`phi_at` / `add_incoming`), integer +//! ops, compares, `select`, the thread / group / lane ids, `waveActiveBallot`, and raw buffer +//! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). The builder state is +//! #1426's translator state (`gpu::dxil::lower::Lw`, built by `Lw::new` and finished by +//! `Lw::finish`), so its per-entry setup (`setup_lanes_compute`) and its instruction +//! lowering are reachable from here. A phi the SSA +//! construction finds trivial has its uses replaced (`Module::replace_uses`); the phi itself +//! stays in its block, unused. The replacements are collected and made in one pass in +//! `DxilIr::finish`: one pass over the module per trivial phi made the lowering quadratic in +//! the program's size, and nothing reads an instruction's operands back before then (the +//! SSA construction resolves a replaced phi itself). + +use super::lower::{self, Bin, Cmp, Ir}; +use super::ssa::{Sink, Var}; +use crate::gpu::dxil::kernel::{Entry, KernelOptions}; +use crate::gpu::dxil::lower::Lw; +use crate::gpu::dxil::module::{BinOp, Block, CastOp, Pred, Value}; +use crate::gpu::dxil::shader::RawUav; +use crate::gpu::rdna2::Decoded; +use std::collections::{BTreeSet, HashMap}; + +struct DxilIr { + lw: Lw, + io: RawUav, + res: Option, + mem: RawUav, + /// each `Ir` block: where it starts (its phis) and where it ends now (its branch; later than + /// the start when #1426's lowering of an instruction in it made blocks of its own) + blocks: Vec, + tails: Vec, + /// the `Ir` block being written + cur: usize, + /// `compute_ids` set up the lanes (`Lw::lane` is the console lane) + lanes_set: bool, + /// a split compute program's thread ids, set up with its lanes in the constructor: the + /// lowering takes `lane()` before `compute_ids`, and in the split form the console lane + /// is not the hardware lane (the upper half's are 32-63) + ids: Option<(Value, [Value; 3])>, + /// trivial phis → what replaces their uses, made in the module by `finish` + replaced: HashMap, +} + +impl DxilIr { + /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory + /// window; a compute program's is coherent, as the HLSL path declares it. + fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// `new` in the split form (two hardware wave32s per console wave64): #1426's `Lw` numbers + /// the threads as the hardware waves arrive and lays out the halves' exchange storage; its + /// `ballot` / `read_lane_uniform` meet the other half (a group barrier for one console + /// wave per group, the spin meet for more). + fn split(insts: &[Decoded], entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// The builder state with the runtime's options `o` (memory windows, sampler registers, the + /// split form). + fn with(insts: &[Decoded], o: KernelOptions, entry: &Entry) -> DxilIr { + // block leaders for the constant-sampler scan: the first instruction, branch targets + // and the instruction after a branch + let mut leaders: BTreeSet = insts.first().map(|d| d.pc).into_iter().collect(); + for (i, d) in insts.iter().enumerate() { + if let Some(t) = crate::gpu::rdna2::branch_target(d) { + leaders.insert(t); + leaders.extend(insts.get(i + 1).map(|n| n.pc)); + } + } + let mut lw = Lw::new(insts, &leaders, o, entry); + // the rounding modes the program sets, as `kernel::translate_on_this_thread` finds them: + // #1426's `s_round_mode` / `s_setreg` refuse a mode they cannot honour from these + let branchy = insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); + (lw.dyn_rm, lw.has_f64_round_op) = crate::gpu::dxil::lower::round_modes(insts, !branchy); + // a kernel's lanes in the split form: the console lane each hardware lane stands for, + // set up in the entry block (a compute program's come with `compute_ids`) + let mut ids = None; + let lanes_set = match entry { + // (a kernel always: `Lw`'s lane bit, `lane31`, is what #1426's lowering of a carry-in or + // a `v_cndmask` reads, and stays 0 without it) + Entry::Kernel => { + lw.setup_lanes(); + true + } + Entry::Compute(cs) if lw.split => { + let lds = lw.lds.is_some(); + ids = Some(lw.setup_lanes_compute(cs.threads, lds)); + true + } + _ => false, + }; + let io = lw.init.io.expect("the I/O buffer"); + let (res, mem) = (lw.res, lw.mems[0]); + DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set, ids, replaced: HashMap::new() } + } + + fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { + match var { + Var::M(_) | Var::Scc => self.lw.s.m.i1(), + Var::S(_) | Var::V(_) => self.lw.s.m.i32(), + } + } + + /// The container: `Lw`'s entry block jumps to the first `Ir` block (as `kernel.rs` ends it), + /// the lowering's blocks are sealed for `Lw`'s variables (every edge into them is known once + /// the lowering is done), then `Lw::finish`. + fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + // the trivial phis' uses first, as `replace` would have left them + self.lw.s.m.replace_uses(&self.replaced); + let first = *self.blocks.first().ok_or("no blocks")?; + self.lw.s.m.set_block(Block(0)); + self.lw.br(first); + for i in 0..self.blocks.len() { + let b = self.blocks[i]; + if !self.lw.ssa.is_sealed(b) { + self.lw.seal(b); + } + } + self.lw.finish(numthreads, hw) + } + + fn bytes(&mut self, dword: Value) -> Value { + let four = self.lw.s.m.i32c(4); + self.lw.s.m.bin(BinOp::Mul, dword, four) + } +} + +impl Sink for DxilIr { + type V = Value; + fn phi(&mut self, block: usize, var: Var) -> Value { + let t = self.ty(var); + self.lw.s.m.phi_at(self.blocks[block], t) + } + fn incoming(&mut self, phi: Value, value: Value, pred: usize) { + self.lw.s.m.add_incoming(phi, value, self.tails[pred]); + } + fn replace(&mut self, old: Value, new: Value) { + // every use of the trivial phi becomes `new` (in `finish`); the phi stays in its + // block, unused + self.replaced.insert(old, new); + } + fn undef(&mut self, var: Var) -> Value { + let t = self.ty(var); + self.lw.s.m.undef(t) + } +} + +impl Ir for DxilIr { + fn new_block(&mut self) -> usize { + // not `Block(0)`: `Lw` keeps writing there (static samplers, scratch) until `finish` + let b = self.lw.s.m.new_block(); + self.blocks.push(b); + self.tails.push(b); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.cur = block; + self.lw.s.m.set_block(self.tails[block]); + } + fn int(&mut self, v: u32) -> Value { + self.lw.s.m.i32c(v) + } + fn boolean(&mut self, v: bool) -> Value { + self.lw.s.m.i1c(v) + } + fn bin(&mut self, op: Bin, a: Value, b: Value) -> Value { + let op = match op { + Bin::Add => BinOp::Add, + Bin::Sub => BinOp::Sub, + Bin::Mul => BinOp::Mul, + Bin::And => BinOp::And, + Bin::Or => BinOp::Or, + Bin::Xor => BinOp::Xor, + Bin::Shl => BinOp::Shl, + Bin::LShr => BinOp::LShr, + Bin::AShr => BinOp::AShr, + }; + self.lw.s.m.bin(op, a, b) + } + fn icmp(&mut self, c: Cmp, a: Value, b: Value) -> Value { + let p = match c { + Cmp::Eq => Pred::Eq, + Cmp::Ne => Pred::Ne, + Cmp::Ult => Pred::ULt, + Cmp::Ule => Pred::ULe, + Cmp::Ugt => Pred::UGt, + Cmp::Uge => Pred::UGe, + Cmp::Slt => Pred::SLt, + Cmp::Sle => Pred::SLe, + Cmp::Sgt => Pred::SGt, + Cmp::Sge => Pred::SGe, + }; + self.lw.s.m.cmp(p, a, b) + } + fn select(&mut self, c: Value, a: Value, b: Value) -> Value { + self.lw.s.m.select(c, a, b) + } + fn zext(&mut self, b: Value) -> Value { + let t = self.lw.s.m.i32(); + self.lw.s.m.cast(CastOp::ZExt, b, t) + } + fn lane(&mut self) -> Value { + if self.lanes_set { + self.lw.lane + } else { + self.lw.s.wave_lane_index() + } + } + fn group_id(&mut self, k: u32) -> Value { + self.lw.s.group_id(k) + } + fn compute_ids(&mut self, threads: [u32; 3]) -> (Value, [Value; 3]) { + // #1426's compute entry: 2-D / 3-D groups numbered as their waves arrive, the counter + // in the program's top LDS word when it has LDS + if let Some(ids) = self.ids { + return ids; + } + let lds = self.lw.lds.is_some(); + let ids = self.lw.setup_lanes_compute(threads, lds); + self.lanes_set = true; + ids + } + fn whole_needs_exchange(&self) -> bool { + self.lw.split + } + fn ballot(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + // this half's word from the hardware, the other's through the exchange + let (lo, hi) = self.lw.ballot(c); + return [lo, hi]; + } + let w = self.lw.s.wave_ballot(c); + [w[0], w[1]] + } + // one hardware wave per console wave (native wave64, or wave32): the half-local forms are + fn mem_windows(&self) -> u32 { + self.lw.mems.len() as u32 + } + // the same operations; in the split form only the reader's half is right (`Ir::ballot_half`) + fn ballot_half(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + let w = self.lw.s.wave_ballot(c); + return [w[0], w[0]]; + } + self.ballot(c) + } + /// #1426's semantics of `d` (`Lw::inst_guarded`) in the current block: the inputs are written + /// into `Lw`'s SSA there first, so it reads them and nothing from other blocks (which its SSA + /// doesn't know). A register it touches that is neither an input nor an output refuses the + /// instruction: `Lw` would read that register's value at the program's start. Blocks it makes + /// (a guarded access, the memory window switch) end the `Ir` block in the last of them. + fn foreign(&mut self, d: &Decoded, guard: Value, inputs: &[(Var, Value)], outputs: &[Var]) -> Result, String> { + use crate::gpu::dxil::lower::{VAR_BUDGET, VAR_SCC, VAR_VGPR}; + let var = |v: Var| match v { + Var::S(r) => r as u32, + Var::V(n) => VAR_VGPR + n as u32, + Var::Scc => VAR_SCC, + Var::M(_) => unreachable!("a lane-bit view is not a register"), + }; + for &(v, x) in inputs { + self.lw.wr(var(v), x); + } + // the registers `Lw` touches for `d` alone + let before = std::mem::take(&mut self.lw.init.touched); + self.lw.pc = d.pc; + let r = self.lw.inst_guarded(d, guard, None); + let used = std::mem::replace(&mut self.lw.init.touched, before); + self.lw.init.touched.extend(&used); + r?; + let known: BTreeSet = inputs.iter().map(|&(v, _)| var(v)).chain(outputs.iter().map(|&v| var(v))).collect(); + if let Some(r) = used.iter().find(|&&r| r < VAR_BUDGET && !known.contains(&r)) { + return Err(format!("it reads register {r} the per-lane form did not pass")); + } + let tail = self.lw.cur(); + self.tails[self.cur] = tail; + Ok(outputs.iter().map(|&v| self.lw.rd(var(v))).collect()) + } + fn read_lane(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + // the lowering's lane reads take the same lane in every lane (readlane, + // readfirstlane, writelane's source) + return self.lw.read_lane_uniform(v, lane); + } + self.lw.s.wave_read_lane_at(v, lane) + } + fn read_lane_half(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + return self.lw.read_lane_half(v, lane); + } + self.read_lane(v, lane) + } + fn count_bits(&mut self, v: Value) -> Value { + self.lw.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) + } + fn io_load(&mut self, dword: Value) -> Value { + let a = self.bytes(dword); + let io = self.io; + self.lw.s.raw_load(io, a, 1)[0] + } + fn res_store(&mut self, dword: Value, value: Value) { + let a = self.bytes(dword); + let res = self.res.expect("res is bound in kernel mode"); + self.lw.s.raw_store(res, a, &[value]); + } + fn mem_load(&mut self, addr: Value) -> Value { + let mem = self.mem; + self.lw.s.raw_load(mem, addr, 1)[0] + } + fn mem_store(&mut self, addr: Value, value: Value) { + let mem = self.mem; + self.lw.s.raw_store(mem, addr, &[value]); + } + // through `Lw`, which records the edges for its own variables (the split form's exchange + // count and dead flag, its temporaries); the lowering's blocks are sealed in `finish` + fn br(&mut self, target: usize) { + let b = self.blocks[target]; + self.lw.br(b); + } + fn br_if(&mut self, c: Value, then: usize, otherwise: usize) { + let (t, f) = (self.blocks[then], self.blocks[otherwise]); + self.lw.cond_br(c, t, f); + } + fn ret(&mut self) { + self.lw.s.m.ret(); + } +} + +/// A kernel-mode program in its per-lane form, as a signed DXIL container (one wave of +/// `WaveSize` = the program's wave size), and the masks whose final value may differ from +/// the console's (`lower::lower_kernel`). +pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(insts, wave64, &Entry::Kernel))?; + let lanes = if wave64 { 64 } else { 32 }; + Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale)) +} + +/// `kernel` in the split form: a wave64 program as two hardware wave32s (`DxilIr::split`). +/// EXEC at launch must be the whole console wave, as the CPU interpreter and the HLSL path +/// start it. +pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, true, DxilIr::split(insts, &Entry::Kernel))?; + Ok((ir.finish([64, 1, 1], 32)?.dxil, stale)) +} + +/// `compute` in the split form: each console wave64 as two hardware wave32s, threads numbered +/// by arrival (`Lw::setup_lanes_compute`). +pub fn compute_split(insts: &[Decoded], cs: &super::CsInterface) -> Result, String> { + let ir = lower::lower_compute(insts, cs, true, DxilIr::split(insts, &Entry::Compute(cs.clone())))?; + Ok(ir.finish(cs.threads, 32)?.dxil) +} + +/// `compute` from the program's code (decoded, far jumps resolved). +pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + compute(&insts, cs, wave64) +} + +/// Survey: every reason the per-lane form refuses a compute program (`lower::survey_compute`). +pub fn survey_compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Vec { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + match crate::gpu::rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + insts.push(d); + } + Err(e) => return vec![format!("cannot decode ({e:?})")], + } + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + lower::survey_compute(&insts, cs, wave64, DxilIr::new(&insts, wave64, &Entry::Compute(cs.clone()))) +} + +/// A compute program in its per-lane form, as a signed DXIL container. +pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(insts, wave64, &Entry::Compute(cs.clone())))?; + Ok(ir.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) +} + + +/// `XCL_PER_LANE=1` (with `XCL_DIRECT_DXIL`): compute programs try the per-lane form first, then +/// #1426's per-instruction form, then the HLSL path. +pub fn enabled() -> bool { + std::env::var("XCL_PER_LANE").is_ok_and(|v| v == "1") +} + +/// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`): +/// the container and its static samplers. +pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + // as `kernel::translate_entry`: a thread with a large stack, a panic is a refusal + let cs = cs.clone(); + std::thread::Builder::new() + .name("xcl-per-lane".into()) + .stack_size(256 << 20) + .spawn(move || { + let ir = lower::lower_compute(&insts, &cs, o.wave64, DxilIr::with(&insts, o, &Entry::Compute(cs.clone())))?; + ir.finish(cs.threads, if o.wave64 && !o.split { 64 } else { 32 }) + }) + .map_err(|e| format!("per-lane thread: {e}"))? + .join() + .map_err(|e| { + let msg = e.downcast_ref::().cloned().or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default(); + format!("the per-lane lowering panicked: {msg}") + })? +} + +#[cfg(test)] +mod tests { + use super::super::lower::tests::*; + use super::super::{dxc, runner, translate, Mode, Options}; + + fn gpu() -> bool { + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); + return false; + } + true + } + + /// A rounding mode #1426's lowering cannot honour refuses the program, as #1426 and the HLSL + /// path do, instead of the per-lane form computing with the default mode (Kalmarv, #1745): + /// f32 toward zero by `s_setreg`, f64 by `s_round_mode` and by `s_setreg`. + #[test] + fn a_rounding_mode_the_lowering_cannot_honour_is_refused() { + let add_f32: I = ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)]); + let add_f64: I = ("V_ADD_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 2)]); + let programs: [(&str, Vec); 3] = [ + ("f32 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x801), ("LITERAL", 3)]), add_f32, ENDPGM]), + ("f64 by s_round_mode", vec![("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 0xC)]), add_f64, ENDPGM]), + ("f64 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x881), ("LITERAL", 3)]), add_f64, ENDPGM]), + ]; + for (name, p) in programs { + assert!(super::kernel(&decode(&p), false).is_err(), "{name}: taken"); + } + // denormal bits only (MODE[7:4]): the default rounding, taken + let denorm: Vec = vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x1901), ("LITERAL", 0xF)]), add_f32, ENDPGM]; + super::kernel(&decode(&denorm), false).unwrap(); + } + + /// An instruction lowered by #1426 that writes to `Lw`'s entry block after the program's + /// blocks are written (scratch) gives a container, and runs. + #[test] + fn a_bridged_instruction_may_write_to_the_entry_block() { + // scratch through #1426's lowering: its array is allocated in `Lw`'s entry block once + // the program's blocks are written (an "instruction after a terminator" before) + let lines: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7F)]), + ("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 3), ("ADDR", 2), ("SADDR", 0x7F)]), + ENDPGM, + ]; + let dxil = super::kernel(&decode(lines), false).map(|r| r.0); + let dxil = dxil.unwrap_or_else(|e| panic!("{e}")); + if !gpu() { + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let out = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + assert_eq!(out.vgpr[l][3], l as u32, "lane {l}"); + } + } + + /// The f16 and packed programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f16_programs_on_the_gpu() { + programs_on_the_gpu(&[("f16 arithmetic", F16_ARITHMETIC, check_f16_arithmetic, &[]), ("f16 packed", F16_PACKED, check_f16_packed, &[])]); + } + + /// The per-lane form as real DXIL on the GPU agrees with the lowering run on the CPU (and so + /// with the HLSL path, which `lower`'s tests compare it with): registers and memory. + #[test] + fn per_lane_kernels_run_on_the_gpu() { + if !gpu() { + return; + } + let run = coalesced_run(false); + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF), + ("leaving loop", LEAVING_LOOP), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY), + ("coalesced run", &run[..]), + ("coalesced breaks", COALESCED_BREAKS), + ("coalesced in partial", COALESCED_IN_PARTIAL), + ("coalesced in loop", COALESCED_IN_LOOP), + ] { + let insts = decode(lines); + let (dxil, stale) = super::kernel(&insts, false).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + /// The integer programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn integer_programs_on_the_gpu() { + programs_on_the_gpu(&[("integer arithmetic", INT_ARITHMETIC, check_int_arithmetic, &[]), ("integer carries", INT_CARRIES, check_int_carries, &[])]); + } + + /// The f32 programs of `lower`'s tests on the GPU: the HLSL path gives the expected + /// registers (`check_f32_*`, wave32), and the per-lane DXIL gives the HLSL path's, register + /// for register (rcp within `f32_close`: HLSL's `rcp` is a fast fdiv). While the per-lane + /// form refuses a program, that half is SKIPPED with the refusal. + #[test] + fn f32_programs_on_the_gpu() { + programs_on_the_gpu(&[ + ("f32 arithmetic", F32_ARITHMETIC, check_f32_arithmetic, &[]), + ("f32 compares", F32_COMPARES, check_f32_compares, &[]), + ("f32 conversions", F32_CONVERSIONS, check_f32_conversions, &[]), + ("f32 rounding", F32_ROUNDING, check_f32_rounding, &[]), + ("f32 transcendentals", F32_TRANSCENDENTALS, check_f32_transcendentals, &[3, 4]), + ("f32 three-source", F32_THREE_SOURCE, check_f32_three_source, &[]), + ]); + } + + /// A program of `lower`'s tests, the check of its registers on the HLSL path (wave32), and + /// the VGPRs the per-lane form need only match within `f32_close`. + type Program = (&'static str, &'static [I], fn(&[u32], &[Vec]), &'static [usize]); + + /// `f32_programs_on_the_gpu`'s two halves, for any programs. + fn programs_on_the_gpu(programs: &[Program]) { + if !gpu() { + return; + } + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let wave64 = runner::wave64_supported() == Ok(true); + for &(name, lines, check, approx) in programs { + for w64 in [false, true] { + let lanes = if w64 { 64 } else { 32 }; + if w64 && !wave64 { + runner::skip_test(&format!("{name}, wave64: no wave64")); + continue; + } + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: w64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &["-Gis"]).unwrap(), &st, &[]).unwrap(); + if !w64 { + check(&hlsl.sgpr, &hlsl.vgpr[..32]); + } + let insts = decode(lines); + let (dxil, stale) = match super::kernel(&insts, w64) { + Ok(k) => k, + Err(e) => { + runner::skip_test(&format!("{name}, wave{lanes}, per-lane form: refused ({e})")); + continue; + } + }; + let direct = runner::run(&dxil, &st, &[]).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if w64 { + sregs.extend([107, 127]); + } + let stale_at = |r: usize| stale.contains(&(r as u8)) || (w64 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r)) { + assert_eq!(direct.sgpr[r], hlsl.sgpr[r], "{name}, wave{lanes}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + let (d, h) = (direct.vgpr[l][r], hlsl.vgpr[l][r]); + let same = if approx.contains(&r) { f32_close(d, h) } else { d == h }; + assert!(same, "{name}, wave{lanes}: lane {l} v{r}: {d:#x} against {h:#x}"); + } + } + } + } + } + + /// 2-D and 3-D groups in the per-lane form: the threads numbered as the waves arrive + /// (`Lw::setup_lanes_compute`), each wave's lanes the console's consecutive threads, as the + /// lowering run on the CPU has them. + #[test] + fn a_per_lane_2d_or_3d_group_runs_on_the_gpu() { + if !gpu() { + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let dxil = super::compute(&decode(&lines), &cs, wave64).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } + } + + /// A wave64 program in the split form through `compute_with` (the runtime's path on a GPU + /// with 32-lane waves only): 32-lane hardware waves (`WaveSize(32)`, not 64), the console's + /// wave64 results (MiguelMachado-dev found `compute_with` passing 64). + #[test] + fn the_runtime_path_takes_the_split_form() { + if !gpu() { + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, true); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&k.dxil, [2, 1, 1], &[100, 0], &mem).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let cpu = run_compute_waves(&lines, &cs, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?}"); + } + } + + /// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f64_programs_on_the_gpu() { + programs_on_the_gpu(&[("f64", F64_ARITHMETIC, check_f64, &[])]); + } + + #[test] + fn a_per_lane_compute_program_runs_on_the_gpu() { + if !gpu() { + return; + } + let cs = compute_cs(); + let dxil = super::compute(&decode(COMPUTE), &cs, false).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + // and the HLSL path, for good measure + if dxc::location().is_ok() { + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + let hlsl = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + assert_eq!(runner::dispatch(&hlsl, [3, 1, 1], &[100, 0], &mem).unwrap(), gpu); + } + } + + /// With the runtime's four memory windows (`compute_with`), the memory instructions go + /// through #1426's window switch (blocks of its own in the `Ir` block) and the program + /// still gives the CPU lowering's memory. + #[test] + fn a_per_lane_program_with_four_memory_windows_runs_on_the_gpu() { + let cs = compute_cs(); + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + if !gpu() { + return; + } + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let mem = vec![0u32; 256]; + let out = runner::dispatch(&k.dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..]); + } + + /// Coalesced guarded runs lowered through `Ir::foreign` (`Lw::inst_guarded` with `guard = true` + /// inside the run's block): f32 arithmetic against HLSL, and 4-window memory load/store inside + /// a coalesced run (wave32 and split wave64, `Lw` making window-switch blocks inside the run) + /// against the CPU lowering. + #[test] + fn coalesced_foreign_runs_agree_on_the_gpu() { + if !gpu() { + return; + } + // 4-window compute: lanes below the cut (16 in wave32; 40 in split wave64, spanning both + // wave32 halves) run a coalesced load + add + store via `foreign` + let cs = compute_cs(); + let mem = memory_image(); + for (wave64, split) in [(false, false), (true, true)] { + let run = coalesced_run(wave64); + let bytes: Vec = run.iter().flat_map(encode_line).collect(); + let o = super::KernelOptions { wave64, split, mem_windows: 4, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let out = runner::dispatch(&k.dxil, [1, 1, 1], &[0, 0], &mem).unwrap(); + let cpu = run_compute_waves(&run, &cs, wave64, 1, &[0, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..], "4-window coalesced memory via foreign (wave64={wave64}, split={split})"); + } + + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = COALESCED_F32_RUN.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + let (dxil, _) = super::kernel(&decode(COALESCED_F32_RUN), false).unwrap(); + let direct = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + for r in 0..=5 { + assert_eq!(direct.vgpr[l][r], hlsl.vgpr[l][r], "lane {l} v{r}"); + } + } + assert_eq!((direct.sgpr[106], direct.sgpr[126]), (hlsl.sgpr[106], hlsl.sgpr[126])); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 71012d565c..1a1a8ba79d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -52,6 +52,10 @@ //! `ByteAddressBuffer` (`mem`); initial SGPRs (user data) come from `io`. Textures come next. pub mod dxc; +pub mod dxil; +pub mod lane_masks; +pub mod lower; +pub mod lower_dxil; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; @@ -59,6 +63,7 @@ pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; pub mod runner; +pub mod ssa; #[cfg(test)] mod tests; #[cfg(test)] @@ -629,6 +634,12 @@ impl Conts { /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// Structured code longer than this many bytes per byte of program falls back to the `pc` form. +/// Each guard of the structured form lists every pending skip flag, so it grows with the +/// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks), +/// the next largest 61 (#1307). +const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128; + /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. @@ -1378,6 +1389,7 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B } pub fn translate(code: &[u8], opt: &Options) -> Result { + let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; @@ -1482,6 +1494,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); + if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { + return translate(program, &Options { structured: false, ..opt.clone() }); + } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { code.push_str(" uint pc = xcl_entry_pc;\n"); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 496543a53c..5360dde638 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -235,12 +235,18 @@ mod translated { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } - identity_with( + let id = identity_with( env!("XCL_TRANSLATOR_SOURCE_ID"), super::dxc::toolchain_identity(), Backend::current(), crate::gpu::dxil::kernel::TRANSLATOR_VERSION, - ) + ); + // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity + if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { + identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) + } else { + id + } }) } @@ -605,6 +611,20 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::detect_wave64(code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; + // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses + if super::lower_dxil::enabled() { + match super::lower_dxil::compute_with(code, &cs, o) { + Ok(k) => { + crate::gpu::dxil::coverage::record_translated("CS per-lane"); + dump_direct(blob, &k.dxil); + return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + } + Err(e) => { + let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); + crate::xlog_info!("[SHADER] per-lane fallback reason=\"{reason}\" detail=\"{}\" – per-instruction form", e.lines().next().unwrap_or("")); + } + } + } let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) diff --git a/crates/xcl/src/gpu/recomp/ssa.rs b/crates/xcl/src/gpu/recomp/ssa.rs new file mode 100644 index 0000000000..0a7fd4698d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/ssa.rs @@ -0,0 +1,304 @@ +//! SSA form of the console registers for the direct DXIL lowering, built while the blocks are +//! lowered (the on-the-fly construction of Braun et al., "Simple and Efficient Construction of +//! Static Single Assignment Form", CC 2013). +//! +//! Every register dword (s0–s127, v0–v255, SCC) is a variable. The lowering writes a variable +//! when an instruction defines it and reads it when one uses it; a read in a block without a +//! definition looks through the predecessors, placing a phi where they can disagree. A block +//! whose predecessors are not all lowered yet (a loop head, before its back edges) is *unsealed*: +//! its phis are left incomplete and filled in when it is sealed. A phi whose operands are all one +//! value (or itself) is trivial and is replaced by that value, through the sink's `replace`. +//! +//! The values themselves live in the DXIL module; this only decides where phis go. The sink is +//! the module builder. + +use std::collections::HashMap; +use std::hash::Hash; + +/// A register dword of the console program: what the SSA form tracks. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Var { + /// s as a number (`i32`) + S(u8), + /// the lane's bit of the mask held in s (wave64: the pair from s) (`i1`) + M(u8), + V(u16), + Scc, +} + +/// What the construction needs from the module builder. +pub trait Sink { + type V: Copy + Eq + Hash + std::fmt::Debug; + /// A new phi at the top of `block` for `var` (`i1` for SCC, `i32` for a register). + fn phi(&mut self, block: usize, var: Var) -> Self::V; + fn incoming(&mut self, phi: Self::V, value: Self::V, pred: usize); + /// Every use of `old` becomes `new`, and `old` (a trivial phi) is dropped. + fn replace(&mut self, old: Self::V, new: Self::V); + /// The value of a variable read before any definition reaches it. + fn undef(&mut self, var: Var) -> Self::V; +} + +pub struct Ssa { + preds: Vec>, + defs: Vec>, + sealed: Vec, + /// per unsealed block: the phis placed before its predecessors were known + incomplete: Vec>, + /// the operands of each live phi, and the phis that use each value + operands: HashMap>, + users: HashMap>, + /// trivial phis removed → what replaced them + forward: HashMap, +} + +impl Ssa { + /// `preds[b]`: the predecessors of block b, all of them, back edges included. + pub fn new(preds: Vec>) -> Self { + let n = preds.len(); + Ssa { + preds, + defs: vec![HashMap::new(); n], + sealed: vec![false; n], + incomplete: vec![Vec::new(); n], + operands: HashMap::new(), + users: HashMap::new(), + forward: HashMap::new(), + } + } + + /// What a value stands for now: itself, or what replaced it as a trivial phi. + pub fn resolve_value(&self, v: V) -> V { + self.resolve(v) + } + + /// The operands of a live phi (None for any other value). + pub fn phi_operands(&self, v: V) -> Option<&[V]> { + self.operands.get(&v).map(|o| o.as_slice()) + } + + fn resolve(&self, mut v: V) -> V { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + + pub fn write(&mut self, block: usize, var: Var, value: V) { + self.defs[block].insert(var, value); + } + + pub fn read>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + if let Some(&v) = self.defs[block].get(&var) { + return self.resolve(v); + } + let v = if !self.sealed[block] { + let phi = self.new_phi(sink, block, var); + self.incomplete[block].push((var, phi)); + phi + } else if self.preds[block].len() == 1 { + let p = self.preds[block][0]; + self.read(sink, p, var) + } else if self.preds[block].is_empty() { + sink.undef(var) + } else { + // the phi is the definition while its operands are read (a loop through here) + let phi = self.new_phi(sink, block, var); + self.write(block, var, phi); + self.add_operands(sink, block, var, phi) + }; + self.write(block, var, v); + v + } + + /// Every predecessor of `block` has been lowered: complete its phis. + pub fn seal>(&mut self, sink: &mut S, block: usize) { + for (var, phi) in std::mem::take(&mut self.incomplete[block]) { + self.add_operands(sink, block, var, phi); + } + self.sealed[block] = true; + } + + fn new_phi>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + let phi = sink.phi(block, var); + self.operands.insert(phi, Vec::new()); + phi + } + + fn add_operands>(&mut self, sink: &mut S, block: usize, var: Var, phi: V) -> V { + for p in self.preds[block].clone() { + let v = self.read(sink, p, var); + sink.incoming(phi, v, p); + self.operands.get_mut(&phi).expect("live phi").push(v); + self.users.entry(v).or_default().push(phi); + } + self.remove_trivial(sink, phi) + } + + fn remove_trivial>(&mut self, sink: &mut S, phi: V) -> V { + let mut same = None; + for &op in &self.operands[&phi] { + let op = self.resolve(op); + if Some(op) == same || op == phi { + continue; + } + if same.is_some() { + return phi; + } + same = Some(op); + } + let Some(same) = same else { return phi }; // only reachable through itself: kept + sink.replace(phi, same); + self.forward.insert(phi, same); + self.operands.remove(&phi); + // phis that used this one may have become trivial in turn + for user in self.users.remove(&phi).unwrap_or_default() { + if user != phi && self.operands.contains_key(&user) { + self.remove_trivial(sink, user); + } + } + same + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Records what the construction asks of a module builder. + #[derive(Default)] + struct Log { + next: u32, + phis: Vec<(u32, usize, Var)>, + incoming: Vec<(u32, u32, usize)>, + replaced: Vec<(u32, u32)>, + } + + impl Log { + fn value(&mut self) -> u32 { + self.next += 1; + self.next + } + fn live_phis(&self) -> Vec { + self.phis.iter().map(|p| p.0).filter(|p| !self.replaced.iter().any(|r| r.0 == *p)).collect() + } + } + + impl Sink for Log { + type V = u32; + fn phi(&mut self, block: usize, var: Var) -> u32 { + let v = self.value(); + self.phis.push((v, block, var)); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + self.incoming.push((phi, value, pred)); + } + fn replace(&mut self, old: u32, new: u32) { + self.replaced.push((old, new)); + } + fn undef(&mut self, _: Var) -> u32 { + 0 + } + } + + const R: Var = Var::V(3); + + #[test] + fn a_straight_line_needs_no_phi() { + // 0 → 1 → 2 + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![1]]), Log::default()); + let a = log.value(); + ssa.write(0, R, a); + for b in 0..3 { + ssa.seal(&mut log, b); + } + assert_eq!(ssa.read(&mut log, 2, R), a); + assert!(log.phis.is_empty()); + } + + #[test] + fn a_diamond_joins_two_definitions() { + // 0 → {1, 2} → 3, each arm defines R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(1, R, a); + ssa.write(2, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.live_phis(), vec![j]); + assert_eq!(log.incoming, vec![(j, a, 1), (j, b, 2)]); + } + + #[test] + fn one_arm_defining_still_joins_with_the_value_from_before() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(0, R, a); + ssa.write(1, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.incoming, vec![(j, b, 1), (j, a, 2)]); + } + + #[test] + fn a_loop_that_changes_the_register_keeps_its_phi() { + // 0 → 1 (head) → 2 (body) → 1, 1 → 3 (exit); the body increments R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); // head not sealed yet: incomplete phi + ssa.seal(&mut log, 2); + let body_in = ssa.read(&mut log, 2, R); + assert_eq!(body_in, head); + let inc = log.value(); + ssa.write(2, R, inc); + ssa.seal(&mut log, 1); // back edge known + ssa.seal(&mut log, 3); + assert_eq!(ssa.read(&mut log, 3, R), head); + assert_eq!(log.live_phis(), vec![head]); + assert_eq!(log.incoming, vec![(head, a, 0), (head, inc, 2)]); + } + + #[test] + fn a_loop_that_leaves_the_register_alone_drops_its_phi() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); + ssa.seal(&mut log, 2); + let _ = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 3); + assert_eq!(log.replaced, vec![(head, a)]); + assert!(log.live_phis().is_empty()); + assert_eq!(ssa.read(&mut log, 3, R), a, "reads after the removal see the replacement"); + } + + #[test] + fn removing_a_phi_cascades_to_the_phis_built_on_it() { + // nested loops that never change R: inner head 2's phi uses outer head 1's phi + // 0 → 1 → 2 → 3 → 2, 3 → 4 → 1, 4 → 5 + let preds = vec![vec![], vec![0, 4], vec![1, 3], vec![2], vec![3], vec![4]]; + let (mut ssa, mut log) = (Ssa::new(preds), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let outer = ssa.read(&mut log, 1, R); + let inner = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 3); + let _ = ssa.read(&mut log, 3, R); + ssa.seal(&mut log, 2); + ssa.seal(&mut log, 4); + let _ = ssa.read(&mut log, 4, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 5); + assert!(log.live_phis().is_empty(), "both heads' phis go: {:?} {:?}", outer, inner); + assert_eq!(ssa.read(&mut log, 5, R), a); + } +} diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 846cb5cd86..55ef19082f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7594,6 +7594,38 @@ fn fspx_containers_translate_and_compile() { assert_eq!(ok, n); } +/// Structured code past `STRUCTURED_BYTES_PER_CODE_BYTE` is translated in the `pc` form (#1307). +/// n conditional forward jumps whose targets all come after them, in the same order, keep up to +/// n skip flags pending, and every guard lists them: 200 cross the bound, 50 do not. This checks +/// the switch only. Here the `pc` form keeps the same stretch under one `pc` guard and is no +/// smaller; the gain is on programs whose `pc` form is split into blocks, such as the retail +/// one of #1307 (148 MB -> 14 MB). +#[test] +fn oversized_structured_code_falls_back_to_pc_blocks() { + let crossing = |n: usize| { + let i = |name: &str, e: &str, f: &[(&str, u64)]| encode(name, e, f, None).unwrap(); + let mut code: Vec = Vec::new(); + let mut at = Vec::new(); + for k in 0..n as u64 { + code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)])); + code.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128 + k % 16)])); + at.push(code.len()); + code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + } + for a in at { + let d = ((code.len() - a) / 4 - 1) as u16; + code[a..a + 2].copy_from_slice(&d.to_le_bytes()); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)])); + } + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl.contains("pc ==") + }; + assert!(!crossing(50), "50 crossing jumps: structured"); + assert!(crossing(200), "200 crossing jumps: past the bound, pc blocks"); +} + /// Random nests of loops with `continue` / `break` of any loop around them – backward jumps out of /// inner loops, loops whose end is an inner loop's – give the same state as structured code and as /// the block dispatcher (`structured: false`). diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 336abd93fb..da5b15ef42 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -287,7 +287,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); } - return pc(this, sig, max, args, args_off, count_buf, count_off); + return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -300,7 +300,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us match bind_abi(this, list, pso, gfx) { Ok(()) => { count(if gfx { DRAWS } else { DISPATCHES }); - pc(this, sig, max, args, args_off, count_buf, count_off) + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } Err(e) => { count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); @@ -312,6 +312,65 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses +static ARGUMENT_ORDER: Mutex> = Mutex::new(None); + +/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. +/// +/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that +/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). +/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that +/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also +/// when the dispatch wrote them through another resource over the same memory, as translated +/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). +/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs +/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver +/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's +/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> +/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and +/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. +unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { + let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); + let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; + let Some(buffer) = buffer else { return op() }; + let b = buffer.as_raw() as usize; + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + op(); + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +} + +/// The device's buffer for `fresh_indirect_arguments` (made on first use) +unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let mut g = ARGUMENT_ORDER.lock().unwrap(); + if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { + return Some(b.clone()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut b: Option = None; + if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); + } + return None; + } + let b = b?; + *g = Some((dev.as_raw() as usize, b.clone())); + Some(b) +} + /// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth /// implied) as two triangles a rectangle; false: not a rect list, or one this cannot expand /// (the caller draws the three vertices as a triangle – half of each rectangle). @@ -991,6 +1050,134 @@ mod tests { assert!(!pso_async::is_pending(building)); } + /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same + /// memory (as translated shaders write through the memory windows), a UAV barrier (what a + /// console barrier becomes), then the ExecuteIndirect: it runs the count just written, not + /// the one the memory held before the list (`fresh_indirect_arguments`; without it an RTX + /// 5090 ran the old count in nearly every try). + #[test] + fn execute_indirect_reads_the_arguments_written_before_it() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use std::mem::{transmute_copy, ManuallyDrop}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + const TRIES: u32 = 40; + // mode 0: write (x, 1, 1) at a[0..12]; mode 1: count the groups + let src = r#" +#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint mode; uint x; }; +RWByteAddressBuffer a : register(u0); +RWByteAddressBuffer c : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint t : SV_GroupIndex) { + if (t != 0u) return; + if (mode == 0u) a.Store3(0, uint3(x, 1u, 1u)); else c.InterlockedAdd(0, 1u); +} +"#; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap(); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let desc = |width| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + // the arguments and the buffer the dispatch writes them through: one memory + let mut heap: Option = None; + let heap_desc = D3D12_HEAP_DESC { SizeInBytes: 1 << 16, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + dev.CreateHeap(&heap_desc, &mut heap).unwrap(); + let heap = heap.unwrap(); + let placed = || { + let mut r: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc(1 << 16), D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (args, written) = (placed(), placed()); + // the group count, read on the CPU + let cpu_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let mut groups: Option = None; + dev.CreateCommittedResource(&cpu_heap, D3D12_HEAP_FLAG_NONE, &desc(256), D3D12_RESOURCE_STATE_COMMON, None, &mut groups).unwrap(); + let groups = groups.unwrap(); + let mut count = std::ptr::null_mut(); + groups.Map(0, None, Some(&mut count)).unwrap(); + let count = count as *mut u32; + let uav_barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, + }; + let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { + close(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let v = done.GetCompletedValue() + 1; + queue.Signal(&done, v).unwrap(); + fence::wait(&done, v, &dev, None, 10_000).unwrap(); + }; + let (mut old, mut wrong) = (0u32, Vec::new()); + for k in 0..TRIES { + // each try writes a count the memory does not hold yet + let new = if k % 2 == 0 { 4096 } else { 0 }; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let record = |x: u32| -> ID3D12GraphicsCommandList { + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pso).unwrap(); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, written.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, groups.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(0, 2, [0u32, x].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list + }; + let before = record(old); + run(&before, &|| before.Close().unwrap()); + alloc.Reset().unwrap(); + *count = 0; + let list = record(new); + list.ResourceBarrier(&[uav_barrier.clone()]); + list.SetComputeRoot32BitConstants(0, 2, [1u32, 0].as_ptr() as _, 0); + // from here as XCL records a title's ExecuteIndirect: on the adopted list + let raw = list.as_raw(); + real::adopt(raw, real::Kind::CommandList); + list_x::on_create(raw, alloc.as_raw() as usize, 0, ty); + type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; + let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); + fresh_indirect_arguments(raw, || ei(raw, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0)); + let close: Close = std::mem::transmute(real::orig_fn(raw, 9)); + run(&list, &|| close(raw).unwrap()); + let ran = std::ptr::read_volatile(count); + if ran != new { + wrong.push((k, ran)); + } + old = new; + } + groups.Unmap(0, None); + assert!(wrong.is_empty(), "{} of {TRIES} ExecuteIndirects ran another group count than the one written before them (try, groups): {wrong:?}", wrong.len()); + } + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 5247d09586..8dec7b1c27 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -674,6 +674,13 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if matches!(format, 86 | 115) && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); } + // R9G9B9E5_SHAREDEXP targets / UAVs: PC D3D12 forbids ALLOW_RENDER_TARGET and + // ALLOW_UNORDERED_ACCESS on format 67 (Series S 1920x1080 target, flags 0x300005: + // E_INVALIDARG) – R11G11B10_FLOAT is the same 32 bpp unsigned HDR float format with full + // PC RTV/UAV/SRV support. Sampled-only R9G9B9E5 textures stay format 67. + if format == 67 && flags & 5 != 0 { + d[0x20..0x24].copy_from_slice(&26u32.to_le_bytes()); + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -723,10 +730,11 @@ fn depth_typeless(f: u32) -> Option { } /// The format of a render target / depth view or pipeline on the PC: `pc_view_format`, and a -/// B5G5R5A1 / B4G4R4A4 target is R8G8B8A8 (`pc_resource_desc`). +/// B5G5R5A1 / B4G4R4A4 target is R8G8B8A8, an R9G9B9E5 target is R11G11B10_FLOAT (`pc_resource_desc`). pub fn pc_target_format(f: u32) -> u32 { match f { 86 | 115 => 28, + 67 => 26, f => pc_view_format(f), } } @@ -749,6 +757,8 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (53 | 55, 0 | 53 | 55) => 56, // a target made R8G8B8A8 (`pc_resource_desc`) (28, 86 | 115) => 28, + // a target made R11G11B10_FLOAT (`pc_resource_desc`) + (26, 67) => 26, (_, v) => v, } } @@ -1142,6 +1152,11 @@ mod tests { x[0x20] = 86; // B5G5R5A1 target that is also a UAV x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); assert_eq!(desc(&x), (28, 0x5)); + x[0x20] = 67; // R9G9B9E5_SHAREDEXP target + UAV + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); + assert_eq!(desc(&x), (26, 0x5)); + x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // sampled-only R9G9B9E5 stays format 67 + assert_eq!(desc(&x), (67, 0)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); assert_eq!(pc_shader_view_format(44, 56), 46); @@ -1152,7 +1167,9 @@ mod tests { assert_eq!(pc_shader_view_format(19, 62), 22); assert_eq!(pc_shader_view_format(28, 86), 28); assert_eq!(pc_shader_view_format(86, 86), 86, "a B5G5R5A1 texture that stayed one"); - assert_eq!((pc_target_format(86), pc_target_format(118), pc_view_format(117)), (28, 45, 10)); + assert_eq!(pc_shader_view_format(26, 67), 26); + assert_eq!(pc_shader_view_format(67, 67), 67, "a sampled-only R9G9B9E5 texture that stayed one"); + assert_eq!((pc_target_format(86), pc_target_format(67), pc_target_format(118), pc_view_format(117)), (28, 26, 45, 10)); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index afa4f91e46..0fdfb78277 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -89,7 +89,13 @@ unsafe fn list_type(list: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { pc:: D3D12_COMMAND_LIST_TYPE>(list, PC_GET_TYPE)(list) } -unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { +/// The type of a list XCL keeps state for (`on_create`), without a call to the list; None for +/// any other +pub(super) fn tracked_list_type(list: *mut c_void) -> Option { + LISTS.lock().unwrap().as_ref()?.get(&(list as usize))?.list_type +} + +pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 040d78a0ce..740b69ef9f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -220,6 +220,165 @@ struct Target { used_extra: Vec<(usize, usize)>, } +/// Per-heap free-tile allocator for `Pages`. +/// +/// Keeping free tiles partitioned by pool heap (sorted descending so `.pop()` yields ascending +/// contiguous tile indices) prevents streaming churn across 100+ 64 MiB pools from scattering a +/// single texture across dozens of heaps — which otherwise explodes `Pages::map` into dozens of +/// `UpdateTileMappings` calls per texture. +struct TilePool { + /// Free tile indices for each pool heap (descending when `!dirty_sort[h]`). + free_by_heap: Vec>, + /// Whether `free_by_heap[h]` must be sorted descending before popping. + dirty_sort: Vec, + /// Total free tiles currently available across all heaps. + free_total: usize, + /// Tiles given back, reusable after `COOL`. + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, +} + +impl TilePool { + fn new() -> Self { + TilePool { + free_by_heap: Vec::new(), + dirty_sort: Vec::new(), + free_total: 0, + cooling: std::collections::VecDeque::new(), + } + } + + fn add_heap(&mut self, pool_pages: u32) -> u32 { + let h = self.free_by_heap.len() as u32; + self.free_by_heap.push((0..pool_pages).rev().collect()); + self.dirty_sort.push(false); + self.free_total += pool_pages as usize; + h + } + + fn push_cooling(&mut self, tile: Tile, now: std::time::Instant) { + self.cooling.push_back((tile, now)); + } + + /// Move every cooled tile (`>= COOL`) into its pool heap's free list so best-fit allocation + /// sees all ready tiles at once. + fn drain_cooling(&mut self, now: std::time::Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + let Some(((h, t), _)) = self.cooling.pop_front() else { break }; + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + fn return_tiles(&mut self, tiles: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + /// Pick the pool heap to take up to `rem` tiles from: + /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), + /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without + /// splitting fuller pools), + /// 3. otherwise the heap with the most free tiles (minimizing distinct heaps touched). + fn pick_heap(&self, rem: usize, preferred: Option) -> Option { + if self.free_total == 0 { + return None; + } + if let Some(p) = preferred.map(|h| h as usize).filter(|&h| h < self.free_by_heap.len()) { + if self.free_by_heap[p].len() >= rem { + return Some(p); + } + } + let mut best_fit: Option<(usize, usize)> = None; + let mut largest: Option<(usize, usize)> = None; + for (h, tiles) in self.free_by_heap.iter().enumerate() { + let len = tiles.len(); + if len == 0 { + continue; + } + if len >= rem { + if best_fit.is_none_or(|(_, blen)| len < blen) { + best_fit = Some((h, len)); + } + } else if largest.is_none_or(|(lh, llen)| len > llen || (len == llen && preferred == Some(h as u32) && preferred != Some(lh as u32))) { + largest = Some((h, len)); + } + } + best_fit.or(largest).map(|(h, _)| h) + } + + /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. + /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. + /// On failure, any tiles already taken are returned untouched. + fn take_batch( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + pool_pages: u32, + mut make_heap: impl FnMut() -> Option, + ) -> Option> { + if count == 0 { + return Some(Vec::new()); + } + self.drain_cooling(now); + let mut out = Vec::with_capacity(count); + while out.len() < count { + let rem = count - out.len(); + let h = match self.pick_heap(rem, preferred) { + Some(h) => h, + None => { + let Some(new_h) = make_heap() else { + self.return_tiles(&out); + return None; + }; + let added = self.add_heap(pool_pages); + debug_assert_eq!(added, new_h); + added as usize + } + }; + if self.dirty_sort[h] { + self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); + self.dirty_sort[h] = false; + } + let free = &mut self.free_by_heap[h]; + let take = rem.min(free.len()); + for _ in 0..take { + let t = free.pop().unwrap(); + out.push((h as u32, t)); + } + self.free_total -= take; + } + Some(out) + } +} + +/// Allocate one 64 MiB default heap for `Pages`. +unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_PAGES as u64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + // every kind of texture (resource heap tier 2: the only flags for both) + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); + return None; + } + heap +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -227,9 +386,7 @@ struct Pages { fence: ID3D12Fence, value: u64, pools: Vec, - free: Vec, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + pool: TilePool, /// title page address → its video memory pages: std::collections::HashMap, /// extra / sub-64 KiB tiles keyed by `(va, tile_index)` so repeated placements at the same @@ -241,6 +398,13 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device + reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// reusable scratch buffers for `map()` + scratch_heaps: Vec, + scratch_flags: Vec, + scratch_offsets: Vec, + scratch_counts: Vec, } // D3D12 objects are free-threaded @@ -259,6 +423,7 @@ impl Pages { return None; } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { @@ -266,58 +431,52 @@ impl Pages { fence, value: 0, pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), + pool: TilePool::new(), pages: std::collections::HashMap::new(), extra_pages: std::collections::HashMap::new(), idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + reservable_cache: std::collections::HashMap::new(), + scratch_heaps: Vec::new(), + scratch_flags: Vec::new(), + scratch_offsets: Vec::new(), + scratch_counts: Vec::new(), }) } /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { - sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.cooling, now); - } - - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } - let desc = D3D12_HEAP_DESC { - SizeInBytes: POOL_PAGES as u64 * PAGE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - Alignment: 0, - // every kind of texture (resource heap tier 2: the only flags for both) - Flags: D3D12_HEAP_FLAG_NONE, - }; - let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); - return None; - } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. unsafe fn map(&mut self, res: &ID3D12Resource, tiles: &[Tile]) { - let mut heaps: Vec = tiles.iter().map(|t| t.0).collect(); - heaps.sort_unstable(); - heaps.dedup(); - for h in heaps { - let ranges = heap_ranges(h, tiles); - let flags: Vec = ranges.iter().map(|r| if r.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); - let offsets: Vec = ranges.iter().map(|r| r.1).collect(); - let counts: Vec = ranges.iter().map(|r| r.2).collect(); + if tiles.is_empty() { + return; + } + self.scratch_heaps.clear(); + self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.sort_unstable(); + self.scratch_heaps.dedup(); + for i in 0..self.scratch_heaps.len() { + let h = self.scratch_heaps[i]; + let ranges = heap_ranges_trimmed(h, tiles); + if ranges.is_empty() { + continue; + } + self.scratch_flags.clear(); + self.scratch_offsets.clear(); + self.scratch_counts.clear(); + let mut num_tiles = 0u32; + for &(mapped, off, count) in &ranges { + self.scratch_flags.push(if mapped { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }); + self.scratch_offsets.push(off); + self.scratch_counts.push(count); + num_tiles += count; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); - let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; self.queue.UpdateTileMappings( res, 1, @@ -325,9 +484,9 @@ impl Pages { Some(®ion), &self.pools[h as usize], ranges.len() as u32, - Some(flags.as_ptr()), - Some(offsets.as_ptr()), - Some(counts.as_ptr()), + Some(self.scratch_flags.as_ptr()), + Some(self.scratch_offsets.as_ptr()), + Some(self.scratch_counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); } @@ -338,6 +497,9 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + if total == 0 { + return; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; @@ -364,7 +526,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -379,7 +541,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.extra_pages.remove(&k) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -395,49 +557,69 @@ impl Pages { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); + + let mut missing = 0usize; + let mut preferred: Option = None; + for i in 0..total as usize { + let existing = if i < own { + self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + } else { + self.extra_pages.get(&(va, i)).map(|p| p.tile.0) + }; + match existing { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + } + + let pools = &mut self.pools; + let pool = &mut self.pool; + let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let heap = alloc_pool_heap(dev)?; + pools.push(heap); + Some(pools.len() as u32 - 1) + })?; + let mut fresh_iter = fresh.into_iter(); + let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); for i in 0..total as usize { let tile = if i < own { let a = first + i * PAGE; - let tile = match self.pages.get_mut(&a) { + let t = match self.pages.get_mut(&a) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used.push(a); - } - tile + used.push(a); + t } else { let k = (va, i); - let tile = match self.extra_pages.get_mut(&k) { + let t = match self.extra_pages.get_mut(&k) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used_extra.push(k); - } - tile + used_extra.push(k); + t }; - let Some(t) = tile else { break }; - tiles.push(t); - } - if tiles.len() < total as usize { - self.release_tiles(used, used_extra, now, true); - return None; + tiles.push(tile); } self.map(res, &tiles); Some((used, used_extra)) @@ -460,6 +642,16 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } +/// Like `heap_ranges`, with any trailing `SKIP` range trimmed so `UpdateTileMappings` only walks +/// up to the last tile belonging to `heap`. +fn heap_ranges_trimmed(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { + let mut out = heap_ranges(heap, tiles); + while out.last().is_some_and(|r| !r.0) { + out.pop(); + } + out +} + /// 64 KiB page boundaries `P` with `va <= P < va + bytes`, capped at `total` tiles: /// `(first_page, count)`. Because every `P` lies strictly inside `[va, va + bytes)`, two /// non-overlapping ranges never share a page here even when `va` is only 4 KiB aligned. @@ -532,12 +724,18 @@ unsafe fn place_on_pages( crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({why}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } }; - if !reservable(dev, &tiled) { + let dev_key = dev.as_raw() as usize; + let is_reservable = { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; + *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) + }; + if !is_reservable { log("no tiled support for its format or sample count"); return None; } - let mut g = PAGES.lock().unwrap(); - let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the + // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { log(&format!("{hr:#x}")); @@ -547,14 +745,24 @@ unsafe fn place_on_pages( let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) else { - drop(g); + let bound = { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(pages)) = g.get_mut(&dev_key) { + if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + true + } else { + false + } + } else { + false + } + }; + if !bound { drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - }; - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); - drop(g); + } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } @@ -620,7 +828,7 @@ fn forget_pages(resource: usize) { } } -/// Before GPU work on `queue`: it waits for the pages mapped since its last work on that device. +/// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut dev: Option = None; if queue.GetDevice(&mut dev).is_err() { @@ -725,10 +933,78 @@ mod tests { let tiles = [(0, 5), (0, 6), (1, 0), (1, 1), (0, 9), (0, 10), (0, 11)]; assert_eq!(heap_ranges(0, &tiles), [(true, 5, 2), (false, 0, 2), (true, 9, 3)]); assert_eq!(heap_ranges(1, &tiles), [(false, 0, 2), (true, 0, 2), (false, 0, 3)]); + assert_eq!(heap_ranges_trimmed(1, &tiles), [(false, 0, 2), (true, 0, 2)]); // shared pages out of order: runs break where the tiles do assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// Streaming churn across 100+ 64 MiB pool heaps: cooling tiles returned in interleaved + /// cross-heap order are regrouped per heap and sorted into contiguous ascending runs, so new + /// textures stay inside 1 pool heap (1 UpdateTileMappings call, 1 contiguous range) instead of + /// scattering across dozens of heaps. + #[test] + fn tile_pool_keeps_churned_allocations_in_single_heap_and_contiguous() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let heaps_made = std::cell::Cell::new(0u32); + let mut make = || { + let h = heaps_made.get(); + heaps_made.set(h + 1); + Some(h) + }; + + // Fill 100 pools (64 tiles each for a fast unit test, same multi-heap topology as 1024). + const P: u32 = 64; + let mut live: Vec> = Vec::new(); + for _ in 0..100 { + live.push(pool.take_batch(P as usize, None, t0, P, &mut make).unwrap()); + } + assert_eq!(heaps_made.get(), 100); + assert_eq!(pool.free_total, 0); + + // Free 32 tiles from every pool in interleaved round-robin order (worst-case churn across + // all 100 pools in `cooling`). + for tile_idx in 0..32usize { + for h in 0..100usize { + pool.push_cooling(live[h][tile_idx], t0); + } + } + assert_eq!(pool.cooling.len(), 3200); + + // After COOL, allocating 100 textures of 32 tiles each must: + // - allocate ZERO new heaps, + // - place EVERY texture into exactly 1 single pool heap (1 UpdateTileMappings call), + // - yield 1 single contiguous tile range (0..32) per texture! + let t1 = t0 + COOL + Duration::from_millis(1); + for _ in 0..100 { + let alloc = pool.take_batch(32, None, t1, P, &mut make).unwrap(); + assert_eq!(alloc.len(), 32); + let h0 = alloc[0].0; + assert!(alloc.iter().all(|&(h, _)| h == h0), "texture scattered across multiple heaps"); + let ranges = heap_ranges_trimmed(h0, &alloc); + assert_eq!(ranges, [(true, 0, 32)], "expected 1 contiguous ascending range"); + } + assert_eq!(heaps_made.get(), 100, "must reuse cooled tiles without making new heaps"); + assert_eq!(pool.free_total, 0); + + // Partial overlap preference: if heap 7 has free tiles and preferred=Some(7), use heap 7. + for t in 10..18u32 { + pool.push_cooling((7, t), t1); + pool.push_cooling((3, t), t1); + } + let t2 = t1 + COOL + Duration::from_millis(1); + let pref = pool.take_batch(8, Some(7), t2, P, &mut make).unwrap(); + assert!(pref.iter().all(|&(h, _)| h == 7), "preferred heap should be chosen"); + assert_eq!(heap_ranges_trimmed(7, &pref), [(true, 10, 8)]); + + // Rollback on OOM: requesting more tiles than available when make_heap fails returns every + // popped tile cleanly so free_total is preserved. + assert_eq!(pool.free_total, 8); + let fail = pool.take_batch(16, None, t2, P, || None); + assert!(fail.is_none()); + assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); + } + /// Idle pages go back after `IDLE`, and a sweep looks at the queue of idle pages alone: one /// used again stays, one idle again later goes when that is `IDLE` ago, and the sweeps of /// 20 000 placements beside 200 000 pages in use take no time to speak of (a look at every @@ -1032,4 +1308,116 @@ mod tests { drop(last); } } + + /// Reproduces the multi-pool streaming churn pattern on the active D3D12 driver (comparing + /// scattered cross-heap `UpdateTileMappings` against single-heap contiguous + /// `UpdateTileMappings`, both with `FLAG_NONE` and per-texture `Signal`): + /// `cargo test -p xcl --lib -- --ignored --exact hle::d3d12x::vram::tests::churn_update_tile_mappings_timing --nocapture` + #[test] + #[ignore] + fn churn_update_tile_mappings_timing() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let mut dev: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("D3D12 device"); + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + const HEAPS: usize = 64; + const TILES_PER_TEX: usize = 32; // 2 MiB tiled texture + const TEX_COUNT: usize = 256; + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: 64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heaps = Vec::with_capacity(HEAPS); + for _ in 0..HEAPS { + let mut h: Option = None; + dev.CreateHeap(&heap_desc, &mut h).unwrap(); + heaps.push(h.unwrap()); + } + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let make_textures = || -> Vec { + (0..TEX_COUNT) + .map(|_| { + let mut r: Option = None; + dev.CreateReservedResource(&tex_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }) + .collect() + }; + + // BEFORE pattern: flat-FIFO cooling scatters each 32-tile texture across 32 heaps, + // calling UpdateTileMappings(FLAG_NONE) per heap + Signal per texture. + let old_res = make_textures(); + let mut fval = 0u64; + let t0 = Instant::now(); + let mut old_calls = 0usize; + for (k, r) in old_res.iter().enumerate() { + let tiles: Vec = (0..TILES_PER_TEX).map(|i| (((k + i) % HEAPS) as u32, (i % 64) as u32)).collect(); + let mut hs: Vec = tiles.iter().map(|t| t.0).collect(); + hs.sort_unstable(); + hs.dedup(); + for h in hs { + let ranges = heap_ranges(h, &tiles); + let flags: Vec = ranges.iter().map(|x| if x.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); + let offsets: Vec = ranges.iter().map(|x| x.1).collect(); + let counts: Vec = ranges.iter().map(|x| x.2).collect(); + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h as usize], ranges.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + old_calls += 1; + } + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let old_submit = t0.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let old_total = t0.elapsed(); + + // AFTER pattern: per-heap contiguous TilePool -> 1 heap, 1 contiguous range, + // D3D12_TILE_MAPPING_FLAG_NONE, per-texture Signal. + let new_res = make_textures(); + let t1 = Instant::now(); + let mut new_calls = 0usize; + for (k, r) in new_res.iter().enumerate() { + let h = k % HEAPS; + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: TILES_PER_TEX as u32, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + let off = 0u32; + let cnt = TILES_PER_TEX as u32; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h], 1, Some(&flag), Some(&off), Some(&cnt), D3D12_TILE_MAPPING_FLAG_NONE); + new_calls += 1; + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let new_submit = t1.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let new_total = t1.elapsed(); + + println!( + "BEFORE ({TEX_COUNT} x 2MiB textures, {old_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={old_submit:?} gpu_done={old_total:?}" + ); + println!( + "AFTER ({TEX_COUNT} x 2MiB textures, {new_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={new_submit:?} gpu_done={new_total:?}" + ); + assert!(new_calls < old_calls); + } + } } diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 6291b5dea0..db9f9ff61c 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -41,6 +41,8 @@ Usage: --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. + --direct --lanes: report per-lane compute coverage and sizes for matched outputs. + With --validate, validate both direct forms before counting successful translations. xcl rpf [--top N] [--find NAME] [--extract NAME --out DIR] Lists or extracts readable inline records. Archives larger than 1 GB use a bounded-memory header probe; --probe requests it explicitly and --full overrides it. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 591ca94cbb..80bfb1a2ec 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -309,6 +309,24 @@ struct RecompAgg { wave_resolved: BTreeMap, /// `--example MNEMONIC`: listing of the first program missing it, its HLSL and profile example: Option<(String, String, &'static str)>, + /// `lane_masks` (direct DXIL): programs analysed, those with no guard left, vector + /// instructions, those still guarded, lane branches, uniform branches; failures by reason + lanes: [usize; 6], + lanes_failed: BTreeMap, + /// compute programs, per-lane DXIL (`lower_dxil`) vs #1426's per-instruction form: tried, + /// per-lane ok, per-instruction ok, both ok, per-lane bytes and per-instruction bytes where + /// both are ok; why the per-lane form refused (first words of the reason) + cs_forms: [usize; 6], + cs_lane_why: BTreeMap, + /// survey of every refusal, per stage (CS, MS): tried, wave64, per-lane ok, per-instruction + /// ok, both ok, per-lane refused only for instructions (no structural reason), the same with + /// the per-instruction form ok, refused by the lane-mask analysis + forms: BTreeMap, + /// "stage | reason" → programs (each reason once per program): every per-lane reason, the + /// structural ones that are a program's only structural reason, the per-instruction reasons + lane_every: BTreeMap, + lane_sole: BTreeMap, + inst_why: BTreeMap, } impl RecompAgg { @@ -349,6 +367,28 @@ impl RecompAgg { e.1 += b; } self.hlsl_bytes += o.hlsl_bytes; + for (a, b) in self.lanes.iter_mut().zip(o.lanes) { + *a += b; + } + for (k, v) in o.lanes_failed { + *self.lanes_failed.entry(k).or_default() += v; + } + for (a, b) in self.cs_forms.iter_mut().zip(o.cs_forms) { + *a += b; + } + for (k, v) in o.cs_lane_why { + *self.cs_lane_why.entry(k).or_default() += v; + } + for (k, v) in o.forms { + for (a, b) in self.forms.entry(k).or_default().iter_mut().zip(v) { + *a += b; + } + } + for (m, o) in [(&mut self.lane_every, o.lane_every), (&mut self.lane_sole, o.lane_sole), (&mut self.inst_why, o.inst_why)] { + for (k, v) in o { + *m.entry(k).or_default() += v; + } + } } fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) { @@ -358,6 +398,20 @@ impl RecompAgg { return; } } + // `XCL_RECOMP_STAGES=CS,MS`: only programs of these stages + if let Ok(st) = std::env::var("XCL_RECOMP_STAGES") { + let l = match &mode { + recomp::Mode::Vertex(_) => "VS", + recomp::Mode::Pixel(_) => "PS", + recomp::Mode::Kernel => "kernel", + recomp::Mode::Mesh(_) => "MS", + recomp::Mode::Geometry(_) => "GS", + recomp::Mode::Compute(_) => "CS", + }; + if !st.split(',').any(|x| x == l) { + return; + } + } self.programs += 1; let wave64 = recomp::detect_wave64(code); self.wave32 += !wave64 as usize; @@ -389,6 +443,69 @@ impl RecompAgg { self.graphics_wave32 += 1; } } + if let recomp::Mode::Compute(cs) = &mode { + let lane = recomp::lower_dxil::compute_code(code, cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = crate::gpu::dxil::kernel::translate_compute(code, o, cs).map(|k| k.dxil); + self.cs_forms[0] += 1; + self.cs_forms[1] += lane.is_ok() as usize; + self.cs_forms[2] += inst.is_ok() as usize; + if let (Ok(a), Ok(b)) = (&lane, &inst) { + self.cs_forms[3] += 1; + self.cs_forms[4] += a.len(); + self.cs_forms[5] += b.len(); + } + if let Err(e) = &lane { + let key: String = e.split([':', '(']).next().unwrap_or("").split_whitespace().take(5).collect::>().join(" "); + *self.cs_lane_why.entry(key).or_default() += 1; + } + } + let survey_cs = match &mode { + recomp::Mode::Compute(cs) => Some(("CS", cs.clone())), + // the mesh pass is a compute pass of the NGG program: its threads in a 1-D group + recomp::Mode::Mesh(ms) => Some(("MS", recomp::CsInterface { threads: [ms.threads, 1, 1], tid_components: 1, ..Default::default() })), + _ => None, + }; + if let Some((st, cs)) = survey_cs { + let lane = recomp::lower_dxil::survey_compute_code(code, &cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = match &mode { + recomp::Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).map(|_| ()), + _ => crate::gpu::dxil::kernel::translate_compute(code, o, &cs).map(|_| ()), + }; + let mut keys: Vec<(String, bool)> = lane.iter().map(|r| (survey_key(r), survey_structural(r))).collect(); + keys.sort(); + keys.dedup(); + let structural: Vec<&String> = keys.iter().filter(|k| k.1).map(|k| &k.0).collect(); + let lm = lane.len() == 1 && ["lane conditions", "indirect jump", "branch to the entry", "irreducible", "no fixpoint", "cannot decode"].iter().any(|w| lane[0].starts_with(w)); + let f = self.forms.entry(st.to_string()).or_default(); + let bridge = !lane.is_empty() && structural.is_empty(); + for (i, c) in [true, wave64, lane.is_empty(), inst.is_ok(), lane.is_empty() && inst.is_ok(), bridge, bridge && inst.is_ok(), lm].into_iter().enumerate() { + f[i] += c as usize; + } + for (k, _) in &keys { + *self.lane_every.entry(format!("{st} | {k}")).or_default() += 1; + } + if let [k] = structural[..] { + *self.lane_sole.entry(format!("{st} | {k}")).or_default() += 1; + } + if let Err(e) = &inst { + *self.inst_why.entry(format!("{st} | {}", survey_key(e.lines().next().unwrap_or("")))).or_default() += 1; + } + } + match recomp::lane_masks::analyze_code(code, wave64) { + Ok(s) => { + let counts = [1, s.guarded.is_empty() as usize, s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches]; + for (a, b) in self.lanes.iter_mut().zip(counts) { + *a += b; + } + } + Err(why) => *self.lanes_failed.entry(why.to_string()).or_default() += 1, + } + // `XCL_RECOMP_NO_HLSL=1`: the direct DXIL survey alone + if std::env::var("XCL_RECOMP_NO_HLSL").is_ok() { + return; + } // `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`) let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { @@ -1493,6 +1610,45 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim "VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}; reads of lanes ≥ 32 resolved (32-lane GPUs): {:?}", rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards, rc.wave_resolved ); + let c = &rc.cs_forms; + let mut why: Vec<_> = rc.cs_lane_why.iter().collect(); + why.sort_by(|a, b| b.1.cmp(a.1)); + println!( + "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {} KB, per-instruction {} KB of DXIL; per-lane refused for: {:?}", + c[0], c[1], c[2], c[3], c[4] / 1024, c[5] / 1024, &why[..why.len().min(15)] + ); + for (st, f) in &rc.forms { + println!( + "{st} programs, every refusal: {} tried ({} wave64); per-lane ok {}, per-instruction ok {}, both {}; per-lane refused for instructions only {} (per-instruction ok on {} of them); lane-mask analysis refused {}", + f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7] + ); + } + for (title, m) in [ + ("per-lane reasons (stage | reason → programs; [S] structural)", &rc.lane_every), + ("the only structural reason of a program (stage | reason → programs)", &rc.lane_sole), + ("per-instruction form (#1426) refused (stage | first line → programs)", &rc.inst_why), + ] { + let mut v: Vec<_> = m.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0))); + println!("{title}:"); + for (k, n) in v.iter().take(top.max(40)) { + let tag = if survey_structural(k.split(" | ").nth(1).unwrap_or("")) { "[S] " } else { "" }; + println!(" {n:>6} {tag}{k}"); + } + } + let l = &rc.lanes; + println!( + "lane masks (direct DXIL, no EXEC emulation): analysed {} of {} programs, {} with no guard left; vector instructions {}, still guarded {} ({:.1}%); branches per lane {}, uniform {}; not analysed: {:?}", + l[0], + rc.programs, + l[1], + l[2], + l[3], + l[3] as f64 * 100.0 / l[2].max(1) as f64, + l[4], + l[5], + rc.lanes_failed + ); if let Some((x, hlsl, profile)) = &rc.example { println!("example: {x}"); @@ -1521,6 +1677,18 @@ mod tests { use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; + #[test] + fn per_lane_sweep_totals_include_only_matched_outputs() { + let mut sweep = LaneSweep::default(); + sweep.record(Ok(15), Some(10)); + sweep.record(Ok(20), None); + sweep.record(Err("validator: refused".into()), Some(30)); + + assert_eq!((sweep.tried, sweep.translated, sweep.paired), (3, 2, 1)); + assert_eq!((sweep.lane_bytes, sweep.instruction_bytes), (15, 10)); + assert_eq!(sweep.refusals.get("validator: refused"), Some(&1)); + } + fn compute_sample() -> Vec { let mut compute = fssm(&CODE, &[(6, 3)]); for offset in [0x13C, 0x140, 0x144] { @@ -1688,7 +1856,34 @@ fn name_hash(name: &str) -> u64 { h } -/// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W]`: +#[derive(Default)] +struct LaneSweep { + tried: usize, + translated: usize, + paired: usize, + lane_bytes: usize, + instruction_bytes: usize, + refusals: HashMap, +} + +impl LaneSweep { + fn record(&mut self, lane: Result, instruction_size: Option) { + self.tried += 1; + match lane { + Ok(size) => { + self.translated += 1; + if let Some(other) = instruction_size { + self.paired += 1; + self.lane_bytes += size; + self.instruction_bytes += other; + } + } + Err(e) => *self.refusals.entry(survey_key(&e)).or_default() += 1, + } + } +} + +/// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W] [--lanes]`: /// every program of a seeded sample of N records (default 200 programs' worth; `--sample 0` = /// all) through the direct DXIL translator; per-stage outcomes, a ranked histogram of what it /// cannot translate, translation times and (`--compare`) DXIL size vs HLSL + DXC. @@ -1713,6 +1908,9 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: let max_bytes = opt("--max-bytes").map(|v| v as usize).unwrap_or(16384); let timeout = std::time::Duration::from_secs(opt("--timeout").unwrap_or(10)); let skipped = AtomicUsize::new(0); + // `--lanes`: measure the compute per-lane form too, with sizes for the programs both forms produce. + let lanes = args.iter().any(|a| a == "--lanes"); + let lane_sweep = Mutex::new(LaneSweep::default()); // `--hash H`: only the container whose `[SHADER]` hash (FNV-64 of the container) is H, every // record searched; `--dump DIR`: write each program's direct DXIL (and with `--compare` the // HLSL path's source and DXIL) to DIR, for diffing the two (`dxc -dumpbin`) @@ -1767,6 +1965,29 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; let time = t.elapsed(); + if let (true, recomp::Mode::Compute(cs)) = (lanes, &mode) { + // under the sweep's timeout too (the thread is left to finish) + let (tx, rx) = std::sync::mpsc::channel(); + let (c, csc) = (code.to_vec(), cs.clone()); + std::thread::spawn(move || { + let lane = recomp::lower_dxil::compute_with(&c, &csc, o).and_then(|k| { + if validate { + crate::gpu::dxil::validate::validate(&k.dxil) + .map_err(|e| format!("validator: {}", e.lines().next().unwrap_or("")))?; + } + Ok(k.dxil.len()) + }); + let _ = tx.send(lane); + }); + let lane = rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))); + let instruction_size = r.as_ref().ok().map(Vec::len); + if trace { + if let Ok(bytes) = &lane { + eprintln!("per-lane: {name} FSSM#{fi}: {bytes} B, per-instruction {instruction_size:?} B"); + } + } + lane_sweep.lock().unwrap().record(lane, instruction_size); + } let dump = |suffix: &str, bytes: &[u8]| { if let Some(d) = &dump_dir { let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); @@ -1809,8 +2030,63 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: println!("{}", rep.json(top)); } else { println!("{} programs from {} sampled records (seed {seed}; {} over {max_bytes} B skipped){}{}", results.len(), order.len().min(input.len()), skipped.load(Ordering::Relaxed), if validate { ", validated" } else { "" }, if compare { ", compared with HLSL+DXC" } else { "" }); + if lanes { + let LaneSweep { tried, translated, paired, lane_bytes, instruction_bytes, refusals } = lane_sweep.into_inner().unwrap(); + let mut why: Vec<(String, usize)> = refusals.into_iter().collect(); + why.sort_by(|a, b| b.1.cmp(&a.1)); + why.truncate(top); + println!("per-lane form: {translated} of {tried} compute programs; {paired} matched for DXIL size: {lane_bytes} B against {instruction_bytes} B per instruction; refused for: {why:?}"); + } print!("{}", rep.text(top)); println!("time {:.1} s", t0.elapsed().as_secs_f64()); } 0 } + +/// A survey reason without its program's numbers: registers as `sN`, other numbers as `N` +/// (an `s_setreg`'s hardware register is kept), at most eight words. +fn survey_key(r: &str) -> String { + let r = r.split(" (").next().unwrap_or(r); + let words: Vec<&str> = r.split_whitespace().collect(); + let mut out: Vec = Vec::new(); + for (i, raw) in words.iter().enumerate() { + let w = raw.trim_end_matches([':', ',']); + let digits = |x: &str| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()); + let w = if w.strip_prefix('s').is_some_and(digits) { + "sN".to_string() + } else if digits(w) && !(i > 0 && words[i - 1] == "hwreg") { + "N".to_string() + } else { + w.to_string() + }; + out.push(if raw.ends_with(':') { format!("{w}:") } else { w }); + if out.len() == 8 { + break; + } + } + out.join(" ") +} + +/// A per-lane refusal no instruction lowering removes (the CFG, masks across joins, lanes +/// elsewhere, the group shape), as opposed to an instruction the per-lane form lacks. +fn survey_structural(r: &str) -> bool { + [ + "2-D / 3-D", + "elsewhere", + "read as a number", + "read as a mask", + "across two masks", + "successors", + "unsupported branch", + "neither a number nor a mask", + "empty program", + "lane conditions", + "indirect jump", + "branch to the entry", + "irreducible", + "no fixpoint", + "cannot decode", + ] + .iter() + .any(|w| r.contains(w)) +} diff --git a/scripts/smoke-title.tests.ps1 b/scripts/smoke-title.tests.ps1 new file mode 100644 index 0000000000..1c94bbbfc6 --- /dev/null +++ b/scripts/smoke-title.tests.ps1 @@ -0,0 +1,40 @@ +# Run with powershell.exe or pwsh.exe. Checks the `title:` line of smoke.ps1's block (#677): the +# hash of the game folder's name, as Python's hashlib.sha256(name.strip().encode()).hexdigest()[:8] +# gives it, or the -Title label. A fixture stands in for xcl.exe. +$ErrorActionPreference = 'Stop' +$smoke = Join-Path $PSScriptRoot 'smoke.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-smoke-title-' + [guid]::NewGuid()) +$null = New-Item -ItemType Directory -Path $fixture +try { + $xcl = Join-Path $fixture 'xcl.cmd' + [IO.File]::WriteAllText($xcl, "@echo off`r`necho Log: %~dp0xcl.log`r`n") + [IO.File]::WriteAllText((Join-Path $fixture 'xcl.log'), "(1 frames shown, 1 PresentX calls)`n") + function Get-SmokeTitle([hashtable]$Arguments) { + $block = & $smoke -Seconds 1 -Xcl $xcl @Arguments + $line = $block -split "`n" | Where-Object { $_ -like 'title:*' } + $line.Substring('title: '.Length).Trim() + } + # names built from character codes: this file stays ASCII for Windows PowerShell 5.1 + $cases = @( + @('SomeTitle', '27693731'), + @(('Caf' + [char]0xE9 + ' Folder'), '5256b5ea'), + @(([string][char]0x65E5 + [char]0x672C + ' pack ' + [char]::ConvertFromUtf32(0x1F3AE)), 'dbd98f4b'), + @(' Padded Name ', 'f8b1d479') + ) + foreach ($case in $cases) { + foreach ($game in @("D:\Games\$($case[0])", "D:\Games\$($case[0])\")) { + $got = Get-SmokeTitle @{ Game = $game } + if ($got -ne $case[1]) { throw "title of '$game' is '$got', expected '$($case[1])'" } + } + } + $got = Get-SmokeTitle @{ Game = 'D:\Games\SomeTitle'; Title = ' my label: one ' } + if ($got -ne 'my label: one') { throw "-Title printed '$got'" } + foreach ($bad in @('', ' ', "a`nb", 'a`b', ('a' + [char]0x2028 + 'commit: 0123456'), ('a' + [char]0x85 + 'b'))) { + $threw = $false + try { $null = & $smoke -Game 'D:\Games\SomeTitle' -Seconds 1 -Xcl $xcl -Title $bad } catch { $threw = $true } + if (-not $threw) { throw "-Title '$bad' was accepted" } + } + 'smoke-title: ok' +} finally { + Remove-Item -LiteralPath $fixture -Recurse -Force +} diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 index f0738cdb98..b7859c9242 100644 --- a/scripts/smoke.ps1 +++ b/scripts/smoke.ps1 @@ -2,16 +2,32 @@ # prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built # from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). # -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] +# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title