From 994efd38f9cabc1cb9c98ec4d45b9ac687318be5 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:35:53 -0600 Subject: [PATCH] shader: decode and execute SOP2 scalar add, subtract and bitwise forms Adds s_add_u32, s_sub_u32, s_addc_u32, s_subb_u32, s_and_b32, s_or_b32 and s_xor_b32 across the chain: generated opcodes from the pinned AMD XML, a typed ScalarAlu instruction, decoding, the reference interpreter, the independent semantic-review interpreter and the translator, which resolves scalar state and SCC as it already does for s_mov/s_cmp. v_mov_b32_e32 may now read a normal SGPR, so results reach vector code as constants. SCC: the XML states carry-out for additions, carry-in for ADDC/SUBB and nonzero results for bitwise forms. For subtraction it says carry-out without fixing the polarity; LLVM's lowering of usubo and of 64-bit subtraction to s_sub_u32/s_subb_u32 requires SCC to be the borrow. s_add_i32/s_sub_i32 stay unsupported: no pinned source settles whether their SCC is the carry or signed overflow. Verified with an original LLVM-assembled fixture and 1,400 boundary programs (every form, 10x10 operands, SCC clear and set) against exact integer definitions; translator, reference (exact integers) and independent interpreter (bit-serial ripple adder) all agree, and all 1,401 programs match on native Metal with validation. LLVM agrees on every encoding. Breaking any one implementation fails the tests. Fixes #185 Independent review fixes: both interpreters now require a known SGPR for v_mov_b32 from an SGPR even in an inactive lane, as translation does; alias, literal and inline cases also assert the translated result and run on Metal; rejections are pinned to the SOP2 word's offset; GPU status is recorded as local evidence with acceptance pending. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 71 ++++++- crates/decoder/tests/gfx1030.rs | 70 ++++++- crates/isa/generate_rdna2.py | 7 + crates/isa/src/lib.rs | 113 +++++++++-- crates/isa/src/rdna2.rs | 35 ++++ crates/ref/src/lib.rs | 104 ++++++++++- crates/shader/src/graphics.rs | 3 + crates/shader/src/lib.rs | 31 ++++ crates/shader/tests/compiler.rs | 14 ++ docs/README.md | 1 + docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 23 ++- docs/shaders/reference-interpreter.md | 1 + docs/shaders/scalar-alu.md | 77 ++++++++ docs/status.toml | 86 ++++++++- fixtures/golden/scalar-alu.ir | 7 + fixtures/golden/scalar-alu.metal | 13 ++ fixtures/rdna2/scalar-alu.bin | Bin 0 -> 96 bytes fixtures/rdna2/scalar-alu.s | 28 +++ scripts/assemble-fixture.sh | 2 +- scripts/test-gpu.sh | 4 + tests/validation/independent_ref.rs | 85 ++++++++- tests/validation/known_answers.rs | 258 ++++++++++++++++++++++++++ 24 files changed, 1000 insertions(+), 42 deletions(-) create mode 100644 docs/shaders/scalar-alu.md create mode 100644 fixtures/golden/scalar-alu.ir create mode 100644 fixtures/golden/scalar-alu.metal create mode 100644 fixtures/rdna2/scalar-alu.bin create mode 100644 fixtures/rdna2/scalar-alu.s diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cbf461..aa7aae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ remains unsupported. ### Added +- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. `s_add_i32`, `s_sub_i32` and the other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`. - Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it. - Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: 25 forms have semantic decoding. - Added `xenora shaders coverage [--json]` and `xenora shaders inspect ` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 91d28d3..0eaf77c 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -3,13 +3,15 @@ use std::fmt; pub use xenora_isa::{ - Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource, + Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, ScalarSource, + VectorSource, }; use xenora_isa::{ - BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, - S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, - V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, - V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, + BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_U32, S_ADDC_U32, S_AND_B32, + S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, + S_OR_B32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32, V_ADD_F32, + V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, + V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; use xenora_isa::meta::EncodingFamily; @@ -17,11 +19,14 @@ use xenora_isa::meta::EncodingFamily; /// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one /// operand combination. Operand restrictions are listed in docs/status.toml; /// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported. -pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [ +pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 32] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), ("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg), + ("S_ADD_U32", EncodingFamily::Sop2), + ("S_ADDC_U32", EncodingFamily::Sop2), + ("S_AND_B32", EncodingFamily::Sop2), ("S_BRANCH", EncodingFamily::Sopp), ("S_CBRANCH_EXECZ", EncodingFamily::Sopp), ("S_CBRANCH_SCC0", EncodingFamily::Sopp), @@ -29,8 +34,12 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [ ("S_CMP_EQ_U32", EncodingFamily::Sopc), ("S_ENDPGM", EncodingFamily::Sopp), ("S_MOV_B32", EncodingFamily::Sop1), + ("S_OR_B32", EncodingFamily::Sop2), + ("S_SUB_U32", EncodingFamily::Sop2), + ("S_SUBB_U32", EncodingFamily::Sop2), ("S_WAITCNT", EncodingFamily::Sopp), ("S_WAITCNT_VSCNT", EncodingFamily::Sopk), + ("S_XOR_B32", EncodingFamily::Sop2), ("V_ADD_F32", EncodingFamily::Vop2), ("V_ADD_NC_U32", EncodingFamily::Vop3), ("V_AND_B32", EncodingFamily::Vop2), @@ -338,6 +347,19 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco let target = branch_target(first, offset, "s_branch")?; return Ok((Instruction::Branch { target }, S_BRANCH.byte_len())); } + for (opcode, op) in [ + (S_ADD_U32, ScalarAluOp::AddU32), + (S_SUB_U32, ScalarAluOp::SubU32), + (S_ADDC_U32, ScalarAluOp::AddcU32), + (S_SUBB_U32, ScalarAluOp::SubbU32), + (S_AND_B32, ScalarAluOp::AndB32), + (S_OR_B32, ScalarAluOp::OrB32), + (S_XOR_B32, ScalarAluOp::XorB32), + ] { + if opcode.matches(first) { + return scalar_alu(op, first, bytes); + } + } if S_CBRANCH_SCC0.matches(first) { let target = branch_target(first, offset, "s_cbranch_scc0")?; return Ok(( @@ -446,6 +468,40 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco Err(DecodeErrorKind::UnsupportedOpcode { word: first }) } +/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22. +/// Other SOP2 opcodes, including S_ADD_I32 and S_SUB_I32 whose SCC rule is +/// not pinned by the sources in docs/shaders/scalar-alu.md, stay unsupported. +fn scalar_alu( + op: ScalarAluOp, + first: u32, + bytes: &[u8], +) -> Result<(Instruction, u8), DecodeErrorKind> { + let mnemonic = op.mnemonic(); + let dst = ((first >> 16) & 0x7f) as u8; + if dst > 105 { + return Err(unsupported(mnemonic, "expected a normal SGPR destination")); + } + let src0_bits = first as u8; + let src1_bits = (first >> 8) as u8; + if src0_bits == 255 && src1_bits == 255 { + return Err(unsupported( + mnemonic, + "only one source may select a literal", + )); + } + let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?; + let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?; + Ok(( + Instruction::ScalarAlu { + op, + dst, + src0, + src1, + }, + len0.max(len1), + )) +} + fn scalar_source( bits: u8, bytes: &[u8], @@ -592,6 +648,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi let source = first & 0x1ff; let base_len = V_MOV_B32.byte_len(); let (src, len) = match source { + 0..=105 => (VectorSource::Scalar(source as u8), base_len), 128..=192 => (VectorSource::Immediate(source - 128), base_len), 193..=208 => ( VectorSource::Immediate(192u32.wrapping_sub(source)), @@ -607,7 +664,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi _ => { return Err(unsupported( "v_mov_b32_e32", - "expected a VGPR, inline integer, inline +1.0f or literal", + "expected a VGPR, normal SGPR, inline integer, inline +1.0f or literal", )); } }; diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 4e56797..0b3af3c 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -3,10 +3,10 @@ use std::path::PathBuf; use std::process::{Command, Stdio}; use xenora_decoder::{ - Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource, - VectorSource, decode, decode_at, + Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarAluOp, + ScalarSource, VectorSource, decode, decode_at, }; -use xenora_ref::{BranchCondition, Op, Source, VectorAlu}; +use xenora_ref::{BranchCondition, Op, ScalarAlu, Source, VectorAlu}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin"); @@ -97,7 +97,7 @@ fn rejects_other_opcodes_and_noncanonical_operands() { (&[0xe070_2000, 0x801b_0100], "buffer_store_dword"), (&[0xbf8c_3f71], "s_waitcnt"), (&[0xbbfd_0001], "s_waitcnt_vscnt"), - (&[0x7e04_0200], "v_mov_b32_e32"), + (&[0x7e04_026a], "v_mov_b32_e32"), // VCC_LO is outside the SGPR subset. (&[0x7e04_02fa, 0], "v_mov_b32_e32"), (&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"), (&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"), @@ -281,6 +281,7 @@ fn reference_source(vector: VectorSource) -> Source { match vector { VectorSource::Register(reg) => Source::Register(reg), VectorSource::Immediate(bits) => Source::Immediate(bits), + VectorSource::Scalar(_) => unreachable!("mapped to Op::MoveScalar"), } } @@ -313,7 +314,30 @@ fn reference_op(instruction: Instruction) -> Op { }, Instruction::WaitLoad => Op::WaitRead, Instruction::WaitStore => Op::WaitWrite, + Instruction::MoveB32 { + dst, + src: VectorSource::Scalar(src), + } => Op::MoveScalar(dst, src), Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)), + Instruction::ScalarAlu { + op, + dst, + src0, + src1, + } => Op::Scalar( + match op { + ScalarAluOp::AddU32 => ScalarAlu::Add, + ScalarAluOp::SubU32 => ScalarAlu::Subtract, + ScalarAluOp::AddcU32 => ScalarAlu::AddWithCarry, + ScalarAluOp::SubbU32 => ScalarAlu::SubtractWithBorrow, + ScalarAluOp::AndB32 => ScalarAlu::And, + ScalarAluOp::OrB32 => ScalarAlu::Or, + ScalarAluOp::XorB32 => ScalarAlu::Xor, + }, + dst, + reference_scalar(src0), + reference_scalar(src1), + ), Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1), Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)), Instruction::ScalarCompareEqU32 { src0, src1 } => { @@ -383,12 +407,13 @@ fn compares_fixture_instructions_against_llvm() { OR_FIXTURE, SHIFT_FIXTURE, include_bytes!("../../../fixtures/rdna2/ashr.bin"), + include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 21, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 28, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() @@ -433,6 +458,18 @@ fn assemble_matrix() -> Vec { v_mov_b32_e32 v255, lit(0x1) s_mov_b32 s105, lit(0x1) s_cmp_eq_u32 s105, lit(0x1) + s_add_u32 s105, s104, 0xdeadbeef + s_add_u32 s8, -16, 64 + s_sub_u32 s105, s1, s2 + s_sub_u32 s9, 0xdeadbeef, -16 + s_addc_u32 s104, 0xdeadbeef, s105 + s_subb_u32 s0, s0, s0 + s_and_b32 s1, -1, s2 + s_or_b32 s103, s3, 0x80000000 + s_xor_b32 s102, s104, -16 + s_xor_b32 s7, s7, lit(0x1) + v_mov_b32_e32 v255, s105 + v_mov_b32_e32 v0, s0 ", ); use std::fmt::Write as _; @@ -440,6 +477,7 @@ fn assemble_matrix() -> Vec { writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap(); writeln!(assembly, "s_mov_b32 s105, {value}").unwrap(); writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap(); + writeln!(assembly, "s_add_u32 s10, {value}, s11").unwrap(); } assembly.push_str("s_endpgm\n"); let output = llvm_mc(&[], assembly.as_bytes()); @@ -563,7 +601,15 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() { &[0xd516_0001], ]; let outside_subset: &[&[u32]] = &[ - &[0x7e04_0200], // VOP1 SGPR source + &[0x7e04_026a], // VOP1 VCC_LO source + &[0x8108_0908], // s_add_i32: SCC rule not pinned + &[0x8188_0908], // s_sub_i32: SCC rule not pinned + &[0x8788_0908], // s_and_b64 + &[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources + &[0x806c_0908], // SOP2 TTMP destination + &[0x807e_0908], // SOP2 EXEC_LO destination + &[0x806a_0908], // SOP2 VCC_LO destination + &[0x8008_096a], // SOP2 VCC_LO source &[0x3803_fe80], // OR with an inline SRC0 &[0x3803_fe08], // OR with an SGPR SRC0 &[0x3803_feff, 0xdead_beef], // OR with a literal SRC0 @@ -651,6 +697,18 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String { }; format!("{mnemonic} {}, {}", scalar(left), scalar(right)) } + "s_add_u32" | "s_sub_u32" | "s_addc_u32" | "s_subb_u32" | "s_and_b32" | "s_or_b32" + | "s_xor_b32" => { + let scalar = |operand: &str| match literal_bits(operand) { + Some(bits) => match bits as i32 { + inline @ -16..=64 => inline.to_string(), + _ => format!("0x{bits:x}"), + }, + None => operand.to_owned(), + }; + let operands: Vec<_> = operands.split(", ").map(scalar).collect(); + format!("{mnemonic} {}", operands.join(", ")) + } _ => assembly.to_owned(), } } diff --git a/crates/isa/generate_rdna2.py b/crates/isa/generate_rdna2.py index 5eb4f44..319ac7c 100644 --- a/crates/isa/generate_rdna2.py +++ b/crates/isa/generate_rdna2.py @@ -18,6 +18,13 @@ VARIANTS = ( ("S_ENDPGM", "ENC_SOPP"), ("S_MOV_B32", "ENC_SOP1"), ("S_CMP_EQ_U32", "ENC_SOPC"), + ("S_ADD_U32", "ENC_SOP2"), + ("S_SUB_U32", "ENC_SOP2"), + ("S_ADDC_U32", "ENC_SOP2"), + ("S_SUBB_U32", "ENC_SOP2"), + ("S_AND_B32", "ENC_SOP2"), + ("S_OR_B32", "ENC_SOP2"), + ("S_XOR_B32", "ENC_SOP2"), ("S_CBRANCH_SCC0", "ENC_SOPP"), ("S_CBRANCH_EXECZ", "ENC_SOPP"), ("S_CBRANCH_VCCZ", "ENC_SOPP"), diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 8646389..bd7d041 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -7,10 +7,11 @@ mod rdna2; #[rustfmt::skip] mod rdna2_meta; pub use rdna2::{ - BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, - S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, - V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, - V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, + BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_U32, S_ADDC_U32, S_AND_B32, + S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, + S_OR_B32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32, V_ADD_F32, + V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, + V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; /// Selects the instruction encoding independently of the container and execution ABI. @@ -45,6 +46,8 @@ impl Opcode { pub enum VectorSource { /// VGPR index. Register(u8), + /// Normal SGPR index (s0-s105), read as a wave-uniform value. + Scalar(u8), /// Inline integer or literal word, represented by its bits. Immediate(u32), } @@ -53,6 +56,7 @@ impl fmt::Display for VectorSource { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Register(register) => write!(formatter, "v{register}"), + Self::Scalar(register) => write!(formatter, "s{register}"), Self::Immediate(value) => write!(formatter, "0x{value:x}"), } } @@ -79,6 +83,71 @@ impl fmt::Display for ScalarSource { } } +/// SOP2 32-bit integer operations in the supported scalar subset. +/// +/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions +/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume +/// SCC as carry-in or borrow-in, and bitwise operations set SCC iff the result +/// is nonzero. See docs/shaders/scalar-alu.md for the sources. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarAluOp { + /// `s_add_u32`: D = S0 + S1, SCC = carry-out. + AddU32, + /// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0). + SubU32, + /// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out. + AddcU32, + /// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow. + SubbU32, + /// `s_and_b32`: D = S0 & S1, SCC = D != 0. + AndB32, + /// `s_or_b32`: D = S0 | S1, SCC = D != 0. + OrB32, + /// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0. + XorB32, +} + +impl ScalarAluOp { + /// Lower-case mnemonic. + pub fn mnemonic(self) -> &'static str { + match self { + Self::AddU32 => "s_add_u32", + Self::SubU32 => "s_sub_u32", + Self::AddcU32 => "s_addc_u32", + Self::SubbU32 => "s_subb_u32", + Self::AndB32 => "s_and_b32", + Self::OrB32 => "s_or_b32", + Self::XorB32 => "s_xor_b32", + } + } + + /// The 32-bit result and the new SCC, with `carry_in` the SCC read by + /// ADDC and SUBB (ignored by the other operations). + pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) { + let carry = u32::from(carry_in && self.reads_scc()); + match self { + Self::AddU32 | Self::AddcU32 => { + let (partial, first) = src0.overflowing_add(src1); + let (value, second) = partial.overflowing_add(carry); + (value, first || second) + } + Self::SubU32 | Self::SubbU32 => { + let (partial, first) = src0.overflowing_sub(src1); + let (value, second) = partial.overflowing_sub(carry); + (value, first || second) + } + Self::AndB32 => (src0 & src1, src0 & src1 != 0), + Self::OrB32 => (src0 | src1, src0 | src1 != 0), + Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0), + } + } + + /// Whether the operation reads SCC as a carry-in or borrow-in. + pub fn reads_scc(self) -> bool { + matches!(self, Self::AddcU32 | Self::SubbU32) + } +} + /// Output targeted by a supported uncompressed four-component export. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ExportTarget { @@ -120,6 +189,13 @@ pub enum Instruction { AddNoCarryU32 { dst: u8, src0: u8, src1: u8 }, /// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half. ScalarMoveB32 { dst: u8, src: ScalarSource }, + /// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC. + ScalarAlu { + op: ScalarAluOp, + dst: u8, + src0: ScalarSource, + src1: ScalarSource, + }, /// SOPC 32-bit equality comparison writing SCC. ScalarCompareEqU32 { src0: ScalarSource, @@ -177,6 +253,21 @@ pub enum Instruction { EndProgram, } +/// Formats an SGPR destination with LLVM's names for the EXEC and VCC halves. +struct ScalarDestination(u8); + +impl fmt::Display for ScalarDestination { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + 106 => formatter.write_str("vcc_lo"), + 107 => formatter.write_str("vcc_hi"), + 126 => formatter.write_str("exec_lo"), + 127 => formatter.write_str("exec_hi"), + register => write!(formatter, "s{register}"), + } + } +} + impl Instruction { /// Returns the mnemonic for the exact encoding family represented. pub fn mnemonic(self) -> &'static str { @@ -188,6 +279,7 @@ impl Instruction { Self::MoveB32 { .. } => "v_mov_b32_e32", Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64", Self::ScalarMoveB32 { .. } => "s_mov_b32", + Self::ScalarAlu { op, .. } => op.mnemonic(), Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32", Self::BranchSccZero { .. } => "s_cbranch_scc0", Self::BranchExecZero { .. } => "s_cbranch_execz", @@ -250,13 +342,12 @@ impl fmt::Display for Instruction { | Self::VectorMulF32 { dst, src0, src1 } => { write!(formatter, " v{dst}, v{src0}, v{src1}") } - Self::ScalarMoveB32 { dst, src } => match dst { - 106 => write!(formatter, " vcc_lo, {src}"), - 107 => write!(formatter, " vcc_hi, {src}"), - 126 => write!(formatter, " exec_lo, {src}"), - 127 => write!(formatter, " exec_hi, {src}"), - _ => write!(formatter, " s{dst}, {src}"), - }, + Self::ScalarMoveB32 { dst, src } => { + write!(formatter, " {}, {src}", ScalarDestination(dst)) + } + Self::ScalarAlu { + dst, src0, src1, .. + } => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)), Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"), Self::Branch { target } | Self::BranchSccZero { target } diff --git a/crates/isa/src/rdna2.rs b/crates/isa/src/rdna2.rs index 8c5b4a8..28026d2 100644 --- a/crates/isa/src/rdna2.rs +++ b/crates/isa/src/rdna2.rs @@ -50,6 +50,41 @@ pub const S_CMP_EQ_U32: Opcode = Opcode { bits: 0xbf060000, bytes: 4, }; +pub const S_ADD_U32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x80000000, + bytes: 4, +}; +pub const S_SUB_U32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x80800000, + bytes: 4, +}; +pub const S_ADDC_U32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x82000000, + bytes: 4, +}; +pub const S_SUBB_U32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x82800000, + bytes: 4, +}; +pub const S_AND_B32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x87000000, + bytes: 4, +}; +pub const S_OR_B32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x88000000, + bytes: 4, +}; +pub const S_XOR_B32: Opcode = Opcode { + mask: 0xff800000, + bits: 0x89000000, + bytes: 4, +}; pub const S_CBRANCH_SCC0: Opcode = Opcode { mask: 0xffff0000, bits: 0xbf840000, diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index 8674bcd..83c694a 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -48,6 +48,10 @@ pub enum Op { Move(u8, Source), Add(u8, u8, u8), ScalarMove(u8, Source), + /// VOP1 move of a normal SGPR into a VGPR. + MoveScalar(u8, u8), + /// SOP2 operation writing an SGPR and SCC. + Scalar(ScalarAlu, u8, Source, Source), CompareEqual(Source, Source), Branch { target: usize, @@ -70,6 +74,22 @@ pub enum BranchCondition { ExecZero, } +/// SOP2 operations decoded by the reference interpreter. +/// +/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC, +/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise +/// operations set SCC iff the result is nonzero. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScalarAlu { + Add, + Subtract, + AddWithCarry, + SubtractWithBorrow, + And, + Or, + Xor, +} + /// VOP2 operations decoded by the reference interpreter. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAlu { @@ -206,6 +226,33 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { let (right, right_length) = decode_scalar(*right, tail, offset)?; (Op::CompareEqual(left, right), left_length.max(right_length)) } + // SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0. + [ + left, + right, + low, + high @ (0x80 | 0x82 | 0x87 | 0x88 | 0x89), + tail @ .., + ] if (*left, *right) != (255, 255) + && low & 0x7f <= 105 + && (low & 0x80 == 0 || matches!(high, 0x80 | 0x82)) => + { + let kind = match (high, low >> 7) { + (0x80, 0) => ScalarAlu::Add, + (0x80, _) => ScalarAlu::Subtract, + (0x82, 0) => ScalarAlu::AddWithCarry, + (0x82, _) => ScalarAlu::SubtractWithBorrow, + (0x87, _) => ScalarAlu::And, + (0x88, _) => ScalarAlu::Or, + _ => ScalarAlu::Xor, + }; + let (left, left_length) = decode_scalar(*left, tail, offset)?; + let (right, right_length) = decode_scalar(*right, tail, offset)?; + ( + Op::Scalar(kind, low & 0x7f, left, right), + left_length.max(right_length), + ) + } [lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => { let words = i16::from_le_bytes([*lo, *hi]); let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?; @@ -251,6 +298,16 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { { let dst = (upper >> 1) | ((tag & 1) << 7); let selector = u16::from(*lo) | (u16::from(packed & 1) << 8); + if selector <= 105 { + // VOP1 SRC0 0-105 selects a normal SGPR. + program.push(DecodedInstruction { + offset, + byte_len: 4, + op: Op::MoveScalar(dst, *lo), + }); + offset += 4; + continue; + } let (src, length) = match selector { 128..=192 => (Source::Immediate(u32::from(selector - 128)), 4), 193..=208 => ( @@ -400,10 +457,19 @@ fn execute_lane( }; if exec != u32::MAX { match op { - Op::Move(dst, _) | Op::Add(dst, ..) | Op::Vector(_, dst, ..) => { + Op::Move(dst, _) + | Op::MoveScalar(dst, _) + | Op::Add(dst, ..) + | Op::Vector(_, dst, ..) => { if exec != 0 && registers[usize::from(dst)].is_none() { return Err(error(offset, "partial EXEC requires an initialized VGPR")); } + // As in translation, an SGPR source must be known even for an inactive lane. + if let Op::MoveScalar(_, src) = op + && exec != 0 + { + read_scalar(Source::Register(src))?; + } if exec & (1 << lane) == 0 { continue; } @@ -458,6 +524,42 @@ fn execute_lane( scc = Some(read_scalar(lhs)? == read_scalar(rhs)?); None } + Op::MoveScalar(dst, src) => Some((dst, read_scalar(Source::Register(src))?)), + Op::Scalar(kind, dst, lhs, rhs) => { + if dst < 8 { + return Err(error(offset, "write to a reserved resource SGPR")); + } + let (lhs, rhs) = (i64::from(read_scalar(lhs)?), i64::from(read_scalar(rhs)?)); + let carry = match kind { + ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from( + scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?, + ), + _ => 0, + }; + // Exact integer arithmetic, then reduction modulo 2^32. + let (exact, flag) = match kind { + ScalarAlu::Add | ScalarAlu::AddWithCarry => { + let sum = lhs + rhs + carry; + (sum, sum >= 1 << 32) + } + ScalarAlu::Subtract | ScalarAlu::SubtractWithBorrow => { + let difference = lhs - rhs - carry; + (difference, difference < 0) + } + ScalarAlu::And | ScalarAlu::Or | ScalarAlu::Xor => { + let bits = match kind { + ScalarAlu::And => lhs & rhs, + ScalarAlu::Or => lhs | rhs, + _ => lhs ^ rhs, + }; + (bits, bits != 0) + } + }; + let value = exact.rem_euclid(1 << 32) as u32; + scalars[usize::from(dst)] = Some(value); + scc = Some(flag); + None + } Op::Branch { target: destination, condition, diff --git a/crates/shader/src/graphics.rs b/crates/shader/src/graphics.rs index ce91166..207b1a2 100644 --- a/crates/shader/src/graphics.rs +++ b/crates/shader/src/graphics.rs @@ -223,6 +223,9 @@ fn lift( VectorSource::Immediate(_) => { return Err(error("graphics move requires finite FP32 bits")); } + VectorSource::Scalar(_) => { + return Err(error("graphics move from an SGPR is unsupported")); + } }; registers[usize::from(dst)] = Some(value); } diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 5528cf3..2a9dbbe 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -474,6 +474,14 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result (Some(dst), Op::Constant(value)), + // SGPR values are wave-uniform and known during translation. + Instruction::MoveB32 { + dst, + src: VectorSource::Scalar(register), + } => ( + Some(dst), + Op::Constant(read_scalar(ScalarSource::Register(register))?), + ), Instruction::AddNoCarryU32 { dst, src0, src1 } => { (Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?)) } @@ -512,6 +520,29 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?); + let carry_in = if op.reads_scc() { + scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))? + } else { + false + }; + if dst < 8 { + return Err(error("scalar ALU would modify a resource descriptor")); + } + let (value, flag) = op.evaluate(src0, src1, carry_in); + let slot = scalars + .get_mut(usize::from(dst)) + .ok_or_else(|| error("scalar destination exceeds the fixture register file"))?; + *slot = Some(value); + scc = Some(flag); + continue; + } Instruction::ScalarCompareEqU32 { src0, src1 } => { scc = Some(read_scalar(src0)? == read_scalar(src1)?); continue; diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index cf77a44..c7f7827 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -265,3 +265,17 @@ fn checks_fixture_layout_and_bindings_even_in_skipped_code() { assert!(compiled.msl.contains("uint t1 = input[index];")); assert!(compiled.msl.contains("output[index] = t3;")); } + +#[test] +fn scalar_alu_results_reach_the_kernel_as_constants() { + let code = include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/scalar-alu.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/scalar-alu.metal") + ); +} diff --git a/docs/README.md b/docs/README.md index 12b1144..02682e0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. ## RDNA 2 decoding and shader translation - [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results. +- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources. - [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models. ## Native Metal backend diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index e499d15..d9538fc 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 21 of 21. Accepted Metal forms · Apple M5: 18 of 21. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 28 of 28. Accepted Metal forms · Apple M5: 18 of 28. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -21 / 21 +28 / 28 Accepted Metal forms · Apple M5 -18 / 21 +18 / 28 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index c94d2b2..9511314 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -15,13 +15,20 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `buffer_load_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL load | implemented | fixture verified | fixture verified | | `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified | -| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified | +| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified | | `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified | | `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified | | `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified | | `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified | | `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified | | `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified | +| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_addc_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; adds SCC; SCC = carry-out | `820980FF 7FFFFFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_subb_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; subtracts SCC; SCC = borrow | `828B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified | | `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified | | `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified | @@ -39,20 +46,20 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin ## Automated three-way comparison LLVM 23.1.6, the production decoder and the independent reference decoder -matched 338 instructions across eight streams: the six synthetic fixtures, -a high-register sequence and a 272-instruction matrix assembled by LLVM. +matched 452 instructions across nine streams: the seven synthetic fixtures, +a high-register sequence and an operand matrix assembled by LLVM. The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic and operands, and the typed reference operation against the production -operation. It covers all 21 forms in this document. +operation. It covers all 28 forms in this document. -The matrix checks the 81 inline integer selectors in VOP1, SOP1 and SOPC, -forced literals that could otherwise be inline, literal selection in either -SOPC operand, high SGPR and VGPR indices, MUBUF descriptor and index +The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and +SOP2, forced literals that could otherwise be inline, literal selection in +either SOPC or SOP2 operand, every supported SOP2 form, VOP1 SGPR sources, high SGPR and VGPR indices, MUBUF descriptor and index operands, and zero and nonzero forward branch displacements. The decoder trace exposes MUBUF operands independently of the synthetic execution ABI, which still requires the original index and resource bindings. -Five malformed LLVM probes produced diagnostics, and 19 valid encodings +Five malformed LLVM probes produced diagnostics, and 27 valid encodings or disassemblable branch sequences were deliberately rejected by both Xenora decoders. Both Xenora decoders also reject all 37 interior truncation offsets in the add fixture and every case in the unsupported-encoding list. diff --git a/docs/shaders/reference-interpreter.md b/docs/shaders/reference-interpreter.md index 0e455eb..1e1ec8e 100644 --- a/docs/shaders/reference-interpreter.md +++ b/docs/shaders/reference-interpreter.md @@ -9,6 +9,7 @@ | VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. | | VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. | | SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. | +| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. | | SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. | | VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. | | VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. | diff --git a/docs/shaders/scalar-alu.md b/docs/shaders/scalar-alu.md new file mode 100644 index 0000000..6f90425 --- /dev/null +++ b/docs/shaders/scalar-alu.md @@ -0,0 +1,77 @@ +# SOP2 scalar ALU subset + +Xenora decodes and executes seven gfx1030 SOP2 forms. Each takes 32-bit +operands, writes a normal SGPR (s0-s105) and sets SCC. + +| Form | D | SCC | +| --- | --- | --- | +| `s_add_u32` | S0 + S1 | carry-out of bit 31 | +| `s_sub_u32` | S0 - S1 | borrow (S1 > S0) | +| `s_addc_u32` | S0 + S1 + SCC | carry-out of bit 31 | +| `s_subb_u32` | S0 - S1 - SCC | borrow (S1 + SCC > S0) | +| `s_and_b32` | S0 & S1 | D != 0 | +| `s_or_b32` | S0 \| S1 | D != 0 | +| `s_xor_b32` | S0 ^ S1 | D != 0 | + +Sources are normal SGPRs, inline integers (-16 to 64) or one literal word. +`v_mov_b32_e32` may read a normal SGPR, so the results can reach vector code. + +## Sources + +- Opcodes, operand fields and which forms read and write SCC come from the + pinned AMD RDNA 2 XML (`crates/isa/generate_rdna2.py`). Its descriptions say + that additions "store the carry-out bit into SCC", ADDC adds "a carry-in bit + from SCC", SUBB subtracts "the carry-in bit", and the bitwise forms "set SCC + iff the result is nonzero". +- For subtraction, the XML's "carry-out" does not say whether SCC is the borrow + or its complement. LLVM's AMDGPU backend settles it. It lowers unsigned + subtract-with-overflow (`S_USUBO_PSEUDO`) to `s_sub_u32` and reads SCC as the + overflow. It also lowers 64-bit subtraction to `s_sub_u32` followed by + `s_subb_u32` (`SIISelLowering.cpp`), which is only correct if SCC is the + borrow and SUBB subtracts it. LLVM 23.1.6 also checks every encoding here + against the decoder and the reference (`compares_fixture_instructions_against_llvm`). + +## Not supported + +- `s_add_i32` and `s_sub_i32`. The XML also says they store "the carry-out + bit", which for signed operands could mean the carry or signed overflow. + The RDNA 2 ISA guide's SOP2 pseudocode is understood to define signed + overflow. That has not been checked against the guide here, so both stay + rejected until a follow-up confirms it and adds overflow vectors. +- Every other SOP2 form, including the 64-bit bitwise forms. +- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0). +- Sources other than normal SGPRs, inline integers and one literal. +- Both sources selecting a literal. +- ADDC or SUBB before SCC is set. +- Writes to the fixture's resource descriptors s0-s7. + +## How it runs + +Scalar state in a compute fixture is wave-uniform and known while the code is +translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates +SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values +read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the +IR and MSL contain the results, not scalar instructions. + +## Verification + +`fixtures/rdna2/scalar-alu.s` is an original program, assembled by LLVM. It +chains a carry through `s_add_u32`/`s_addc_u32` and a borrow through +`s_sub_u32`/`s_subb_u32`. It also covers aliased destinations, inline and +literal operands, bitwise results that set and clear SCC, and an +`s_cbranch_scc0` that depends on them. Its expected output, input ^ 0x8000000e, +was derived by hand. + +`tests/validation/known_answers.rs` runs every supported form over 10 boundary +operands squared, with SCC clear and set. That is 1,400 programs. The same file +covers aliasing, inline and literal operands, and rejected forms. Expected +values come from exact integer definitions in the test. Three implementations +must agree with them: +- the translator (resolved branch and emitted constant); +- the reference interpreter (exact integers, reduced modulo 2^32); +- the independent interpreter (a bit-serial ripple-carry adder). + +`scalar_alu_native_metal_known_answers` runs the fixture, the 1,400 programs +and the aliasing and immediate cases on native Metal with API and shader +validation. `scripts/test-gpu.sh` runs it. This is local evidence from one +Apple M5 Pro; independent acceptance is pending. diff --git a/docs/status.toml b/docs/status.toml index 17fb600..8a4e2a0 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -65,7 +65,7 @@ llvm = "three-way passed" [[instruction]] form = "v_mov_b32_e32" -encoding = "VOP1, VGPR destination, VGPR or inline integer or literal source, plus the inline bit pattern for +1.0f" +encoding = "VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation) or inline integer or literal source, plus the inline bit pattern for +1.0f" representation = "4 or 8 B" lowering = "constant or register value" reference = "implemented" @@ -147,6 +147,90 @@ recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "s_add_u32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out" +representation = "`80088308`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_sub_u32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow" +representation = "`808A8180`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_addc_u32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; adds SCC; SCC = carry-out" +representation = "`820980FF 7FFFFFFF`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_subb_u32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; subtracts SCC; SCC = borrow" +representation = "`828B0809`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_and_b32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0" +representation = "`870D090C`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_or_b32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0" +representation = "`880ED00D`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "s_xor_b32" +encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0" +representation = "`890C0A0B`" +lowering = "resolved scalar state and SCC" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + [[instruction]] form = "s_cbranch_scc0" encoding = "Nonnegative signed dword displacement" diff --git a/fixtures/golden/scalar-alu.ir b/fixtures/golden/scalar-alu.ir new file mode 100644 index 0000000..b41b9f9 --- /dev/null +++ b/fixtures/golden/scalar-alu.ir @@ -0,0 +1,7 @@ +0000: t0 = load.u32 input[index] +0034: branch.uniform 0x0040 taken=true +0040: t2 = const.u32 0x7ffffffe +0044: t3 = const.u32 0xfffffff0 +0048: t4 = xor.b32 t2, t3 +004c: t5 = xor.b32 t0, t4 +0050: store.u32 output[index], t5 diff --git a/fixtures/golden/scalar-alu.metal b/fixtures/golden/scalar-alu.metal new file mode 100644 index 0000000..0072fb2 --- /dev/null +++ b/fixtures/golden/scalar-alu.metal @@ -0,0 +1,13 @@ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + uint t0 = input[index]; + uint t2 = 0x7ffffffeu; + uint t3 = 0xfffffff0u; + uint t4 = t2 ^ t3; + uint t5 = t0 ^ t4; + output[index] = t5; +} diff --git a/fixtures/rdna2/scalar-alu.bin b/fixtures/rdna2/scalar-alu.bin new file mode 100644 index 0000000000000000000000000000000000000000..e8cf87909d24a779abfe51ca66ba57c62f73f5fb GIT binary patch literal 96 zcmZQjFnGYg$k0$=-?RS^bH_f8W{!sc4V+E?|NpOVXzXg>V@OL)@L*sq`J9izK literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/scalar-alu.s b/fixtures/rdna2/scalar-alu.s new file mode 100644 index 0000000..7a99535 --- /dev/null +++ b/fixtures/rdna2/scalar-alu.s @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original SOP2 vectors: a carry chain through s_add_u32/s_addc_u32, a borrow +// chain through s_sub_u32/s_subb_u32, bitwise results feeding SCC, an SCC +// branch, and SGPR results moved into VGPRs. Expected: input ^ 0x8000000e. +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen +s_waitcnt vmcnt(0) +s_mov_b32 s8, 0xfffffffe +s_add_u32 s8, s8, 3 // s8 = 1, SCC = 1 (carry-out; dst aliases src0) +s_addc_u32 s9, 0x7fffffff, 0 // s9 = 0x80000000, SCC = 0 +s_sub_u32 s10, 0, 1 // s10 = 0xffffffff, SCC = 1 (borrow) +s_subb_u32 s11, s9, s8 // s11 = 0x7ffffffe, SCC = 0 +s_xor_b32 s12, s11, s10 // s12 = 0x80000001, SCC = 1 +s_and_b32 s13, s12, s9 // s13 = 0x80000000, SCC = 1 +s_or_b32 s14, s13, -16 // s14 = 0xfffffff0, SCC = 1 +s_and_b32 s15, s14, 15 // s15 = 0, SCC = 0 +s_cbranch_scc0 .Lzero +v_mov_b32_e32 v2, 0 +s_branch .Ldone +.Lzero: +v_mov_b32_e32 v2, s11 +v_mov_b32_e32 v3, s14 +v_xor_b32_e32 v2, v2, v3 +v_xor_b32_e32 v2, v1, v2 +.Ldone: +buffer_store_dword v2, v0, s[4:7], 0 idxen +s_waitcnt_vscnt null, 0 +s_endpgm diff --git a/scripts/assemble-fixture.sh b/scripts/assemble-fixture.sh index 8e29698..a88562f 100755 --- a/scripts/assemble-fixture.sh +++ b/scripts/assemble-fixture.sh @@ -12,7 +12,7 @@ case "${1:-}" in esac for name in add bitwise-branch float-exact or shifts ashr \ - x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs; do + x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu; do "$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \ -filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o" "$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin" diff --git a/scripts/test-gpu.sh b/scripts/test-gpu.sh index 143b219..40dfb16 100755 --- a/scripts/test-gpu.sh +++ b/scripts/test-gpu.sh @@ -24,3 +24,7 @@ timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test run cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 --no-run timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \ --nocapture --test-threads=1 + +# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU. +cargo test --locked -p xenora-semantic-review --no-run +timeout 60s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index 1bf7e74..93cb167 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -8,12 +8,15 @@ //! field layout and executes them with an explicit program-counter machine, so //! a defect in the production decoder or reference cannot cancel out here. //! -//! Scope matches the demo fixtures: scalar move/compare/branch, VOP1 move, +//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 add, +//! subtract, add-with-carry, subtract-with-borrow, AND, OR and XOR, VOP1 move +//! (including from an SGPR), //! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, 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 -//! production operator. +//! production operator. SOP2 arithmetic runs through a bit-serial ripple +//! adder (subtraction as addition of the complement), not host integer ops. const MAX_CODE_BYTES: usize = 1024; const MAX_INPUT_WORDS: usize = 4096; @@ -27,11 +30,17 @@ enum Src { #[derive(Clone, Copy, Debug)] enum Insn { SMov(u8, Src), + /// SOP2 opcode 0, 1, 4, 5, 14, 16 or 18. + SAlu(u32, u8, Src, Src), SCmpEq(Src, Src), BranchScc0(usize), - BranchMaskZero { target: usize, register: usize }, + BranchMaskZero { + target: usize, + register: usize, + }, Branch(usize), VMov(u8, Src), + VMovFromSgpr(u8, u8), VAddNc(u8, u8, u8), VAnd(u8, u8, u8), VOr(u8, u8, u8), @@ -103,6 +112,7 @@ fn run_lane(program: &[(usize, Insn)], lane_input: u32, lane: usize) -> Result Result Result { + let value = read_s(Src::Reg(src))?; + check_destination(dst, pending_read, offset)?; + vgpr[dst as usize] = Some(value); + } Insn::VAddNc(dst, a, b) => { check_destination(dst, pending_read, offset)?; let sum = u64::from(read_v(a)?) + u64::from(read_v(b)?); @@ -215,6 +233,38 @@ fn run_lane(program: &[(usize, Insn)], lane_input: u32, lane: usize) -> Result { scc = Some(read_s(a)? == read_s(b)?); } + Insn::SAlu(opcode, dst, a, b) => { + if dst < 8 { + return Err(format!("{offset:#x}: write to a resource SGPR")); + } + let (a, b) = (read_s(a)?, read_s(b)?); + let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC")); + let (value, flag) = match opcode { + 0 => ripple(a, b, false), + 4 => ripple(a, b, carry_in()?), + // a - b - borrow = a + !b + (1 - borrow); borrow-out = !carry-out. + 1 | 5 => { + let borrow = opcode == 5 && carry_in()?; + let (value, carry) = ripple(a, !b, !borrow); + (value, !carry) + } + _ => { + let mut value = 0; + for bit in 0..32 { + let (x, y) = ((a >> bit) & 1 == 1, (b >> bit) & 1 == 1); + let set = match opcode { + 14 => x && y, + 16 => x || y, + _ => x != y, + }; + value |= u32::from(set) << bit; + } + (value, value != 0) + } + }; + sgpr[dst as usize] = Some(value); + scc = Some(flag); + } Insn::BranchScc0(target) => { let condition = scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))?; if !condition { @@ -244,6 +294,18 @@ fn run_lane(program: &[(usize, Insn)], lane_input: u32, lane: usize) -> Result (u32, bool) { + let mut carry = carry_in; + let mut sum = 0; + for bit in 0..32 { + let (x, y) = ((a >> bit) & 1 == 1, (b >> bit) & 1 == 1); + sum |= u32::from(x ^ y ^ carry) << bit; + carry = (x && y) || (carry && (x ^ y)); + } + (sum, carry) +} + fn check_destination(dst: u8, load: Option, offset: usize) -> Result<(), String> { if dst == 0 || load == Some(dst) { return Err(format!("{offset:#x}: write to the index or pending VGPR")); @@ -346,6 +408,9 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { if first & 0xfe01_fe00 == 0x7e00_0200 { let dst = (first >> 17) as u8; let selector = first & 0x1ff; + if selector <= 105 { + return Ok((Insn::VMovFromSgpr(dst, selector as u8), 4)); + } let (src, len) = if selector == 255 { (Src::Imm(word(code, offset + 4)?), 8) } else { @@ -373,6 +438,20 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { let (src, len) = scalar_source(code, offset, first as u8)?; return Ok((Insn::SMov(dst, src), len)); } + // SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22. + if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0 | 1 | 4 | 5 | 14 | 16 | 18) { + let dst = ((first >> 16) & 0x7f) as u8; + if dst > 105 { + return Err(fail("unsupported SOP2 destination")); + } + let (a, b) = (first as u8, (first >> 8) as u8); + if a == 255 && b == 255 { + return Err(fail("two scalar literals")); + } + let (sa, la) = scalar_source(code, offset, a)?; + let (sb, lb) = scalar_source(code, offset, b)?; + return Ok((Insn::SAlu((first >> 23) & 0x7f, dst, sa, sb), la.max(lb))); + } if first & 0xffff_0000 == 0xbf06_0000 { let a = first as u8; let b = (first >> 8) as u8; diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index c7b12c4..c728900 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -766,4 +766,262 @@ mod review { verify(&code, &[1], expected.as_ref().map(|words| words.as_slice())); } } + + const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin"); + // SOP2 opcodes of the supported subset (RDNA 2 XML opcode table). + const SOP2_OPCODES: [u32; 7] = [0, 1, 4, 5, 14, 16, 18]; + const SCALAR_VALUES: [u32; 10] = [ + 0, + 1, + 2, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fffe, + u32::MAX, + 0x1234_5678, + 0xedcb_a988, + ]; + + /// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7. + fn sop2(opcode: u32, dst: u32, src0: u32, src1: u32) -> u32 { + 0x8000_0000 | opcode << 23 | dst << 16 | src1 << 8 | src0 + } + + /// D and SCC from the operation's definition, with exact integers: additions + /// carry out of bit 31, subtractions borrow, bitwise results set SCC iff nonzero. + fn sop2_expected(opcode: u32, a: u32, b: u32, carry: bool) -> (u32, bool) { + let (a, b) = (u64::from(a), u64::from(b)); + let c = u64::from(carry && matches!(opcode, 4 | 5)); + let (exact, scc) = match opcode { + 0 | 4 => (a + b + c, a + b + c >= 1 << 32), + 1 | 5 => (((1 << 32) + a - b - c) % (1 << 32), b + c > a), + 14 => (a & b, a & b != 0), + 16 => (a | b, a | b != 0), + _ => (a ^ b, a ^ b != 0), + }; + ((exact % (1 << 32)) as u32, scc) + } + + /// s8 = a, s9 = b, SCC = `carry` (if set), then `alu` (with an optional literal), + /// then v2 = s; lanes are XORed with their input only when SCC is set. + fn sop2_program(alu: &[u32], result: u32, a: u32, b: u32, carry: Option) -> Vec { + let mut words = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; + words.extend([0xbe88_03ff, a, 0xbe89_03ff, b]); + if let Some(carry) = carry { + // s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it. + words.push(if carry { 0xbf06_8080 } else { 0xbf06_8180 }); + } + words.extend(alu); + words.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]); + words.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]); + words.iter().flat_map(|word| word.to_le_bytes()).collect() + } + + fn lanes(value: u32, scc: bool) -> [u32; 2] { + [value, if scc { !value } else { value }] + } + + /// Every supported opcode over boundary operands, with SCC both clear and set + /// before the carry-consuming forms. + fn sop2_vectors() -> Vec<(Vec, [u32; 2])> { + let mut vectors = Vec::new(); + for opcode in SOP2_OPCODES { + for a in SCALAR_VALUES { + for b in SCALAR_VALUES { + for carry in [false, true] { + let (value, scc) = sop2_expected(opcode, a, b, carry); + let code = sop2_program(&[sop2(opcode, 10, 8, 9)], 10, a, b, Some(carry)); + vectors.push((code, lanes(value, scc))); + } + } + } + } + vectors + } + + #[test] + fn scalar_alu_fixture_chains_carry_borrow_and_bitwise_scc() { + let input = [0, 1, u32::MAX, 0x8000_000e, 0x1234_5678]; + let expected: Vec<_> = input.iter().map(|word| word ^ 0x8000_000e).collect(); + verify(SCALAR_ALU_FIXTURE, &input, Some(&expected)); + let compiled = compile(Architecture::Gfx1030, SCALAR_ALU_FIXTURE).unwrap(); + // The scalar results reach the kernel as constants; the branch is resolved. + assert!(compiled.disassembly.contains("s_subb_u32 s11, s9, s8")); + assert!(compiled.ir.contains("const.u32"), "{}", compiled.ir); + // Clearing the final AND's SCC-zero edge (s15 = s14 & 15 = 0) is observable: + // with 31 instead of 15 the result is 0x10, SCC = 1, and v2 = 0. + let mut nonzero = SCALAR_ALU_FIXTURE.to_vec(); + assert_eq!(nonzero[0x31], 0x8f); + nonzero[0x31] = 0x9f; + verify(&nonzero, &input, Some(&[0; 5])); + } + + /// The translator's own folding: v2 = D as a constant, and the SCC-zero edge + /// is taken exactly when SCC is clear. + fn assert_translated(code: &[u8], expected: &[u32; 2]) { + let ir = compile(Architecture::Gfx1030, code).unwrap().ir; + assert!( + ir.contains(&format!("const.u32 0x{:08x}", expected[0])), + "{ir}" + ); + let taken = expected[0] == expected[1]; + assert!(ir.contains(&format!("taken={taken}")), "{ir}"); + } + + /// Aliased destinations, literals in either source and inline integers. + fn sop2_operand_cases() -> Vec<(Vec, [u32; 2])> { + let (a, b) = (0xffff_fff0, 0x0000_0011); + let mut cases = Vec::new(); + for opcode in SOP2_OPCODES { + for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9)] { + let x = if src0 == 9 { b } else { a }; + let y = if src1 == 8 { a } else { b }; + let (value, scc) = sop2_expected(opcode, x, y, true); + let code = sop2_program(&[sop2(opcode, dst, src0, src1)], dst, a, b, Some(true)); + cases.push((code, lanes(value, scc))); + } + let (value, scc) = sop2_expected(opcode, a, b, true); + cases.push(( + sop2_program(&[sop2(opcode, 10, 8, 255), b], 10, a, 7, Some(true)), + lanes(value, scc), + )); + let (value, scc) = sop2_expected(opcode, b, a, true); + cases.push(( + sop2_program(&[sop2(opcode, 10, 255, 8), b], 10, a, 7, Some(true)), + lanes(value, scc), + )); + for (selector, inline) in [(0x80, 0), (0xc0, 64), (0xc1, u32::MAX), (0xd0, 0xffff_fff0)] + { + let (value, scc) = sop2_expected(opcode, a, inline, true); + let code = sop2_program(&[sop2(opcode, 10, 8, selector)], 10, a, b, Some(true)); + cases.push((code, lanes(value, scc))); + } + } + cases + } + + #[test] + fn scalar_alu_matches_definitions_on_boundary_operands() { + let vectors = sop2_vectors(); + assert_eq!(vectors.len(), 7 * 10 * 10 * 2); + for (code, expected) in &vectors { + verify(code, &[0, u32::MAX], Some(expected)); + assert_translated(code, expected); + } + } + + #[test] + fn scalar_alu_aliasing_inline_and_literal_operands() { + let cases = sop2_operand_cases(); + assert_eq!(cases.len(), 7 * 10); + for (code, expected) in &cases { + verify(code, &[0, u32::MAX], Some(expected)); + assert_translated(code, expected); + } + } + + /// All three implementations reject `code`, and at byte `offset`. + fn rejected_at(code: &[u8], offset: usize) { + rejected_at_with(code, offset, &[0, 1]); + } + + fn rejected_at_with(code: &[u8], offset: usize, input: &[u32]) { + let error = compile(Architecture::Gfx1030, code).unwrap_err(); + let at = match error { + xenora_shader::CompileError::Verify { offset, .. } => offset, + xenora_shader::CompileError::Decode(ref decode) => decode.offset, + ref other => panic!("{other:?}"), + }; + assert_eq!(at, offset, "{error:?}"); + assert_eq!(xenora_ref::execute(code, input).unwrap_err().offset, offset); + let independent = independent_ref::execute(code, input).unwrap_err(); + assert!( + independent.starts_with(&format!("{offset:#x}:")), + "{independent}" + ); + } + + #[test] + fn scalar_alu_rejects_forms_outside_the_subset() { + // load 8, wait 4, two literal moves 8 each, s_cmp 4: the SOP2 word is at 0x20. + for opcode in [2, 3, 15, 17, 19] { + // s_add_i32 and s_sub_i32 (SCC rule not confirmed), 64-bit bitwise forms. + rejected_at( + &sop2_program(&[sop2(opcode, 10, 8, 9)], 10, 1, 2, Some(false)), + 0x20, + ); + } + for opcode in [4, 5] { + // Without the s_cmp, the carry-in reads SCC before anything set it. + rejected_at( + &sop2_program(&[sop2(opcode, 10, 8, 9)], 10, 1, 2, None), + 0x1c, + ); + } + for (alu, result) in [ + (&[sop2(0, 4, 8, 9)][..], 9), // Resource descriptor destination. + (&[sop2(0, 106, 8, 9)][..], 9), // VCC_LO destination. + (&[sop2(0, 10, 8, 11)][..], 9), // Uninitialized s11. + (&[sop2(0, 10, 106, 9)][..], 9), // VCC_LO source. + (&[sop2(0, 10, 255, 255), 0x1234_5678][..], 9), // Two literal sources. + ] { + // v2 reads s9, which is valid, so only the SOP2 word can fail. + rejected_at(&sop2_program(alu, result, 1, 2, Some(false)), 0x20); + } + // v_mov_b32 from VCC_LO stays outside the subset. + let mut code = sop2_program(&[sop2(0, 10, 8, 9)], 10, 1, 2, Some(false)); + assert_eq!(code[0x24..0x28], 0x7e04_020a_u32.to_le_bytes()); + code[0x24] = 106; + rejected_at(&code, 0x24); + } + + #[test] + fn sgpr_moves_need_known_values_even_for_inactive_lanes() { + let words: [u32; 11] = [ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, // load v1, wait + 0x7e04_0280, // v_mov_b32 v2, 0 + 0xbefe_0382, // s_mov_b32 exec_lo, 2 + 0x7e04_0208, // v_mov_b32 v2, s8 (s8 never written) + 0xbefe_03c1, // s_mov_b32 exec_lo, -1 + 0xe070_2000, + 0x8001_0200, + 0xbbfd_0000, + 0xbf81_0000, + ]; + let code: Vec = words[..11] + .iter() + .flat_map(|word| word.to_le_bytes()) + .collect(); + // One lane, inactive under EXEC_LO = 2: the interpreters must not skip the check. + rejected_at_with(&code, 0x14, &[0]); + } + + #[test] + #[ignore = "requires a native Metal device with API and shader validation"] + fn scalar_alu_native_metal_known_answers() { + 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 metal = xenora_metal::NativeCompute::new().unwrap(); + let run = |code: &[u8], input: &[u32]| { + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + metal + .run_words(&compiled.msl, xenora_shader::ENTRY_POINT, input) + .unwrap() + }; + let input: Vec = (0..64).map(|lane| lane * 0x0101_0101).collect(); + let expected: Vec<_> = input.iter().map(|word| word ^ 0x8000_000e).collect(); + assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected); + let mut vectors = sop2_vectors(); + vectors.extend(sop2_operand_cases()); + for (code, expected) in &vectors { + assert_eq!(&run(code, &[0, u32::MAX]), expected); + } + eprintln!( + "{} SOP2 programs matched on native Metal", + vectors.len() + 1 + ); + } }