Merge commit '2914ee3' into task/215-vop3-int

This commit is contained in:
elforeign committed 2026-11-24 08:39:30 -06:00
commit 596af4b2c9
4 files changed
+669 -27

No files matched your search

+72 -9
View File
@@ -57,6 +57,8 @@ pub enum Op {
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// VOP3A integer compare writing a Wave32 mask to SDST.
CompareVop3(u8, Comparison, CompareSource, u8),
/// SOP2 operation writing an SGPR and SCC.
Scalar(ScalarAlu, u8, Source, Source),
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
@@ -134,6 +136,8 @@ pub enum BranchCondition {
SccZero,
/// Take the branch when the low half of VCC is clear.
VccZero,
/// Take the branch when the low half of VCC is nonzero.
VccNonzero,
/// Take the branch when the low half of EXEC is clear.
ExecZero,
}
@@ -539,7 +543,13 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
left_length.max(right_length),
)
}
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
[
lo,
hi,
opcode @ (0x82 | 0x84 | 0x86 | 0x87 | 0x88),
0xbf,
..,
] => {
let words = i16::from_le_bytes([*lo, *hi]);
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
(
@@ -548,6 +558,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
condition: match opcode {
0x84 => BranchCondition::SccZero,
0x86 => BranchCondition::VccZero,
0x87 => BranchCondition::VccNonzero,
0x88 => BranchCondition::ExecZero,
_ => BranchCondition::Always,
},
@@ -575,9 +586,50 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let src1 = (second >> 1) | ((third & 1) << 7);
(Op::Vector(kind, dst, *first, src1), 4)
}
[dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => {
// Guide §§12.7.1, 12.9.1, 12.12 and 13.3.4: VOP3A extends
// VOP2 by 0x100 and preserves the VOPC opcode. This subset
// fixes unused SRC2 to inline 0 and excludes FP ABS/NEG/OMOD,
// halfword OP_SEL, and CLAMP (integer saturation or FP compare
// exceptions, §6.5).
[
dst,
0,
op,
tag @ (0xd4 | 0xd5),
lo,
middle,
hi @ 2..=3,
0x02,
..,
] if middle & 1 != 0 => {
let src0 = CompareSource::Vector(*lo);
let src1 = (middle >> 1) | ((hi & 1) << 7);
(Op::Add(*dst, *lo, src1), 8)
match tag {
0xd4 if matches!(op, 128..=135 | 192..=199) && *dst <= 106 => (
Op::CompareVop3(
*dst,
Comparison {
offset: op & 7,
signed: *op < 192,
},
src0,
src1,
),
8,
),
0xd5 if *op == 37 => (Op::Add(*dst, *lo, src1), 8),
0xd5 => (
Op::VectorInteger(
VectorInteger::from_opcode(*op)
.ok_or_else(|| error(offset, "unsupported VOP3 opcode"))?,
*dst,
src0,
src1,
),
8,
),
_ => return Err(error(offset, "unsupported VOP3 opcode or destination")),
}
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
@@ -1109,7 +1161,11 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(comparison, src0, src1) => {
Op::Compare(comparison, src0, src1) | Op::CompareVop3(_, comparison, src0, src1) => {
let dst = match op {
Op::CompareVop3(dst, ..) => usize::from(dst),
_ => VCC_LO,
};
let mut mask = 0u32;
if exec != 0 {
// Sources are checked once for the wave, even if no present lane is active.
@@ -1137,18 +1193,24 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
}
scalars[VCC_LO] = Some(mask);
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
scalars[dst] = Some(mask);
if dst == VCC_LO {
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
}
}
Op::Branch {
target: destination,
condition,
} => {
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
let tests_vcc = matches!(
condition,
BranchCondition::VccZero | BranchCondition::VccNonzero
);
if tests_vcc && scalars[VCC_LO].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if condition == BranchCondition::VccZero && lane_derived_vcc {
if tests_vcc && lane_derived_vcc {
check_runtime_region(
&program[position + 1..],
destination,
@@ -1165,6 +1227,7 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
}
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
BranchCondition::VccNonzero => scalars[VCC_LO] != Some(0),
BranchCondition::ExecZero => exec == 0,
};
if take_branch {
+49 -18
View File
@@ -20,7 +20,7 @@
//! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32,
//! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a
//! shift-and-add multiplier and floor division for the high half, the ripple
//! adder for add and subtract), VOP3 add-no-carry, MUBUF
//! adder for add and subtract), VOP3A integer arithmetic and compares, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
//! error. The arithmetic shift is evaluated as a floor division by a power of
//! two rather than with a host signed shift, so the oracle does not share the
@@ -66,17 +66,19 @@ enum Insn {
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
SCmp(u32, Src, Src),
BranchScc0(usize),
BranchMaskZero {
BranchMask {
target: usize,
register: usize,
nonzero: bool,
},
Branch(usize),
VMov(u8, Src),
VMovFromSgpr(u8, u8),
/// `v_mov_b32_e32 vD, vcc_lo`.
VMovFromVcc(u8),
/// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// Integer vector compare: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
VCmp {
dst: u8,
relation: u8,
signed: bool,
src0: CmpSrc,
@@ -194,6 +196,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
return Ok(lanes.iter().map(|lane| lane.written.unwrap()).collect());
}
Insn::VCmp {
dst,
relation,
signed,
src0,
@@ -212,10 +215,12 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
offset,
)
.map(|mask| {
sgpr[106] = Some(mask);
// VCC_HI has no known value after a compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
sgpr[usize::from(dst)] = Some(mask);
if dst == 106 {
// VCC_HI has no known value after a VCC compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
}
None
})
}
@@ -264,12 +269,17 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
index_of(program, target, offset).map(Some)
}
}),
Insn::BranchMaskZero { target, register } => {
Insn::BranchMask {
target,
register,
nonzero,
} => {
let takes = |mask| (mask != 0) == nonzero;
if register == 106 && vcc_lane_derived {
let live = lanes.iter().find(|lane| lane.error.is_none()).unwrap();
check_runtime_region(program, pc, target, live, &sgpr, execution_mask, offset)
.and_then(|()| {
if sgpr[106] == Some(0) {
if takes(sgpr[106].unwrap()) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -279,7 +289,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
sgpr[register]
.ok_or_else(|| format!("{offset:#x}: uninitialized mask"))
.and_then(|mask| {
if mask == 0 {
if takes(mask) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -540,7 +550,7 @@ fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
lane.vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
}
/// Evaluate one VOPC compare for the whole wave and return the new VCC_LO.
/// Evaluate one integer vector compare for the whole wave and return its mask.
fn compare(
lanes: &[Lane],
sgpr: &[Option<u32>; 128],
@@ -985,7 +995,7 @@ fn decode(code: &[u8]) -> Result<Vec<(usize, Insn)>, String> {
offset += len;
}
for &(at, insn) in &program {
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMaskZero { target, .. } =
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMask { target, .. } =
insn
&& !program.iter().any(|(boundary, _)| *boundary == target)
{
@@ -1049,6 +1059,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
};
let (src0, len) = vector_src0(code, offset, first, "VOPC")?;
let insn = Insn::VCmp {
dst: 106,
relation: relation as u8,
signed,
src0,
@@ -1063,14 +1074,33 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8);
return Ok((insn, len));
}
if first & 0xffff_0000 == 0xd525_0000 {
let second = word(code, offset + 4)?;
if first >> 26 == 0b110101 {
let dst = first as u8;
let opcode = (first >> 16) & 0x3ff;
let second = word(code, offset + 4).map_err(|_| fail("truncated VOP3A"))?;
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(fail("bad VOP3 add form"));
return Err(fail("unsupported VOP3A modifiers or sources"));
}
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
// Guide §§3.9, 12.7.1 and 12.9.1: re-encoded VOP2 writes a VGPR,
// while VOPC uses the destination field for the scalar mask.
let (src0, src1) = (src0 as u8, src1 as u8);
let insn = match opcode {
128..=135 | 192..=199 if dst <= 106 => Insn::VCmp {
dst,
relation: (opcode % 8) as u8,
signed: opcode < 192,
src0: CmpSrc::Vgpr(src0),
src1,
},
293 => Insn::VAddNc(dst, src0, src1),
265..=268 | 273..=276 | 286 | 294..=295 => {
Insn::VInt(opcode - 256, dst, CmpSrc::Vgpr(src0), src1)
}
_ => return Err(fail("unsupported VOP3A opcode or destination")),
};
return Ok((insn, 8));
}
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
let sop1_op = (first >> 8) & 0xff;
@@ -1146,15 +1176,16 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::BranchScc0(branch_target(first, offset)?), 4));
}
let tested_register = match first >> 16 {
0xbf86 => Some(106),
0xbf86 | 0xbf87 => Some(106),
0xbf88 => Some(126),
_ => None,
};
if let Some(register) = tested_register {
return Ok((
Insn::BranchMaskZero {
Insn::BranchMask {
target: branch_target(first, offset)?,
register,
nonzero: first >> 16 == 0xbf87,
},
4,
));
+302
View File
@@ -0,0 +1,302 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer compares. Guide §3.9 permits an SGPR destination in
//! the 64-bit encoding and describes the fully rewritten per-lane mask.
//! A Wave32 mask has 32 bits (§2.1), so SDST consumes one 32-bit SGPR (§5.2).
//! The opcode relations are in §12.9, the re-encoding in §12.9.1, and the
//! VOP3A fields in §13.3.4. These are spec-derived expectations.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 16] = [
(128, "v_cmp_f_i32"),
(129, "v_cmp_lt_i32"),
(130, "v_cmp_eq_i32"),
(131, "v_cmp_le_i32"),
(132, "v_cmp_gt_i32"),
(133, "v_cmp_ne_i32"),
(134, "v_cmp_ge_i32"),
(135, "v_cmp_t_i32"),
(192, "v_cmp_f_u32"),
(193, "v_cmp_lt_u32"),
(194, "v_cmp_eq_u32"),
(195, "v_cmp_le_u32"),
(196, "v_cmp_gt_u32"),
(197, "v_cmp_ne_u32"),
(198, "v_cmp_ge_u32"),
(199, "v_cmp_t_u32"),
];
const VALUES: [u32; 10] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
0x00ff_ffff,
0x0080_0000,
0xff80_0000,
0x0100_0001,
0xff00_0003,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn passes(op: u32, a: u32, b: u32) -> bool {
let operand = |value: u32| {
if op < 192 {
i64::from(value as i32)
} else {
i64::from(value)
}
};
let (a, b) = (operand(a), operand(b));
match op & 7 {
// D[threadId] = 0.
0 => false,
// D[threadId] = (S0 < S1).
1 => a < b,
// D[threadId] = (S0 == S1).
2 => a == b,
// D[threadId] = (S0 <= S1).
3 => a <= b,
// D[threadId] = (S0 > S1).
4 => a > b,
// D[threadId] = (S0 <> S1).
5 => a != b,
// D[threadId] = (S0 >= S1).
6 => a >= b,
// D[threadId] = 1.
_ => true,
}
}
fn expected_mask(op: u32, exec: u32, wave: &[u32], bound: u32, reverse: bool) -> u32 {
// §3.9: VCC[n] = EXEC[n] & (test passed for thread[n]).
// §3.9 uses the same result for the alternate scalar destination.
wave.iter().enumerate().fold(0, |mask, (n, &x)| {
let (a, b) = if reverse { (bound, x) } else { (x, bound) };
mask | (exec & (u32::from(passes(op, a, b)) << n))
})
}
fn vop3(op: u32, dst: u32, reverse: bool) -> [u32; 2] {
let (a, b) = if reverse { (511, 257) } else { (257, 511) };
[0xd400_0000 | op << 16 | dst, a | b << 9 | 128 << 18]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(bound: u32, exec: u32) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend([0x7ffe_02ff, bound]); // v255 = literal
code.extend(smov(126, exec));
code
}
fn store(mut code: Vec<u32>) -> Vec<u8> {
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn mask_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for bound in VALUES {
for reverse in [false, true] {
for exec in MASKS {
for (lanes, dst) in [(7, 106), (32, 106), (45, 106), (45, 0), (45, 105)] {
let mut code = setup(bound, exec);
// Give the old VCC bits on both sides of EXEC.
code.extend(smov(106, 0xa5a5_5a5a));
code.extend(vop3(op, dst, reverse));
code.extend([0xbefe_03c1, 0x7e04_0200 | dst]);
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.chunks(32)
.flat_map(|wave| {
let mask = expected_mask(op, exec, wave, bound, reverse);
std::iter::repeat_n(mask, wave.len())
})
.collect();
cases.push(Case {
form: name,
family: if dst == 106 { "vcc_lo" } else { "sgpr" },
label: format!("{name} s{dst}, bound={bound:#x}, reverse={reverse}, EXEC={exec:#x}, {lanes} lanes"),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
fn branch_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for dst in [0, 105, 106] {
for exec in MASKS {
for old_vcc in [0, 0xa5a5_5a5a] {
for nonzero in [false, true] {
let scc = old_vcc != 0;
let mut code = setup(0, u32::MAX);
// Seed s1 to detect an accidental second SGPR write to s0:s1.
code.extend(vop3(199, 1, false));
code.extend(smov(106, old_vcc));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend([0x7e04_0280, 0x7e08_0280, 0x7e0c_0284]); // v2 = v4 = 0, v6 = 4
code.extend(smov(126, exec));
code.extend(vop3(op, dst, false));
code.extend([
0x7e08_0281, // v4 = 1 only where EXEC was set
0xbefe_03c1,
// Independent bits for the VCC edge, SCC, and EXEC.
if nonzero { 0xbf87_0001 } else { 0xbf86_0001 },
0x7e04_0282, // v2 = 2 on fallthrough
0xbf84_0001,
0x3a04_0d02, // v2 ^= 4 if SCC = 1
0x3a04_0902, // v2 ^= v4
0x7e06_0201,
0x3a04_0702, // v2 ^= s1
0x7e06_026a,
0x3a04_0702, // v2 ^= VCC_LO
]);
// The two waves give opposite results for several relations.
let input: Vec<_> = std::iter::repeat_n(1, 32)
.chain(std::iter::repeat_n(u32::MAX, 13))
.collect();
let mut expected = Vec::new();
for wave in input.chunks(32) {
let mask = expected_mask(op, exec, wave, 0, false);
let vcc = if dst == 106 { mask } else { old_vcc };
// §12.5: if (VCC == 0) / if (VCC != 0), PC = PC + signext(SIMM16 * 4) + 4.
let taken = (vcc != 0) == nonzero;
let s1 = u32::MAX >> (32 - wave.len());
let marker = (u32::from(scc) << 2) | (u32::from(!taken) << 1);
expected.extend(
wave.iter()
.enumerate()
.map(|(n, _)| marker ^ ((exec >> n) & 1) ^ s1 ^ vcc),
);
}
cases.push(Case {
form: name,
family: "vcc branch and flags",
label: format!(
"{name} s{dst}, EXEC={exec:#x}, VCC={old_vcc:#x}, NZ={nonzero}"
),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_compare_matches_the_guide() {
let masks = mask_cases();
let branches = branch_cases();
assert_eq!(masks.len(), 16 * 10 * 2 * 4 * 5);
assert_eq!(branches.len(), 16 * 3 * 4 * 2 * 2);
for case in masks.iter().chain(&branches) {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!(
"vop3_compare: {} mask and {} branch/flag cases per CPU interpreter",
masks.len(),
branches.len()
);
}
#[test]
fn vop3_compare_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 106, false);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
// A successful decode would read its mask here and complete.
code.push(0x7e04_026a);
store(code)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
for dst in 107..=255 {
check(&[(head & !255) | dst, tail]);
}
check(&[head]);
}
assert_eq!(count, 16 * (13 + 512 + 511 + 149 + 1));
eprintln!("vop3_compare: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires native Metal and the VOP3A compiler implementation"]
fn vop3_vcc_compare_matches_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: Vec<_> = mask_cases()
.into_iter()
.filter(|case| case.family == "vcc_lo")
.collect();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop3_compare: {} Metal cases in {programs} programs",
cases.len()
);
}
+246
View File
@@ -0,0 +1,246 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer ALU forms. AMD RDNA 2 ISA guide §§12.7, 12.7.1,
//! 12.12 and 13.3.4. The expectations use the guide's arithmetic per lane.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 11] = [
(265, "v_mul_i32_i24"),
(266, "v_mul_hi_i32_i24"),
(267, "v_mul_u32_u24"),
(268, "v_mul_hi_u32_u24"),
(273, "v_min_i32"),
(274, "v_max_i32"),
(275, "v_min_u32"),
(276, "v_max_u32"),
(286, "v_xnor_b32"),
(294, "v_sub_nc_u32"),
(295, "v_subrev_nc_u32"),
];
const VALUES: [u32; 12] = [
0,
1,
2,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
0x00ff_ffff,
0xff80_0000,
0xff00_0003,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn expected(op: u32, a: u32, b: u32) -> u32 {
// S.i24 is bits 23:0 sign-extended from bit 23; S.u24 is zero-extended.
let i24 = |x: u32| (i64::from(x & 0x7f_ffff)) - i64::from(x & 0x80_0000);
let u24 = |x: u32| i64::from(x & 0xff_ffff);
match op {
// D.i32 = S0.i24 * S1.i24.
265 => (i24(a) * i24(b)) as u32,
// D.i32 = (S0.i24 * S1.i24)>>32.
266 => (i24(a) * i24(b)).div_euclid(1 << 32) as u32,
// D.u32 = S0.u24 * S1.u24.
267 => (u24(a) * u24(b)) as u32,
// D.u32 = (S0.u24 * S1.u24)>>32.
268 => (u24(a) * u24(b)).div_euclid(1 << 32) as u32,
// D.i32 = (S0.i32 < S1.i32 ? S0.i32 : S1.i32).
273 => (a as i32).min(b as i32) as u32,
// D.i32 = (S0.i32 >= S1.i32 ? S0.i32 : S1.i32).
274 => (a as i32).max(b as i32) as u32,
// D.u32 = (S0.u32 < S1.u32 ? S0.u32 : S1.u32).
275 => a.min(b),
// D.u32 = (S0.u32 >= S1.u32 ? S0.u32 : S1.u32).
276 => a.max(b),
// D.u32 = ~(S0.u32 ^ S1.u32).
286 => !(a ^ b),
// D.u32 = S0.u32 - S1.u32.
294 => (i64::from(a) - i64::from(b)) as u32,
// D.u32 = S1.u32 - S0.u32.
295 => (i64::from(b) - i64::from(a)) as u32,
_ => unreachable!("test only uses the listed forms"),
}
}
/// VOP3A: OP 25:16, VDST 7:0, three 9-bit sources, inline zero at SRC2.
fn vop3(op: u32, dst: u32, a: u32, b: u32) -> [u32; 2] {
[
0xd400_0000 | op << 16 | dst,
(256 + a) | (256 + b) << 9 | 128 << 18,
]
}
fn vmov(dst: u32, value: u32) -> [u32; 2] {
[0x7e00_02ff | dst << 17, value]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(b: u32, exec: u32, scc: bool) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend(vmov(255, b));
code.extend(vmov(2, 0xabad_1dea));
code.extend(smov(106, 0x1357_9bdf));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(smov(126, exec));
code
}
fn finish(mut code: Vec<u32>, dst: u32) -> Vec<u8> {
// Restore EXEC, read D and VCC_LO, and XOR in v1 when SCC is set.
code.extend([
0xbefe_03c1,
0x7e04_0300 | dst,
0x7e0c_026a,
0x3a04_0506,
0xbf84_0001,
0x3a04_0501,
0xe070_2000,
0x8001_0200,
0xbbfd_0000,
0xbf81_0000,
]);
words(&code)
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for b in VALUES {
for (dst, src0, src1) in [
(2, 1, 255),
(2, 255, 1),
(1, 1, 255),
(255, 1, 255),
(255, 255, 255),
] {
for exec in MASKS {
for lanes in [7, 32, 45] {
let scc = dst == 255;
let mut code = setup(b, exec, scc);
code.extend(vop3(op, dst, src0, src1));
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.iter()
.enumerate()
.map(|(lane, &x)| {
let read = |reg| if reg == 1 { x } else { b };
// Guide §3.3: a disabled lane retains its previous VGPR.
let d = if exec & (1 << (lane % 32)) != 0 {
expected(op, read(src0), read(src1))
} else {
match dst {
1 => x,
255 => b,
_ => 0xabad_1dea,
}
};
d ^ 0x1357_9bdf ^ if scc { x } else { 0 }
})
.collect();
cases.push(Case {
form: name,
family: "vop3 integer",
label: format!("{name} v{dst}, v{src0}, v{src1} ({b:#x}), EXEC={exec:#x}, {lanes} lanes"),
code: finish(code, dst),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_integer_matches_the_guide() {
let cases = cases();
assert_eq!(cases.len(), 11 * 12 * 5 * 4 * 3);
for case in &cases {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!("vop3_integer: {} cases per CPU interpreter", cases.len());
}
#[test]
fn vop3_integer_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX, false);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 2, 1, 255);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
finish(code, 2)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
check(&[head]);
}
assert_eq!(count, 11 * (13 + 512 + 511 + 1));
eprintln!("vop3_integer: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires native Metal and the VOP3A compiler implementation"]
fn vop3_integer_matches_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!(
"vop3_integer: {} Metal cases in {programs} programs",
cases.len()
);
}