From ad5a6f9c53da5c93f114fc9fee9fa9972b582415 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:50:44 -0600 Subject: [PATCH 1/2] validation: operand-domain harness for SOP2 and VOPC forms (part of #215, stage E) The nine SOP2 forms and twelve VOPC integer compares had known answers for a few chosen inputs only. This harness generates their operand domains (boundary values, 64-bit carry and borrow chains observing both words, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC with VCC seeded to -1, VCCZ through s_cbranch_vccz, 32 distinct lane inputs) and runs each case on the reference interpreter and on native Metal against expectations written out from the public RDNA 2 guide in oracle.rs, which imports no Xenora crate. Rejections cover a missing literal word (as truncated) and encodings outside Xenora's subset (two literal selectors, VCC/TTMP/M0/ EXEC destinations, float inline constants), at the expected offset. 4788 cases and 498 rejections. Failures are listed per family. The Metal part compiles its 1777 distinct programs on four threads: 16 s with a cold shader cache on an M5 Pro, against 47 s on one thread. The oracle agrees with an independent guide-only table on 436 of 440 cases; the other 4 are s_subb_u32 with S1 = 0xffffffff and SCC set, where the guide leaves the width of S1 + SCC open. The oracle reads it at full width and keeps those cases in their own family. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- tests/validation/tests/operand_domains.rs | 65 ++++ .../tests/operand_domains/harness.rs | 203 ++++++++++++ .../tests/operand_domains/oracle.rs | 174 ++++++++++ .../validation/tests/operand_domains/sop2.rs | 302 ++++++++++++++++++ .../validation/tests/operand_domains/vopc.rs | 280 ++++++++++++++++ 5 files changed, 1024 insertions(+) create mode 100644 tests/validation/tests/operand_domains.rs create mode 100644 tests/validation/tests/operand_domains/harness.rs create mode 100644 tests/validation/tests/operand_domains/oracle.rs create mode 100644 tests/validation/tests/operand_domains/sop2.rs create mode 100644 tests/validation/tests/operand_domains/vopc.rs diff --git a/tests/validation/tests/operand_domains.rs b/tests/validation/tests/operand_domains.rs new file mode 100644 index 00000000..72aacbc0 --- /dev/null +++ b/tests/validation/tests/operand_domains.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Operand-domain verification for the supported SOP2 and VOPC forms (part of +//! #215, stage E). +//! +//! Every case runs three ways: the expected value written out below from the +//! public AMD "RDNA 2" Instruction Set Architecture Reference Guide, the +//! reference interpreter `xenora_ref`, and the translated MSL on native Metal. +//! The expected values come only from `oracle`, which imports nothing from the +//! ISA crate, the decoder, the shader compiler or the semantic registry, so a +//! mistake there cannot also produce the expectation. + +#[path = "operand_domains/harness.rs"] +mod harness; +#[path = "operand_domains/oracle.rs"] +mod oracle; +#[path = "operand_domains/sop2.rs"] +mod sop2; +#[path = "operand_domains/vopc.rs"] +mod vopc; + +use harness::{Case, Rejection}; + +fn cases() -> Vec { + let mut all = sop2::cases(); + all.extend(vopc::cases()); + all +} + +fn rejections() -> Vec { + let mut all = sop2::rejections(); + all.extend(vopc::rejections()); + all +} + +#[test] +fn operand_domains_match_the_guide_on_the_reference() { + let cases = cases(); + harness::assert_counts(&cases, sop2::COUNTS.iter().chain(vopc::COUNTS)); + harness::check_reference(&cases).assert_none("reference disagrees with the guide"); + eprintln!("operand_domains: {} reference cases", cases.len()); + harness::print_counts(&cases); +} + +#[test] +fn unsupported_and_truncated_operands_are_rejected() { + let rejections = rejections(); + assert_eq!(rejections.len(), sop2::REJECTIONS + vopc::REJECTIONS); + harness::check_rejected(&rejections).assert_none("not rejected as the guide requires"); + eprintln!("operand_domains: {} rejections", rejections.len()); +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation"] +fn operand_domains_match_the_guide_on_native_metal() { + assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1")); + assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1")); + let cases = cases(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!( + "operand_domains: {} native Metal cases ({programs} distinct programs)", + cases.len() + ); +} diff --git a/tests/validation/tests/operand_domains/harness.rs b/tests/validation/tests/operand_domains/harness.rs new file mode 100644 index 00000000..d263d3bb --- /dev/null +++ b/tests/validation/tests/operand_domains/harness.rs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Running a case on the reference and on Metal. The helpers mirror the ones in +//! `known_answers.rs` (copied, not shared, so that file stays untouched). + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use xenora_shader::{Architecture, CompileError, ENTRY_POINT, compile}; + +/// One program, its lane input and the guide's expected lane output. +pub struct Case { + pub form: &'static str, + pub family: &'static str, + pub label: String, + pub code: Vec, + pub input: Vec, + pub expected: Vec, +} + +/// A program every implementation must refuse, at byte `offset`: as truncated +/// when `truncated`, else as outside the supported subset. +pub struct Rejection { + pub family: &'static str, + pub truncated: bool, + pub label: String, + pub code: Vec, + pub offset: usize, +} + +pub fn words(code: &[u32]) -> Vec { + code.iter().copied().flat_map(u32::to_le_bytes).collect() +} + +/// The cases that failed, grouped by family: the count and the first message. +#[derive(Default)] +pub struct Failures(BTreeMap<&'static str, (usize, String)>); + +impl Failures { + fn record(&mut self, family: &'static str, message: String) { + let entry = self.0.entry(family).or_insert((0, message)); + entry.0 += 1; + } + + /// Panics with one line per failing family. + pub fn assert_none(&self, what: &str) { + let lines: Vec = self + .0 + .iter() + .map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}")) + .collect(); + assert!(lines.is_empty(), "{what}:\n{}", lines.join("\n")); + } +} + +pub fn check_reference(cases: &[Case]) -> Failures { + let mut failures = Failures::default(); + for case in cases { + let compiled = compile(Architecture::Gfx1030, &case.code); + let reference = xenora_ref::execute(&case.code, &case.input); + if compiled.is_err() { + failures.record(case.family, format!("{}: {compiled:?}", case.label)); + } else if reference.as_deref().ok() != Some(case.expected.as_slice()) { + let expected = &case.expected; + let message = format!("{}: {reference:?}, expected {expected:?}", case.label); + failures.record(case.family, message); + } + } + failures +} + +pub fn check_rejected(rejections: &[Rejection]) -> Failures { + let mut failures = Failures::default(); + for rejection in rejections { + if let Err(message) = rejected_at(rejection) { + failures.record(rejection.family, format!("{}: {message}", rejection.label)); + } + } + failures +} + +fn rejected_at(rejection: &Rejection) -> Result<(), String> { + let (compiler, compiler_truncated) = match compile(Architecture::Gfx1030, &rejection.code) { + Ok(_) => return Err("the compiler accepted it".into()), + Err(CompileError::Verify { offset, .. }) => (offset, false), + // The decoder crate is not a dependency of this package, so its + // `DecodeErrorKind::Truncated` variant is recognised by name. + Err(CompileError::Decode(decode)) => ( + decode.offset, + format!("{:?}", decode.kind).starts_with("Truncated "), + ), + Err(other) => return Err(format!("{other:?}")), + }; + let reference = match xenora_ref::execute(&rejection.code, &[0, 1]) { + Ok(_) => return Err("the reference accepted it".into()), + Err(error) => error, + }; + // The reference names a missing word "truncated ..."; its fall-through + // "unsupported or truncated ..." does not say which, and counts as unsupported. + let reference_truncated = reference.detail.starts_with("truncated"); + if compiler != rejection.offset || reference.offset != rejection.offset { + return Err(format!( + "compiler at {compiler:#x}, reference at {:#x}, expected {:#x}", + reference.offset, rejection.offset + )); + } + if compiler_truncated != rejection.truncated || reference_truncated != rejection.truncated { + return Err(format!( + "truncated: compiler {compiler_truncated}, reference {reference_truncated} ({}), \ + expected {}", + reference.detail, rejection.truncated + )); + } + Ok(()) +} + +/// Runs every case on Metal. Cases whose translated MSL and input are identical +/// are one program, so each distinct program runs once and its output is +/// compared with every case that shares it. The programs are spread over +/// `THREADS` threads, each with its own device queue, because pipeline +/// compilation dominates the run time. Returns the failures and the number of +/// programs. +pub fn check_metal(cases: &[Case]) -> (Failures, usize) { + const THREADS: usize = 4; + let mut programs = BTreeSet::new(); + let mut failures = Failures::default(); + let mut keys = Vec::with_capacity(cases.len()); + for case in cases { + match compile(Architecture::Gfx1030, &case.code) { + Ok(compiled) => { + let key = (compiled.msl, case.input.clone()); + programs.insert(key.clone()); + keys.push(Some(key)); + } + Err(error) => { + failures.record(case.family, format!("{}: {error:?}", case.label)); + keys.push(None); + } + } + } + let work: Vec<&(String, Vec)> = programs.iter().collect(); + let chunk = work.len().div_ceil(THREADS).max(1); + let outputs: HashMap<(String, Vec), Result, String>> = std::thread::scope(|s| { + let handles: Vec<_> = work + .chunks(chunk) + .map(|part| { + s.spawn(move || { + let metal = xenora_metal::NativeCompute::new().unwrap(); + part.iter() + .map(|&key| { + let output = metal + .run_words(&key.0, ENTRY_POINT, &key.1) + .map_err(|error| error.to_string()); + (key.clone(), output) + }) + .collect::>() + }) + }) + .collect(); + handles + .into_iter() + .flat_map(|handle| handle.join().unwrap()) + .collect() + }); + for (case, key) in cases.iter().zip(keys) { + let Some(key) = key else { continue }; + match &outputs[&key] { + Ok(output) if *output == case.expected => {} + Ok(output) => { + let expected = &case.expected; + let message = format!("{}: {output:?}, expected {expected:?}", case.label); + failures.record(case.family, message); + } + Err(error) => failures.record(case.family, format!("{}: {error}", case.label)), + } + } + (failures, outputs.len()) +} + +/// The number of cases in each family, which `expected` lists in full. +pub fn assert_counts<'a>( + cases: &[Case], + expected: impl Iterator, +) { + let expected: BTreeMap<_, _> = expected.map(|&(family, n)| (family, n)).collect(); + assert_eq!(tally(cases, |case| case.family), expected); +} + +pub fn print_counts(cases: &[Case]) { + for (name, n) in tally(cases, |case| case.form) { + eprintln!(" form {name}: {n}"); + } + for (name, n) in tally(cases, |case| case.family) { + eprintln!(" family {name}: {n}"); + } +} + +fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> { + let mut counts = BTreeMap::new(); + for case in cases { + *counts.entry(key(case)).or_default() += 1; + } + counts +} diff --git a/tests/validation/tests/operand_domains/oracle.rs b/tests/validation/tests/operand_domains/oracle.rs new file mode 100644 index 00000000..d94e22bc --- /dev/null +++ b/tests/validation/tests/operand_domains/oracle.rs @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Expected results transcribed from the AMD "RDNA 2" Instruction Set +//! Architecture Reference Guide (30 November 2020). Section numbers refer to +//! that guide. Nothing here comes from Xenora's own decoder, ISA tables, +//! compiler or semantic registry. + +/// The SOP2 forms under test with their opcode numbers (guide 12.1). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Sop2 { + AddU32 = 0, + SubU32 = 1, + AddI32 = 2, + SubI32 = 3, + AddcU32 = 4, + SubbU32 = 5, + AndB32 = 14, + OrB32 = 16, + XorB32 = 18, +} + +pub const SOP2_FORMS: [(Sop2, &str); 9] = [ + (Sop2::AddU32, "s_add_u32"), + (Sop2::SubU32, "s_sub_u32"), + (Sop2::AddI32, "s_add_i32"), + (Sop2::SubI32, "s_sub_i32"), + (Sop2::AddcU32, "s_addc_u32"), + (Sop2::SubbU32, "s_subb_u32"), + (Sop2::AndB32, "s_and_b32"), + (Sop2::OrB32, "s_or_b32"), + (Sop2::XorB32, "s_xor_b32"), +]; + +fn bit31(value: u32) -> bool { + value >> 31 == 1 +} + +/// D and SCC as guide 12.1 writes them; `scc` is the SCC value before the +/// instruction. The `>= 0x100000000ULL` tests are evaluated in 64 bits, as the +/// ULL constant says. +pub fn sop2(op: Sop2, s0: u32, s1: u32, scc: bool) -> (u32, bool) { + let (a, b, c) = (u64::from(s0), u64::from(s1), u64::from(scc)); + match op { + // D.u32 = S0.u32 + S1.u32; SCC = S0.u32 + S1.u32 >= 0x100000000ULL. + Sop2::AddU32 => (s0.wrapping_add(s1), a + b >= 0x1_0000_0000), + // D.u = S0.u - S1.u; SCC = (S1.u > S0.u). + Sop2::SubU32 => (s0.wrapping_sub(s1), s1 > s0), + // D.i = S0.i + S1.i; SCC = (S0.u[31] == S1.u[31] && S0.u[31] != D.u[31]). + Sop2::AddI32 => { + let d = s0.wrapping_add(s1); + (d, bit31(s0) == bit31(s1) && bit31(s0) != bit31(d)) + } + // D.i = S0.i - S1.i; SCC = (S0.u[31] != S1.u[31] && S0.u[31] != D.u[31]). + Sop2::SubI32 => { + let d = s0.wrapping_sub(s1); + (d, bit31(s0) != bit31(s1) && bit31(s0) != bit31(d)) + } + // D.u32 = S0.u32 + S1.u32 + SCC; SCC = S0.u32 + S1.u32 + SCC >= 0x100000000ULL. + Sop2::AddcU32 => ( + s0.wrapping_add(s1).wrapping_add(u32::from(scc)), + a + b + c >= 0x1_0000_0000, + ), + // D.u = S0.u - S1.u - SCC; SCC = (S1.u + SCC > S0.u), "unsigned overflow". + // The guide does not say whether S1.u + SCC wraps at 32 bits. It is read + // here at full width: only then does SCC report the borrow out of the + // subtraction, which the comment names. This decides only S1 = 0xffffffff + // with SCC set; `sop2::cases` keeps those in their own family. + Sop2::SubbU32 => (s0.wrapping_sub(s1).wrapping_sub(u32::from(scc)), b + c > a), + // D = S0 & S1, S0 | S1, S0 ^ S1; SCC = (D != 0). + Sop2::AndB32 => (s0 & s1, s0 & s1 != 0), + Sop2::OrB32 => (s0 | s1, s0 | s1 != 0), + Sop2::XorB32 => (s0 ^ s1, s0 ^ s1 != 0), + } +} + +/// Integer inline constants (guide 5.2, scalar source operand table): codes +/// 128-192 are 0..=64 and codes 193-208 are -1..=-16. +pub fn inline_integer(code: u32) -> Option { + match code { + 128..=192 => Some(code - 128), + 193..=208 => Some((192_i32 - code as i32) as u32), + _ => None, + } +} + +/// Literal constant code: one 32-bit word follows the instruction (guide 5.2). +pub const LITERAL: u32 = 255; + +/// The VOPC integer compares (guide 12.9): V_CMP_{LT,EQ,LE,GT,NE,GE}_I32 are +/// opcodes 129-134 and the _U32 forms 193-198. +#[derive(Clone, Copy, Debug)] +pub struct Compare { + pub opcode: u32, + pub name: &'static str, +} + +pub const COMPARES: [Compare; 12] = [ + Compare { + opcode: 129, + name: "v_cmp_lt_i32", + }, + Compare { + opcode: 130, + name: "v_cmp_eq_i32", + }, + Compare { + opcode: 131, + name: "v_cmp_le_i32", + }, + Compare { + opcode: 132, + name: "v_cmp_gt_i32", + }, + Compare { + opcode: 133, + name: "v_cmp_ne_i32", + }, + Compare { + opcode: 134, + name: "v_cmp_ge_i32", + }, + Compare { + opcode: 193, + name: "v_cmp_lt_u32", + }, + Compare { + opcode: 194, + name: "v_cmp_eq_u32", + }, + Compare { + opcode: 195, + name: "v_cmp_le_u32", + }, + Compare { + opcode: 196, + name: "v_cmp_gt_u32", + }, + Compare { + opcode: 197, + name: "v_cmp_ne_u32", + }, + Compare { + opcode: 198, + name: "v_cmp_ge_u32", + }, +]; + +/// "D[threadId] = (S0 < S1)" and so on (guide 12.9), with I32 operands read as +/// two's complement and U32 operands as unsigned (chapter 12 suffix rules). +pub fn compare(form: Compare, s0: u32, s1: u32) -> bool { + let signed = form.name.ends_with("_i32"); + let order = if signed { + (s0 as i32).cmp(&(s1 as i32)) + } else { + s0.cmp(&s1) + }; + match &form.name[6..8] { + "lt" => order.is_lt(), + "eq" => order.is_eq(), + "le" => order.is_le(), + "gt" => order.is_gt(), + "ne" => order.is_ne(), + "ge" => order.is_ge(), + other => unreachable!("{other}"), + } +} + +/// VCC for one Wave32 wave (guide 3.9): "VCC[n] = EXEC[n] & (test passed for +/// thread[n])", and "VCC is fully written", so inactive lanes read 0. +pub fn vcc(exec: u32, passed: impl Fn(usize) -> bool) -> u32 { + (0..32) + .filter(|&lane| exec >> lane & 1 == 1 && passed(lane)) + .fold(0, |mask, lane| mask | 1 << lane) +} diff --git a/tests/validation/tests/operand_domains/sop2.rs b/tests/validation/tests/operand_domains/sop2.rs new file mode 100644 index 00000000..417cf593 --- /dev/null +++ b/tests/validation/tests/operand_domains/sop2.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! SOP2 programs: the operands start in SGPRs (or as inline or literal +//! sources), SCC is set or cleared first, and the result reaches the output as +//! v2 = D, XORed with the lane input only when SCC is set afterwards. With the +//! lane input [0, 0xffffffff] the output is [D, D] or [D, !D]. + +use super::harness::{Case, Rejection, words}; +use super::oracle::{self, LITERAL, SOP2_FORMS, Sop2, sop2 as expect}; + +/// Boundary operands: zero, one, signed max/min and min + 1, unsigned max and +/// max - 1, and an ordinary pattern. +const VALUES: [u32; 8] = [ + 0, + 1, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fffe, + u32::MAX, + 0x1234_5678, +]; +const LITERALS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1234_5678]; +/// 64-bit operands for add/addc and sub/subb chains. +const WIDE: [u64; 6] = [ + 0, + 1, + 0xffff_ffff, + 0x1_0000_0000, + 0x8000_0000_0000_0000, + u64::MAX, +]; +const INPUT: [u32; 2] = [0, u32::MAX]; + +pub const COUNTS: &[(&str, usize)] = &[ + ("sop2 domain", 9 * 8 * 8 * 2 - 8), + ("sop2 subb full-width borrow", 8), + ("sop2 carry chain", 2 * 6 * 6 * 2 * 2), + ("sop2 aliasing", 9 * 5 * 2), + ("sop2 inline integer", 9 * 81 * 2), + ("sop2 literal", 9 * 6 * 2 * 2), + ("sop2 max register", 9 * 4), +]; +/// Two literals, 21 special destinations, 9 float inline codes in two slots, +/// and a missing literal word in two slots, for each of the 9 forms. +pub const REJECTIONS: usize = 9 * (1 + 21 + 9 * 2 + 2); +/// The SOP2 word's offset: load 8, wait 4, two literal moves 8 each, s_cmp 4. +const ALU_OFFSET: usize = 0x20; + +/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7 +/// (guide 13.1.1). +pub fn sop2(op: Sop2, dst: u32, src0: u32, src1: u32) -> u32 { + 0x8000_0000 | (op as u32) << 23 | dst << 16 | src1 << 8 | src0 +} + +/// `s_mov_b32 s, literal` (SOP1 opcode 3). +fn mov(reg: u32, value: u32) -> [u32; 2] { + [0xbe80_03ff | reg << 16, value] +} + +/// The program around `alu`: `init` sets SGPRs, SCC = `scc`, then `alu`, then +/// v2 = s, XORed with v1 when SCC is set. +fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec { + let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; + for &(reg, value) in init { + code.extend(mov(reg, value)); + } + // s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it. + code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 }); + code.extend(alu); + code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]); + code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]); + words(&code) +} + +fn lanes((d, scc): (u32, bool)) -> Vec { + vec![d, if scc { !d } else { d }] +} + +fn case( + form: &'static str, + family: &'static str, + label: String, + code: Vec, + out: (u32, bool), +) -> Case { + Case { + form, + family, + label: format!("{form} {label}"), + code, + input: INPUT.to_vec(), + expected: lanes(out), + } +} + +pub fn cases() -> Vec { + let mut cases = Vec::new(); + for (op, name) in SOP2_FORMS { + let alu = [sop2(op, 10, 8, 9)]; + for a in VALUES { + for b in VALUES { + for scc in [false, true] { + let family = if op == Sop2::SubbU32 && b == u32::MAX && scc { + "sop2 subb full-width borrow" + } else { + "sop2 domain" + }; + let code = program(&[(8, a), (9, b)], scc, &alu, 10); + cases.push(case( + name, + family, + format!("{a:#x}, {b:#x}, scc {scc}"), + code, + expect(op, a, b, scc), + )); + } + } + } + // dst/src aliasing, SCC set: (dst, src0, src1) with s8 = a, s9 = b. + for (a, b) in [(0xffff_fff0, 0x11), (0x8000_0000, 0x8000_0000)] { + for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] { + let pick = |reg| if reg == 8 { a } else { b }; + let code = program(&[(8, a), (9, b)], true, &[sop2(op, dst, src0, src1)], dst); + let out = expect(op, pick(src0), pick(src1), true); + cases.push(case( + name, + "sop2 aliasing", + format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})"), + code, + out, + )); + } + } + // Every integer inline constant in each source slot, s8 = 0xfffffff0, SCC set. + let a = 0xffff_fff0; + for code_point in (128..=208).filter_map(|c| oracle::inline_integer(c).map(|v| (c, v))) { + let (selector, value) = code_point; + for slot in 0..2 { + let (alu, out) = if slot == 0 { + (sop2(op, 10, selector, 8), expect(op, value, a, true)) + } else { + (sop2(op, 10, 8, selector), expect(op, a, value, true)) + }; + let code = program(&[(8, a), (9, 0)], true, &[alu], 10); + cases.push(case( + name, + "sop2 inline integer", + format!("inline {selector} ({value:#x}) slot {slot}"), + code, + out, + )); + } + } + // A literal word in each source slot, with SCC clear. + for a in [1, 0x8000_0000] { + for literal in LITERALS { + for slot in 0..2 { + let (alu, out) = if slot == 0 { + (sop2(op, 10, LITERAL, 8), expect(op, literal, a, false)) + } else { + (sop2(op, 10, 8, LITERAL), expect(op, a, literal, false)) + }; + let code = program(&[(8, a), (9, 0)], false, &[alu, literal], 10); + cases.push(case( + name, + "sop2 literal", + format!("literal {literal:#x} slot {slot}, s8 {a:#x}"), + code, + out, + )); + } + } + } + // s105, the highest SGPR a SOP2 operand may name (guide 5.2), as + // destination and source; s105 = a, s8 = s9 = b, SCC set. + let (a, b) = (0x8000_0001, u32::MAX); + for (dst, src0, src1) in [(105, 105, 9), (105, 8, 105), (105, 105, 105), (8, 105, 9)] { + let pick = |reg| if reg == 105 { a } else { b }; + let code = program( + &[(105, a), (8, b), (9, b)], + true, + &[sop2(op, dst, src0, src1)], + dst, + ); + let out = expect(op, pick(src0), pick(src1), true); + cases.push(case( + name, + "sop2 max register", + format!("s{dst} = s{src0}, s{src1}"), + code, + out, + )); + } + } + cases.extend(chains()); + cases +} + +/// 64-bit add and subtract built from the u32 forms: low word with +/// s_add_u32/s_sub_u32, high word with s_addc_u32/s_subb_u32 consuming its +/// SCC. SCC is preset both ways first to show the low form overwrites it. Each +/// chain runs twice, outputting the low word and then the high word, both with +/// the final SCC. The expected words and SCC follow the guide; they are also +/// checked against 64-bit arithmetic here. +fn chains() -> Vec { + let mut cases = Vec::new(); + for (low, high, name) in [ + (Sop2::AddU32, Sop2::AddcU32, "s_addc_u32"), + (Sop2::SubU32, Sop2::SubbU32, "s_subb_u32"), + ] { + for x in WIDE { + for y in WIDE { + for preset in [false, true] { + let (xl, xh, yl, yh) = (x as u32, (x >> 32) as u32, y as u32, (y >> 32) as u32); + let (d_low, carry) = expect(low, xl, yl, preset); + let (d_high, scc) = expect(high, xh, yh, carry); + let exact = if low == Sop2::AddU32 { + (x.wrapping_add(y), x.checked_add(y).is_none()) + } else { + (x.wrapping_sub(y), y > x) + }; + let joined = u64::from(d_high) << 32 | u64::from(d_low); + assert_eq!((joined, scc), exact, "{x:#x} {y:#x}"); + let alu = [sop2(low, 12, 8, 9), sop2(high, 13, 10, 11)]; + let init = [(8, xl), (9, yl), (10, xh), (11, yh)]; + for (word, d) in [("low", d_low), ("high", d_high)] { + let result = if word == "low" { 12 } else { 13 }; + cases.push(case( + name, + "sop2 carry chain", + format!("{x:#x}, {y:#x}, preset {preset}, {word} word"), + program(&init, preset, &alu, result), + (d, scc), + )); + } + } + } + } + } + cases +} + +pub fn rejections() -> Vec { + let mut rejections = Vec::new(); + let reject = |family, label: String, alu: &[u32]| Rejection { + family, + truncated: false, + label, + code: program(&[(8, 1), (9, 2)], false, alu, 10), + offset: ALU_OFFSET, + }; + for (op, name) in SOP2_FORMS { + // Both sources select the literal. The guide allows at most one literal + // constant per instruction; whether two selectors may share one word is + // not stated, and Xenora's subset rejects it. + rejections.push(reject( + "sop2 two literals", + format!("{name} two literals"), + &[sop2(op, 10, LITERAL, LITERAL), 3, 3], + )); + // VCC_LO, VCC_HI, TTMP0-15, M0, EXEC_LO, EXEC_HI as destination. The + // guide lists these as scalar destinations; Xenora's SOP2 subset writes + // only s0-s105, so these are rejections of the subset, not of the guide. + for dst in (106..=123).chain([124, 126, 127]) { + rejections.push(reject( + "sop2 special destination", + format!("{name} dst {dst}"), + &[sop2(op, dst, 8, 9)], + )); + } + // Float inline constants 0.5 .. -4.0 and 1/(2*pi) (codes 240-248). The + // guide defines them for every source; Xenora's subset rejects them for + // these integer forms. + for selector in 240..=248 { + rejections.push(reject( + "sop2 float inline", + format!("{name} float inline {selector} src0"), + &[sop2(op, 10, selector, 8)], + )); + rejections.push(reject( + "sop2 float inline", + format!("{name} float inline {selector} src1"), + &[sop2(op, 10, 8, selector)], + )); + } + // The stream ends where the literal word should be. + for (slot, alu) in [(0, sop2(op, 10, LITERAL, 8)), (1, sop2(op, 10, 8, LITERAL))] { + let mut code = program(&[(8, 1), (9, 2)], false, &[], 10); + code.truncate(ALU_OFFSET); + code.extend(alu.to_le_bytes()); + rejections.push(Rejection { + family: "sop2 missing literal", + truncated: true, + label: format!("{name} missing literal slot {slot}"), + code, + offset: ALU_OFFSET, + }); + } + } + rejections +} diff --git a/tests/validation/tests/operand_domains/vopc.rs b/tests/validation/tests/operand_domains/vopc.rs new file mode 100644 index 00000000..83bbd10c --- /dev/null +++ b/tests/validation/tests/operand_domains/vopc.rs @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! VOPC programs on one Wave32 wave: v1 = lane input, v3 (or v255) = a literal +//! `b`, an optional EXEC mask around the compare, then every lane outputs +//! VCC_LO. The 32 lane inputs are distinct, so a mask bit landing in the wrong +//! lane changes the output. +//! +//! Not covered: whether a compare also writes EXEC. The supported subset has +//! no instruction that reads EXEC back, so the EXEC cases restore it before +//! the output move. + +use super::harness::{Case, Rejection, words}; +use super::oracle::{COMPARES, Compare, LITERAL, compare, inline_integer, vcc}; + +/// Boundary operands, also the first ten lane inputs: zero, one, signed max - 1 +/// and max, signed min and min + 1, -16, unsigned max - 1 and max, and a +/// pattern. +const VALUES: [u32; 10] = [ + 0, + 1, + 0x7fff_fffe, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fff0, + 0xffff_fffe, + u32::MAX, + 0x0f0f_0f0f, +]; +/// The other 22 lane inputs: more values near the boundaries and patterns. +const MORE_LANES: [u32; 22] = [ + 2, + 3, + 15, + 16, + 63, + 64, + 65, + 0x7fff_fffd, + 0x8000_0002, + 0xffff_fffd, + 0xffff_ffef, + 0xffff_fff1, + 0x4000_0000, + 0xc000_0000, + 0x0000_ffff, + 0xffff_0000, + 0x1234_5678, + 0x8765_4321, + 0x00ff_00ff, + 0xff00_ff00, + 0x5555_5555, + 0xaaaa_aaaa, +]; +const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX]; +const EXEC_MASKS: [u32; 5] = [0, 0x5555_5555, 0xaaaa_aaaa, 0x8000_0001, 0x0000_ffff]; + +pub const COUNTS: &[(&str, usize)] = &[ + ("vopc domain", 12 * 10 * 2), + ("vopc aliasing", 12), + ("vopc inline integer", 12 * 81), + ("vopc literal", 12 * 5), + ("vopc sgpr source", 12 * 2 * 2), + ("vopc max register", 12 * 2), + ("vopc exec mask", 12 * 5), + ("vopc vccz", 12 * 11), +]; +/// A missing literal word and 9 float inline codes (defined by the guide, outside +/// Xenora's subset for integer compares), for each of the 12 forms. +pub const REJECTIONS: usize = 12 * (1 + 9); +/// The compare's offset: load 8, wait 4, v_mov with literal 8. +const COMPARE_OFFSET: usize = 0x14; + +/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8 +/// (guide 13.3.3); SRC0 256 + n is VGPR n. +fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 { + 0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0 +} + +const fn vgpr(n: u32) -> u32 { + 256 + n +} + +/// `v_mov_b32 v, literal` (VOP1 opcode 1). +fn vmov(reg: u32, value: u32) -> [u32; 2] { + [0x7e00_02ff | reg << 17, value] +} + +/// `s_mov_b32 vcc_lo, 0xffffffff`, so a compare that leaves bits untouched +/// shows up. +const SEED_VCC: [u32; 2] = [0xbeea_03ff, u32::MAX]; +/// `s_mov_b32 exec_lo, literal` and `s_mov_b32 exec_lo, -1`. +const SET_EXEC: u32 = 0xbefe_03ff; +const FULL_EXEC: u32 = 0xbefe_03c1; +/// After v2 = VCC_LO: `s_cbranch_vccz` over `v_xor_b32 v2, v1, v2`. +const VCCZ_TAIL: [u32; 2] = [0xbf86_0001, 0x3a04_0501]; + +/// Load v1, v = b, then `before`, the compare words, `after`, and every +/// lane outputs VCC_LO. +fn program(breg: u32, b: u32, before: &[u32], compare: &[u32], after: &[u32]) -> Vec { + program_with_tail(breg, b, before, compare, after, &[]) +} + +/// As `program`, with `tail` between the output move and the store. +fn program_with_tail( + breg: u32, + b: u32, + before: &[u32], + compare: &[u32], + after: &[u32], + tail: &[u32], +) -> Vec { + let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; + code.extend(vmov(breg, b)); + code.extend(before); + code.extend(compare); + code.extend(after); + code.push(0x7e04_026a); + code.extend(tail); + code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]); + words(&code) +} + +fn lanes() -> Vec { + VALUES.iter().chain(&MORE_LANES).copied().collect() +} + +fn case(form: Compare, family: &'static str, label: String, code: Vec, mask: u32) -> Case { + Case { + form: form.name, + family, + label: format!("{} {label}", form.name), + code, + input: lanes(), + expected: vec![mask; 32], + } +} + +pub fn cases() -> Vec { + let input = lanes(); + let all = u32::MAX; + let mut cases = Vec::new(); + for form in COMPARES { + let op = form.opcode; + for b in VALUES { + let code = program(3, b, &[], &[vopc(op, vgpr(1), 3)], &[]); + let mask = vcc(all, |n| compare(form, input[n], b)); + cases.push(case(form, "vopc domain", format!("v1, {b:#x}"), code, mask)); + let code = program(3, b, &[], &[vopc(op, vgpr(3), 1)], &[]); + let mask = vcc(all, |n| compare(form, b, input[n])); + cases.push(case(form, "vopc domain", format!("{b:#x}, v1"), code, mask)); + } + let code = program(3, 0, &[], &[vopc(op, vgpr(1), 1)], &[]); + let mask = vcc(all, |n| compare(form, input[n], input[n])); + cases.push(case(form, "vopc aliasing", "v1, v1".into(), code, mask)); + for selector in 128..=208 { + let value = inline_integer(selector).unwrap(); + let code = program(3, 0, &[], &[vopc(op, selector, 1)], &[]); + let mask = vcc(all, |n| compare(form, value, input[n])); + cases.push(case( + form, + "vopc inline integer", + format!("inline {selector} ({value:#x})"), + code, + mask, + )); + } + for literal in LITERALS { + let code = program(3, 0, &[], &[vopc(op, LITERAL, 1), literal], &[]); + let mask = vcc(all, |n| compare(form, literal, input[n])); + cases.push(case( + form, + "vopc literal", + format!("literal {literal:#x}"), + code, + mask, + )); + } + // SGPR source s8 and s105, the highest SGPR (guide 5.2). + for reg in [8, 105] { + for value in [0x8000_0000, 0xffff_fff0] { + let set = [0xbe80_03ff | reg << 16, value]; + let code = program(3, 0, &set, &[vopc(op, reg, 1)], &[]); + let mask = vcc(all, |n| compare(form, value, input[n])); + cases.push(case( + form, + "vopc sgpr source", + format!("s{reg} = {value:#x}"), + code, + mask, + )); + } + } + // v255, the highest VGPR, in each slot. + let b = 0x8000_0001; + let code = program(255, b, &[], &[vopc(op, vgpr(1), 255)], &[]); + let mask = vcc(all, |n| compare(form, input[n], b)); + cases.push(case( + form, + "vopc max register", + "v1, v255".into(), + code, + mask, + )); + let code = program(255, b, &[], &[vopc(op, vgpr(255), 1)], &[]); + let mask = vcc(all, |n| compare(form, b, input[n])); + cases.push(case( + form, + "vopc max register", + "v255, v1".into(), + code, + mask, + )); + // Partial and empty EXEC around the compare, with VCC_LO = -1 before + // it, so inactive lanes must be cleared ("VCC is fully written"); + // EXEC_LO = -1 again before the output move so every lane stores VCC_LO. + let b = 0x8000_0000; + for exec in EXEC_MASKS { + let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, exec]; + let code = program(3, b, &before, &[vopc(op, vgpr(1), 3)], &[FULL_EXEC]); + let mask = vcc(exec, |n| compare(form, input[n], b)); + cases.push(case( + form, + "vopc exec mask", + format!("exec {exec:#x}"), + code, + mask, + )); + } + // VCCZ after the compare (guide 3.9: VCCZ is VCC == 0), read with + // s_cbranch_vccz: lanes output VCC_LO when it is zero, else input ^ VCC_LO. + let vccz = |mask: u32| -> Vec { + if mask == 0 { + vec![0; 32] + } else { + input.iter().map(|lane| lane ^ mask).collect() + } + }; + for b in VALUES { + let code = program_with_tail(3, b, &[], &[vopc(op, vgpr(1), 3)], &[], &VCCZ_TAIL); + let mask = vcc(all, |n| compare(form, input[n], b)); + let mut case = case(form, "vopc vccz", format!("v1, {b:#x}"), code, mask); + case.expected = vccz(mask); + cases.push(case); + } + let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, 0]; + let compare_words = [vopc(op, vgpr(1), 3)]; + let code = program_with_tail(3, 0, &before, &compare_words, &[FULL_EXEC], &VCCZ_TAIL); + let mut case = case(form, "vopc vccz", "exec 0".into(), code, 0); + case.expected = vccz(0); + cases.push(case); + } + cases +} + +pub fn rejections() -> Vec { + let mut rejections = Vec::new(); + for form in COMPARES { + let mut code = program(3, 0, &[], &[], &[]); + code.truncate(COMPARE_OFFSET); + code.extend(vopc(form.opcode, LITERAL, 1).to_le_bytes()); + rejections.push(Rejection { + family: "vopc missing literal", + truncated: true, + label: format!("{} missing literal", form.name), + code, + offset: COMPARE_OFFSET, + }); + for selector in 240..=248 { + rejections.push(Rejection { + family: "vopc float inline", + truncated: false, + label: format!("{} float inline {selector}", form.name), + code: program(3, 0, &[], &[vopc(form.opcode, selector, 1)], &[]), + offset: COMPARE_OFFSET, + }); + } + } + rejections +} From 791b736b0ecd9e183975b0f1b9bee99024ac93c0 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:51:06 -0600 Subject: [PATCH 2/2] changelog: note the operand-domain verification harness (#215 stage E) Contributors need to know the harness exists, what it covers and that its expectations are spec-derived, not hardware results. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f92ec2c6..05c80425 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ remains unsupported. ### Added +- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family. - Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B. - Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved. - Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.