diff --git a/crates/stela-compiler/src/aarch64.rs b/crates/stela-compiler/src/aarch64.rs index afc543e8d0..266ff8268a 100644 --- a/crates/stela-compiler/src/aarch64.rs +++ b/crates/stela-compiler/src/aarch64.rs @@ -101,6 +101,7 @@ pub enum FloatingPointOperation { Complex(simd::complex::Operand), Conversion(simd::conversion::Operand), Comparison(simd::comparison::Operand), + ExtremaScale(simd::extrema_scale::Operand), MinMax(simd::minmax::Operand), Rounding(simd::rounding::Operand), SquareRoot(simd::sqrt::Operand), @@ -123,6 +124,8 @@ impl FloatingPointOperation { Some(result.map(Self::Complex)) } else if let Some(result) = simd::conversion::decode(word) { Some(result.map(Self::Conversion)) + } else if let Some(result) = simd::extrema_scale::decode(word) { + Some(result.map(Self::ExtremaScale)) } else if let Some(result) = simd::comparison::decode(word) { Some(result.map(Self::Comparison)) } else if let Some(result) = simd::minmax::decode(word) { @@ -174,6 +177,11 @@ impl From for FloatingPointOperation { Self::Comparison(operand) } } +impl From for FloatingPointOperation { + fn from(operand: simd::extrema_scale::Operand) -> Self { + Self::ExtremaScale(operand) + } +} impl From for FloatingPointOperation { fn from(operand: simd::minmax::Operand) -> Self { Self::MinMax(operand) diff --git a/crates/stela-compiler/src/aarch64/simd.rs b/crates/stela-compiler/src/aarch64/simd.rs index e77e387a44..e920c0b622 100644 --- a/crates/stela-compiler/src/aarch64/simd.rs +++ b/crates/stela-compiler/src/aarch64/simd.rs @@ -9,6 +9,7 @@ pub mod comparison; pub mod complex; pub mod conversion; pub mod estimate; +pub mod extrema_scale; pub mod floating; pub mod fp8_conversion; pub mod fused; diff --git a/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs b/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs new file mode 100644 index 0000000000..555ea5de30 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/simd/extrema_scale.rs @@ -0,0 +1,148 @@ +//! AdvSIMD absolute extrema and integer power-of-two scaling (Arm A64 June 2026). +//! +//! FAMIN/MAX require AdvSIMD + FAMINMAX; FSCALE requires FP8. Decoding does +//! not establish guest feature availability or FP/AdvSIMD access permission. +use crate::aarch64::floating::{Format, absolute_minmax::AbsoluteMinMaxOperation}; + +use super::arithmetic::Shape; + +const REGISTER_MASK: u32 = 31; +const LEFT_SHIFT: u32 = 5; +const RIGHT_SHIFT: u32 = 16; +const VECTOR_Q: u32 = 1 << 30; +const DOUBLE_SIZE: u32 = 1 << 22; +const ORDINARY_MASK: u32 = 0xbfa0_fc00; +const HALF_MASK: u32 = 0xbfe0_fc00; +const FAMAX: u32 = 0x0ea0_dc00; +const FAMIN: u32 = 0x2ea0_dc00; +const FSCALE: u32 = 0x2ea0_fc00; +const HALF_FAMAX: u32 = 0x0ec0_1c00; +const HALF_FAMIN: u32 = 0x2ec0_1c00; +const HALF_FSCALE: u32 = 0x2ec0_3c00; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Absolute(AbsoluteMinMaxOperation), + Scale, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub format: Format, + pub shape: Shape, + pub destination: u8, + pub left: u8, + pub right: u8, +} + +/// V31 is ordinary data in every position. Q=0 writes clear the upper 64 bits. +/// The one-double arrangement is reserved; scalar/pairwise neighbors decline. +#[allow(clippy::result_unit_err)] +pub fn decode(word: u32) -> Option> { + for (mask, half) in [(HALF_MASK, true), (ORDINARY_MASK, false)] { + let kind = match (word & mask, half) { + (HALF_FAMAX, true) | (FAMAX, false) => Kind::Absolute(AbsoluteMinMaxOperation::Maximum), + (HALF_FAMIN, true) | (FAMIN, false) => Kind::Absolute(AbsoluteMinMaxOperation::Minimum), + (HALF_FSCALE, true) | (FSCALE, false) => Kind::Scale, + _ => continue, + }; + let format = if half { + Format::Half + } else if word & DOUBLE_SIZE != 0 { + Format::Double + } else { + Format::Single + }; + let shape = if word & VECTOR_Q == 0 { + Shape::Vector64 + } else { + Shape::Vector128 + }; + if format == Format::Double && shape == Shape::Vector64 { + return Some(Err(())); + } + return Some(Ok(Operand { + kind, + format, + shape, + destination: (word & REGISTER_MASK) as u8, + left: ((word >> LEFT_SHIFT) & REGISTER_MASK) as u8, + right: ((word >> RIGHT_SHIFT) & REGISTER_MASK) as u8, + })); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_allocated_arrangements_and_register_aliases_decode() { + for (ordinary, half, kind) in [ + ( + FAMAX, + HALF_FAMAX, + Kind::Absolute(AbsoluteMinMaxOperation::Maximum), + ), + ( + FAMIN, + HALF_FAMIN, + Kind::Absolute(AbsoluteMinMaxOperation::Minimum), + ), + (FSCALE, HALF_FSCALE, Kind::Scale), + ] { + for (base, format) in [ + (ordinary, Format::Single), + (ordinary | DOUBLE_SIZE, Format::Double), + (half, Format::Half), + ] { + for (q, shape) in [(0, Shape::Vector64), (VECTOR_Q, Shape::Vector128)] { + for (destination, left, right) in [ + (0, 1, 2), + (0, 0, 2), + (0, 1, 0), + (0, 1, 1), + (0, 0, 0), + (31, 31, 31), + (31, 0, 30), + (28, 31, 0), + ] { + let word = + base | q | destination | (left << LEFT_SHIFT) | (right << RIGHT_SHIFT); + let expected = if format == Format::Double && shape == Shape::Vector64 { + Err(()) + } else { + Ok(Operand { + kind, + format, + shape, + destination: destination as u8, + left: left as u8, + right: right as u8, + }) + }; + assert_eq!(decode(word), Some(expected), "{word:08x}"); + } + } + } + } + } + + #[test] + fn neighboring_families_and_unallocated_sizes_are_not_consumed() { + for word in [ + 0x0e20_dc00, + 0x2e20_dc00, + 0x0e40_1c00, + 0x2e40_1c00, + 0x0e20_f400, + 0x2e20_f400, + 0x1e20_4800, + 0x0e20_e400, + ] { + assert_eq!(decode(word), None, "{word:08x}"); + } + } +} diff --git a/crates/stela-compiler/src/aarch64/sme.rs b/crates/stela-compiler/src/aarch64/sme.rs index 9329ea5b22..f4594791d2 100644 --- a/crates/stela-compiler/src/aarch64/sme.rs +++ b/crates/stela-compiler/src/aarch64/sme.rs @@ -1,6 +1,8 @@ //! Scalable-matrix operands. Mode and feature checks are execution contracts. +pub mod extrema_scale; pub mod fp8_conversion; +pub mod fp8_matrix; pub mod fp_matrix; pub mod fp_vector; pub mod integer_dots; diff --git a/crates/stela-compiler/src/aarch64/sme/extrema_scale.rs b/crates/stela-compiler/src/aarch64/sme/extrema_scale.rs new file mode 100644 index 0000000000..aabd0ff0e5 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/sme/extrema_scale.rs @@ -0,0 +1,192 @@ +//! SME2 destructive grouped absolute extrema and integer exponent scaling. +//! +//! H/S/D groups are aligned pairs/quartets; broadcast scales name Z0..Z15. +//! Execution requires streaming SVE access, without ZA access. Decode grants no +//! permission: extrema also require FAMINMAX and scaling requires FP8. +use crate::aarch64::floating::{Format, absolute_minmax::AbsoluteMinMaxOperation}; + +const SIZE_SHIFT: u32 = 22; +const SIZE_MASK: u32 = 3; +const RIGHT_SHIFT: u32 = 16; +const REGISTER_MASK: u32 = 31; +const BROADCAST_REGISTER_MASK: u32 = 15; +const GROUP_PAIR_MASK: u32 = 0xff21_ffe1; +const GROUP_QUARTET_MASK: u32 = 0xff23_ffe3; +const BROADCAST_PAIR_MASK: u32 = 0xff30_ffe1; +const BROADCAST_QUARTET_MASK: u32 = 0xff30_ffe3; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Group { + Pair, + Quartet, +} +impl Group { + pub const fn count(self) -> u8 { + match self { + Self::Pair => 2, + Self::Quartet => 4, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + AbsoluteMinMax(AbsoluteMinMaxOperation), + Scale, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operand { + pub kind: Kind, + pub destination: u8, + pub right: u8, + pub group: Group, + pub format: Format, + pub right_grouped: bool, +} + +#[derive(Clone, Copy)] +struct Encoding { + mask: u32, + opcode: u32, + kind: Kind, + group: Group, + right_grouped: bool, +} + +const ENCODINGS: [Encoding; 8] = [ + Encoding { + mask: GROUP_PAIR_MASK, + opcode: 0xc120_b140, + kind: Kind::AbsoluteMinMax(AbsoluteMinMaxOperation::Maximum), + group: Group::Pair, + right_grouped: true, + }, + Encoding { + mask: GROUP_QUARTET_MASK, + opcode: 0xc120_b940, + kind: Kind::AbsoluteMinMax(AbsoluteMinMaxOperation::Maximum), + group: Group::Quartet, + right_grouped: true, + }, + Encoding { + mask: GROUP_PAIR_MASK, + opcode: 0xc120_b141, + kind: Kind::AbsoluteMinMax(AbsoluteMinMaxOperation::Minimum), + group: Group::Pair, + right_grouped: true, + }, + Encoding { + mask: GROUP_QUARTET_MASK, + opcode: 0xc120_b941, + kind: Kind::AbsoluteMinMax(AbsoluteMinMaxOperation::Minimum), + group: Group::Quartet, + right_grouped: true, + }, + Encoding { + mask: BROADCAST_PAIR_MASK, + opcode: 0xc120_a180, + kind: Kind::Scale, + group: Group::Pair, + right_grouped: false, + }, + Encoding { + mask: BROADCAST_QUARTET_MASK, + opcode: 0xc120_a980, + kind: Kind::Scale, + group: Group::Quartet, + right_grouped: false, + }, + Encoding { + mask: GROUP_PAIR_MASK, + opcode: 0xc120_b180, + kind: Kind::Scale, + group: Group::Pair, + right_grouped: true, + }, + Encoding { + mask: GROUP_QUARTET_MASK, + opcode: 0xc120_b980, + kind: Kind::Scale, + group: Group::Quartet, + right_grouped: true, + }, +]; + +pub fn decode(word: u32) -> Option { + let encoding = ENCODINGS + .iter() + .find(|encoding| word & encoding.mask == encoding.opcode)?; + let format = match (word >> SIZE_SHIFT) & SIZE_MASK { + 1 => Format::Half, + 2 => Format::Single, + 3 => Format::Double, + // Size zero belongs to other instructions (including BFSCALE). + _ => return None, + }; + Some(Operand { + kind: encoding.kind, + destination: (word & REGISTER_MASK) as u8 & !(encoding.group.count() - 1), + right: if encoding.right_grouped { + ((word >> RIGHT_SHIFT) & REGISTER_MASK) as u8 & !(encoding.group.count() - 1) + } else { + ((word >> RIGHT_SHIFT) & BROADCAST_REGISTER_MASK) as u8 + }, + group: encoding.group, + format, + right_grouped: encoding.right_grouped, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_form_width_and_group_register_combination_decodes_exactly() { + for encoding in ENCODINGS { + let count = encoding.group.count(); + for (size, format) in [(1, Format::Half), (2, Format::Single), (3, Format::Double)] { + for destination in (0..32).step_by(usize::from(count)) { + let right_count = if encoding.right_grouped { count } else { 1 }; + let right_limit = if encoding.right_grouped { 32 } else { 16 }; + for right in (0..right_limit).step_by(usize::from(right_count)) { + let word = encoding.opcode + | size << SIZE_SHIFT + | destination + | right << RIGHT_SHIFT; + assert_eq!( + decode(word), + Some(Operand { + kind: encoding.kind, + destination: destination as u8, + right: right as u8, + group: encoding.group, + format, + right_grouped: encoding.right_grouped, + }) + ); + } + } + } + assert_eq!(decode(encoding.opcode), None); + } + } + + #[test] + fn fixed_register_alignment_and_neighbor_operation_bits_are_not_ignored() { + for encoding in ENCODINGS { + let word = encoding.opcode | 1 << SIZE_SHIFT; + assert!(decode(word ^ 1 << 10).is_none()); + if encoding.group == Group::Quartet { + assert!(decode(word | 1 << 1).is_none()); + if encoding.right_grouped { + assert!(decode(word | 1 << 17).is_none()); + } + } + if !encoding.right_grouped { + assert!(decode(word | 1 << 20).is_none()); + } + } + } +} diff --git a/crates/stela-compiler/src/aarch64/sme/fp8_matrix.rs b/crates/stela-compiler/src/aarch64/sme/fp8_matrix.rs new file mode 100644 index 0000000000..67848754d3 --- /dev/null +++ b/crates/stela-compiler/src/aarch64/sme/fp8_matrix.rs @@ -0,0 +1,605 @@ +//! SME FP8 arithmetic into ZA. Decoding is independent of execution state. +//! +//! The caller checks SME_F8F16/SME_F8F32 according to `accumulator`, then FPMR +//! access and streaming/ZA access, in that order. These forms do not update FPSR. + +use crate::aarch64::{ + floating::Format, + scalable::{VECTOR_CHUNK_BYTES, VECTOR_REGISTER_COUNT, VectorLength}, +}; + +const SELECTOR_SHIFT: u32 = 13; +const SELECTOR_MASK: u32 = 3; +const FIRST_SELECTOR: u8 = 8; +const LEFT_SHIFT: u32 = 5; +const RIGHT_SHIFT: u32 = 16; +const REGISTER_MASK: u32 = 31; +const SINGLE_RIGHT_MASK: u32 = 15; +const INDEX_HIGH_SHIFT: u32 = 10; +const INDEX_SINGLE_HIGH_SHIFT: u32 = 15; +const INDEX_LOW_SHIFT: u32 = 3; +const INDEX_PAIR_LOW_SHIFT: u32 = 2; +const INDEX_QUARTET_LOW_SHIFT: u32 = 1; +const OFFSET_MASK: u32 = 7; +const MAX_ROWS: usize = 16; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VectorOperation { + Dot, + MultiplyAdd, + /// Half precision uses `top: false`; single precision has bottom/top forms. + VerticalDot { + top: bool, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RightSource { + Vector(u8), + Group(u8), + /// Byte, pair, or quartet index within each 128-bit source segment. + Indexed { + register: u8, + index: u8, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VectorOperand { + pub operation: VectorOperation, + pub accumulator: Format, + /// Number of destination groups, distinct from the number of source Zs. + pub groups: u8, + pub left: u8, + pub right: RightSource, + pub vector_select: u8, + /// Decoded byte-vector offset, including the implicit low zero bits. + pub offset: u8, +} + +impl VectorOperand { + pub const fn accumulator_bytes(self) -> usize { + match self.accumulator { + Format::Half => 2, + Format::Single => 4, + Format::Double => 8, + } + } + + pub const fn rows_per_group(self) -> u8 { + match self.operation { + VectorOperation::MultiplyAdd => self.accumulator_bytes() as u8, + _ => 1, + } + } + + pub const fn row_count(self) -> u8 { + self.groups * self.rows_per_group() + } + + pub const fn terms(self) -> u8 { + match self.operation { + VectorOperation::MultiplyAdd => 1, + VectorOperation::VerticalDot { .. } => 2, + VectorOperation::Dot => self.accumulator_bytes() as u8, + } + } + + /// Ordered by destination group, then by adjacent row within that group. + /// The selector addition is mathematical, before modulo and alignment. + pub fn rows(self, length: VectorLength, selector: u32) -> [u16; MAX_ROWS] { + let stride = length.bytes() as u16 / u16::from(self.groups); + let adjacent = u16::from(self.rows_per_group()); + let base = ((u64::from(selector) + u64::from(self.offset)) % u64::from(stride)) as u16; + let base = base - base % adjacent; + let mut rows = [0; MAX_ROWS]; + for group in 0..self.groups { + for row in 0..self.rows_per_group() { + rows[usize::from(group * self.rows_per_group() + row)] = + base + u16::from(group) * stride + u16::from(row); + } + } + rows + } + + /// Byte locations of one product. `row` is relative to its ZA group. + /// Source registers are read before writing ZA; Z/ZA aliasing is impossible. + pub fn source_bytes( + self, + group: u8, + row: u8, + element: usize, + term: u8, + ) -> Option<(SourceByte, SourceByte)> { + if group >= self.groups || row >= self.rows_per_group() || term >= self.terms() { + return None; + } + let bytes = self.accumulator_bytes(); + let segment = element / (VECTOR_CHUNK_BYTES / bytes) * VECTOR_CHUNK_BYTES; + let (left_register, left_byte) = match self.operation { + VectorOperation::VerticalDot { .. } => { + (self.left + term, bytes * element + usize::from(group)) + } + VectorOperation::MultiplyAdd => ( + (self.left + group) % VECTOR_REGISTER_COUNT, + bytes * element + usize::from(row), + ), + VectorOperation::Dot => ( + (self.left + group) % VECTOR_REGISTER_COUNT, + bytes * element + usize::from(term), + ), + }; + let (right_register, right_byte) = match self.right { + RightSource::Vector(register) => (register, left_byte), + RightSource::Group(register) => (register + group, left_byte), + RightSource::Indexed { register, index } => { + let byte = match self.operation { + VectorOperation::MultiplyAdd => segment + usize::from(index), + VectorOperation::Dot => { + segment + bytes * usize::from(index) + usize::from(term) + } + VectorOperation::VerticalDot { top } => { + segment + + bytes * usize::from(index) + + if top { 2 } else { 0 } + + usize::from(term) + } + }; + (register, byte) + } + }; + Some(( + SourceByte { + register: left_register, + byte: left_byte, + }, + SourceByte { + register: right_register, + byte: right_byte, + }, + )) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SourceByte { + pub register: u8, + pub byte: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OuterOperand { + pub accumulator: Format, + pub tile: u8, + pub left: u8, + pub right: u8, + pub row_predicate: u8, + pub column_predicate: u8, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Operand { + Vector(VectorOperand), + Outer(OuterOperand), +} + +#[derive(Debug, Clone, Copy)] +enum Layout { + Indexed, + Vector, + Group, +} + +#[derive(Debug, Clone, Copy)] +struct Encoding { + mask: u32, + value: u32, + accumulator: Format, + operation: VectorOperation, + groups: u8, + layout: Layout, +} + +macro_rules! encoding { + ($mask:expr, $value:expr, $format:ident, $operation:expr, $groups:expr, $layout:ident) => { + Encoding { + mask: $mask, + value: $value, + accumulator: Format::$format, + operation: $operation, + groups: $groups, + layout: Layout::$layout, + } + }; +} + +// Exact fixed bits from hash-pinned June 2026 XML. No aliases exist on these pages. +const ENCODINGS: [Encoding; 31] = { + use VectorOperation::{Dot, MultiplyAdd, VerticalDot}; + [ + encoding!(0xfff0_9038, 0xc150_0038, Single, Dot, 2, Indexed), // fdot_za32_z8z8i_2xi + encoding!(0xfff0_9078, 0xc150_8008, Single, Dot, 4, Indexed), // fdot_za32_z8z8i_4xi + encoding!(0xfff0_9c18, 0xc120_1018, Single, Dot, 2, Vector), // fdot_za32_z8z8v_2x1 + encoding!(0xfff0_9c18, 0xc130_1018, Single, Dot, 4, Vector), // fdot_za32_z8z8v_4x1 + encoding!(0xffe1_9c38, 0xc1a0_1030, Single, Dot, 2, Group), // fdot_za32_z8z8w_2x2 + encoding!(0xffe3_9c78, 0xc1a1_1030, Single, Dot, 4, Group), // fdot_za32_z8z8w_4x4 + encoding!(0xfff0_9030, 0xc1d0_0020, Half, Dot, 2, Indexed), // fdot_za_z8z8i_2xi + encoding!(0xfff0_9070, 0xc110_9040, Half, Dot, 4, Indexed), // fdot_za_z8z8i_4xi + encoding!(0xfff0_9c18, 0xc120_1008, Half, Dot, 2, Vector), // fdot_za_z8z8v_2x1 + encoding!(0xfff0_9c18, 0xc130_1008, Half, Dot, 4, Vector), // fdot_za_z8z8v_4x1 + encoding!(0xffe1_9c38, 0xc1a0_1020, Half, Dot, 2, Group), // fdot_za_z8z8w_2x2 + encoding!(0xffe3_9c78, 0xc1a1_1020, Half, Dot, 4, Group), // fdot_za_z8z8w_4x4 + encoding!(0xfff0_1010, 0xc1c0_0000, Half, MultiplyAdd, 1, Indexed), // fmlal_za_z8z8i_1 + encoding!(0xfff0_9030, 0xc190_1030, Half, MultiplyAdd, 2, Indexed), // fmlal_za_z8z8i_2xi + encoding!(0xfff0_9070, 0xc190_9020, Half, MultiplyAdd, 4, Indexed), // fmlal_za_z8z8i_4xi + encoding!(0xfff0_9c18, 0xc130_0c00, Half, MultiplyAdd, 1, Vector), // fmlal_za_z8z8v_1 + encoding!(0xfff0_9c1c, 0xc120_0804, Half, MultiplyAdd, 2, Vector), // fmlal_za_z8z8v_2x1 + encoding!(0xfff0_9c1c, 0xc130_0804, Half, MultiplyAdd, 4, Vector), // fmlal_za_z8z8v_4x1 + encoding!(0xffe1_9c3c, 0xc1a0_0820, Half, MultiplyAdd, 2, Group), // fmlal_za_z8z8w_2x2 + encoding!(0xffe3_9c7c, 0xc1a1_0820, Half, MultiplyAdd, 4, Group), // fmlal_za_z8z8w_4x4 + encoding!(0xfff0_001c, 0xc140_0000, Single, MultiplyAdd, 1, Indexed), // fmlall_za32_z8z8i_1 + encoding!(0xfff0_9038, 0xc190_0020, Single, MultiplyAdd, 2, Indexed), // fmlall_za32_z8z8i_2xi + encoding!(0xfff0_9078, 0xc110_8040, Single, MultiplyAdd, 4, Indexed), // fmlall_za32_z8z8i_4xi + encoding!(0xfff0_9c1c, 0xc130_0400, Single, MultiplyAdd, 1, Vector), // fmlall_za32_z8z8v_1 + encoding!(0xfff0_9c1e, 0xc120_0002, Single, MultiplyAdd, 2, Vector), // fmlall_za32_z8z8v_2x1 + encoding!(0xfff0_9c1e, 0xc130_0002, Single, MultiplyAdd, 4, Vector), // fmlall_za32_z8z8v_4x1 + encoding!(0xffe1_9c3e, 0xc1a0_0020, Single, MultiplyAdd, 2, Group), // fmlall_za32_z8z8w_2x2 + encoding!(0xffe3_9c7e, 0xc1a1_0020, Single, MultiplyAdd, 4, Group), // fmlall_za32_z8z8w_4x4 + encoding!( + 0xfff0_9030, + 0xc1d0_1020, + Half, + VerticalDot { top: false }, + 2, + Indexed + ), // fvdot_za_z8z8i_2xi + encoding!( + 0xfff0_9830, + 0xc1d0_0800, + Single, + VerticalDot { top: false }, + 4, + Indexed + ), // fvdotb_za32_z8z8i_2xi + encoding!( + 0xfff0_9830, + 0xc1d0_0810, + Single, + VerticalDot { top: true }, + 4, + Indexed + ), // fvdott_za32_z8z8i_2xi + ] +}; + +fn indexed_element(word: u32, encoding: Encoding) -> u8 { + let high = word >> INDEX_HIGH_SHIFT; + let low = word >> INDEX_LOW_SHIFT; + (match (encoding.operation, encoding.accumulator, encoding.groups) { + (VectorOperation::MultiplyAdd, Format::Half, 1) => { + ((word >> INDEX_SINGLE_HIGH_SHIFT & 1) << 3) | ((high & 3) << 1) | (low & 1) + } + (VectorOperation::MultiplyAdd, Format::Single, 1) => { + ((word >> INDEX_SINGLE_HIGH_SHIFT & 1) << 3) | (high & 7) + } + (VectorOperation::MultiplyAdd, Format::Half, _) => { + ((high & 3) << 2) | (word >> INDEX_PAIR_LOW_SHIFT & 3) + } + (VectorOperation::MultiplyAdd, Format::Single, _) => { + ((high & 3) << 2) | (word >> INDEX_QUARTET_LOW_SHIFT & 3) + } + (VectorOperation::VerticalDot { .. }, Format::Single, _) => ((high & 1) << 1) | (low & 1), + (_, Format::Half, _) => ((high & 3) << 1) | (low & 1), + _ => high & 3, + }) as u8 +} + +pub fn decode(word: u32) -> Option { + const OUTER_HALF_MASK: u32 = 0xffe0_001e; + const OUTER_HALF: u32 = 0x80a0_0008; + const OUTER_SINGLE_MASK: u32 = 0xffe0_001c; + const OUTER_SINGLE: u32 = 0x80a0_0000; + let outer = if word & OUTER_HALF_MASK == OUTER_HALF { + Some((Format::Half, 1)) + } else if word & OUTER_SINGLE_MASK == OUTER_SINGLE { + Some((Format::Single, 3)) + } else { + None + }; + if let Some((accumulator, tile_mask)) = outer { + const LEFT_PREDICATE_SHIFT: u32 = 10; + const RIGHT_PREDICATE_SHIFT: u32 = 13; + const PREDICATE_MASK: u32 = 7; + return Some(Operand::Outer(OuterOperand { + accumulator, + tile: (word & tile_mask) as u8, + left: (word >> LEFT_SHIFT & REGISTER_MASK) as u8, + right: (word >> RIGHT_SHIFT & REGISTER_MASK) as u8, + row_predicate: (word >> LEFT_PREDICATE_SHIFT & PREDICATE_MASK) as u8, + column_predicate: (word >> RIGHT_PREDICATE_SHIFT & PREDICATE_MASK) as u8, + })); + } + let encoding = *ENCODINGS + .iter() + .find(|encoding| word & encoding.mask == encoding.value)?; + let source_groups = if matches!(encoding.operation, VectorOperation::VerticalDot { .. }) { + 2 + } else { + encoding.groups + }; + let aligned = !matches!(encoding.layout, Layout::Vector); + let left = (word >> LEFT_SHIFT & REGISTER_MASK) as u8; + let left = if aligned { + left / source_groups * source_groups + } else { + left + }; + let right = match encoding.layout { + Layout::Group => RightSource::Group( + (word >> RIGHT_SHIFT & REGISTER_MASK) as u8 / source_groups * source_groups, + ), + Layout::Vector => RightSource::Vector((word >> RIGHT_SHIFT & SINGLE_RIGHT_MASK) as u8), + Layout::Indexed => RightSource::Indexed { + register: (word >> RIGHT_SHIFT & SINGLE_RIGHT_MASK) as u8, + index: indexed_element(word, encoding), + }, + }; + let offset = if matches!(encoding.operation, VectorOperation::MultiplyAdd) { + let bytes = if encoding.accumulator == Format::Half { + 2 + } else { + 4 + }; + let mask = if encoding.groups == 1 { + OFFSET_MASK / (bytes / 2) + } else { + OFFSET_MASK / bytes + }; + (word & mask) * bytes + } else { + word & OFFSET_MASK + }; + Some(Operand::Vector(VectorOperand { + operation: encoding.operation, + accumulator: encoding.accumulator, + groups: encoding.groups, + left, + right, + vector_select: FIRST_SELECTOR + (word >> SELECTOR_SHIFT & SELECTOR_MASK) as u8, + offset: offset as u8, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vector(word: u32) -> VectorOperand { + let Some(Operand::Vector(operand)) = decode(word) else { + panic!("expected vector operand for {word:08x}"); + }; + operand + } + + #[test] + fn all_canonical_forms_have_disjoint_fixed_bits() { + assert_eq!(ENCODINGS.len() + 2, 33); + for (index, encoding) in ENCODINGS.iter().enumerate() { + assert_eq!(encoding.value & encoding.mask, encoding.value); + for other in &ENCODINGS[index + 1..] { + assert_ne!( + (encoding.value ^ other.value) & encoding.mask & other.mask, + 0 + ); + } + for variable in [0, !encoding.mask] { + let operand = vector(encoding.value | variable); + assert_eq!(operand.operation, encoding.operation); + assert_eq!(operand.accumulator, encoding.accumulator); + assert_eq!(operand.groups, encoding.groups); + assert_eq!(operand.vector_select, if variable == 0 { 8 } else { 11 }); + let source_groups = + if matches!(encoding.operation, VectorOperation::VerticalDot { .. }) { + 2 + } else { + encoding.groups + }; + assert_eq!( + operand.left, + if variable == 0 { + 0 + } else if matches!(encoding.layout, Layout::Vector) { + 31 + } else { + 32 - source_groups + } + ); + match operand.right { + RightSource::Indexed { register, index } => { + assert_eq!(register, if variable == 0 { 0 } else { 15 }); + let maximum = match (encoding.operation, encoding.accumulator) { + (VectorOperation::MultiplyAdd, _) => 15, + (_, Format::Half) => 7, + _ => 3, + }; + assert_eq!(index, if variable == 0 { 0 } else { maximum }); + } + RightSource::Vector(register) => { + assert_eq!(register, if variable == 0 { 0 } else { 15 }) + } + RightSource::Group(register) => { + assert_eq!(register, if variable == 0 { 0 } else { 32 - source_groups }) + } + } + } + } + } + + #[test] + fn split_immediates_and_implicit_offset_bits() { + // Each source-index bit independently; the selector and ZA offset do not overlap. + for (word, bits) in [ + (0xc1c0_0000, [3, 10, 11, 15]), + (0xc190_1030, [2, 3, 10, 11]), + (0xc140_0000, [10, 11, 12, 15]), + (0xc190_0020, [1, 2, 10, 11]), + ] { + for index in 0..16 { + let word = bits.iter().enumerate().fold(word, |word, (bit, shift)| { + word | ((index >> bit & 1) << shift) + }); + assert_eq!( + vector(word).right, + RightSource::Indexed { + register: 0, + index: index as u8 + } + ); + assert_eq!(vector(word).offset, 0); + } + } + for (word, maximum) in [ + (0xc130_0c00, 14), + (0xc120_0804, 6), + (0xc130_0400, 12), + (0xc120_0002, 4), + ] { + let encoding = ENCODINGS.iter().find(|e| e.value == word).unwrap(); + assert_eq!(vector(word | !encoding.mask).offset, maximum); + } + } + + #[test] + fn outer_tile_register_and_predicate_fields() { + for (word, format, tile_mask) in [ + (0x80a0_0008, Format::Half, 1), + (0x80a0_0000, Format::Single, 3), + ] { + for tile in 0..=tile_mask { + let Some(Operand::Outer(operand)) = + decode(word | (31 << 16) | (6 << 13) | (5 << 10) | (29 << 5) | tile) + else { + panic!() + }; + assert_eq!( + operand, + OuterOperand { + accumulator: format, + tile: tile as u8, + left: 29, + right: 31, + row_predicate: 5, + column_predicate: 6 + } + ); + } + } + } + + #[test] + fn long_rows_align_after_mathematical_selector_addition() { + for bytes in [16, 32, 64, 128, 256] { + let length = VectorLength::from_bytes(bytes).unwrap(); + for encoding in ENCODINGS { + let operand = vector(encoding.value | !encoding.mask); + for selector in [0, 1, 3, u32::MAX] { + let rows = operand.rows(length, selector); + let stride = bytes / usize::from(operand.groups); + let adjacent = usize::from(operand.rows_per_group()); + let base = ((u64::from(selector) + u64::from(operand.offset)) % stride as u64) + as usize; + let base = base / adjacent * adjacent; + for group in 0..usize::from(operand.groups) { + for row in 0..adjacent { + assert_eq!( + usize::from(rows[group * adjacent + row]), + base + group * stride + row + ); + } + } + assert!( + rows[..usize::from(operand.row_count())] + .iter() + .all(|&row| usize::from(row) < bytes) + ); + } + } + } + } + + #[test] + fn vector_sources_wrap_and_aligned_sources_end_at_z31() { + let operand = vector(0xc130_1008 | (31 << 5) | (15 << 16)); + for group in 0..4 { + let (left, right) = operand.source_bytes(group, 0, 0, 0).unwrap(); + assert_eq!(left.register, (31 + group) % 32); + assert_eq!(right.register, 15); + } + let operand = vector(0xc1a1_1030 | (28 << 5) | (28 << 16)); + assert_eq!(operand.source_bytes(3, 0, 0, 0).unwrap().0.register, 31); + assert_eq!(operand.source_bytes(3, 0, 0, 0).unwrap().1.register, 31); + } + + #[test] + fn indexed_sources_repeat_within_each_128_bit_segment() { + let half_dot = vector(0xc1d0_0020 | (3 << 10) | (1 << 3)); + assert_eq!(half_dot.source_bytes(0, 0, 8, 1).unwrap().1.byte, 31); + let single_dot = vector(0xc150_0038 | (3 << 10)); + assert_eq!(single_dot.source_bytes(0, 0, 4, 3).unwrap().1.byte, 31); + let half_long = vector(0xc190_1030 | (3 << 10) | (3 << 2)); + assert_eq!(half_long.source_bytes(0, 1, 8, 0).unwrap().0.byte, 17); + assert_eq!(half_long.source_bytes(0, 1, 8, 0).unwrap().1.byte, 31); + let single_long = vector(0xc190_0020 | (3 << 10) | (3 << 1)); + assert_eq!(single_long.source_bytes(0, 3, 4, 0).unwrap().0.byte, 19); + assert_eq!(single_long.source_bytes(0, 3, 4, 0).unwrap().1.byte, 31); + } + + #[test] + fn vertical_pair_gathers_and_bottom_top_select_distinct_pairs() { + for (word, groups, bytes, top) in [ + (0xc1d0_1020, 2, 2, false), + (0xc1d0_0800, 4, 4, false), + (0xc1d0_0810, 4, 4, true), + ] { + let operand = vector(word | (30 << 5) | (1 << 3)); + assert_eq!(operand.groups, groups); + assert_eq!(operand.row_count(), groups); + assert_eq!(operand.terms(), 2); + for group in 0..groups { + for term in 0..2 { + let (left, right) = operand.source_bytes(group, 0, 16 / bytes, term).unwrap(); + assert_eq!( + left, + SourceByte { + register: 30 + term, + byte: 16 + usize::from(group) + } + ); + assert_eq!( + right.byte, + 16 + bytes + if top { 2 } else { 0 } + usize::from(term) + ); + } + } + } + } + + #[test] + fn invalid_source_coordinates_and_reserved_encodings_are_explicit() { + let operand = vector(0xc1a1_0020); + assert_eq!(operand.row_count(), 16); + assert_eq!(operand.source_bytes(4, 0, 0, 0), None); + assert_eq!(operand.source_bytes(0, 4, 0, 0), None); + assert_eq!(operand.source_bytes(0, 0, 0, 1), None); + for word in [ + 0, + u32::MAX, + 0x80a0_0018, + 0x80a0_0004, + 0xc1d0_0030, + 0xc1d0_1800, + ] { + assert_eq!(decode(word), None, "reserved {word:08x}"); + } + } +} diff --git a/crates/stela-compiler/src/block/scalable.rs b/crates/stela-compiler/src/block/scalable.rs index 1d18794508..fa8a67b303 100644 --- a/crates/stela-compiler/src/block/scalable.rs +++ b/crates/stela-compiler/src/block/scalable.rs @@ -4,10 +4,10 @@ use crate::{ CompileError, GuestAddress, aarch64::{ - floating::features::NumericalFeatures, + floating::{Format, features::NumericalFeatures}, scalable::features::{FeatureRequirement, ScalableFeature, ScalableFeatures}, simd::fp8_conversion as fixed_fp8_conversion, - sme::{fp_matrix, fp_vector, fp8_conversion}, + sme::{extrema_scale, fp_matrix, fp_vector, fp8_conversion, fp8_matrix}, sve::floating, }, extended::ScalableProfile, @@ -20,6 +20,8 @@ pub enum ScalableNumericalOperation { Sve(floating::Operation), FixedFp8Conversion(fixed_fp8_conversion::Operand), SmeFp8Conversion(fp8_conversion::Operand), + SmeFp8Matrix(fp8_matrix::Operand), + SmeExtremaScale(extrema_scale::Operand), SmeVector(fp_vector::Operand), SmeMatrix(fp_matrix::Operand), } @@ -76,12 +78,30 @@ impl ScalableNumericalOperation { let sme2 = sme.with(Feature::Sme2); match self { Self::Sve(operation) => operation.required_streaming_features(numerical_features), + Self::SmeExtremaScale(operand) => { + FeatureRequirement::all(sme2.with(match operand.kind { + extrema_scale::Kind::AbsoluteMinMax(_) => Feature::FaMinMax, + extrema_scale::Kind::Scale => Feature::Fp8, + })) + } Self::FixedFp8Conversion(_) => { FeatureRequirement::all(ScalableFeatures::of(Feature::Fp8).with(Feature::Fpmr)) } Self::SmeFp8Conversion(_) => { FeatureRequirement::all(sme2.with(Feature::Fp8).with(Feature::Fpmr)) } + Self::SmeFp8Matrix(operand) => { + let accumulator = match operand { + fp8_matrix::Operand::Vector(operand) => operand.accumulator, + fp8_matrix::Operand::Outer(operand) => operand.accumulator, + }; + let feature = match accumulator { + Format::Half => Feature::SmeF8F16, + Format::Single => Feature::SmeF8F32, + Format::Double => unreachable!("FP8 matrix decoder allocates Half and Single"), + }; + FeatureRequirement::all(sme.with(feature).with(Feature::Fpmr)) + } Self::SmeVector(operand) => FeatureRequirement::all(match operand.feature { fp_vector::Feature::Sme2 => sme2, fp_vector::Feature::Sme2SveB16B16 => sme2.with(Feature::SveB16B16), @@ -125,6 +145,22 @@ pub fn admit_scalable_numerical_instruction( "scalable numerical source/descriptor mismatch".into(), )); } + // A typed descriptor is not execution evidence. Keep all vertical-dot forms + // private until an independently usable original execution domain exists. + if matches!( + instruction.operation, + ScalableNumericalOperation::SmeFp8Matrix(fp8_matrix::Operand::Vector( + fp8_matrix::VectorOperand { + operation: fp8_matrix::VectorOperation::VerticalDot { .. }, + .. + } + )) + ) { + return Err(CompileError(format!( + "unadmitted SME FP8 vertical dot at {:#x}: original execution verification is pending", + instruction.instruction_pc.0 + ))); + } // This allocated form stays unadmitted until genuine original execution // verification exists. A decoder descriptor never grants execution permission. if matches!( @@ -145,6 +181,7 @@ pub fn admit_scalable_numerical_instruction( ScalableNumericalOperation::FixedFp8Conversion(_) | ScalableNumericalOperation::SmeFp8Conversion(_) | ScalableNumericalOperation::Sve(floating::Operation::Fp8(_)) + | ScalableNumericalOperation::SmeFp8Matrix(_) ) && !profile.controls().fpmr_enabled() { return Err(CompileError( @@ -162,7 +199,7 @@ pub fn admit_scalable_numerical_instruction( !mode.streaming() }) || (matches!( instruction.operation, - ScalableNumericalOperation::SmeMatrix(_) + ScalableNumericalOperation::SmeMatrix(_) | ScalableNumericalOperation::SmeFp8Matrix(_) ) && !mode.za_enabled()) { return Err(CompileError(format!( @@ -204,6 +241,10 @@ pub fn decode_scalable_numerical_instruction( ScalableNumericalOperation::FixedFp8Conversion(operand) } else if let Some(operand) = fp8_conversion::decode(word) { ScalableNumericalOperation::SmeFp8Conversion(operand) + } else if let Some(operand) = fp8_matrix::decode(word) { + ScalableNumericalOperation::SmeFp8Matrix(operand) + } else if let Some(operand) = extrema_scale::decode(word) { + ScalableNumericalOperation::SmeExtremaScale(operand) } else if let Some(result) = floating::Operation::decode(word) { let operand = result.map_err(|()| CompileError("reserved scalable numerical encoding".into()))?; @@ -268,3 +309,6 @@ mod numerical22_scope_tests; #[cfg(test)] mod sme_matrix_tests; + +#[cfg(test)] +mod fp8_matrix_scope_tests; diff --git a/crates/stela-compiler/src/block/scalable/fp8_matrix_scope_tests.rs b/crates/stela-compiler/src/block/scalable/fp8_matrix_scope_tests.rs new file mode 100644 index 0000000000..a8b39cc293 --- /dev/null +++ b/crates/stela-compiler/src/block/scalable/fp8_matrix_scope_tests.rs @@ -0,0 +1,208 @@ +//! Public matrix30 admission and the private vertical-dot verification boundary. +use super::*; +use crate::{ + TargetCpu, + aarch64::scalable::{ScalableMode, VectorLength, profile::ScalableControls}, + block::BlockProfile, + extended::block::{ExtendedBlockProfile, compile_for_profile}, +}; + +const PC: GuestAddress = GuestAddress(0x1000); +const BFCVT_PENDING: u32 = 0xc164_e000; +const NOP_WORD: u32 = 0xd503_201f; +// Pinned June encoding facts: canonical ID, lowest operands, highest operands. +const PUBLIC_FORMS: &[(&str, u32, u32)] = &[ + ("fdot_za_z8z8i_2xi", 0xc1d00020, 0xc1df6fef), + ("fdot_za_z8z8i_4xi", 0xc1109040, 0xc11fffcf), + ("fdot_za_z8z8v_2x1", 0xc1201008, 0xc12f73ef), + ("fdot_za_z8z8v_4x1", 0xc1301008, 0xc13f73ef), + ("fdot_za_z8z8w_2x2", 0xc1a01020, 0xc1be73e7), + ("fdot_za_z8z8w_4x4", 0xc1a11020, 0xc1bd73a7), + ("fmlal_za_z8z8i_1", 0xc1c00000, 0xc1cfefef), + ("fmlal_za_z8z8i_2xi", 0xc1901030, 0xc19f7fff), + ("fmlal_za_z8z8i_4xi", 0xc1909020, 0xc19fffaf), + ("fmlal_za_z8z8v_1", 0xc1300c00, 0xc13f6fe7), + ("fmlal_za_z8z8v_2x1", 0xc1200804, 0xc12f6be7), + ("fmlal_za_z8z8v_4x1", 0xc1300804, 0xc13f6be7), + ("fmlal_za_z8z8w_2x2", 0xc1a00820, 0xc1be6be3), + ("fmlal_za_z8z8w_4x4", 0xc1a10820, 0xc1bd6ba3), + ("fmopa_za16_pp_z8z8_8", 0x80a00008, 0x80bfffe9), + ("fmopa_za32_pp_z8z8_8", 0x80a00000, 0x80bfffe3), + ("fmlall_za32_z8z8i_1", 0xc1400000, 0xc14fffe3), + ("fmlall_za32_z8z8i_2xi", 0xc1900020, 0xc19f6fe7), + ("fmlall_za32_z8z8i_4xi", 0xc1108040, 0xc11fefc7), + ("fmlall_za32_z8z8v_1", 0xc1300400, 0xc13f67e3), + ("fmlall_za32_z8z8v_2x1", 0xc1200002, 0xc12f63e3), + ("fmlall_za32_z8z8v_4x1", 0xc1300002, 0xc13f63e3), + ("fmlall_za32_z8z8w_2x2", 0xc1a00020, 0xc1be63e1), + ("fmlall_za32_z8z8w_4x4", 0xc1a10020, 0xc1bd63a1), + ("fdot_za32_z8z8i_2xi", 0xc1500038, 0xc15f6fff), + ("fdot_za32_z8z8i_4xi", 0xc1508008, 0xc15fef8f), + ("fdot_za32_z8z8v_2x1", 0xc1201018, 0xc12f73ff), + ("fdot_za32_z8z8v_4x1", 0xc1301018, 0xc13f73ff), + ("fdot_za32_z8z8w_2x2", 0xc1a01030, 0xc1be73f7), + ("fdot_za32_z8z8w_4x4", 0xc1a11030, 0xc1bd73b7), +]; +const PRIVATE_VERTICAL_FORMS: &[(&str, u32, u32)] = &[ + ("fvdotb_za32_z8z8i_2xi", 0xc1d00800, 0xc1df6fcf), + ("fvdott_za32_z8z8i_2xi", 0xc1d00810, 0xc1df6fdf), + ("fvdot_za_z8z8i_2xi", 0xc1d01020, 0xc1df7fef), +]; + +fn declared_profile(length: usize, available: bool, streaming: bool) -> ScalableProfile { + let features = if available { + ScalableFeatures::checked_from_names([ + "FEAT_SME", + "FEAT_SME2", + "FEAT_FPMR", + "FEAT_FP8", + "FEAT_SME_F8F16", + "FEAT_SME_F8F32", + ]) + .unwrap() + } else { + ScalableFeatures::of(ScalableFeature::Sme) + }; + ScalableProfile::new_with_features( + VectorLength::from_bytes(length).unwrap(), + ScalableMode::new(streaming, streaming), + features, + ScalableControls::new(VectorLength::from_bytes(256).unwrap(), false) + .with_fpmr_enabled(available), + ) + .unwrap() +} + +#[test] +fn public_thirty_forms_admit_and_emit_exact_source() { + assert_eq!(PUBLIC_FORMS.len(), 30); + let profile = declared_profile(64, true, true); + let numerical = NumericalFeatures::default(); + for &(id, low, high) in PUBLIC_FORMS { + for word in [low, high] { + let decoded = decode_scalable_numerical_instruction(PC, word) + .unwrap() + .unwrap(); + assert!( + matches!( + decoded.operation, + ScalableNumericalOperation::SmeFp8Matrix(_) + ), + "{id}" + ); + let admitted = + admit_scalable_numerical_instruction(decoded, profile, numerical).unwrap(); + assert_eq!(admitted.word(), word); + assert_eq!(admitted.next_pc(), GuestAddress(0x1004)); + let compiled = compile_for_profile( + &word.to_le_bytes(), + PC, + ExtendedBlockProfile::new(profile, BlockProfile::Ordinary, numerical), + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(compiled.source_bytes, size_of::(), "{id}"); + assert_eq!(compiled.native.source_map.len(), 1, "{id}"); + assert_eq!(compiled.native.source_map[0].0, PC, "{id}"); + assert!(!compiled.native.x86_64_code.is_empty(), "{id}"); + } + } +} + +#[test] +fn all_vertical_forms_refuse_before_profile_or_emission() { + assert_eq!(PRIVATE_VERTICAL_FORMS.len(), 3); + for length in [16, 64, 256] { + for available in [false, true] { + for streaming in [false, true] { + let profile = declared_profile(length, available, streaming); + for &(id, low, high) in PRIVATE_VERTICAL_FORMS { + for word in [low, high] { + let decoded = decode_scalable_numerical_instruction(PC, word) + .unwrap() + .unwrap(); + let error = admit_scalable_numerical_instruction( + decoded, + profile, + NumericalFeatures::default(), + ) + .unwrap_err(); + assert!( + error.0.contains("unadmitted SME FP8 vertical dot"), + "{id}: {error}" + ); + let emitted = compile_for_profile( + &word.to_le_bytes(), + PC, + ExtendedBlockProfile::new( + profile, + BlockProfile::Ordinary, + NumericalFeatures::default(), + ), + TargetCpu::Baseline, + ); + assert!( + emitted + .unwrap_err() + .0 + .contains("unadmitted SME FP8 vertical dot"), + "{id}" + ); + } + } + } + } + } +} + +#[test] +fn source_descriptor_mismatch_precedes_vertical_verification_refusal() { + let word = PRIVATE_VERTICAL_FORMS[0].1; + let mut decoded = decode_scalable_numerical_instruction(PC, word) + .unwrap() + .unwrap(); + decoded.word = NOP_WORD; + let error = admit_scalable_numerical_instruction( + decoded, + declared_profile(16, false, false), + NumericalFeatures::default(), + ) + .unwrap_err(); + assert!(error.0.contains("source/descriptor mismatch")); +} + +#[test] +fn supported_forms_retain_fpmr_and_za_access_requirements() { + let word = PUBLIC_FORMS[0].1; + let decoded = decode_scalable_numerical_instruction(PC, word) + .unwrap() + .unwrap(); + let error = admit_scalable_numerical_instruction( + decoded, + declared_profile(16, false, true), + NumericalFeatures::default(), + ) + .unwrap_err(); + assert!(error.0.contains("FPMR access")); + let error = admit_scalable_numerical_instruction( + decoded, + declared_profile(16, true, false), + NumericalFeatures::default(), + ) + .unwrap_err(); + assert!(error.0.contains("mode unavailable")); +} + +#[test] +fn existing_bfcvt_pending_policy_is_preserved() { + let decoded = decode_scalable_numerical_instruction(PC, BFCVT_PENDING) + .unwrap() + .unwrap(); + let error = admit_scalable_numerical_instruction( + decoded, + declared_profile(16, true, true), + NumericalFeatures::default(), + ) + .unwrap_err(); + assert!(error.0.contains("unadmitted SME BF16-to-FP8 narrowing")); +} diff --git a/crates/stela-compiler/src/extended/block.rs b/crates/stela-compiler/src/extended/block.rs index 9b72d9fdd0..9998e557bf 100644 --- a/crates/stela-compiler/src/extended/block.rs +++ b/crates/stela-compiler/src/extended/block.rs @@ -229,10 +229,21 @@ pub fn compile_for_profile( pc, target, )?, + ScalableNumericalOperation::SmeExtremaScale(operand) => { + x86_64::sme::extrema_scale::emit( + &mut code, + operand, + profile.scalable.vector_length(), + profile.numerical_features, + pc, + target, + )? + } ScalableNumericalOperation::SmeVector(_) | ScalableNumericalOperation::SmeMatrix(_) | ScalableNumericalOperation::FixedFp8Conversion(_) - | ScalableNumericalOperation::SmeFp8Conversion(_) => false, + | ScalableNumericalOperation::SmeFp8Conversion(_) + | ScalableNumericalOperation::SmeFp8Matrix(_) => false, }; if emitted { // The guarded family mapping owns the exact-PC cold exit. diff --git a/crates/stela-compiler/src/lib.rs b/crates/stela-compiler/src/lib.rs index 4b497b91fe..9e3734251b 100644 --- a/crates/stela-compiler/src/lib.rs +++ b/crates/stela-compiler/src/lib.rs @@ -357,6 +357,13 @@ pub const SOURCE_FINGERPRINT_MATERIAL: &str = concat!( include_str!("aarch64/sme/lut_v2.rs"), include_str!("x86_64/simd/lut.rs"), include_str!("x86_64/sme/tables/lookup/lut_v2.rs"), + include_str!("aarch64/sme/fp8_matrix.rs"), + include_str!("block/scalable/fp8_matrix_scope_tests.rs"), + include_str!("aarch64/simd/extrema_scale.rs"), + include_str!("x86_64/simd/extrema_scale.rs"), + include_str!("aarch64/sme/extrema_scale.rs"), + include_str!("x86_64/sme/extrema_scale.rs"), + include_str!("x86_64/simd/exponent_scale.rs"), ); #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/stela-compiler/src/x86_64/simd.rs b/crates/stela-compiler/src/x86_64/simd.rs index 213b3063e0..2cb4b7117d 100644 --- a/crates/stela-compiler/src/x86_64/simd.rs +++ b/crates/stela-compiler/src/x86_64/simd.rs @@ -11,6 +11,8 @@ pub(in crate::x86_64) mod bfloat16; mod comparison; mod complex; mod estimate; +pub(in crate::x86_64) mod exponent_scale; +mod extrema_scale; mod floating; mod fused; pub(in crate::x86_64) mod half; @@ -171,6 +173,7 @@ pub(super) fn numerical_always_exits(operation: &crate::aarch64::FloatingPointOp simd::conversion::Operand, }; match operation { + FloatingPointOperation::ExtremaScale(operand) => extrema_scale::always_exits(operand), FloatingPointOperation::Binary(operand) => arithmetic::always_exits(operand), FloatingPointOperation::Fused(operand) => operand.format == Format::Half, FloatingPointOperation::Widening(_) @@ -224,6 +227,9 @@ pub(super) fn emit_numerical( crate::aarch64::FloatingPointOperation::Comparison(operand) => { comparison::emit(code, operand, pc) } + crate::aarch64::FloatingPointOperation::ExtremaScale(operand) => { + extrema_scale::emit(code, operand, pc, target); + } crate::aarch64::FloatingPointOperation::MinMax(operand) => minmax::emit(code, operand, pc), crate::aarch64::FloatingPointOperation::Rounding(operand) => { rounding::emit(code, operand, pc, target) diff --git a/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs b/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs new file mode 100644 index 0000000000..99ecdbc0ac --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/exponent_scale.rs @@ -0,0 +1,162 @@ +//! Exact integer power-of-two adjustment shared by fixed and SME vector lanes. +//! Inputs are XMM0/1, result XMM0, scratch XMM2..5/RAX/RCX/RDX/flags. Every +//! failure edge precedes guest writes. Only normal inputs/results are admitted; +//! callers stage complete instruction outputs and own cold numerical completion. +use super::{ + Host, + numerical::{Condition, branch, prepare_vector_input_range, vector_exponent_range}, + packed, +}; +use crate::{ + TargetCpu, + aarch64::{floating::Format, simd::arithmetic::Shape}, + x86_64::isa::ShiftOpcode, +}; + +const LEFT: u8 = 0; +const RIGHT: u8 = 1; +const EXPONENT: u8 = 2; +const VALID: u8 = 3; +const MAXIMUM: u8 = 4; +const ZERO: u8 = 5; +const ONE_BIT: u8 = 1; +const MOV_EAX_IMMEDIATE: u8 = 0xb8; +const MOVD_XMM4_EAX: &[u8] = &[0x66, 0x0f, 0x6e, 0xe0]; +const REPEAT_LOW_DWORD: u8 = 0; +const PMOVMSKB_EAX_XMM3: &[u8] = &[0x66, 0x0f, 0xd7, 0xc3]; +const CMP_EAX_IMMEDIATE: u8 = 0x3d; +const LOW_VECTOR_BYTE_MASK: u32 = 0xff; +const FULL_VECTOR_BYTE_MASK: u32 = 0xffff; +const MOVQ_RAX_XMM2: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xd0]; +const MOVQ_RCX_XMM3: &[u8] = &[0x66, 0x48, 0x0f, 0x7e, 0xd9]; +const MOV_RDX_RAX: &[u8] = &[0x48, 0x89, 0xc2]; +const SHR_RDX: &[u8] = &[0x48, 0xc1, 0xea]; +const AND_EDX: &[u8] = &[0x81, 0xe2]; +const SUB_RDX_ONE: &[u8] = &[0x48, 0x83, 0xea, 1]; +const ADD_RDX_ONE: &[u8] = &[0x48, 0x83, 0xc2, 1]; +const ADD_RDX_RCX: &[u8] = &[0x48, 0x01, 0xca]; +const CMP_RDX: &[u8] = &[0x48, 0x81, 0xfa]; +const SHL_RCX: &[u8] = &[0x48, 0xc1, 0xe1]; +const ADD_RAX_RCX: &[u8] = &[0x48, 0x01, 0xc8]; +const MOVQ_XMM4_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xe0]; +const MOVQ_XMM5_RAX: &[u8] = &[0x66, 0x48, 0x0f, 0x6e, 0xe8]; +const DOUBLE_EXPONENT_SHIFT: u8 = Format::Double.fraction_bits() as u8; +const DOUBLE_EXPONENT_MASK: u32 = + (Format::Double.exponent_mask() >> Format::Double.fraction_bits()) as u32; +const DOUBLE_MAXIMUM_NORMAL_MINUS_ONE: u32 = DOUBLE_EXPONENT_MASK - 1; + +pub(in crate::x86_64) fn emit( + code: &mut Vec, + format: Format, + shape: Shape, + failures: &mut Vec, + target: TargetCpu, +) { + if format == Format::Double && !target.supports(TargetCpu::Sse42) { + scale_double(code, failures); + return; + } + prepare_vector_input_range(code, format); + vector_exponent_range(code, format, shape, LEFT); + failures.push(branch(code, Condition::NotZero)); + let (left_shift, right_shift, add, greater) = match format { + Format::Half => ( + ShiftOpcode::LeftWord, + ShiftOpcode::RightWord, + Host::AddWord, + Host::GreaterWord, + ), + Format::Single => ( + ShiftOpcode::LeftDword, + ShiftOpcode::RightDword, + Host::AddDword, + Host::GreaterDword, + ), + Format::Double => ( + ShiftOpcode::LeftQword, + ShiftOpcode::RightQword, + Host::AddQword, + Host::GreaterQword, + ), + }; + // Extract the positive exponent with no sign/fraction bits. Addition of a + // bounded positive exponent to a signed lane can overflow only to negative; + // the signed range guards therefore reject every unrepresentable sum. + packed(code, Host::MoveAligned, EXPONENT, LEFT); + left_shift.emit(code, EXPONENT, ONE_BIT); + right_shift.emit(code, EXPONENT, (format.fraction_bits() + 1) as u8); + packed(code, add, EXPONENT, RIGHT); + packed(code, Host::Xor, ZERO, ZERO); + packed(code, Host::MoveAligned, VALID, EXPONENT); + greater.register(code, VALID, ZERO, target); + let maximum = (format.exponent_mask() >> format.fraction_bits()) as u32; + let constant = if format == Format::Half { + maximum | (maximum << u16::BITS) + } else { + maximum + }; + code.push(MOV_EAX_IMMEDIATE); + code.extend(constant.to_le_bytes()); + if format == Format::Double { + code.extend(MOVQ_XMM4_RAX); + packed(code, Host::UnpackLowQword, MAXIMUM, MAXIMUM); + } else { + code.extend(MOVD_XMM4_EAX); + packed(code, Host::ShuffleDword, MAXIMUM, MAXIMUM); + code.push(REPEAT_LOW_DWORD); + } + greater.register(code, MAXIMUM, EXPONENT, target); + packed(code, Host::And, VALID, MAXIMUM); + code.extend(PMOVMSKB_EAX_XMM3); + code.push(CMP_EAX_IMMEDIATE); + // Q0's upper zero lanes are outside the architectural vector and must not + // reject an otherwise valid operation. + let mask = if shape == Shape::Vector64 { + LOW_VECTOR_BYTE_MASK + } else { + FULL_VECTOR_BYTE_MASK + }; + code.extend(mask.to_le_bytes()); + failures.push(branch(code, Condition::NotZero)); + left_shift.emit(code, RIGHT, format.fraction_bits() as u8); + packed(code, add, LEFT, RIGHT); +} + +fn scale_double(code: &mut Vec, failures: &mut Vec) { + for lane in 0..2 { + packed(code, Host::MoveAligned, EXPONENT, LEFT); + packed(code, Host::MoveAligned, VALID, RIGHT); + if lane != 0 { + ShiftOpcode::RightBytes.emit(code, EXPONENT, size_of::() as u8); + ShiftOpcode::RightBytes.emit(code, VALID, size_of::() as u8); + } + code.extend(MOVQ_RAX_XMM2); + code.extend(MOVQ_RCX_XMM3); + code.extend(MOV_RDX_RAX); + code.extend(SHR_RDX); + code.push(DOUBLE_EXPONENT_SHIFT); + code.extend(AND_EDX); + code.extend(DOUBLE_EXPONENT_MASK.to_le_bytes()); + // (exponent - 1) < 2046 admits exactly normal exponent fields. + code.extend(SUB_RDX_ONE); + code.extend(CMP_RDX); + code.extend(DOUBLE_MAXIMUM_NORMAL_MINUS_ONE.to_le_bytes()); + failures.push(branch(code, Condition::AboveOrEqual)); + code.extend(ADD_RDX_ONE); + code.extend(ADD_RDX_RCX); + code.extend(SUB_RDX_ONE); + code.extend(CMP_RDX); + code.extend(DOUBLE_MAXIMUM_NORMAL_MINUS_ONE.to_le_bytes()); + failures.push(branch(code, Condition::AboveOrEqual)); + code.extend(SHL_RCX); + code.push(DOUBLE_EXPONENT_SHIFT); + code.extend(ADD_RAX_RCX); + code.extend(if lane == 0 { + MOVQ_XMM4_RAX + } else { + MOVQ_XMM5_RAX + }); + } + packed(code, Host::UnpackLowQword, MAXIMUM, ZERO); + packed(code, Host::MoveAligned, LEFT, MAXIMUM); +} diff --git a/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs b/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs new file mode 100644 index 0000000000..c0657ca0c9 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/extrema_scale.rs @@ -0,0 +1,84 @@ +//! Baseline SSE2 absolute extrema and exact normal-result exponent scaling. +//! +//! The integer FSCALE path admits H/S/D normal inputs and normal outputs. It +//! changes only exponent bits, performs no host FP operation and raises no +//! status. Other inputs retain complete transactional numerical completion. +use crate::{ + GuestAddress, TargetCpu, + aarch64::{ + floating::{FPCR_EXCEPTION_ENABLE_MASK, absolute_minmax::AbsoluteMinMaxOperation}, + simd::{ + arithmetic::Shape, + extrema_scale::{Kind, Operand}, + }, + }, + block::ExitKind, +}; + +use super::{ + commit, + numerical::{Condition, MOVQ_XMM0_XMM0, branch, read_numerical_vector, resolve, test_control}, +}; + +const LEFT: u8 = 0; +const RIGHT: u8 = 1; +const SCRATCH: [u8; 4] = [2, 3, 4, 5]; + +pub(super) fn always_exits(_operand: &Operand) -> bool { + false +} + +fn absolute( + code: &mut Vec, + operand: &Operand, + operation: AbsoluteMinMaxOperation, + failures: &mut Vec, + target: TargetCpu, +) { + super::absolute_selection::guard_and_magnitudes( + code, + operand.format, + LEFT, + RIGHT, + SCRATCH, + failures, + target, + ); + super::absolute_selection::emit( + code, + operand.format, + operation, + LEFT, + RIGHT, + SCRATCH, + target, + ); +} + +pub(super) fn emit(code: &mut Vec, operand: &Operand, pc: GuestAddress, target: TargetCpu) { + let mut failures = Vec::new(); + test_control(code, FPCR_EXCEPTION_ENABLE_MASK); + failures.push(branch(code, Condition::NotZero)); + read_numerical_vector(code, operand.shape, operand.left, LEFT); + read_numerical_vector(code, operand.shape, operand.right, RIGHT); + match operand.kind { + Kind::Absolute(operation) => absolute(code, operand, operation, &mut failures, target), + Kind::Scale => { + super::exponent_scale::emit(code, operand.format, operand.shape, &mut failures, target) + } + } + if operand.shape == Shape::Vector64 { + code.extend(MOVQ_XMM0_XMM0); + } + commit(code, operand.destination, LEFT); + code.push(0xe9); // JMP rel32 skips the cold numerical exit. + let success = code.len(); + code.extend([0; size_of::()]); + let fallback = code.len(); + super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); + let end = code.len(); + for failure in failures { + resolve(code, failure, fallback); + } + resolve(code, success, end); +} diff --git a/crates/stela-compiler/src/x86_64/simd/lut.rs b/crates/stela-compiler/src/x86_64/simd/lut.rs index 3137b3a655..66b2d976e7 100644 --- a/crates/stela-compiler/src/x86_64/simd/lut.rs +++ b/crates/stela-compiler/src/x86_64/simd/lut.rs @@ -3,20 +3,29 @@ use super::{commit, read_vector}; use crate::TargetCpu; -use crate::aarch64::scalable::ElementSize; +use crate::aarch64::scalable::{ElementSize, VECTOR_REGISTER_COUNT}; use crate::aarch64::simd::lut::Operand; use crate::x86_64::isa::ShiftOpcode; use crate::x86_64::scalable::lut; +const INDICES_XMM: u8 = 0; +const LOW_TABLE_XMM: u8 = 4; +const HIGH_TABLE_XMM: u8 = 5; +const RESULT_XMM: u8 = 6; + pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { - read_vector(code, operand.indices, 0); + read_vector(code, operand.indices, INDICES_XMM); let offset = operand.index_byte_offset(); if offset != 0 { - ShiftOpcode::RightBytes.emit(code, 0, offset as u8); + ShiftOpcode::RightBytes.emit(code, INDICES_XMM, offset as u8); } - read_vector(code, operand.table, 4); + read_vector(code, operand.table, LOW_TABLE_XMM); if operand.table_registers() == 2 { - read_vector(code, (operand.table + 1) % 32, 5); + read_vector( + code, + (operand.table + 1) % VECTOR_REGISTER_COUNT, + HIGH_TABLE_XMM, + ); } lut::emit_chunk( code, @@ -24,5 +33,5 @@ pub(super) fn emit(code: &mut Vec, operand: &Operand, target: TargetCpu) { ElementSize::from_bytes(usize::from(operand.element_bytes)).unwrap(), target, ); - commit(code, operand.destination, 6); + commit(code, operand.destination, RESULT_XMM); } diff --git a/crates/stela-compiler/src/x86_64/sme.rs b/crates/stela-compiler/src/x86_64/sme.rs index 96826ff6d8..bf0c5f0a6b 100644 --- a/crates/stela-compiler/src/x86_64/sme.rs +++ b/crates/stela-compiler/src/x86_64/sme.rs @@ -1,5 +1,6 @@ //! Scalable-matrix mappings using immutable streaming-length specialization. +pub(crate) mod extrema_scale; pub(crate) mod integer_dots; pub(crate) mod integer_matrix; pub(crate) mod integer_products; diff --git a/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs b/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs new file mode 100644 index 0000000000..b5d8b2209a --- /dev/null +++ b/crates/stela-compiler/src/x86_64/sme/extrema_scale.rs @@ -0,0 +1,115 @@ +//! Integer SME2 extrema and normal exponent scaling with whole-group staging. +use crate::{ + CompileError, GuestAddress, GuestState, TargetCpu, + aarch64::{ + floating::{FPCR_EXCEPTION_ENABLE_MASK, features::NumericalFeatures}, + scalable::{VECTOR_REGISTER_COUNT, VectorLength}, + simd::arithmetic::Shape, + sme::extrema_scale::{Kind, Operand}, + }, + x86_64::{ + scalable::{ + load_z_chunk, + numerical::{self, Environment, Output}, + }, + simd::{absolute_selection, exponent_scale}, + }, +}; + +const LEFT: u8 = 0; +const RIGHT: u8 = 1; +const SCRATCH: [u8; 4] = [2, 3, 4, 5]; +const TEST_STATE_IMMEDIATE: &[u8] = &[0xf7, 0x87]; +const JNZ: &[u8] = &[0x0f, 0x85]; + +/// Absolute extrema admit every numeric lane. FSCALE admits normal inputs and +/// normal results using the shared exact exponent-adjustment kernel. All other +/// lanes, and retained enables, exit once before any architectural group commit. +/// Integer operations preserve complete caller MXCSR. +/// Clobbers RAX/RCX/RDX, host flags, XMM0..5; preserves RDI/R15 and guest NZCV. +pub(crate) fn emit( + code: &mut Vec, + operand: Operand, + length: VectorLength, + features: NumericalFeatures, + pc: GuestAddress, + target: TargetCpu, +) -> Result { + let count = operand.group.count(); + if !operand.destination.is_multiple_of(count) + || usize::from(operand.destination) + usize::from(count) + > usize::from(VECTOR_REGISTER_COUNT) + || if operand.right_grouped { + !operand.right.is_multiple_of(count) + || usize::from(operand.right) + usize::from(count) + > usize::from(VECTOR_REGISTER_COUNT) + } else { + operand.kind != Kind::Scale || operand.right >= VECTOR_REGISTER_COUNT / 2 + } + { + return Ok(false); + } + let outputs: Vec<_> = (0..count) + .map(|index| Output::Z(operand.destination + index)) + .collect(); + let frame = numerical::begin(code, length, &outputs, Environment::Exact)?; + let mut failures = Vec::new(); + if features.full_a64() { + code.extend(TEST_STATE_IMMEDIATE); + code.extend((std::mem::offset_of!(GuestState, fpcr) as u32).to_le_bytes()); + code.extend(FPCR_EXCEPTION_ENABLE_MASK.to_le_bytes()); + code.extend(JNZ); + failures.push(code.len()); + code.extend(0_i32.to_le_bytes()); + } + for index in 0..count { + for chunk in 0..length.chunks() { + load_z_chunk( + code, + operand.destination + index, + chunk, + LEFT, + length, + target, + ); + let right = if operand.right_grouped { + operand.right + index + } else { + operand.right + }; + load_z_chunk(code, right, chunk, RIGHT, length, target); + match operand.kind { + Kind::AbsoluteMinMax(operation) => { + absolute_selection::guard_and_magnitudes( + code, + operand.format, + LEFT, + RIGHT, + SCRATCH, + &mut failures, + target, + ); + absolute_selection::emit( + code, + operand.format, + operation, + LEFT, + RIGHT, + SCRATCH, + target, + ); + } + Kind::Scale => exponent_scale::emit( + code, + operand.format, + Shape::Vector128, + &mut failures, + target, + ), + } + numerical::stage_vector_chunk(code, &frame, usize::from(index), chunk, LEFT, target); + } + } + numerical::finish(code, &frame, &failures, pc, target); + Ok(true) +} diff --git a/crates/stela-runtime/src/floating.rs b/crates/stela-runtime/src/floating.rs index e031aba29d..e9f0067d19 100644 --- a/crates/stela-runtime/src/floating.rs +++ b/crates/stela-runtime/src/floating.rs @@ -4,6 +4,7 @@ mod bfloat16; mod comparison; mod complex; mod estimate; +mod extrema_scale; mod minmax; mod refinement; mod rounding; @@ -72,6 +73,9 @@ pub(crate) fn complete( FloatingPointOperation::Comparison(operand) => { return comparison::complete(state, operand); } + FloatingPointOperation::ExtremaScale(operand) => { + return extrema_scale::complete(state, operand); + } FloatingPointOperation::MinMax(operand) => return minmax::complete(state, operand), FloatingPointOperation::Rounding(operand) => return rounding::complete(state, operand), FloatingPointOperation::SquareRoot(operand) => return sqrt::complete(state, operand), @@ -109,6 +113,7 @@ pub(crate) fn complete( | FloatingPointOperation::Complex(_) | FloatingPointOperation::Conversion(_) | FloatingPointOperation::Comparison(_) + | FloatingPointOperation::ExtremaScale(_) | FloatingPointOperation::MinMax(_) | FloatingPointOperation::Rounding(_) | FloatingPointOperation::SquareRoot(_) diff --git a/crates/stela-runtime/src/floating/extrema_scale.rs b/crates/stela-runtime/src/floating/extrema_scale.rs new file mode 100644 index 0000000000..c5b855f8ad --- /dev/null +++ b/crates/stela-runtime/src/floating/extrema_scale.rs @@ -0,0 +1,121 @@ +//! Transactional AdvSIMD FAMIN/MAX and FSCALE completion. +use stela_compiler::{ + GuestState, + aarch64::{ + floating::{UnsupportedControl, absolute_minmax, exponent}, + simd::extrema_scale::{Kind, Operand}, + }, +}; + +use super::{VECTOR_LIMBS, read_lane, write_lane}; + +pub(super) fn complete( + state: &mut GuestState, + operand: &Operand, +) -> Result<(), UnsupportedControl> { + // Every source is snapshotted before staging, including Vd=Vn=Vm and V31. + let left = state.v[usize::from(operand.left)]; + let right = state.v[usize::from(operand.right)]; + let mut result = [0; VECTOR_LIMBS]; + let mut exceptions = 0; + for lane in 0..operand.shape.lane_count(operand.format) { + let left = read_lane(&left, operand.format.bits(), lane); + let right = read_lane(&right, operand.format.bits(), lane); + let outcome = match operand.kind { + Kind::Absolute(operation) => { + absolute_minmax::evaluate(operand.format, operation, state.fpcr, left, right) + } + Kind::Scale => exponent::scale(operand.format, state.fpcr, left, right), + }?; + write_lane(&mut result, operand.format.bits(), lane, outcome.bits); + exceptions |= outcome.exceptions; + } + state.v[usize::from(operand.destination)] = result; + state.fpsr |= exceptions; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use stela_compiler::aarch64::{ + floating::{EXCEPTIONS, FPCR_EXCEPTION_ENABLE_SHIFT, FPSR_QC, INVALID, OVERFLOW}, + simd::extrema_scale, + }; + + #[test] + fn scale_alias_signed_integer_and_upper_clear_preserve_other_state() { + for (destination, left, right) in [(0_u8, 1_u8, 2_u8), (1, 1, 2), (2, 1, 2), (31, 31, 31)] { + let mut state = GuestState::default(); + state.x[0] = 0xfeed; + state.nzcv = 0xa000_0000; + state.v[usize::from(left)] = [0x4000_0000_3f80_0000, u64::MAX]; + state.v[usize::from(right)] = [0xffff_ffff_0000_0001, u64::MAX]; + state.fpsr = FPSR_QC | INVALID; + let operand = extrema_scale::decode( + 0x2ea0_fc00 + | u32::from(destination) + | (u32::from(left) << 5) + | (u32::from(right) << 16), + ) + .unwrap() + .unwrap(); + let before = state.clone(); + let mut expected = before.clone(); + expected.v[usize::from(destination)] = if left == right { + // Raw1 scaled by1 gives2; the second lane is an already quiet + // negative NaN whose payload/sign survive the integer scale. + [0xffff_ffff_0000_0002, 0] + } else { + [0x3f80_0000_4000_0000, 0] + }; + complete(&mut state, &operand).unwrap(); + assert_eq!(state, expected); + } + } + + #[test] + fn absolute_extrema_ignore_flush_keep_signed_nan_and_snapshot_aliases() { + use stela_compiler::aarch64::floating::{FPCR_AH, FPCR_FIZ, FPCR_FZ, FPCR_FZ16}; + let mut state = GuestState { + fpcr: FPCR_AH | FPCR_FIZ | FPCR_FZ | FPCR_FZ16, + fpsr: FPSR_QC, + ..GuestState::default() + }; + state.v[1] = [0x8000_0001_8000_0000, 0xff80_0003_bf80_0000]; + state.v[2] = [0x0000_0002_0000_0000, 0x3f80_0000_4000_0000]; + let operand = extrema_scale::decode(0x6ea0_dc22 | (2 << 16)) + .unwrap() + .unwrap(); + let mut expected = state.clone(); + expected.v[2] = [0x0000_0001_0000_0000, 0xffc0_0003_3f80_0000]; + expected.fpsr |= INVALID; + complete(&mut state, &operand).unwrap(); + assert_eq!(state, expected); + } + + #[test] + fn enabled_exception_refusal_preserves_complete_state_for_all_six_forms() { + for word in [ + 0x0ea0_dc00, + 0x2ea0_dc00, + 0x2ea0_fc00, + 0x0ec0_1c00, + 0x2ec0_1c00, + 0x2ec0_3c00, + ] { + for enable in [INVALID, OVERFLOW, EXCEPTIONS] { + let mut state = GuestState { + fpcr: enable << FPCR_EXCEPTION_ENABLE_SHIFT, + fpsr: FPSR_QC, + ..GuestState::default() + }; + state.v[0] = [u64::MAX; VECTOR_LIMBS]; + let before = state.clone(); + let operand = extrema_scale::decode(word).unwrap().unwrap(); + assert!(complete(&mut state, &operand).is_err()); + assert_eq!(state, before); + } + } + } +} diff --git a/crates/stela-runtime/src/floating/scalable.rs b/crates/stela-runtime/src/floating/scalable.rs index 46953488b0..786ae3738b 100644 --- a/crates/stela-runtime/src/floating/scalable.rs +++ b/crates/stela-runtime/src/floating/scalable.rs @@ -8,7 +8,9 @@ mod faminmax; mod fp8; mod fp8_conversion_fixed; mod rounding; +mod sme_extrema_scale; mod sme_fp8_conversion; +mod sme_fp8_matrix; mod sme_matrix; mod sme_vector; @@ -110,6 +112,9 @@ pub(crate) fn complete( ScalableNumericalOperation::SmeFp8Conversion(operand) => { sme_fp8_conversion::complete(state, scalable, operand, controls) } + ScalableNumericalOperation::SmeFp8Matrix(operand) => { + sme_fp8_matrix::complete(state, scalable, operand, controls) + } ScalableNumericalOperation::Sve(operation) => match operation { Operation::Arithmetic(operand) => { arithmetic::complete(state, scalable, operand, controls) @@ -126,6 +131,9 @@ pub(crate) fn complete( conversion::complete(state, scalable, operand, controls) } }, + ScalableNumericalOperation::SmeExtremaScale(operand) => { + sme_extrema_scale::complete(state, scalable, operand, controls) + } ScalableNumericalOperation::SmeVector(operand) => { sme_vector::complete(state, scalable, operand, controls) } diff --git a/crates/stela-runtime/src/floating/scalable/sme_extrema_scale.rs b/crates/stela-runtime/src/floating/scalable/sme_extrema_scale.rs new file mode 100644 index 0000000000..0f117f881a --- /dev/null +++ b/crates/stela-runtime/src/floating/scalable/sme_extrema_scale.rs @@ -0,0 +1,349 @@ +//! Transactional H/S/D SME2 absolute extrema and signed exponent scaling. +use super::{CompletionError, NumericalControls}; +use crate::scalable::ScalableState; +use stela_compiler::{ + GuestState, + aarch64::{ + floating::{absolute_minmax, exponent}, + scalable::{BITS_PER_BYTE, MAX_VECTOR_BYTES, VECTOR_REGISTER_COUNT}, + sme::extrema_scale::{Kind, Operand}, + }, +}; + +const MAX_GROUP_COUNT: usize = 4; +type GroupBytes = [[u8; MAX_VECTOR_BYTES]; MAX_GROUP_COUNT]; + +fn snapshot( + state: &GuestState, + scalable: &ScalableState, + first: u8, + count: u8, +) -> Result { + if !matches!(count, 1 | 2 | 4) + || !first.is_multiple_of(count) + || usize::from(first) + usize::from(count) > usize::from(VECTOR_REGISTER_COUNT) + { + return Err(anyhow::anyhow!("invalid SME extrema/scale register group").into()); + } + let length = scalable.vector_length().bytes(); + let mut values = [[0; MAX_VECTOR_BYTES]; MAX_GROUP_COUNT]; + for (index, output) in values.iter_mut().take(usize::from(count)).enumerate() { + scalable.read_z(state, first + index as u8, &mut output[..length])?; + } + Ok(values) +} + +fn lane(values: &[u8], offset: usize, bytes: usize) -> u64 { + let mut result = [0; size_of::()]; + result[..bytes].copy_from_slice(&values[offset..offset + bytes]); + u64::from_le_bytes(result) +} + +/// All original inputs are captured before lane evaluation, including a scale +/// broadcast alias within the destination group. Unsupported controls commit +/// neither Z output nor FPSR. FPCR, NZCV, P, ZA, ZT and FPMR are preserved. +pub(super) fn complete( + state: &mut GuestState, + scalable: &mut ScalableState, + operand: &Operand, + controls: NumericalControls, +) -> Result<(), CompletionError> { + if !scalable.mode().streaming() { + return Err(anyhow::anyhow!("SME extrema/scale requires streaming state").into()); + } + let count = operand.group.count(); + if !operand.right_grouped && (operand.kind != Kind::Scale || operand.right >= 16) { + return Err(anyhow::anyhow!("invalid SME extrema/scale broadcast operand").into()); + } + let mut results = snapshot(state, scalable, operand.destination, count)?; + let rights = snapshot( + state, + scalable, + operand.right, + if operand.right_grouped { count } else { 1 }, + )?; + let length = scalable.vector_length().bytes(); + let bytes = operand.format.bits() as usize / BITS_PER_BYTE; + let mut exceptions = 0; + for (index, result) in results.iter_mut().take(usize::from(count)).enumerate() { + let right = &rights[if operand.right_grouped { index } else { 0 }]; + for offset in (0..length).step_by(bytes) { + let left = lane(result, offset, bytes); + let right = lane(right, offset, bytes); + let outcome = match operand.kind { + Kind::AbsoluteMinMax(operation) => { + absolute_minmax::evaluate(operand.format, operation, controls.fpcr, left, right) + } + Kind::Scale => exponent::scale(operand.format, controls.fpcr, left, right), + }?; + result[offset..offset + bytes].copy_from_slice(&outcome.bits.to_le_bytes()[..bytes]); + exceptions |= outcome.exceptions; + } + } + for (index, result) in results.iter().take(usize::from(count)).enumerate() { + scalable.write_z(state, operand.destination + index as u8, &result[..length])?; + } + state.fpsr |= exceptions; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use stela_compiler::aarch64::{ + floating::{ + FPCR_AH, FPCR_DN, FPCR_EXCEPTION_ENABLE_MASK, FPCR_FIZ, FPCR_FZ, FPCR_FZ16, Format, + INEXACT, INVALID, OVERFLOW, absolute_minmax::AbsoluteMinMaxOperation, + features::NumericalFeatures, + }, + scalable::{ScalableMode, VectorLength}, + sme::extrema_scale::Group, + }; + + const QC: u32 = 1 << 27; + + fn fraction_bits(format: Format) -> u32 { + match format { + Format::Half => 10, + Format::Single => 23, + Format::Double => 52, + } + } + fn sign(format: Format) -> u64 { + 1 << (format.bits() - 1) + } + fn infinity(format: Format) -> u64 { + match format { + Format::Half => 0x7c00, + Format::Single => 0x7f80_0000, + Format::Double => 0x7ff0_0000_0000_0000, + } + } + fn one(format: Format) -> u64 { + match format { + Format::Half => 0x3c00, + Format::Single => 0x3f80_0000, + Format::Double => 0x3ff0_0000_0000_0000, + } + } + fn quiet_bit(format: Format) -> u64 { + 1 << (fraction_bits(format) - 1) + } + + fn setup(length: usize) -> (GuestState, ScalableState) { + let mut state = GuestState::default(); + let mut scalable = ScalableState::new(VectorLength::from_bytes(length).unwrap(), true); + scalable + .apply_mode(&mut state, ScalableMode::new(true, true)) + .unwrap(); + scalable.set_fpmr(0x1234); + state.nzcv = 0xa000_0000; + state.fpsr = QC; + (state, scalable) + } + + fn fill( + state: &mut GuestState, + scalable: &mut ScalableState, + register: u8, + format: Format, + bits: u64, + ) { + let bytes = format.bits() as usize / BITS_PER_BYTE; + let values = bits.to_le_bytes()[..bytes].repeat(scalable.vector_length().bytes() / bytes); + scalable.write_z(state, register, &values).unwrap(); + } + + fn assert_filled( + state: &GuestState, + scalable: &ScalableState, + register: u8, + format: Format, + bits: u64, + ) { + let mut values = vec![0; scalable.vector_length().bytes()]; + scalable.read_z(state, register, &mut values).unwrap(); + let bytes = format.bits() as usize / BITS_PER_BYTE; + assert!( + values + .chunks_exact(bytes) + .all(|value| value == &bits.to_le_bytes()[..bytes]) + ); + } + + #[test] + fn scale_broadcast_alias_reads_original_register_at_every_length_and_width() { + for length in [16, 32, 64, 128, 256] { + for format in [Format::Half, Format::Single, Format::Double] { + for group in [Group::Pair, Group::Quartet] { + let (mut state, mut scalable) = setup(length); + let one = one(format); + for register in 0..group.count() { + fill(&mut state, &mut scalable, register, format, one); + } + // First destination aliases the broadcast, so premature commit + // would change subsequent scale factors from integer 1. + fill(&mut state, &mut scalable, 0, format, 1); + let operand = Operand { + kind: Kind::Scale, + destination: 0, + right: 0, + group, + format, + right_grouped: false, + }; + complete( + &mut state, + &mut scalable, + &operand, + NumericalControls::new(0, true, NumericalFeatures::default()), + ) + .unwrap(); + assert_filled(&state, &scalable, 0, format, 2); + for register in 1..group.count() { + assert_filled( + &state, + &scalable, + register, + format, + one + (1 << fraction_bits(format)), + ); + } + assert_eq!(state.fpsr, QC); + assert_eq!(state.nzcv, 0xa000_0000); + assert_eq!(scalable.fpmr(), 0x1234); + } + } + } + } + + #[test] + fn extrema_group_alias_and_specials_ignore_flush_and_keep_sticky_status() { + for format in [Format::Half, Format::Single, Format::Double] { + for operation in [ + AbsoluteMinMaxOperation::Minimum, + AbsoluteMinMaxOperation::Maximum, + ] { + let (mut state, mut scalable) = setup(64); + state.fpcr = FPCR_AH | FPCR_FIZ | FPCR_FZ | FPCR_FZ16; + for register in 28..32 { + fill( + &mut state, + &mut scalable, + register, + format, + sign(format) | 1, + ); + } + let operand = Operand { + kind: Kind::AbsoluteMinMax(operation), + destination: 28, + right: 28, + group: Group::Quartet, + format, + right_grouped: true, + }; + let controls = + NumericalControls::new(state.fpcr, true, NumericalFeatures::default()); + complete(&mut state, &mut scalable, &operand, controls).unwrap(); + for register in 28..32 { + assert_filled(&state, &scalable, register, format, 1); + } + assert_eq!(state.fpsr, QC); + let signaling = sign(format) | infinity(format) | 1; + fill(&mut state, &mut scalable, 31, format, signaling); + state.fpcr |= FPCR_DN; + let controls = + NumericalControls::new(state.fpcr, true, NumericalFeatures::default()); + complete(&mut state, &mut scalable, &operand, controls).unwrap(); + assert_filled( + &state, + &scalable, + 31, + format, + infinity(format) | quiet_bit(format), + ); + assert_eq!(state.fpsr, QC | INVALID); + } + } + } + + #[test] + fn scale_group_signed_factors_accumulate_rounding_status() { + let (mut state, mut scalable) = setup(32); + for register in 0..2 { + fill( + &mut state, + &mut scalable, + register, + Format::Single, + 0x7f7f_ffff, + ); + } + fill(&mut state, &mut scalable, 30, Format::Single, 1); + fill( + &mut state, + &mut scalable, + 31, + Format::Single, + u64::from(u32::MAX), + ); + let operand = Operand { + kind: Kind::Scale, + destination: 0, + right: 30, + group: Group::Pair, + format: Format::Single, + right_grouped: true, + }; + complete( + &mut state, + &mut scalable, + &operand, + NumericalControls::new(0, true, NumericalFeatures::default()), + ) + .unwrap(); + assert_filled(&state, &scalable, 0, Format::Single, 0x7f80_0000); + assert_filled(&state, &scalable, 1, Format::Single, 0x7eff_ffff); + assert_eq!(state.fpsr, QC | OVERFLOW | INEXACT); + } + + #[test] + fn failures_are_transactional_and_streaming_exception_enables_are_effective() { + let (mut state, mut scalable) = setup(16); + fill(&mut state, &mut scalable, 0, Format::Single, 0xbf80_0000); + fill(&mut state, &mut scalable, 1, Format::Single, 0xff80_0001); + let operand = Operand { + kind: Kind::AbsoluteMinMax(AbsoluteMinMaxOperation::Maximum), + destination: 0, + right: 0, + group: Group::Pair, + format: Format::Single, + right_grouped: true, + }; + state.fpcr = FPCR_EXCEPTION_ENABLE_MASK; + let before = state.clone(); + let controls = + NumericalControls::new(state.fpcr, true, NumericalFeatures::new(true, false, false)); + assert!(matches!( + complete(&mut state, &mut scalable, &operand, controls), + Err(CompletionError::UnsupportedControl(_)) + )); + assert_eq!(state, before); + let controls = NumericalControls::new(state.fpcr, true, NumericalFeatures::default()); + complete(&mut state, &mut scalable, &operand, controls).unwrap(); + assert_eq!(state.fpcr, FPCR_EXCEPTION_ENABLE_MASK); + assert_eq!(state.fpsr, QC | INVALID); + let bad = Operand { + destination: 31, + ..operand + }; + let before = state.clone(); + assert!(complete(&mut state, &mut scalable, &bad, controls).is_err()); + assert_eq!(state, before); + scalable + .apply_mode(&mut state, ScalableMode::new(false, true)) + .unwrap(); + assert!(complete(&mut state, &mut scalable, &operand, controls).is_err()); + } +} diff --git a/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix.rs b/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix.rs new file mode 100644 index 0000000000..2ec09ae43f --- /dev/null +++ b/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix.rs @@ -0,0 +1,298 @@ +//! Transactional FP8 ZA arithmetic using the common affected-row staging owner. + +use stela_compiler::{ + GuestState, + aarch64::{ + floating::{Format, fp8}, + scalable::{BITS_PER_BYTE, MAX_VECTOR_BYTES, VECTOR_CHUNK_BYTES, VECTOR_REGISTER_COUNT}, + sme::fp8_matrix::{Operand, OuterOperand, RightSource, VectorOperand, VectorOperation}, + }, +}; + +use super::{ + CompletionError, NumericalControls, + sme_matrix::{ZaResults, read_lane, read_z, require, selector, write_lane}, +}; +use crate::scalable::ScalableState; + +const MAX_GROUPS: usize = 4; +const MAX_ROWS: usize = MAX_GROUPS * MAX_GROUPS; +const MAX_TERMS: usize = 4; +const MAX_PREDICATE_BYTES: usize = MAX_VECTOR_BYTES / BITS_PER_BYTE; + +fn width(format: Format) -> Result { + require( + matches!(format, Format::Half | Format::Single), + "FP8 ZA accumulation requires Half or Single", + )?; + Ok(format.bits() as usize / BITS_PER_BYTE) +} + +struct Sources { + left: [[u8; MAX_VECTOR_BYTES]; MAX_GROUPS], + right: [[u8; MAX_VECTOR_BYTES]; MAX_GROUPS], + grouped_right: bool, + index: Option, +} + +fn snapshot_sources( + state: &GuestState, + scalable: &ScalableState, + operand: &VectorOperand, +) -> Result { + let groups = usize::from(operand.groups); + require(matches!(groups, 1 | 2 | 4), "invalid FP8 ZA source group")?; + let vertical = matches!(operand.operation, VectorOperation::VerticalDot { .. }); + let source_groups = if vertical { 2 } else { groups }; + let (right, grouped_right, index) = match operand.right { + RightSource::Vector(register) => (register, false, None), + RightSource::Group(register) => (register, true, None), + RightSource::Indexed { register, index } => (register, false, Some(usize::from(index))), + }; + let left = usize::from(operand.left); + let right = usize::from(right); + let registers = usize::from(VECTOR_REGISTER_COUNT); + let wrap_left = matches!(operand.right, RightSource::Vector(_)) && !vertical; + require( + left < registers && right < registers, + "FP8 ZA source register out of range", + )?; + require( + (wrap_left || (left.is_multiple_of(source_groups) && left + source_groups <= registers)) + && (!grouped_right || (right.is_multiple_of(groups) && right + groups <= registers)) + && (grouped_right || right < registers / 2), + "FP8 ZA source group exceeds its encoding", + )?; + let bytes = width(operand.accumulator)?; + let index_limit = if operand.operation == VectorOperation::MultiplyAdd { + VECTOR_CHUNK_BYTES + } else { + VECTOR_CHUNK_BYTES / bytes + }; + require( + index.is_none_or(|index| index < index_limit), + "FP8 ZA source index out of range", + )?; + require( + !vertical || index.is_some(), + "FP8 vertical dot requires indexed source", + )?; + require( + operand.accumulator != Format::Half + || !matches!( + operand.operation, + VectorOperation::VerticalDot { top: true } + ), + "Half FP8 vertical dot has no top form", + )?; + let mut result = Sources { + left: [[0; MAX_VECTOR_BYTES]; MAX_GROUPS], + right: [[0; MAX_VECTOR_BYTES]; MAX_GROUPS], + grouped_right, + index, + }; + for group in 0..source_groups { + result.left[group] = read_z(state, scalable, ((left + group) % registers) as u8)?; + } + for group in 0..if grouped_right { groups } else { 1 } { + result.right[group] = read_z(state, scalable, (right + group) as u8)?; + } + Ok(result) +} + +fn complete_vector<'scratch>( + state: &GuestState, + scalable: &ScalableState, + operand: &VectorOperand, + fpcr: u32, + scratch: &'scratch mut [u8], +) -> Result, CompletionError> { + let bytes = width(operand.accumulator)?; + let groups = usize::from(operand.groups); + let sources = snapshot_sources(state, scalable, operand)?; + let long = operand.operation == VectorOperation::MultiplyAdd; + let vertical = matches!(operand.operation, VectorOperation::VerticalDot { .. }); + require( + !vertical || groups == bytes, + "FP8 vertical dot output group differs", + )?; + require(long || groups != 1, "FP8 dot requires multiple ZA vectors")?; + let rows_per_group = if long { bytes } else { 1 }; + let length = scalable.vector_length().bytes(); + let stride = length / groups; + let mut base = ((u64::from(selector(state, operand.vector_select)?) + + u64::from(operand.offset)) + % stride as u64) as usize; + base -= base % rows_per_group; + let mut rows = [0; MAX_ROWS]; + for group in 0..groups { + for parity in 0..rows_per_group { + rows[group * rows_per_group + parity] = base + group * stride + parity; + } + } + let mut result = ZaResults::stage(scalable, &rows[..groups * rows_per_group], scratch)?; + let segment_elements = VECTOR_CHUNK_BYTES / bytes; + for group in 0..groups { + let right = &sources.right[if sources.grouped_right { group } else { 0 }]; + for parity in 0..rows_per_group { + let row = group * rows_per_group + parity; + for element in 0..length / bytes { + let segment = element - element % segment_elements; + let mut left_terms = [0; MAX_TERMS]; + let mut right_terms = [0; MAX_TERMS]; + let terms = if long { + left_terms[0] = sources.left[group][bytes * element + parity]; + let right_byte = sources + .index + .map_or(bytes * element + parity, |index| bytes * segment + index); + right_terms[0] = right[right_byte]; + 1 + } else if vertical { + let left_byte = bytes * element + group; + left_terms[0] = sources.left[0][left_byte]; + left_terms[1] = sources.left[1][left_byte]; + let top = matches!( + operand.operation, + VectorOperation::VerticalDot { top: true } + ); + let right_byte = bytes + * (segment + sources.index.expect("validated indexed source")) + + if top { size_of::() } else { 0 }; + right_terms[..2].copy_from_slice(&right[right_byte..right_byte + 2]); + 2 + } else { + let left_byte = bytes * element; + let right_byte = bytes * sources.index.map_or(element, |index| segment + index); + left_terms[..bytes] + .copy_from_slice(&sources.left[group][left_byte..left_byte + bytes]); + right_terms[..bytes].copy_from_slice(&right[right_byte..right_byte + bytes]); + bytes + }; + let addend = read_lane(result.row(row), element, bytes); + let bits = fp8::dot_add( + operand.accumulator, + fpcr, + scalable.fpmr(), + addend, + &left_terms[..terms], + &right_terms[..terms], + ); + write_lane(result.row_mut(row), element, bytes, bits); + } + } + } + Ok(result) +} + +fn active(predicate: &[u8], byte: usize) -> bool { + predicate[byte / BITS_PER_BYTE] & (1 << (byte % BITS_PER_BYTE)) != 0 +} + +fn complete_outer<'scratch>( + state: &GuestState, + scalable: &ScalableState, + operand: &OuterOperand, + fpcr: u32, + scratch: &'scratch mut [u8], +) -> Result, CompletionError> { + let bytes = width(operand.accumulator)?; + require( + usize::from(operand.tile) < bytes, + "FP8 ZA tile out of range", + )?; + require( + operand.row_predicate < 8 && operand.column_predicate < 8, + "FP8 ZA predicate out of range", + )?; + let left = read_z(state, scalable, operand.left)?; + let right = read_z(state, scalable, operand.right)?; + let length = scalable.vector_length().bytes(); + let dimension = length / bytes; + let mut row_predicate = [0; MAX_PREDICATE_BYTES]; + let mut column_predicate = [0; MAX_PREDICATE_BYTES]; + scalable.read_predicate( + operand.row_predicate, + &mut row_predicate[..length / BITS_PER_BYTE], + )?; + scalable.read_predicate( + operand.column_predicate, + &mut column_predicate[..length / BITS_PER_BYTE], + )?; + let mut rows = [0; MAX_VECTOR_BYTES / size_of::()]; + for (row, physical) in rows.iter_mut().enumerate().take(dimension) { + *physical = usize::from(operand.tile) + row * bytes; + } + let mut result = ZaResults::stage(scalable, &rows[..dimension], scratch)?; + for row in 0..dimension { + for column in 0..dimension { + let mut left_terms = [0; MAX_TERMS]; + let mut right_terms = [0; MAX_TERMS]; + let mut any_active = false; + for term in 0..bytes { + let row_byte = bytes * row + term; + let column_byte = bytes * column + term; + let row_active = active(&row_predicate, row_byte); + let column_active = active(&column_predicate, column_byte); + any_active |= row_active && column_active; + if row_active { + left_terms[term] = left[row_byte]; + } + if column_active { + right_terms[term] = right[column_byte]; + } + } + if !any_active { + continue; + } + let addend = read_lane(result.row(row), column, bytes); + let bits = fp8::dot_add( + operand.accumulator, + fpcr, + scalable.fpmr(), + addend, + &left_terms[..bytes], + &right_terms[..bytes], + ); + write_lane(result.row_mut(row), column, bytes, bits); + } + } + Ok(result) +} + +pub(super) fn complete( + state: &mut GuestState, + scalable: &mut ScalableState, + operand: &Operand, + controls: NumericalControls, +) -> Result<(), CompletionError> { + require( + scalable.mode().streaming() && scalable.mode().za_enabled(), + "FP8 ZA arithmetic requires streaming and ZA state", + )?; + let rows = match operand { + Operand::Vector(operand) => { + usize::from(operand.groups) + * if operand.operation == VectorOperation::MultiplyAdd { + width(operand.accumulator)? + } else { + 1 + } + } + Operand::Outer(operand) => scalable.vector_length().bytes() / width(operand.accumulator)?, + }; + scalable.with_za_row_scratch(rows, |scalable, scratch| { + let result = match operand { + Operand::Vector(operand) => { + complete_vector(state, scalable, operand, controls.fpcr, scratch)? + } + Operand::Outer(operand) => { + complete_outer(state, scalable, operand, controls.fpcr, scratch)? + } + }; + result.commit(scalable); + Ok(()) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix/tests.rs b/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix/tests.rs new file mode 100644 index 0000000000..8cafeaa5d3 --- /dev/null +++ b/crates/stela-runtime/src/floating/scalable/sme_fp8_matrix/tests.rs @@ -0,0 +1,236 @@ +use super::*; +use stela_compiler::aarch64::{ + floating::{FPCR_AH, FPCR_EXCEPTION_ENABLE_MASK, features::NumericalFeatures}, + scalable::{ScalableMode, VectorLength}, +}; + +const TEST_SVL_BYTES: usize = 16; +const E4M3_ONE: u8 = 0x38; +const E4M3_SOURCES: u64 = 1 | (1 << fp8::FPMR_F8S2_SHIFT); +const HALF_ONE: u64 = 0x3c00; +const HALF_TWO: u64 = 0x4000; +const SINGLE_ONE: u64 = 0x3f80_0000; +const SINGLE_FOUR: u64 = 0x4080_0000; + +fn state() -> (GuestState, ScalableState) { + let mut state = GuestState { + fpcr: FPCR_EXCEPTION_ENABLE_MASK, + fpsr: 0x0800_009f, + ..GuestState::default() + }; + let mut scalable = ScalableState::new(VectorLength::from_bytes(TEST_SVL_BYTES).unwrap(), true); + scalable + .apply_mode(&mut state, ScalableMode::new(true, true)) + .unwrap(); + scalable.set_fpmr(E4M3_SOURCES); + for register in 0..VECTOR_REGISTER_COUNT { + scalable + .write_z(&mut state, register, &[E4M3_ONE; TEST_SVL_BYTES]) + .unwrap(); + } + (state, scalable) +} + +fn controls(state: &GuestState) -> NumericalControls { + NumericalControls::new(state.fpcr, true, NumericalFeatures::default()) +} + +fn vector(operation: VectorOperation, accumulator: Format, groups: u8) -> VectorOperand { + VectorOperand { + operation, + accumulator, + groups, + left: 0, + right: RightSource::Vector(0), + vector_select: 8, + offset: 0, + } +} + +#[test] +fn every_vector_layout_preserves_unselected_rows_and_raw_state() { + for format in [Format::Half, Format::Single] { + let bytes = width(format).unwrap(); + for groups in [1, 2, 4] { + for operation in [VectorOperation::Dot, VectorOperation::MultiplyAdd] { + if groups == 1 && operation == VectorOperation::Dot { + continue; + } + for right in [ + RightSource::Vector(0), + RightSource::Group(0), + RightSource::Indexed { + register: 0, + index: 15, + }, + ] { + if operation == VectorOperation::Dot + && matches!(right, RightSource::Indexed { .. }) + { + continue; + } + if groups == 1 && matches!(right, RightSource::Group(_)) { + continue; + } + let (mut state, mut scalable) = state(); + let original = state.clone(); + let mut operand = vector(operation, format, groups); + operand.right = right; + let selected_rows = usize::from(groups) + * if operation == VectorOperation::MultiplyAdd { + bytes + } else { + 1 + }; + let controls = controls(&state); + complete( + &mut state, + &mut scalable, + &Operand::Vector(operand), + controls, + ) + .unwrap(); + assert_eq!(state, original); + assert_eq!(scalable.fpmr(), E4M3_SOURCES); + let mut za = [0; TEST_SVL_BYTES * TEST_SVL_BYTES]; + scalable.read_za(0, &mut za).unwrap(); + let expected = match (operation, format) { + (VectorOperation::MultiplyAdd, Format::Half) => HALF_ONE, + (VectorOperation::MultiplyAdd, Format::Single) => SINGLE_ONE, + (_, Format::Half) => HALF_TWO, + (_, Format::Single) => SINGLE_FOUR, + (_, Format::Double) => unreachable!(), + }; + let mut changed = 0; + for row in za.as_chunks::().0 { + if row.iter().any(|byte| *byte != 0) { + changed += 1; + for element in 0..TEST_SVL_BYTES / bytes { + assert_eq!(read_lane(row, element, bytes), expected); + } + } + } + assert_eq!(changed, selected_rows); + } + } + } + } +} + +#[test] +fn vertical_pairs_cross_source_registers_and_select_bottom_or_top() { + for (format, top) in [ + (Format::Half, false), + (Format::Single, false), + (Format::Single, true), + ] { + let (mut state, mut scalable) = state(); + let bytes = width(format).unwrap(); + // The first source contributes1, the second2. A pair with right1 sums3. + scalable + .write_z(&mut state, 1, &[0x40; TEST_SVL_BYTES]) + .unwrap(); + if format == Format::Single { + let mut right = [E4M3_ONE; TEST_SVL_BYTES]; + for quartet in right.as_chunks_mut::<4>().0 { + quartet[2..].fill(0x40); + } + scalable.write_z(&mut state, 2, &right).unwrap(); + } + let original = state.clone(); + let mut operand = vector(VectorOperation::VerticalDot { top }, format, bytes as u8); + operand.right = RightSource::Indexed { + register: 2, + index: (VECTOR_CHUNK_BYTES / bytes - 1) as u8, + }; + let controls = controls(&state); + complete( + &mut state, + &mut scalable, + &Operand::Vector(operand), + controls, + ) + .unwrap(); + assert_eq!(state, original); + let mut row = [0; TEST_SVL_BYTES]; + for group in 0..bytes { + scalable + .read_za(group * (TEST_SVL_BYTES / bytes) * TEST_SVL_BYTES, &mut row) + .unwrap(); + for element in 0..TEST_SVL_BYTES / bytes { + assert_eq!( + read_lane(&row, element, bytes), + if format == Format::Half { + 0x4200 + } else if top { + 0x40c0_0000 + } else { + 0x4040_0000 + } + ); + } + } + } +} + +#[test] +fn inactive_outer_cells_preserve_signaling_nan_without_classifying() { + let (mut state, mut scalable) = state(); + state.fpcr |= FPCR_AH; + let original = state.clone(); + let before = [0x01; TEST_SVL_BYTES * TEST_SVL_BYTES]; + scalable.write_za(0, &before).unwrap(); + scalable + .write_predicate(0, &[0; TEST_SVL_BYTES / BITS_PER_BYTE]) + .unwrap(); + let operand = OuterOperand { + accumulator: Format::Single, + tile: 3, + left: 0, + right: 0, + row_predicate: 0, + column_predicate: 0, + }; + let controls = controls(&state); + complete( + &mut state, + &mut scalable, + &Operand::Outer(operand), + controls, + ) + .unwrap(); + let mut actual = [0; TEST_SVL_BYTES * TEST_SVL_BYTES]; + scalable.read_za(0, &mut actual).unwrap(); + assert_eq!(actual, before); + assert_eq!(state, original); +} + +#[test] +fn malformed_sources_fail_without_committing_and_release_scratch() { + let (mut state, mut scalable) = state(); + let before = [0xa5; TEST_SVL_BYTES * TEST_SVL_BYTES]; + scalable.write_za(0, &before).unwrap(); + let mut operand = vector(VectorOperation::MultiplyAdd, Format::Single, 4); + operand.right = RightSource::Group(30); + let controls = controls(&state); + assert!( + complete( + &mut state, + &mut scalable, + &Operand::Vector(operand), + controls + ) + .is_err() + ); + let mut actual = [0; TEST_SVL_BYTES * TEST_SVL_BYTES]; + scalable.read_za(0, &mut actual).unwrap(); + assert_eq!(actual, before); + operand.right = RightSource::Group(0); + complete( + &mut state, + &mut scalable, + &Operand::Vector(operand), + controls, + ) + .unwrap(); +} diff --git a/crates/stela-runtime/src/floating/scalable/sme_matrix.rs b/crates/stela-runtime/src/floating/scalable/sme_matrix.rs index a460d2be73..0a2d198f50 100644 --- a/crates/stela-runtime/src/floating/scalable/sme_matrix.rs +++ b/crates/stela-runtime/src/floating/scalable/sme_matrix.rs @@ -25,7 +25,7 @@ const HALF_BYTES: usize = size_of::(); const SINGLE_BYTES: usize = size_of::(); const MAX_ZA_ROWS: usize = MAX_VECTOR_BYTES / HALF_BYTES; -fn require(condition: bool, message: &'static str) -> Result<(), CompletionError> { +pub(super) fn require(condition: bool, message: &'static str) -> Result<(), CompletionError> { if condition { Ok(()) } else { @@ -33,7 +33,7 @@ fn require(condition: bool, message: &'static str) -> Result<(), CompletionError } } -struct ZaResults<'scratch> { +pub(super) struct ZaResults<'scratch> { rows: [usize; MAX_ZA_ROWS], count: usize, length: usize, @@ -41,7 +41,7 @@ struct ZaResults<'scratch> { } impl<'scratch> ZaResults<'scratch> { - fn stage( + pub(super) fn stage( scalable: &ScalableState, rows: &[usize], bytes: &'scratch mut [u8], @@ -72,17 +72,17 @@ impl<'scratch> ZaResults<'scratch> { Ok(result) } - fn row(&self, index: usize) -> &[u8] { + pub(super) fn row(&self, index: usize) -> &[u8] { let start = index * self.length; &self.bytes[start..start + self.length] } - fn row_mut(&mut self, index: usize) -> &mut [u8] { + pub(super) fn row_mut(&mut self, index: usize) -> &mut [u8] { let start = index * self.length; &mut self.bytes[start..start + self.length] } - fn commit(self, scalable: &mut ScalableState) { + pub(super) fn commit(self, scalable: &mut ScalableState) { for index in 0..self.count { // All rows were validated against this same exclusively borrowed // owner before evaluation. No mode, length or backing changes occur. @@ -93,7 +93,7 @@ impl<'scratch> ZaResults<'scratch> { } } -fn read_z( +pub(super) fn read_z( state: &GuestState, scalable: &ScalableState, register: u8, @@ -107,7 +107,7 @@ fn read_z( Ok(bytes) } -fn selector(state: &GuestState, register: u8) -> Result { +pub(super) fn selector(state: &GuestState, register: u8) -> Result { require( (8..=11).contains(®ister), "ZA vector selector must be W8..W11", @@ -115,14 +115,14 @@ fn selector(state: &GuestState, register: u8) -> Result { Ok(state.x[usize::from(register)] as u32) } -fn read_lane(bytes: &[u8], lane: usize, width: usize) -> u64 { +pub(super) fn read_lane(bytes: &[u8], lane: usize, width: usize) -> u64 { let mut result = [0; size_of::()]; let start = lane * width; result[..width].copy_from_slice(&bytes[start..start + width]); u64::from_le_bytes(result) } -fn write_lane(bytes: &mut [u8], lane: usize, width: usize, bits: u64) { +pub(super) fn write_lane(bytes: &mut [u8], lane: usize, width: usize, bits: u64) { let start = lane * width; bytes[start..start + width].copy_from_slice(&bits.to_le_bytes()[..width]); } diff --git a/crates/stela-runtime/src/scalable.rs b/crates/stela-runtime/src/scalable.rs index af3bd17861..02bd86e77c 100644 --- a/crates/stela-runtime/src/scalable.rs +++ b/crates/stela-runtime/src/scalable.rs @@ -7,15 +7,13 @@ use anyhow::{Result, ensure}; use stela_compiler::{ GuestState, aarch64::scalable::{ - ElementSize, LOOKUP_TABLE_BYTES, PREDICATE_REGISTER_COUNT, STREAMING_RESET_FPSR, - ScalableMode, VECTOR_CHUNK_BYTES, VECTOR_REGISTER_COUNT, VectorLength, - is_predicate_register, is_z_register, + LOOKUP_TABLE_BYTES, PREDICATE_REGISTER_COUNT, STREAMING_RESET_FPSR, ScalableMode, + VECTOR_CHUNK_BYTES, VECTOR_REGISTER_COUNT, VectorLength, is_predicate_register, + is_z_register, }, context::ScalableStateView, }; -const MIN_NUMERICAL_ZA_ELEMENT_BYTES: usize = ElementSize::Halfword.bytes(); - /// Owns one guest thread's scalable state, without duplicating GuestState.v. /// Controls exist before either of the independently lazy buffers is allocated. #[derive(Debug)] @@ -61,7 +59,7 @@ impl ScalableState { } /// Borrow reusable staging for affected numerical ZA rows, bounded by the - /// largest Half tile. The callback owns evaluation and architectural commit; + /// complete physical matrix. The callback owns evaluation and architectural commit; /// this loan does not roll back writes the callback chooses to perform. /// Contents are unspecified: initialize every staged row before evaluation. /// Initialized high-water storage is retained without repeated zeroing after @@ -74,9 +72,9 @@ impl ScalableState { where E: From, { - let maximum_rows = self.length.bytes() / MIN_NUMERICAL_ZA_ELEMENT_BYTES; + let maximum_rows = self.length.bytes(); if rows == 0 || rows > maximum_rows { - return Err(anyhow::anyhow!("ZA scratch row count exceeds a numerical tile").into()); + return Err(anyhow::anyhow!("ZA scratch row count exceeds the physical matrix").into()); } let storage = self .za_scratch @@ -86,7 +84,7 @@ impl ScalableState { state: self, storage, }; - // Validated architectural lengths and row counts bound this to 32KiB. + // Validated architectural lengths and physical row counts bound this to 64KiB. let bytes = rows * loan.state.length.bytes(); if bytes > loan.storage.len() { loan.storage @@ -593,7 +591,7 @@ mod tests { state.set_tpidr2_el0(123); state.set_fpmr(456); let original = state.clone(); - let rows = bytes / MIN_NUMERICAL_ZA_ELEMENT_BYTES; + let rows = bytes; let pointer = state.with_za_row_scratch(rows, |_, scratch| -> Result<_> { assert_eq!(scratch.len(), rows * bytes); assert!(scratch.iter().all(|byte| *byte == 0)); @@ -633,7 +631,7 @@ mod tests { #[test] fn za_scratch_bounds_reentrancy_and_clone_are_independent() -> Result<()> { let mut state = ScalableState::new(length(32), true); - let maximum_rows = state.vector_length().bytes() / MIN_NUMERICAL_ZA_ELEMENT_BYTES; + let maximum_rows = state.vector_length().bytes(); for invalid in [0, maximum_rows + 1, usize::MAX] { let result: Result<()> = state.with_za_row_scratch(invalid, |_, _| panic!("invalid loan entered callback")); diff --git a/dev/simd_fixtures/extrema_scale.py b/dev/simd_fixtures/extrema_scale.py new file mode 100644 index 0000000000..3cbcc4eb17 --- /dev/null +++ b/dev/simd_fixtures/extrema_scale.py @@ -0,0 +1,104 @@ +"""AdvSIMD FAMIN/MAX and FSCALE fixtures for the shared full-frame observer. + +The integer/Fraction models are shared with the consolidated SVE numerical +fixtures. They provide a separate mathematical comparison, never an original +execution substitute. Source words are from the pinned June 2026 allocation. +""" +import hashlib +import struct + +from differential import State, seed_extended_state +from .sve_floating.faminmax import Operation, evaluate_lane +from .sve_floating.arithmetic_special import scale_lane + +FOCUS = 'extrema_scale_numerical' +CANONICAL_FORMS = tuple(name + suffix for name in ('FAMAX', 'FAMIN', 'FSCALE') + for suffix in ('_asimdsame_only', '_asimdsamefp16_only')) +BASES = {'famax': (0x0ea0dc00, 0x0ec01c00), + 'famin': (0x2ea0dc00, 0x2ec01c00), + 'fscale': (0x2ea0fc00, 0x2ec03c00)} +ROLES = ((0, 1, 2), (1, 1, 2), (2, 1, 2), (0, 1, 1), (31, 31, 31), (31, 30, 29)) +CONTROLS = (0, 1 << 1, 1, 1 << 2, 1 << 24, 1 << 19, 1 << 25, + 1 << 26, (1 << 1) | (1 << 24), (1 << 1) | (1 << 25), + 1 << 22, 2 << 22, 3 << 22, 0x9f00) +MASK64 = (1 << 64) - 1 + + +def operation(name, lane, width, d=0, n=1, m=2): + if name not in BASES or (lane, width) not in ((2, 8), (2, 16), (4, 8), (4, 16), (8, 16)): + raise ValueError('Unallocated absolute-extrema/scale arrangement') + if any(not 0 <= register < 32 for register in (d, n, m)): + raise ValueError('Vector register out of range') + word = BASES[name][lane == 2] | (lane == 8) << 22 | (width == 16) << 30 + return dict(name=name, word=word | m << 16 | n << 5 | d, + canonical_id=name.upper() + ('_asimdsamefp16_only' if lane == 2 else '_asimdsame_only'), + d=d, n=n, m=m, lane=lane, bytes=width, scalar=False, + merge='none', output_kind='vector', return_register=30) + + +def functions(): + return [operation(name, lane, width, *roles) for name in BASES + for lane, width in ((2, 8), (2, 16), (4, 8), (4, 16), (8, 16)) + for roles in ROLES] + + +def expected(op, initial): + state = State.from_buffer_copy(initial) + bits = op['lane'] * 8 + mask = (1 << bits) - 1 + left, right = (initial.v[op[key]][0] | initial.v[op[key]][1] << 64 for key in ('n', 'm')) + result = exceptions = 0 + for lane in range(op['bytes'] // op['lane']): + a, b = (left >> (bits * lane) & mask), (right >> (bits * lane) & mask) + if op['name'] == 'fscale': + outcome = scale_lane(bits, initial.fpcr, a, b) + else: + kind = Operation.MINIMUM if op['name'] == 'famin' else Operation.MAXIMUM + outcome = evaluate_lane(kind, bits, initial.fpcr, a, b) + result |= outcome.bits << (bits * lane) + exceptions |= outcome.exceptions + state.v[op['d']][:] = [result & MASK64, result >> 64] + state.fpsr |= exceptions + return state + + +def corpus(): + ops, records = functions(), [] + for function, op in enumerate(ops): + bits = op['lane'] * 8 + fraction = {16: 10, 32: 23, 64: 52}[bits] + bias = {16: 15, 32: 127, 64: 1023}[bits] + sign = 1 << (bits - 1) + infinity = sign - (1 << fraction) + one = bias << fraction + numeric = (0, sign, 1, sign | 1, (1 << fraction) - 1, 1 << fraction, + one, sign | one, one + (1 << fraction), infinity - 1, + infinity, sign | infinity, infinity | 1, + sign | infinity | (1 << (fraction - 1)) | 13) + controls = CONTROLS if (op['d'], op['n'], op['m']) == ROLES[0] else (0, 1 << 25, 0x9f00) + for control in controls: + patterns = range(len(numeric)) if control == 0 else range(0, len(numeric), 3) + for pattern in patterns: + state = State() + seed_extended_state(state, function * 17 + pattern) + state.fpcr, state.fpsr = control, (1 << 27) | (1 << 2) + state.nzcv, state.reserved = 0xa0000000, 0x51ad1234 + for register in range(31): + state.x[register] = (register + 1) * 0x123456789 + state.sp = 0x7ffffff0 + a = numeric[pattern] + b = ((-1, 0, 1, 2, -2, sign - 1, -sign)[pattern % 7] & (2 * sign - 1) + if op['name'] == 'fscale' else numeric[(pattern + 5) % len(numeric)]) + def vector(value, offset): + values = [value if lane % 2 == 0 else numeric[(pattern + lane + offset) % len(numeric)] + for lane in range(16 // op['lane'])] + if op['name'] == 'fscale' and offset == 1: + values = [value] * len(values) + return struct.unpack('<2Q', b''.join(v.to_bytes(op['lane'], 'little') for v in values)) + state.v[op['n']][:] = vector(a, 0) + state.v[op['m']][:] = vector(b, 1) + raw = bytes(state) + records.append(dict(case=len(records), function=function, function_index=function, + label=f'pattern_{pattern}_fpcr_{control:x}', + initial=raw, initial_state_sha256=hashlib.sha256(raw).hexdigest())) + return ops, records diff --git a/dev/simd_fixtures/sme/extrema_scale.py b/dev/simd_fixtures/sme/extrema_scale.py new file mode 100644 index 0000000000..0ae21d6f36 --- /dev/null +++ b/dev/simd_fixtures/sme/extrema_scale.py @@ -0,0 +1,123 @@ +"""SME2 absolute extrema and signed exponent scaling, with full Snapshot fixtures. + +Mathematical lanes reuse the independent integer/Fraction SVE models. Originals +remain exact encoded subjects captured separately by scalable_original. +""" +from dataclasses import replace +import struct + +import scalable_frame as frame +from simd_fixtures.sve_floating.faminmax import Operation, evaluate_lane +from simd_fixtures.sve_floating.arithmetic_special import scale_lane +from simd_fixtures.sve_floating.control import FP_EXCEPTION_ENABLE_MASK + +# Factual pinned June2026 form identifiers, fixed masks/opcodes, group/layout. +ENCODINGS = ( + ('famax_mz_zzw_2x2', 0xff21ffe1, 0xc120b140, 2, True, 'famax'), + ('famax_mz_zzw_4x4', 0xff23ffe3, 0xc120b940, 4, True, 'famax'), + ('famin_mz_zzw_2x2', 0xff21ffe1, 0xc120b141, 2, True, 'famin'), + ('famin_mz_zzw_4x4', 0xff23ffe3, 0xc120b941, 4, True, 'famin'), + ('fscale_mz_zzv_2x1', 0xff30ffe1, 0xc120a180, 2, False, 'fscale'), + ('fscale_mz_zzv_4x1', 0xff30ffe3, 0xc120a980, 4, False, 'fscale'), + ('fscale_mz_zzw_2x2', 0xff21ffe1, 0xc120b180, 2, True, 'fscale'), + ('fscale_mz_zzw_4x4', 0xff23ffe3, 0xc120b980, 4, True, 'fscale'), +) +REQUIRED = (frame.Component.PRIMARY | frame.Component.Z | frame.Component.P + | frame.Component.ZA | frame.Component.ZT0 | frame.Component.SVCR + | frame.Component.TPIDR2) + + +def decode(word): + for canonical, mask, opcode, count, grouped, name in ENCODINGS: + if word & mask != opcode: + continue + size = word >> 22 & 3 + if size == 0: + return None + return dict(word=word, canonical_id=canonical, count=count, grouped=grouped, + name=name, bits=8 << size, destination=word & (32 - count), + right=(word >> 16 & (32 - count)) if grouped else (word >> 16 & 15)) + return None + + +def expected(operation, initial, ram=None): + op = decode(operation['word']) + if op is None or not initial.control('svcr') & frame.SVCR_SM: + raise ValueError('Allocated SME extrema/scale streaming subject required') + if initial.valid & REQUIRED != REQUIRED: + raise ValueError('Full observable SME state is required') + fpcr, fpsr = struct.unpack_from('