From cd472c30c8e012ba2986bbfe7c97fed792fd5144 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:33:52 -0500 Subject: [PATCH] perf(compiler): keep cached V registers across lane moves, permutes, reductions and constants, load and store Q registers through their homes, and commit straight to the state before a flush --- crates/stela-compiler/src/x86_64/asm.rs | 13 ++++++ crates/stela-compiler/src/x86_64/asm/sse.rs | 6 +-- crates/stela-compiler/src/x86_64/block.rs | 41 +++++++++++++------ .../src/x86_64/block/vector_cache_tests.rs | 27 ++++++++---- crates/stela-compiler/src/x86_64/simd.rs | 34 +++++++++++++-- .../stela-compiler/src/x86_64/simd/memory.rs | 21 ++++++++++ .../src/x86_64/simd/products.rs | 10 +++-- .../src/x86_64/simd/rearrange.rs | 26 ++++++++++++ .../stela-compiler/src/x86_64/vector_cache.rs | 35 ++++++++++++++++ 9 files changed, 182 insertions(+), 31 deletions(-) diff --git a/crates/stela-compiler/src/x86_64/asm.rs b/crates/stela-compiler/src/x86_64/asm.rs index 1484a49d3c..8136dd52bc 100644 --- a/crates/stela-compiler/src/x86_64/asm.rs +++ b/crates/stela-compiler/src/x86_64/asm.rs @@ -222,6 +222,19 @@ impl<'a> Asm<'a> { assert!(!matches!(rm, Rm::Xmm(register) if register >= 16)); self.legacy(Size::Dword, prefix, opcode, xmm, false, rm); } + /// [`Self::sse`] of a form whose ModRM.reg register is a source (a + /// store), which may name a register holding a guest vector. + pub(crate) fn sse_reading( + &mut self, + prefix: Option, + opcode: &[u8], + xmm: u8, + rm: impl Into, + ) { + let guarded = core::mem::replace(&mut self.guarded, 0); + self.sse(prefix, opcode, xmm, rm); + self.guarded = guarded; + } /// [`Self::sse`] with an 8-bit immediate. pub(crate) fn sse_imm( &mut self, diff --git a/crates/stela-compiler/src/x86_64/asm/sse.rs b/crates/stela-compiler/src/x86_64/asm/sse.rs index a0deb48eab..3a9c3d35c8 100644 --- a/crates/stela-compiler/src/x86_64/asm/sse.rs +++ b/crates/stela-compiler/src/x86_64/asm/sse.rs @@ -175,12 +175,12 @@ impl Asm<'_> { } /// `movdqu xmm/m128, xmm`. pub(crate) fn movdqu_store(&mut self, rm: impl Into, xmm: u8) { - self.sse(Some(0xf3), &[0x0f, 0x7f], xmm, rm); + self.sse_reading(Some(0xf3), &[0x0f, 0x7f], xmm, rm); } /// `movdqa xmm/m128, xmm`: one 16-byte access, which faults unless /// 16-byte aligned. pub(crate) fn movdqa_store(&mut self, rm: impl Into, xmm: u8) { - self.sse(Some(0x66), &[0x0f, 0x7f], xmm, rm); + self.sse_reading(Some(0x66), &[0x0f, 0x7f], xmm, rm); } /// `pextrw r32, xmm, imm8` (66 0F C5): zero-extends word `lane`. pub(crate) fn pextrw(&mut self, destination: Gpr, xmm: u8, lane: u8) { @@ -214,7 +214,7 @@ impl Asm<'_> { } /// `movd r/m32, xmm`. pub(crate) fn movd_from_xmm(&mut self, rm: impl Into, xmm: u8) { - self.sse(Some(0x66), &[0x0f, 0x7e], xmm, rm); + self.sse_reading(Some(0x66), &[0x0f, 0x7e], xmm, rm); } /// `stmxcsr m32`. pub(crate) fn stmxcsr(&mut self, memory: impl Into) { diff --git a/crates/stela-compiler/src/x86_64/block.rs b/crates/stela-compiler/src/x86_64/block.rs index 9c9cca1898..ba0184d9fe 100644 --- a/crates/stela-compiler/src/x86_64/block.rs +++ b/crates/stela-compiler/src/x86_64/block.rs @@ -718,13 +718,23 @@ fn emit_selected( // A join lands here from a point that stored them all. code.settle_vectors(); } - let mut class = vector_use(&instructions[cursor].operation); // A fused group addresses the state itself. - if fuse_simd - && super::simd::sha256::HashGroup::recognize(&instructions[cursor..]).is_some() - { - class = VectorUse::Settle; - } + let class_at = |at: usize| { + if fuse_simd + && super::simd::sha256::HashGroup::recognize(&instructions[at..]).is_some() + { + VectorUse::Settle + } else { + vector_use(&instructions[at].operation, target) + } + }; + let class = class_at(cursor); + // Where the next instruction stores or forgets the homes + // anyway, results go straight to the state. + let next_keeps = cursor + 1 < instructions.len() + && !landing[cursor + 1] + && class_at(cursor + 1) == VectorUse::Keep; + code.set_vector_write_through(!next_keeps); match class { VectorUse::Keep => code.set_vector_cache(true), VectorUse::Flush => { @@ -1663,7 +1673,7 @@ pub(super) enum VectorUse { Settle, } -fn vector_use(operation: &Operation) -> VectorUse { +fn vector_use(operation: &Operation, target: crate::TargetCpu) -> VectorUse { match operation { Operation::AddSub { .. } | Operation::AddSubRegister { .. } @@ -1686,7 +1696,7 @@ fn vector_use(operation: &Operation) -> VectorUse { | Operation::BranchCondition { .. } | Operation::BranchZero { .. } | Operation::BranchBit { .. } => VectorUse::Flush, - Operation::Simd(operand) => super::simd::vector_use(operand), + Operation::Simd(operand) => super::simd::vector_use(operand, target), _ => VectorUse::Settle, } } @@ -1761,7 +1771,10 @@ fn emit_single( super::simd::emit_after(code, operand, target, checks, held.xmm0, held.xmm_pair); // A first load of the vector XMM0 holds changes nothing. if let Some(vector) = held.xmm0 { - let load = super::simd::xmm0_load(scratch, vector); + let load = match code.vector_cache().peek(vector) { + Some(host) => super::simd::xmm0_home_load(scratch, host), + None => super::simd::xmm0_load(scratch, vector), + }; if code[start..].starts_with(load) && code.len() > start + load.len() { code.remove_instruction(start..start + load.len()); } @@ -1933,9 +1946,13 @@ fn emit_single( }); let keep_vectors = !code.constant_time() && preserves_held_vectors(&instruction.operation); let xmm0 = match &instruction.operation { - Operation::Simd(operand) => { - super::simd::xmm0_after(scratch, operand, &code[start..], held.xmm0) - } + Operation::Simd(operand) => super::simd::xmm0_after( + scratch, + operand, + &code[start..], + held.xmm0, + code.vector_cache(), + ), _ if keep_vectors => held.xmm0, _ => None, }; diff --git a/crates/stela-compiler/src/x86_64/block/vector_cache_tests.rs b/crates/stela-compiler/src/x86_64/block/vector_cache_tests.rs index c8bf4cee0c..b3c923134f 100644 --- a/crates/stela-compiler/src/x86_64/block/vector_cache_tests.rs +++ b/crates/stela-compiler/src/x86_64/block/vector_cache_tests.rs @@ -225,10 +225,14 @@ fn every_fault_site_finds_the_cached_writes_stored() { // cached results are stored before it. let load = accesses[0]; assert_eq!(load.retirement.position().unwrap().retired_instructions, 3); + // The last is written straight to its slot from the recipe's + // register, since the access follows it. let code = &block.x86_64_code[block.source_map[2].1..load.start]; - let stores = code - .windows(4) - .filter(|w| *w == [0xf3, 0x44, 0x0f, 0x7f]) + let stores = (0..code.len().saturating_sub(4)) + .filter(|&at| { + code[at..at + 4] == [0xf3, 0x44, 0x0f, 0x7f] + || code[at..at + 3] == [0xf3, 0x0f, 0x7f] && code[at + 3] & 0xc7 == 0x87 + }) .count(); assert_eq!(stores, 3); } @@ -251,7 +255,8 @@ fn a_guest_access_after_an_unstored_write_is_refused() { } /// The cache stores the dirty homes before an access, a side exit, an -/// uncached instruction and the terminal, and only there. +/// uncached instruction and the terminal, and only there; a result the +/// next of those follows goes straight to its slot. #[test] fn dirty_vectors_are_stored_where_the_state_must_be_current() { // add v0.4s,v1.4s,v2.4s; add v0.4s,v0.4s,v2.4s; ldr x2,[x1]; @@ -279,12 +284,18 @@ fn dirty_vectors_are_stored_where_the_state_must_be_current() { // movdqu [rdi+0x108+16v],xmm8..15: a home stored to V`v`'s slot. let stores_of = |range: core::ops::Range| -> Vec { let bytes = &code[range]; - (0..bytes.len().saturating_sub(4)) - .filter(|&at| { - bytes[at..at + 4] == [0xf3, 0x44, 0x0f, 0x7f] && bytes[at + 4] & 0xc7 == 0x87 + // From a home (REX.R) or straight from a recipe's register. + (0..bytes.len().saturating_sub(7)) + .filter_map(|at| { + let rex = usize::from(bytes[at + 1] == 0x44); + (at + 8 + rex <= bytes.len() + && bytes[at] == 0xf3 + && bytes[at + 1 + rex..at + 3 + rex] == [0x0f, 0x7f] + && bytes[at + 3 + rex] & 0xc7 == 0x87) + .then_some(at + 4 + rex) }) .map(|at| { - let offset = u32::from_le_bytes(bytes[at + 5..at + 9].try_into().unwrap()); + let offset = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()); ((offset - 0x108) / 16) as u8 }) .collect() diff --git a/crates/stela-compiler/src/x86_64/simd.rs b/crates/stela-compiler/src/x86_64/simd.rs index 232a49affa..efb34f6ab7 100644 --- a/crates/stela-compiler/src/x86_64/simd.rs +++ b/crates/stela-compiler/src/x86_64/simd.rs @@ -132,7 +132,9 @@ fn vector_memory(vector: u8) -> Mem { /// Write guest vector `vector` from `xmm`: to its home where the block /// keeps vectors in registers ([`super::vector_cache`]), else to the state. fn commit(code: &mut Code, vector: u8, xmm: u8) { - if code.vector_cache().active() { + if code.vector_cache().writes_through() { + code.discard_vector(vector); + } else if code.vector_cache().active() { let host = code.allocate_vector(vector); if host != xmm { code.asm_unguarded().sse( @@ -484,7 +486,7 @@ pub(super) fn emit_for_target( /// [`read_vector`], [`vector_source`], [`vector_operand`] and [`commit`] and /// names only the scratch registers XMM0 to XMM7. Accesses store the dirty /// homes before their fault sites. -pub(super) fn vector_use(operand: &Operand) -> super::block::VectorUse { +pub(super) fn vector_use(operand: &Operand, target: crate::TargetCpu) -> super::block::VectorUse { use super::block::VectorUse::*; match operand { Operand::Integer { .. } @@ -492,7 +494,11 @@ pub(super) fn vector_use(operand: &Operand) -> super::block::VectorUse { | Operand::MoveImmediate { .. } | Operand::Product(_) | Operand::Saturate(_) - | Operand::Halving(_) => Keep, + | Operand::Halving(_) + | Operand::Reduce(_) + | Operand::Immediate(crate::aarch64::simd::immediates::Operand::Constant { .. }) => Keep, + Operand::Immediate(crate::aarch64::simd::immediates::Operand::LaneMove(lane)) + | Operand::Rearrange(lane) => rearrange::vector_use(lane, target), // The register forms and scalar saturating shifts stage lanes // through the state (`shifts::register_shift`). Operand::Shift(shift) => match shift.kind { @@ -828,10 +834,21 @@ pub(super) fn xmm0_after( operand: &Operand, code: &[u8], held: Option, + homes: &super::vector_cache::VectorCache, ) -> Option { + let cached = homes.active(); let mut committed = |vector: u8| { scratch.clear(); - commit(scratch, vector, 0); + match homes.peek(vector) { + // The commit to a home from XMM0. + Some(host) => scratch.asm_unguarded().sse( + Some(0x66), + &[0x0f, 0x6f], + host, + crate::x86_64::asm::Rm::Xmm(0), + ), + None => commit(scratch, vector, 0), + } code.ends_with(scratch).then_some(vector) }; match *operand { @@ -850,6 +867,8 @@ pub(super) fn xmm0_after( destination, .. }) => committed(destination), + // With vectors in host registers, a transfer may use the home. + Operand::Memory { .. } | Operand::MemoryRegisterOffset(_) if cached => None, Operand::Memory { load, bytes, @@ -872,6 +891,13 @@ pub(super) fn xmm0_load(scratch: &mut Code, vector: u8) -> &[u8] { scratch } +/// [`read_vector`]'s bytes for a vector whose home is `host` into XMM0. +pub(super) fn xmm0_home_load(scratch: &mut Code, host: u8) -> &[u8] { + scratch.clear(); + packed(scratch, Host::MoveAligned, 0, host); + scratch +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/stela-compiler/src/x86_64/simd/memory.rs b/crates/stela-compiler/src/x86_64/simd/memory.rs index f929fce429..ce5a9a97fb 100644 --- a/crates/stela-compiler/src/x86_64/simd/memory.rs +++ b/crates/stela-compiler/src/x86_64/simd/memory.rs @@ -66,6 +66,27 @@ pub(super) fn transfers_xmm0(load: bool, bytes: u8) -> bool { /// commits nothing. With `held`, XMM0 holds the vector whole, and a store /// through XMM0 ([`transfers_xmm0`]) takes it from there. pub(in crate::x86_64) fn transfer(code: &mut Code, load: bool, bytes: u8, vector: u8, held: bool) { + let cache = code.vector_cache(); + if load && bytes == VECTOR_BYTES && cache.active() && !cache.writes_through() { + // Straight into the vector's home ([`super::super::vector_cache`]). + let host = code.allocate_vector(vector); + let address = Mem::base(Gpr::Rax, 0); + code.guest_access(|code| { + code.asm_unguarded() + .sse(Some(0xf3), &[0x0f, 0x6f], host, address) + }); + code.mark_vector_dirty(vector); + return; + } + if !load + && bytes == VECTOR_BYTES + && !held + && let Some(host) = code.vector_home(vector) + { + // Straight from the vector's home. + wide_transfer(code, false, bytes, host, 0); + return; + } if load { match bytes { BYTE_BYTES | HALFWORD_BYTES => { diff --git a/crates/stela-compiler/src/x86_64/simd/products.rs b/crates/stela-compiler/src/x86_64/simd/products.rs index 178565a186..65c935f64a 100644 --- a/crates/stela-compiler/src/x86_64/simd/products.rs +++ b/crates/stela-compiler/src/x86_64/simd/products.rs @@ -2,6 +2,7 @@ use super::rearrange::{add_or_subtract, lane_constant}; use super::{ Host, commit, greater, packed, packed_imm, read_vector, rearrange::constant, shuffle, three, + vector_source, }; use crate::x86_64::asm::{Code, Cond, Gpr, Size, resolve, vector_extensions}; use crate::{ @@ -137,12 +138,13 @@ fn accumulate(code: &mut Code, destination: u8, lane: u8, operation: Accumulate) if operation == Accumulate::None { return 0; } - read_vector(code, destination, 1); if operation == Accumulate::Subtract { + read_vector(code, destination, 1); packed(code, add_or_subtract(lane, true), 1, 0); 1 } else { - packed(code, add_or_subtract(lane, false), 0, 1); + let accumulator = vector_source(code, destination, 1); + packed(code, add_or_subtract(lane, false), 0, accumulator); 0 } } @@ -728,8 +730,8 @@ fn word_long_product( match operation { Accumulate::None => result, Accumulate::Add => { - read_vector(code, operand.destination, 1); - three::three(code, Host::AddDword, result, result, 1, target); + let accumulator = vector_source(code, operand.destination, 1); + three::three(code, Host::AddDword, result, result, accumulator, target); result } Accumulate::Subtract => { diff --git a/crates/stela-compiler/src/x86_64/simd/rearrange.rs b/crates/stela-compiler/src/x86_64/simd/rearrange.rs index 8d94a2d36b..7af7c7253d 100644 --- a/crates/stela-compiler/src/x86_64/simd/rearrange.rs +++ b/crates/stela-compiler/src/x86_64/simd/rearrange.rs @@ -181,6 +181,10 @@ pub(super) fn add_or_subtract(lane: u8, subtract: bool) -> Host { fn load_lane(code: &mut Code, source: LaneSource, bytes: u8) { use crate::aarch64::Register; + if let LaneSource::Vector { register, .. } = source { + // The lane is read from the slot: store a newer home first. + code.write_back_vector(register); + } let mut asm = code.asm(); let storage = match source { LaneSource::General(Register::Zero) => { @@ -266,6 +270,8 @@ fn insert_lane(code: &mut Code, destination: u8, byte: u8, bytes: u8) { 8 => Size::Qword, _ => unreachable!("reviewed lane size"), }; + // The lane is written to the slot: the home, stored if newer, goes. + code.evict_vector(destination); code.asm().mov_store( size, guest(vector_offset(destination) + u32::from(byte)), @@ -683,6 +689,26 @@ fn duplicate(code: &mut Code, source: LaneSource, lane: u8, bytes: u8, target: T } } +/// Whether `operand` keeps the block's vector homes +/// ([`super::vector_use`]): lane moves store or give up the home of the +/// vector whose slot they address; the SSSE3 permutation and the byte +/// extraction use the operand layer alone; tables and the scalar byte +/// gather address slots. +pub(in crate::x86_64) fn vector_use( + operand: &Operand, + target: TargetCpu, +) -> crate::x86_64::block::VectorUse { + use crate::x86_64::block::VectorUse::{Keep, Settle}; + match *operand { + Operand::Duplicate { .. } + | Operand::Insert { .. } + | Operand::Extract { .. } + | Operand::ByteExtract(_) => Keep, + Operand::Permute { .. } if target >= TargetCpu::Ssse3 => Keep, + Operand::Permute { .. } | Operand::Table { .. } => Settle, + } +} + pub(super) fn emit(code: &mut Code, operand: &Operand, target: TargetCpu, held: Option) { match *operand { Operand::Duplicate { diff --git a/crates/stela-compiler/src/x86_64/vector_cache.rs b/crates/stela-compiler/src/x86_64/vector_cache.rs index 7df6453f66..690918873f 100644 --- a/crates/stela-compiler/src/x86_64/vector_cache.rs +++ b/crates/stela-compiler/src/x86_64/vector_cache.rs @@ -47,6 +47,9 @@ pub(crate) struct VectorCache { /// The last use of each pool register, for the least recently used spill. used: [u32; HOSTS], clock: u32, + /// Whether commits go to the state: the next instruction stores or + /// forgets every home anyway, so a home would cost a second move. + write_through: bool, } impl Default for VectorCache { @@ -58,6 +61,7 @@ impl Default for VectorCache { dirty: 0, used: [0; HOSTS], clock: 0, + write_through: false, } } } @@ -98,9 +102,18 @@ impl VectorCache { host }) } + /// The home of `vector`, without counting a use. + pub(crate) fn peek(&self, vector: u8) -> Option { + let host = self.home[usize::from(vector)]; + (self.active && host != NONE).then_some(host) + } pub(crate) fn is_dirty(&self, vector: u8) -> bool { self.dirty & 1 << vector != 0 } + /// Whether a commit goes to the state rather than to a home. + pub(crate) const fn writes_through(&self) -> bool { + self.active && self.write_through + } } impl Code { @@ -147,6 +160,27 @@ impl Code { self.vectors.touch(index); host } + /// Commit to the state from here on, or to homes. + pub(crate) fn set_vector_write_through(&mut self, through: bool) { + self.vectors.write_through = through; + } + /// Give up `vector`'s home without storing it: the caller writes the + /// whole register to the state next. + pub(crate) fn discard_vector(&mut self, vector: u8) { + let host = self.vectors.home[usize::from(vector)]; + if host != NONE { + self.vectors.dirty &= !(1 << vector); + self.vectors.home[usize::from(vector)] = NONE; + self.vectors.owner[usize::from(host - FIRST_HOST)] = NONE; + } + } + /// Store `vector` if its home is dirty, keeping the home: for a + /// recipe that then reads part of its slot. + pub(crate) fn write_back_vector(&mut self, vector: u8) { + if self.vectors.home[usize::from(vector)] != NONE && self.vectors.is_dirty(vector) { + self.store_vector(vector); + } + } /// `vector`'s home holds a value the state block lacks. pub(crate) fn mark_vector_dirty(&mut self, vector: u8) { debug_assert_ne!(self.vectors.home[usize::from(vector)], NONE); @@ -186,6 +220,7 @@ impl Code { let active = self.vectors.active; self.vectors = VectorCache { active, + write_through: self.vectors.write_through, clock: self.vectors.clock, ..VectorCache::default() };