From 3c325a9080790815bae0e79349ac24d93f2bb52b Mon Sep 17 00:00:00 2001 From: TG0000 <122870448+TG0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:56:39 +0100 Subject: [PATCH] Shaders: console containers are walked without decoding instructions xbox::parse decoded every program twice in full (segments, branch targets; a third time for a segment that may be data) and the statistics of a captured shader once more: three Vecs, hash lookups and bit-at-a-time fields per instruction, for its length, terminator, branch offset and mnemonic. Sampled in a retail title's first 40 s, the two were 31 % of the samples of its running threads, on the threads that make its pipelines. rdna2_scan::step gives those from tables made of the decoder's own, without allocating; mnemonics are counted by number and named once. decode() is unchanged and stays the reference: every opcode of every encoding, random dwords and random programs are compared with it, and a segment with a far jump still goes through it. A whole retail pack (26 503 shaders, 44.4 M instructions), one thread: parse 38.1 -> 4.7 s (2 s of both is inflate), statistics 23.3 -> 1.8 s, with the same result for every shader. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/build.rs | 1 + crates/xcl/src/gpu/mod.rs | 1 + crates/xcl/src/gpu/rdna2.rs | 14 +- crates/xcl/src/gpu/rdna2_scan.rs | 244 ++++++++++++++++++++++++++ crates/xcl/src/gpu/xbox.rs | 287 ++++++++++++++++++++++++++++--- 5 files changed, 515 insertions(+), 32 deletions(-) create mode 100644 crates/xcl/src/gpu/rdna2_scan.rs diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index caf2ef4c7e..a55d91ff57 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -8,6 +8,7 @@ const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v1"; const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/dxbc.rs", "src/gpu/rdna2.rs", + "src/gpu/rdna2_scan.rs", "src/gpu/rdna2_spec.rs", "src/gpu/rdna2_xbox.rs", "src/gpu/recomp/dxc.rs", diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 06ebeedc0b..ef9e60aa53 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -10,6 +10,7 @@ pub(crate) mod fence; pub mod pack; pub mod rdna2; pub mod recomp; +mod rdna2_scan; mod rdna2_spec; mod rdna2_xbox; pub mod shader; diff --git a/crates/xcl/src/gpu/rdna2.rs b/crates/xcl/src/gpu/rdna2.rs index 9c60d3d382..5af2e4db35 100644 --- a/crates/xcl/src/gpu/rdna2.rs +++ b/crates/xcl/src/gpu/rdna2.rs @@ -158,18 +158,18 @@ fn read_words(code: &[u8], n: usize) -> Vec { /// Operand types that are encoded as a scalar/vector source code and therefore can /// select the 32-bit literal (code 255). -fn is_src_type(ty: &str) -> bool { +pub(super) fn is_src_type(ty: &str) -> bool { matches!( ty, "OPR_SRC" | "OPR_SRC_NOLDS" | "OPR_SRC_VGPR" | "OPR_SSRC" | "OPR_SSRC_NOLDS" | "OPR_SSRC_LANESEL" | "OPR_SIMM32" ) } -fn is_valu32(enc: &Encoding) -> bool { +pub(super) fn is_valu32(enc: &Encoding) -> bool { matches!(enc.name, "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC") } -fn is_valu(enc: &Encoding) -> bool { +pub(super) fn is_valu(enc: &Encoding) -> bool { is_valu32(enc) || matches!(enc.name, "ENC_VOP3" | "ENC_VOP3P") } @@ -552,8 +552,12 @@ pub fn resolve_far_jumps(insts: &mut [Decoded]) { } pub fn mnemonic(d: &Decoded) -> String { - let mut m = d.inst.name.to_ascii_lowercase(); - match d.variant { + mnemonic_of(d.inst, d.variant) +} + +pub(super) fn mnemonic_of(inst: &Inst, variant: Variant) -> String { + let mut m = inst.name.to_ascii_lowercase(); + match variant { Variant::Sdwa => m.push_str("_sdwa"), Variant::Dpp16 => m.push_str("_dpp"), Variant::Dpp8 => m.push_str("_dpp8"), diff --git a/crates/xcl/src/gpu/rdna2_scan.rs b/crates/xcl/src/gpu/rdna2_scan.rs new file mode 100644 index 0000000000..239f7f2347 --- /dev/null +++ b/crates/xcl/src/gpu/rdna2_scan.rs @@ -0,0 +1,244 @@ +//! Walking RDNA2 code without decoding it: an instruction's length, opcode and direct branch +//! target, from tables made of the decoder's own (`rdna2_spec`, `rdna2_xbox`). +//! +//! `rdna2::decode` builds a `Decoded` (its words on the heap, operands by field name) for the +//! recompiler. Finding the programs of a console container (`xbox::parse`) and counting their +//! instructions (`xbox::InstStats`) need none of that, yet decoded every program three times: +//! 31 % of the samples of a retail game's running threads in its first 40 s. `step` answers as +//! `decode` does, instruction by instruction (`tests`). + +use std::sync::OnceLock; + +use super::rdna2::{self, Field, Inst, InstEnc, Variant, F_BRANCH, F_INDIRECT}; +use super::rdna2_spec::ENCODINGS; + +/// A field in the first 64 bits: the parts `((raw >> shift) & mask) << to`. +#[derive(Clone, Copy, Default)] +struct Bits([(u8, u16, u8); 2]); + +impl Bits { + fn of(f: &Field) -> Bits { + assert!(f.ranges.len() <= 2, "{}: more than two parts", f.name); + let (mut out, mut to) = (Bits::default(), 0u8); + for (part, &(off, n)) in out.0.iter_mut().zip(f.ranges) { + assert!(off + n <= 64 && to + n <= 16, "{}: past the first 64 bits, or wider than 16", f.name); + *part = (off, ((1u32 << n) - 1) as u16, to); + to += n; + } + out + } + + fn get(&self, raw: u64) -> u64 { + self.0.iter().fold(0, |v, &(shift, mask, to)| v | (raw >> shift & mask as u64) << to) + } +} + +/// One opcode of one encoding. +pub struct Op { + pub inst: &'static Inst, + /// the number of `inst` in `rdna2::all_instructions()` + pub index: usize, + pub getpc: bool, + pub setpc: bool, + base: u8, + /// VOP1 / VOP2 / VOPC: SRC0 may select an extension dword + src0: Option, + /// the fields that select a literal: (the field's bits, their value there); an unused one + /// never matches + literal: [(u64, u64); 4], + /// MIMG: extra address dwords + nsa: Option, + /// the offset of a direct branch (dwords, signed) + label: Option, +} + +/// A primary encoding: its opcodes are `slots[first + OP]`. +struct Enc { + mask: u64, + value: u64, + op: Bits, + first: usize, +} + +struct Tables { + /// the top 9 bits of the first dword → the encodings it may be, in the decoder's order + by_top: Vec>, + /// index in `ops`, or `NONE` + slots: Vec, + ops: Vec, +} + +const NONE: u16 = u16::MAX; + +fn make_op(inst: &'static Inst, index: usize, ie: &'static InstEnc) -> Op { + let enc = &ENCODINGS[ie.encoding as usize]; + let field = |n: &str| enc.field(n).map(Bits::of); + let mut sources: Vec<&str> = ie.operands.iter().filter(|o| !o.implicit && rdna2::is_src_type(o.ty)).filter_map(|o| o.field).collect(); + if rdna2::is_valu(enc) { + sources.extend(["SRC0", "SRC1", "SRC2"]); + } + sources.sort_unstable(); + sources.dedup(); + let mut literal = [(0, 1); 4]; + for (k, f) in sources.into_iter().filter_map(|n| enc.field(n)).enumerate() { + let &[(off, n)] = f.ranges else { panic!("{}: a source field in parts", f.name) }; + assert!(n >= 8 && off + n <= 64, "{}: cannot be 255", f.name); + literal[k] = (((1 << n) - 1) << off, 255 << off); + } + let direct = inst.flags & F_BRANCH != 0 && inst.flags & F_INDIRECT == 0; + Op { + inst, + index, + getpc: inst.name == "S_GETPC_B64", + setpc: inst.name == "S_SETPC_B64", + base: (enc.bits / 8) as u8, + src0: if rdna2::is_valu32(enc) { field("SRC0") } else { None }, + literal, + nsa: if enc.name == "ENC_MIMG" { field("NSA") } else { None }, + label: if direct { ie.operands.iter().find(|o| o.ty == "OPR_LABEL").and_then(|o| o.field).and_then(field) } else { None }, + } +} + +fn tables() -> &'static Tables { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| { + let mut primary: Vec = (0..ENCODINGS.len()).filter(|&i| ENCODINGS[i].primary).collect(); + primary.sort_by_key(|&i| ENCODINGS[i].order); + // where each encoding's opcodes start (one without an OP field has a single slot) + let mut first = vec![0usize; ENCODINGS.len()]; + let mut n = 0; + for &e in &primary { + first[e] = n; + n += 1 << ENCODINGS[e].field_width("OP"); + } + let (mut slots, mut ops) = (vec![NONE; n], Vec::new()); + for (index, inst) in rdna2::all_instructions().enumerate() { + for ie in inst.encs { + let e = ie.encoding as usize; + if !ENCODINGS[e].primary { + continue; + } + let op = if ENCODINGS[e].field("OP").is_some() { ie.opcode as usize } else { 0 }; + // (an opcode two instructions claim is the first one's) + if slots[first[e] + op] == NONE { + slots[first[e] + op] = ops.len() as u16; + ops.push(make_op(inst, index, ie)); + } + } + } + let of = |e: usize| Enc { + mask: ENCODINGS[e].fixed_mask, + value: ENCODINGS[e].fixed_value, + op: ENCODINGS[e].field("OP").map(Bits::of).unwrap_or_default(), + first: first[e], + }; + let by_top = (0..512u64) + .map(|top| primary.iter().copied().map(of).filter(|e| (top << 23 ^ e.value) & e.mask & 0xFF80_0000 == 0).collect()) + .collect(); + Tables { by_top, slots, ops } + }) +} + +/// An instruction as `rdna2::decode` would give it. +pub struct Step { + pub op: &'static Op, + pub variant: Variant, + pub len: usize, + raw: u64, +} + +impl Step { + /// `rdna2::branch_target` of the instruction at `pc`. + pub fn branch_target(&self, pc: u64) -> Option { + let v = self.op.label.as_ref()?.get(self.raw); + Some((pc as i64 + 4 + (v as u16 as i16 as i64) * 4) as u64) + } +} + +/// The instruction `code` starts with; None where `rdna2::decode` fails. +pub fn step(code: &[u8]) -> Option { + let word = |o: usize| code.get(o..o + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let w0 = word(0)?; + let raw = w0 as u64 | (word(4).unwrap_or(0) as u64) << 32; + let t = tables(); + let slot = |e: &Enc| t.slots[e.first + e.op.get(raw) as usize]; + let slot = t.by_top[(w0 >> 23) as usize].iter().filter(|e| raw & e.mask == e.value).map(slot).find(|&s| s != NONE)?; + let op = &t.ops[slot as usize]; + let variant = match op.src0.map(|f| f.get(raw)) { + Some(0xF9) => Variant::Sdwa, + Some(0xFA) => Variant::Dpp16, + Some(0xE9 | 0xEA) => Variant::Dpp8, + _ => Variant::Plain, + }; + let literal = op.inst.always_literal || variant == Variant::Plain && op.literal.iter().fold(false, |any, &(mask, value)| any | (raw & mask == value)); + let extra = (variant != Variant::Plain) as usize + literal as usize + op.nsa.map_or(0, |f| f.get(raw) as usize); + let len = op.base as usize + 4 * extra; + (len <= code.len()).then_some(Step { op, variant, len, raw }) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + fn check(code: &[u8]) { + match (step(code), rdna2::decode(code, 0x1000)) { + (Some(s), Ok(d)) => { + assert!(std::ptr::eq(s.op.inst, d.inst), "{} / {}: {code:02x?}", s.op.inst.name, d.inst.name); + assert!(std::ptr::eq(rdna2::all_instructions().nth(s.op.index).unwrap(), d.inst)); + assert_eq!((s.len, s.variant), (d.len, d.variant), "{}: {code:02x?}", d.inst.name); + assert_eq!(s.branch_target(0x1000), rdna2::branch_target(&d), "{}: {code:02x?}", d.inst.name); + assert_eq!((s.op.getpc, s.op.setpc), (d.inst.name == "S_GETPC_B64", d.inst.name == "S_SETPC_B64")); + } + (None, Err(_)) => {} + (s, d) => panic!("step {:?}, decode {:?}: {code:02x?}", s.map(|s| s.op.inst.name), d.map(|d| d.inst.name)), + } + } + + pub(crate) fn rng() -> impl FnMut() -> u64 { + let mut x = 0x9E37_79B9_7F4A_7C15u64; + move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + } + + /// Every opcode of every primary encoding, assigned or not, with random other bits and with + /// the source fields selecting an extension or a literal; whole and cut short. + #[test] + fn every_opcode_steps_as_it_decodes() { + let mut r = rng(); + for enc in ENCODINGS.iter().filter(|e| e.primary) { + let op = enc.field("OP").map(Bits::of).unwrap_or_default(); + for opcode in 0..1u64 << enc.field_width("OP") { + for k in 0..24u64 { + let mut raw = r() & !enc.fixed_mask | enc.fixed_value; + for (shift, mask, to) in op.0 { + raw = raw & !((mask as u64) << shift) | (opcode >> to & mask as u64) << shift; + } + let special = [255u64, 0xF9, 0xFA, 0xE9, 0xEA][k as usize % 5]; + for (i, n) in ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().enumerate() { + if let (Some(f), true) = (enc.field(n), k >> i & 1 == 1) { + let (off, cnt) = f.ranges[0]; + raw = raw & !(((1u64 << cnt) - 1) << off) | special << off; + } + } + let mut code = raw.to_le_bytes().to_vec(); + code.extend((0..4).flat_map(|_| (r() as u32).to_le_bytes())); + check(&code); + check(&code[..r() as usize % 24]); + } + } + } + } + + #[test] + fn random_dwords_step_as_they_decode() { + let mut r = rng(); + for _ in 0..100_000 { + let code: Vec = (0..3).flat_map(|_| r().to_le_bytes()).collect(); + check(&code); + } + } +} diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index 3986882b4b..35f6733e52 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -31,7 +31,7 @@ use serde::{Deserialize, Serialize}; -use super::rdna2; +use super::{rdna2, rdna2_scan}; use super::shader::container_parts; pub const XDAT_HASH: u32 = 0x12; @@ -352,6 +352,28 @@ fn analyze_fssm(f: &mut Fssm) { /// Static branch targets of a code segment (PCs in the same space as `pc`), far jumps included. fn branch_targets(seg: &[u8], pc: u64) -> Vec { + let mut out = Vec::new(); + let mut off = 0usize; + // bit n: the instruction n + 1 back is an s_getpc_b64 + let mut getpc = 0u32; + while off + 4 <= seg.len() { + let Some(s) = rdna2_scan::step(&seg[off..]) else { + off += 4; + continue; + }; + if s.op.setpc && getpc & 4 != 0 { + // where a far jump ends (`resolve_far_jumps`): its target is in the operands + return branch_targets_decoded(seg, pc); + } + getpc = getpc << 1 | s.op.getpc as u32; + out.extend(s.branch_target(pc + off as u64)); + off += s.len; + } + out +} + +/// `branch_targets` from whole decoded instructions. +fn branch_targets_decoded(seg: &[u8], pc: u64) -> Vec { let mut insts = Vec::new(); let mut off = 0usize; while off + 4 <= seg.len() { @@ -382,12 +404,12 @@ pub fn is_data_block(seg: &[u8]) -> bool { let mut off = 0usize; let (mut words, mut bad) = (0usize, 0usize); while off + 4 <= seg.len() { - match rdna2::decode(&seg[off..], off as u64) { - Ok(d) => { - words += d.len / 4; - off += d.len; + match rdna2_scan::step(&seg[off..]) { + Some(s) => { + words += s.len / 4; + off += s.len; } - Err(_) => { + None => { if off == 0 { return true; } @@ -470,20 +492,20 @@ pub fn split_segments(code: &[u8]) -> Vec { } let mut ended = false; while off + 4 <= code.len() { - match rdna2::decode(&code[off..], off as u64) { - Ok(d) => { - off += d.len; - if d.inst.flags & rdna2::F_TERMINATOR != 0 && word(off - d.len) == S_ENDPGM { + match rdna2_scan::step(&code[off..]) { + Some(s) => { + off += s.len; + if s.op.inst.flags & rdna2::F_TERMINATOR != 0 && word(off - s.len) == S_ENDPGM { ended = true; break; } // an ES that continues into its GS: the jump, then only padding - if is_setpc(word(off - d.len)) && (off..code.len()).step_by(4).all(|o| o + 4 > code.len() || matches!(word(o), S_CODE_END | 0)) { + if is_setpc(word(off - s.len)) && (off..code.len()).step_by(4).all(|o| o + 4 > code.len() || matches!(word(o), S_CODE_END | 0)) { ended = true; break; } } - Err(_) => off += 4, + None => off += 4, } } out.push(Segment { offset: start, len: off.min(code.len()) - start, counted_data: false }); @@ -494,6 +516,44 @@ pub fn split_segments(code: &[u8]) -> Vec { out } +/// Instructions counted by their number (`rdna2::all_instructions`) and variant: the names are +/// made once per mnemonic (`flush`), not per instruction. +#[derive(Default)] +struct InstCounts { + by_inst: Vec<[u64; 4]>, + instructions: u64, + undecoded: u64, +} + +impl InstCounts { + const VARIANTS: [rdna2::Variant; 4] = [rdna2::Variant::Plain, rdna2::Variant::Sdwa, rdna2::Variant::Dpp16, rdna2::Variant::Dpp8]; + + fn add_code(&mut self, code: &[u8]) { + self.by_inst.resize(rdna2::all_instructions().count(), [0; 4]); + let mut off = 0usize; + while off + 4 <= code.len() { + let Some(s) = rdna2_scan::step(&code[off..]) else { + self.undecoded += 1; + off += 4; + continue; + }; + self.instructions += 1; + self.by_inst[s.op.index][s.variant as usize] += 1; + off += s.len; + } + } + + fn flush(&self, to: &mut InstStats) { + to.instructions += self.instructions; + to.undecoded += self.undecoded; + for (inst, counts) in rdna2::all_instructions().zip(&self.by_inst) { + for (variant, &n) in Self::VARIANTS.into_iter().zip(counts).filter(|(_, &n)| n != 0) { + *to.by_mnemonic.entry(rdna2::mnemonic_of(inst, variant)).or_default() += n; + } + } + } +} + /// Instruction statistics for a set of programs. #[derive(Debug, Default, Clone)] pub struct InstStats { @@ -504,28 +564,19 @@ pub struct InstStats { impl InstStats { pub fn add_code(&mut self, code: &[u8]) { - let mut off = 0usize; - while off + 4 <= code.len() { - match rdna2::decode(&code[off..], off as u64) { - Ok(d) => { - self.instructions += 1; - *self.by_mnemonic.entry(rdna2::mnemonic(&d)).or_default() += 1; - off += d.len; - } - Err(_) => { - self.undecoded += 1; - off += 4; - } - } - } + let mut counts = InstCounts::default(); + counts.add_code(code); + counts.flush(self); } pub fn add_shader(&mut self, sh: &XboxShader) { + let mut counts = InstCounts::default(); for f in &sh.fssm { for p in &f.programs { - self.add_code(&f.data[p.offset..p.offset + p.len]); + counts.add_code(&f.data[p.offset..p.offset + p.len]); } } + counts.flush(self); } pub fn merge(&mut self, other: &InstStats) { @@ -841,3 +892,185 @@ mod merged_es_tests { assert!(is_setpc(0xBE80_2020) && !is_setpc(S_ENDPGM)); } } + +/// `rdna2_scan` against the same walks with `rdna2::decode`, as they were. +#[cfg(test)] +mod scan_tests { + use super::*; + use crate::gpu::rdna2_scan::tests::rng; + + /// (words, undecodable words) of `is_data_block`; instruction statistics + fn add_code_decoded(st: &mut InstStats, code: &[u8]) -> (usize, usize) { + let (mut words, mut bad, mut off) = (0, 0, 0); + while off + 4 <= code.len() { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + st.instructions += 1; + *st.by_mnemonic.entry(rdna2::mnemonic(&d)).or_default() += 1; + words += d.len / 4; + off += d.len; + } + Err(_) => { + st.undecoded += 1; + words += 1; + bad += 1; + off += 4; + } + } + } + (words, bad) + } + + fn split_segments_decoded(code: &[u8]) -> Vec { + let word = |o: usize| u32::from_le_bytes(code[o..o + 4].try_into().unwrap()); + let mut out: Vec = Vec::new(); + let mut off = 0usize; + loop { + while off + 4 <= code.len() && matches!(word(off), S_CODE_END | 0) { + off += 4; + } + if off + 4 > code.len() { + return out; + } + let start = off; + let end = start + 4 + 4 * word(start) as usize; + if !out.is_empty() && word(start) > 0 && end + 4 <= code.len() && word(end) == S_ENDPGM { + out.push(Segment { offset: start, len: end + 4 - start, counted_data: true }); + off = end + 4; + continue; + } + let mut ended = false; + while off + 4 <= code.len() && !ended { + match rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + let w = word(off); + off += d.len; + let rest = || (off..code.len()).step_by(4).all(|o| o + 4 > code.len() || matches!(word(o), S_CODE_END | 0)); + ended = d.inst.flags & rdna2::F_TERMINATOR != 0 && w == S_ENDPGM || is_setpc(w) && rest(); + } + Err(_) => off += 4, + } + } + out.push(Segment { offset: start, len: off.min(code.len()) - start, counted_data: false }); + if !ended { + return out; + } + } + } + + /// Dwords as code has them: instructions of every encoding, branches, program ends, counted + /// data, padding, far jumps and jumps that look like one. + fn code(r: &mut impl FnMut() -> u64, n: usize) -> Vec { + let mut v = Vec::new(); + while v.len() < n { + let k = r() as u32; + match r() % 32 { + 0 => le(&mut v, S_ENDPGM), + 1 => le(&mut v, [S_CODE_END, 0][k as usize & 1]), + 2 => { + le(&mut v, k % 5); + (0..k % 5).for_each(|_| le(&mut v, r() as u32)); + le(&mut v, S_ENDPGM); + } + // s_getpc_b64 s[8:9]; s_add_u32 s8, s8, c; s_addc_u32 s9, s9, 0; (s_nop;) s_setpc_b64 s[8:9] + 3 => { + for w in [0xBE88_1F00, 0x8008_8008 | (k % 64) << 8, 0x8209_8009] { + le(&mut v, w); + } + if k >> 8 & 1 == 1 { + le(&mut v, 0xBF80_0000); + } + le(&mut v, 0xBE80_2008); + } + 4 => le(&mut v, 0xBE80_2000 | k & 0x7F), + 5 | 6 => le(&mut v, 0xBF80_0000 | (k % 9 + 2) << 16 | (k >> 8) % 64), + 7 => le(&mut v, k), + 8..=15 => le(&mut v, k & 0x7FFF_FFFF), + 16..=19 => le(&mut v, 0x8000_0000 | k & 0x3FFF_FFFF), + _ => { + le(&mut v, 0xC000_0000 | k); + le(&mut v, r() as u32); + } + } + } + v + } + + fn le(v: &mut Vec, w: u32) { + v.extend_from_slice(&w.to_le_bytes()); + } + + #[test] + fn programs_and_statistics_are_as_decoded() { + let mut r = rng(); + let (mut far, mut data) = (0, 0); + for i in 0..3000 { + let c = code(&mut r, 8 + i % 600); + let c = &c[..c.len() - r() as usize % 4]; + let segs = split_segments(c); + assert_eq!(segs, split_segments_decoded(c)); + for s in &segs { + let seg = &c[s.offset..s.offset + s.len]; + let targets = branch_targets(seg, s.offset as u64); + assert_eq!(targets, branch_targets_decoded(seg, s.offset as u64)); + let (mut a, mut b) = (InstStats::default(), InstStats::default()); + a.add_code(seg); + let (words, bad) = add_code_decoded(&mut b, seg); + assert_eq!((a.instructions, a.undecoded, &a.by_mnemonic), (b.instructions, b.undecoded, &b.by_mnemonic)); + let first_bad = seg.len() >= 4 && rdna2::decode(seg, 0).is_err(); + assert_eq!(is_data_block(seg), counted_data_block(seg) || first_bad || bad * 4 >= words.max(1)); + data += is_data_block(seg) as usize; + far += seg.windows(16).step_by(4).filter(|w| w[..4] == 0xBE88_1F00u32.to_le_bytes() && w[12..] == 0xBE80_2008u32.to_le_bytes()).count(); + } + } + assert!(data > 100 && far > 100, "{data} data blocks, {far} far jumps"); + let jump = [0xBE88_1F00u32, 0x8008_A008, 0x8209_8009, 0xBE80_2008]; + let seg: Vec = jump.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert_eq!(branch_targets(&seg, 0x100), vec![0x100 + 4 + 32]); + } + + /// `cargo test --release -p xcl --lib scan_tests -- --ignored --nocapture` + #[test] + #[ignore] + fn bench_scan() { + let mut r = rng(); + // straight code: what a program mostly is (an s_endpgm only at its end) + let mut c = Vec::new(); + while c.len() < 4 << 20 { + let k = r(); + let w = match k % 8 { + 0..=2 => 0x0600_0100 | (k >> 8) as u32 & 0x01FF_FFFF, // VOP2 v_add_f32 + 3 => 0x7E00_0300 | (k >> 8) as u32 & 0x00FE_00FF, // VOP1 v_mov_b32 + 4 => 0x8780_0000 | (k >> 8) as u32 & 0x007F_7F7F, // SOP2 s_and_b64 + 5 => 0xBF8C_0000 | (k >> 8) as u32 & 0xFFFF, // s_waitcnt + 6 => 0xD54B_0000 | (k >> 8) as u32 & 0xFF, // VOP3 v_fma_f32 + _ => 0xF080_0F08 | (k >> 8) as u32 & 0x1000, // MIMG image_sample + }; + le(&mut c, w); + if k % 8 >= 6 { + le(&mut c, 0x0402_0100 | (k >> 32) as u32 & 0x03FF_FFFF); + } + } + le(&mut c, S_ENDPGM); + let mut n = InstStats::default(); + n.add_code(&c); + let n = n.instructions as f64; + let best = |f: &mut dyn FnMut()| { + (0..9).fold(f64::MAX, |m, _| { + let t = std::time::Instant::now(); + f(); + m.min(t.elapsed().as_secs_f64() * 1e9 / n) + }) + }; + let row = |what: &str, old: f64, new: f64| println!("{what}: {old:.1} -> {new:.2} ns / instruction ({:.0}x)", old / new); + row("split_segments", best(&mut || assert_eq!(split_segments_decoded(&c).len(), 1)), best(&mut || assert_eq!(split_segments(&c).len(), 1))); + let targets = |f: fn(&[u8], u64) -> Vec| assert!(f(&c, 0).is_empty()); + row("branch_targets", best(&mut || targets(branch_targets_decoded)), best(&mut || targets(branch_targets))); + let stats = |f: &dyn Fn(&mut InstStats)| { + let mut st = InstStats::default(); + f(&mut st); + assert_eq!(st.instructions as f64, n); + }; + row("instruction statistics", best(&mut || stats(&|st| assert_eq!(add_code_decoded(st, &c).1, 0))), best(&mut || stats(&|st| st.add_code(&c)))); + } +}