From c95e175210b49196ba25720b53a0a3cd6fdc0808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartosz=20Szczepa=C5=84ski?= Date: Tue, 24 Nov 2026 19:12:29 +0100 Subject: [PATCH 1/4] loader: run ADC and SBB register and immediate forms natively in the DBT (#195) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DBT now lowers the 32- and 64-bit register and immediate forms of ADC and SBB to ADCS and SBCS instead of calling the shared semantics. The guest CF is moved into the host carry first, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms stay on the shared semantics. Adds the ADCS and SBCS encodings to the ARM64 assembler, checked against llvm-mc, and tests/x86_carry_chain.rs: 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening u128/i128 reference arithmetic in both engines, plus 128-bit immediate increments and decrements and the sbb reg, reg carry mask. Signed-off-by: Bartosz SzczepaƄski --- CHANGELOG.md | 1 + crates/loader/src/arm64.rs | 40 +++ crates/loader/src/dbt.rs | 22 +- crates/loader/tests/arm64_encodings.rs | 42 +++ crates/loader/tests/x86_carry_chain.rs | 384 +++++++++++++++++++++++++ 5 files changed, 488 insertions(+), 1 deletion(-) create mode 100644 crates/loader/tests/x86_carry_chain.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index e686c9c..48c1804 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only. - Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215. - Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215. - Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215. diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index f8daa67..4428eac 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -430,6 +430,46 @@ impl Arm64Assembler { ); } + /// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C. + pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) { + self.emit( + 0xba000000 + | ((xm as u32 & 0x1f) << 16) + | ((xn as u32 & 0x1f) << 5) + | (xd as u32 & 0x1f), + ); + } + + /// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C. + pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) { + self.emit( + 0x3a000000 + | ((wm as u32 & 0x1f) << 16) + | ((wn as u32 & 0x1f) << 5) + | (wd as u32 & 0x1f), + ); + } + + /// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C. + pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) { + self.emit( + 0xfa000000 + | ((xm as u32 & 0x1f) << 16) + | ((xn as u32 & 0x1f) << 5) + | (xd as u32 & 0x1f), + ); + } + + /// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C. + pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) { + self.emit( + 0x7a000000 + | ((wm as u32 & 0x1f) << 16) + | ((wn as u32 & 0x1f) << 5) + | (wd as u32 & 0x1f), + ); + } + /// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12 pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) { self.emit( diff --git a/crates/loader/src/dbt.rs b/crates/loader/src/dbt.rs index 4aba211..98b8b8b 100644 --- a/crates/loader/src/dbt.rs +++ b/crates/loader/src/dbt.rs @@ -335,6 +335,9 @@ pub fn is_native(insn: &Insn) -> bool { let scanned = matches!(insn.size, 2 | 4 | 8); match insn.op { Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide, + // Register and immediate forms only; a memory destination would have + // to restore the guest carry again after the store helper call. + Op::Adc | Op::Sbb => wide && insn.memory().is_none(), Op::Inc | Op::Dec | Op::Neg | Op::Not => wide, Op::Cmov => wide, Op::Bsf | Op::Bsr => scanned, @@ -587,9 +590,26 @@ impl Emitter<'_> { } /// X11 = X9 op X10, setting host NZCV only for the arithmetic operations. + /// ADC and SBB also read the guest CF and clobber X12 and X13. fn compute(&mut self, op: Op, wide: bool) { let asm = &mut *self.asm; + if matches!(op, Op::Adc | Op::Sbb) { + // ADCS adds the host C, so C must equal the guest CF. SBCS + // subtracts NOT C, while x86 SBB subtracts the borrow CF, so there + // C must be its inverse. A compare sets C when it does not borrow. + asm.ldrb_uoff(X12, X19, CF); + if op == Op::Adc { + asm.load_imm_64(X13, 1); + asm.cmp_reg_32(X12, X13); // C = CF >= 1 + } else { + asm.cmp_reg_32(XZR, X12); // C = 0 >= CF + } + } match (op, wide) { + (Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10), + (Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10), + (Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10), + (Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10), (Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10), (Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10), (Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10), @@ -623,7 +643,7 @@ impl Emitter<'_> { match op { // INC and DEC leave CF unchanged. Op::Inc | Op::Dec => {} - Op::Add => { + Op::Add | Op::Adc => { asm.cset_32(X12, Condition::Cs); asm.strb_uoff(X12, X19, CF); } diff --git a/crates/loader/tests/arm64_encodings.rs b/crates/loader/tests/arm64_encodings.rs index 47d8615..90fff4a 100644 --- a/crates/loader/tests/arm64_encodings.rs +++ b/crates/loader/tests/arm64_encodings.rs @@ -164,3 +164,45 @@ fn vector_operations_match_llvm() { assert_eq!(assembler.instructions(), [*word], "{text}"); } } + +#[test] +fn carry_arithmetic_matches_llvm() { + // `llvm-mc -triple=aarch64-apple-macos -show-encoding`. + let cases: &[(&str, Emit, u32)] = &[ + ( + "adcs x11, x9, x10", + |a| a.adcs_reg_64(11, 9, 10), + 0xba0a012b, + ), + ( + "adcs w11, w9, w10", + |a| a.adcs_reg_32(11, 9, 10), + 0x3a0a012b, + ), + ( + "adcs x0, x30, x17", + |a| a.adcs_reg_64(0, 30, 17), + 0xba1103c0, + ), + ( + "sbcs x11, x9, x10", + |a| a.sbcs_reg_64(11, 9, 10), + 0xfa0a012b, + ), + ( + "sbcs w11, w9, w10", + |a| a.sbcs_reg_32(11, 9, 10), + 0x7a0a012b, + ), + ( + "sbcs w0, w30, w17", + |a| a.sbcs_reg_32(0, 30, 17), + 0x7a1103c0, + ), + ]; + for (text, emit, word) in cases { + let mut assembler = Arm64Assembler::new(); + emit(&mut assembler); + assert_eq!(assembler.instructions(), [*word], "{text}"); + } +} diff --git a/crates/loader/tests/x86_carry_chain.rs b/crates/loader/tests/x86_carry_chain.rs new file mode 100644 index 0000000..26638bc --- /dev/null +++ b/crates/loader/tests/x86_carry_chain.rs @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Multiword ADC and SBB carry chains through the interpreter and the native +//! DBT. +//! +//! Encodings were assembled with LLVM (`llvm-mc -triple=x86_64`, Intel syntax). +//! Expected values come from widening `u128` and `i128` arithmetic over the +//! limbs, following the ADC and SBB operation sections of the Intel SDM Vol. 2: +//! DEST = DEST + SRC + CF and DEST = DEST - (SRC + CF). They never read the +//! production semantics. Both engines must also agree on the complete state, +//! including PF and AF, which the reference does not model. + +use xenora_loader::cpu::{CpuState, ExitReason, Interpreter}; +use xenora_loader::dbt::{DbtEngine, is_native}; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; +use xenora_loader::x86_decode::decode; +use xenora_loader::x86_table::Op; + +const ENTRY: u64 = 0x1000; +/// `jmp +0`: ends the translated block, so the next instruction reads CF from +/// the guest state stored by the previous block. +const JMP: [u8; 2] = [0xEB, 0x00]; +const HLT: u8 = 0xF4; + +/// Limb registers: A in RAX, RBX, RCX, RDX and B in R8 to R11. +const A: [usize; 4] = [0, 3, 1, 2]; +const B: [usize; 4] = [8, 9, 10, 11]; + +// add rax, r8; adc rbx, r9; adc rcx, r10; adc rdx, r11 (and the SUB/SBB and +// 32-bit equivalents). +const ADD64: [&[u8]; 4] = [ + &[0x4C, 0x01, 0xC0], + &[0x4C, 0x11, 0xCB], + &[0x4C, 0x11, 0xD1], + &[0x4C, 0x11, 0xDA], +]; +const SUB64: [&[u8]; 4] = [ + &[0x4C, 0x29, 0xC0], + &[0x4C, 0x19, 0xCB], + &[0x4C, 0x19, 0xD1], + &[0x4C, 0x19, 0xDA], +]; +const ADD32: [&[u8]; 4] = [ + &[0x44, 0x01, 0xC0], + &[0x44, 0x11, 0xCB], + &[0x44, 0x11, 0xD1], + &[0x44, 0x11, 0xDA], +]; +const SUB32: [&[u8]; 4] = [ + &[0x44, 0x29, 0xC0], + &[0x44, 0x19, 0xCB], + &[0x44, 0x19, 0xD1], + &[0x44, 0x19, 0xDA], +]; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Chain { + Add, + Sub, +} + +/// Expected limbs and CF, ZF, SF, OF of the last limb. +#[derive(PartialEq, Eq, Debug)] +struct Expected { + limbs: [u64; 4], + cf: bool, + zf: bool, + sf: bool, + of: bool, +} + +fn reference(chain: Chain, bits: u32, a: [u64; 4], b: [u64; 4]) -> Expected { + let mask = if bits == 64 { + u64::MAX + } else { + (1u64 << bits) - 1 + }; + let modulus = 1u128 << bits; + let signed = |value: u64| -> i128 { + let value = i128::from(value & mask); + if value >= (1i128 << (bits - 1)) { + value - (1i128 << bits) + } else { + value + } + }; + let mut limbs = [0; 4]; + let mut carry = 0u128; + let mut of = false; + for i in 0..4 { + let (x, y) = (u128::from(a[i] & mask), u128::from(b[i] & mask)); + let wide = match chain { + Chain::Add => x + y + carry, + Chain::Sub => x + modulus - y - carry, + }; + limbs[i] = (wide % modulus) as u64; + let exact = match chain { + Chain::Add => signed(a[i]) + signed(b[i]) + carry as i128, + Chain::Sub => signed(a[i]) - signed(b[i]) - carry as i128, + }; + of = exact != signed(limbs[i]); + carry = match chain { + Chain::Add => u128::from(wide >= modulus), + Chain::Sub => u128::from(y + carry > x), + }; + } + Expected { + limbs, + cf: carry != 0, + zf: limbs[3] == 0, + sf: limbs[3] >> (bits - 1) & 1 != 0, + of, + } +} + +fn program(parts: &[&[u8]], split: bool) -> Vec { + let mut code = Vec::new(); + for (i, part) in parts.iter().enumerate() { + if split && i > 0 { + code.extend_from_slice(&JMP); + } + code.extend_from_slice(part); + } + code.push(HLT); + code +} + +fn load(code: &[u8], gpr: [u64; 16], cf: bool) -> (CpuState, GuestMemory) { + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code) + .unwrap(); + let mut cpu = CpuState::new(ENTRY, 0); + cpu.gpr = gpr; + cpu.flags.cf = cf; + (cpu, memory) +} + +/// Run `code` to its HLT in both engines, check they agree on the whole state +/// and that the DBT never left native code, and return the final state. +fn run_both(code: &[u8], gpr: [u64; 16], cf: bool, context: &str) -> CpuState { + let (cpu, mut memory) = load(code, gpr, cf); + let interpreted = Interpreter::new(cpu, &mut memory, 64).run(); + let (mut cpu, mut memory) = load(code, gpr, cf); + let mut engine = DbtEngine::new(16 * 1024).unwrap(); + let translated = engine.run(&mut cpu, &mut memory, 64); + assert_eq!(interpreted.exit_reason, ExitReason::Halt, "{context}"); + assert_eq!(translated.exit_reason, ExitReason::Halt, "{context}"); + assert_eq!(translated.final_state, interpreted.final_state, "{context}"); + assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{context}"); + interpreted.final_state +} + +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } +} + +/// Limb values at the carry and overflow boundaries of a `bits`-wide limb. +fn edges(bits: u32) -> [u64; 6] { + let max = if bits == 64 { + u64::MAX + } else { + (1u64 << bits) - 1 + }; + let sign = 1u64 << (bits - 1); + [0, 1, max - 1, max, sign, sign - 1] +} + +fn operand_sets(bits: u32) -> Vec<([u64; 4], [u64; 4])> { + let edges = edges(bits); + let mut sets = Vec::new(); + for &x in &edges { + for &y in &edges { + sets.push(([x; 4], [y; 4])); + sets.push(([x, y, x, y], [y, x, y, x])); + } + } + let mut random = Random(0x0195_ADC5_BB00_0001); + for _ in 0..256 { + let mut pick = || { + let raw = random.next(); + if raw & 3 == 0 { + edges[(raw >> 8) as usize % edges.len()] | raw & !edges[3] + } else { + raw + } + }; + let a = [pick(), pick(), pick(), pick()]; + let b = [pick(), pick(), pick(), pick()]; + sets.push((a, b)); + } + sets +} + +fn check_chain(chain: Chain, bits: u32, parts: [&[u8]; 4]) { + for part in &parts[1..] { + let insn = decode(ENTRY, |address| { + part.get((address - ENTRY) as usize).copied().ok_or(()) + }) + .unwrap(); + assert!(matches!(insn.op, Op::Adc | Op::Sbb)); + assert!(is_native(&insn), "{:?}", insn.op); + } + let mut random = Random(u64::from(bits) << 8 | chain as u64); + for (a, b) in operand_sets(bits) { + let expected = reference(chain, bits, a, b); + for split in [false, true] { + let code = program(&parts, split); + let mut gpr: [u64; 16] = std::array::from_fn(|_| random.next()); + for i in 0..4 { + gpr[A[i]] = a[i]; + gpr[B[i]] = b[i]; + } + // The leading ADD or SUB must ignore the incoming carry. + for cf in [false, true] { + let context = format!("{chain:?}{bits} split={split} cf={cf} a={a:x?} b={b:x?}"); + let state = run_both(&code, gpr, cf, &context); + let limbs = A.map(|index| state.gpr[index]); + // A 32-bit destination clears bits 63:32. + assert_eq!(limbs, expected.limbs, "{context}"); + assert_eq!(B.map(|index| state.gpr[index]), b, "{context}"); + let flags = ( + state.flags.cf, + state.flags.zf, + state.flags.sf, + state.flags.of, + ); + let wanted = (expected.cf, expected.zf, expected.sf, expected.of); + assert_eq!(flags, wanted, "{context}"); + } + } + } +} + +#[test] +fn reference_matches_native_wide_arithmetic() { + // 128-bit sanity checks of the reference itself on the low two limbs. + let cases = [ + (u128::MAX, 1u128), + (0, 1), + (1u128 << 64, 1), + (0x8000_0000_0000_0000_0000_0000_0000_0000, 1), + ]; + for (x, y) in cases { + let a = [x as u64, (x >> 64) as u64, 0, 0]; + let b = [y as u64, (y >> 64) as u64, 0, 0]; + let sum = reference(Chain::Add, 64, a, b); + let expected = x.wrapping_add(y); + assert_eq!(sum.limbs[0], expected as u64); + assert_eq!(sum.limbs[1], (expected >> 64) as u64); + let difference = reference(Chain::Sub, 64, a, b); + let expected = x.wrapping_sub(y); + assert_eq!(difference.limbs[0], expected as u64); + assert_eq!(difference.limbs[1], (expected >> 64) as u64); + // The upper limbs are zero, so the 256-bit borrow is the 128-bit one. + assert_eq!(difference.cf, y > x); + } +} + +#[test] +fn add_adc_chains_of_64_bit_limbs_carry_across_blocks() { + check_chain(Chain::Add, 64, ADD64); +} + +#[test] +fn sub_sbb_chains_of_64_bit_limbs_borrow_across_blocks() { + check_chain(Chain::Sub, 64, SUB64); +} + +#[test] +fn add_adc_chains_of_32_bit_limbs_carry_across_blocks() { + check_chain(Chain::Add, 32, ADD32); +} + +#[test] +fn sub_sbb_chains_of_32_bit_limbs_borrow_across_blocks() { + check_chain(Chain::Sub, 32, SUB32); +} + +#[test] +fn split_chains_run_one_block_per_limb() { + let code = program(&ADD64, true); + let (mut cpu, mut memory) = load(&code, [0; 16], false); + let mut engine = DbtEngine::new(16 * 1024).unwrap(); + let result = engine.run(&mut cpu, &mut memory, 64); + assert_eq!(result.exit_reason, ExitReason::Halt); + assert_eq!(engine.metrics.blocks_compiled, 4); + assert_eq!(engine.metrics.interpreter_fallbacks, 0); +} + +#[test] +fn immediate_forms_increment_and_decrement_a_128_bit_value() { + // add rax, 1; adc rbx, 0 and sub rax, 1; sbb rbx, 0. + let increment: [&[u8]; 2] = [&[0x48, 0x83, 0xC0, 0x01], &[0x48, 0x83, 0xD3, 0x00]]; + let decrement: [&[u8]; 2] = [&[0x48, 0x83, 0xE8, 0x01], &[0x48, 0x83, 0xDB, 0x00]]; + let values = [ + 0u128, + 1, + u64::MAX as u128, + 1u128 << 64, + u128::MAX, + u128::MAX - 1, + 1u128 << 127, + (1u128 << 127) - 1, + ]; + for value in values { + for split in [false, true] { + for (parts, expected, carry, overflow) in [ + ( + &increment, + value.wrapping_add(1), + value == u128::MAX, + value == (1u128 << 127) - 1, + ), + ( + &decrement, + value.wrapping_sub(1), + value == 0, + value == 1u128 << 127, + ), + ] { + let code = program(parts, split); + let mut gpr = [0x5A5A_5A5A_5A5A_5A5A; 16]; + gpr[0] = value as u64; + gpr[3] = (value >> 64) as u64; + let context = format!("{value:#x} split={split} {:x?}", parts[0]); + let state = run_both(&code, gpr, true, &context); + assert_eq!(state.gpr[0], expected as u64, "{context}"); + assert_eq!(state.gpr[3], (expected >> 64) as u64, "{context}"); + assert_eq!(state.flags.cf, carry, "{context}"); + assert_eq!(state.flags.of, overflow, "{context}"); + assert_eq!(state.flags.zf, (expected >> 64) == 0, "{context}"); + assert_eq!(state.flags.sf, expected >> 127 != 0, "{context}"); + } + } + } +} + +#[test] +fn sbb_of_a_register_with_itself_materializes_the_carry_mask() { + // sbb esi, esi and sbb rsi, rsi give -CF and borrow exactly when CF was + // set; adc edi, 0 adds CF to 0x89ABCDEF without a carry out. The 32-bit + // forms clear bits 63:32. + // (code, destination register, value from CF, CF out from CF in) + type Case = (&'static [u8], usize, fn(bool) -> u64, fn(bool) -> bool); + let cases: [Case; 3] = [ + ( + &[0x19, 0xF6], + 6, + |cf| if cf { 0xFFFF_FFFF } else { 0 }, + |cf| cf, + ), + ( + &[0x48, 0x19, 0xF6], + 6, + |cf| if cf { u64::MAX } else { 0 }, + |cf| cf, + ), + ( + &[0x83, 0xD7, 0x00], + 7, + |cf| u64::from(cf) + 0x89AB_CDEF, + |_| false, + ), + ]; + for (code, register, value, carry) in cases { + for cf in [false, true] { + let mut gpr = [0x0123_4567_89AB_CDEF; 16]; + gpr[6] = 0xDEAD_BEEF_0000_0001; + let program = [code, &[HLT]].concat(); + let context = format!("{code:x?} cf={cf}"); + let state = run_both(&program, gpr, cf, &context); + assert_eq!(state.gpr[register], value(cf), "{context}"); + assert_eq!(state.flags.cf, carry(cf), "{context}"); + } + } +} From 6f1ac2a906ff817f4d933c799cd1f8fa4822cbf9 Mon Sep 17 00:00:00 2001 From: katherinebytes Date: Tue, 24 Nov 2026 19:12:15 +0000 Subject: [PATCH 2/4] Reuse Metal compute pipelines Signed-off-by: katherinebytes --- CHANGELOG.md | 1 + crates/metal/src/compute.rs | 103 +++++++++++----- crates/metal/tests/native_compute.rs | 174 +++++++++++++++++++++++++++ 3 files changed, 251 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e686c9c..2dd8d02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132. - Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215. - Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215. - Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215. diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index ebed2ad..7be347e 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::fmt; use std::mem::size_of_val; @@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64; const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP; const MAX_SOURCE_BYTES: usize = 64 * 1024; const MAX_IN_FLIGHT: usize = 16; +const MAX_CACHED_PIPELINES: usize = 16; + +type ComputePipeline = Retained>; + +struct CachedPipeline { + source: Box, + entry: Box, + shader_validation: bool, + pipeline: ComputePipeline, +} const BC_READBACK: &str = r" #include @@ -148,7 +158,9 @@ impl std::error::Error for MetalError {} /// measure a single submission and are not a benchmark distribution. #[derive(Debug, Clone)] pub struct RunProfile { + /// Host library compilation time, or zero when reusing a compute pipeline. pub library_seconds: f64, + /// Host pipeline creation time, or zero when reusing a compute pipeline. pub pipeline_seconds: f64, pub gpu_seconds: f64, /// Host wall time from the start of setup until wait observes completion. @@ -171,6 +183,8 @@ pub struct NativeCompute { device: Retained>, queue: Retained>, submissions: Mutex, + // Least recently used first. In-flight submissions retain their own reference. + compute_pipelines: Mutex>, } /// A submitted dispatch whose result can be collected by its issuing context. @@ -247,7 +261,7 @@ struct SubmissionEntry { /// Metal reports Completed or Error. struct InFlightResources { command: Retained>, - _pipeline: Retained>, + _pipeline: ComputePipeline, _input: Option>>, output: Retained>, _texture: Option>>, @@ -348,6 +362,7 @@ impl NativeCompute { device, queue, submissions: Mutex::default(), + compute_pipelines: Mutex::default(), }) }) } @@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], self.run_profiled_words(source, entry, input, Some(width)) } - /// Compile the kernel and report the smaller of the device and pipeline width limits. + /// Find or compile the kernel and report the smaller of the device and pipeline width limits. /// /// Input size and threadgroup count are checked separately at dispatch. /// @@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], pub fn max_group_width(&self, source: &str, entry: &str) -> Result { validate_source(source, &[entry])?; autoreleasepool(|_| { - let options = compile_options()?; - let library = self.compile_library(source, &options)?; - let function = find_function(&library, entry)?; - let pipeline = self.compute_pipeline(&function)?; - verify_shader_validation(&pipeline)?; + let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?; Ok(self.pipeline_group_width_limit(&pipeline)) }) } @@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], host_start: Instant, ) -> Result, MetalError> { self.submissions().check_capacity()?; - let options = compile_options()?; - let library_start = Instant::now(); - let library = self.compile_library(source, &options)?; - let library_seconds = library_start.elapsed().as_secs_f64(); - let function = find_function(&library, entry)?; - let pipeline_start = Instant::now(); - let pipeline = self.compute_pipeline(&function)?; - let pipeline_seconds = pipeline_start.elapsed().as_secs_f64(); - verify_shader_validation(&pipeline)?; + let (pipeline, library_seconds, pipeline_seconds) = + self.prepare_compute_pipeline(source, entry)?; let limit = self.pipeline_group_width_limit(&pipeline); let width = match group_width { @@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], }) } - fn compute_pipeline( + fn prepare_compute_pipeline( &self, - function: &ProtocolObject, - ) -> Result>, MetalError> { - self.device - .newComputePipelineStateWithFunction_error(function) + source: &str, + entry: &str, + ) -> Result<(ComputePipeline, f64, f64), MetalError> { + let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1"); + // Device identity is fixed by this context. All misses use the same + // compile options (safe math, precise functions, default language, + // no macros) and unspecialized functions. Any configurable options + // must become part of the key before they are used here. + let mut cache = self + .compute_pipelines + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(index) = cache.iter().position(|cached| { + cached.source.as_ref() == source + && cached.entry.as_ref() == entry + && cached.shader_validation == shader_validation + }) { + let cached = cache.remove(index).expect("position in the locked cache"); + let pipeline = cached.pipeline.clone(); + cache.push_back(cached); + return Ok((pipeline, 0.0, 0.0)); + } + + // Serialize cache misses in this context so concurrent requests for + // one key share the same build. The submission table is unlocked here. + let options = compile_options()?; + let library_start = Instant::now(); + let library = self.compile_library(source, &options)?; + let library_seconds = library_start.elapsed().as_secs_f64(); + let function = find_function(&library, entry)?; + let pipeline_start = Instant::now(); + let pipeline = self + .device + .newComputePipelineStateWithFunction_error(&function) .map_err(|error| { MetalError::new( "newComputePipelineStateWithFunction", error.localizedDescription().to_string(), ) - }) + })?; + let pipeline_seconds = pipeline_start.elapsed().as_secs_f64(); + if shader_validation { + verify_shader_validation(&pipeline)?; + } + + // Bound owned key text to 1 MiB. A valid oversized key can run + // uncached, so this budget does not alter source or entry validation. + if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) { + if cache.len() == MAX_CACHED_PIPELINES { + cache.pop_front(); + } + cache.push_back(CachedPipeline { + source: source.into(), + entry: entry.into(), + shader_validation, + pipeline: pipeline.clone(), + }); + } + Ok((pipeline, library_seconds, pipeline_seconds)) } fn pipeline_group_width_limit( @@ -1232,10 +1285,6 @@ fn check_command_status( fn verify_shader_validation( pipeline: &ProtocolObject, ) -> Result<(), MetalError> { - if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") { - return Ok(()); - } - if !pipeline.respondsToSelector(sel!(shaderValidation)) { return Err(MetalError::new( "shaderValidation", diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 0cdce52..b4e9b69 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -356,6 +356,131 @@ fn multiple_submissions() { assert_eq!(second, [5, 5, 1, 5]); } +fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool { + profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0 +} + +#[test] +fn compute_pipeline_cache_distinguishes_source_entry_and_context() { + let context = context(); + let source = fixture("output[id] = input[id] + 1u;"); + let second_entry = + fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other("); + let source = format!("{source}\n{second_entry}"); + let changed = source.replace("input[id] + 1u", "input[id] - 1u"); + let input = [0, 11, u32::MAX]; + + for (msl, entry, expected) in [ + (source.as_str(), "fixture", [1, 12, 0]), + (source.as_str(), "other", [0, 22, u32::MAX - 1]), + (changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]), + ] { + let cold = native(context.run_words_profiled(msl, entry, &input)); + let warm = native(context.run_words_profiled(msl, entry, &input)); + assert!(!pipeline_was_reused(&cold), "{entry}"); + assert!(pipeline_was_reused(&warm), "{entry}"); + assert_eq!(cold.output, expected, "{entry}"); + assert_eq!(warm.output, expected, "{entry}"); + } + let separate = native(NativeCompute::new()); + let fresh = native(separate.run_words_profiled(&source, "fixture", &input)); + assert!(!pipeline_was_reused(&fresh)); + assert_eq!(fresh.output, [1, 12, 0]); + + for _ in 0..2 { + for (msl, entry, operation) in [ + (source.as_str(), "missing", "newFunctionWithName"), + ("not valid MSL", "fixture", "newLibraryWithSource"), + ] { + let error = context + .run_words_profiled(msl, entry, &input) + .expect_err("invalid pipeline must still fail after warming the cache"); + assert_eq!(error.operation, operation); + } + } + let error = context + .run_words_with_group_width(&source, "fixture", &input, 0) + .expect_err("cached pipeline must still check dispatch width"); + assert_eq!(error.operation, "threadgroup width"); +} + +#[test] +fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() { + const SOURCE_LIMIT: usize = 64 * 1024; + let context = context(); + let mut source = fixture("output[id] = input[id] ^ 1u;"); + source.push_str("\n// "); + source.push_str(&" ".repeat(SOURCE_LIMIT - source.len())); + + for _ in 0..2 { + let profile = native(context.run_words_profiled(&source, "fixture", &[8])); + assert_eq!(profile.output, [9]); + assert!(!pipeline_was_reused(&profile)); + } + source.push(' '); + let error = context + .run_words_profiled(&source, "fixture", &[8]) + .expect_err("source above 64 KiB must fail before pipeline lookup"); + assert_eq!(error.operation, "source bounds"); +} + +#[test] +fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() { + let context = context(); + // Seventeen entries in one source fit in Metal's input limit and exceed + // Xenora's 16-pipeline cache. Each kernel writes a distinct result. + let source: String = (0..=16) + .map(|id| { + fixture(&format!("output[id] = input[id] + {id}u;")) + .replace("void fixture(", &format!("void entry{id}(")) + }) + .collect::>() + .join("\n"); + native(context.max_group_width(&source, "entry0")); + let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7])); + for id in 2..16 { + native(context.max_group_width(&source, &format!("entry{id}"))); + } + native(context.max_group_width(&source, "entry0")); + native(context.max_group_width(&source, "entry16")); + gate.open(); + let finished = native(context.wait(pending)); + assert_eq!(finished.output, [8]); + + let recent = native(context.run_words_profiled(&source, "entry0", &[29])); + assert!(pipeline_was_reused(&recent)); + assert_eq!(recent.output, [29]); + let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17])); + assert!(!pipeline_was_reused(&rebuilt)); + assert_eq!(rebuilt.output, [18]); +} + +#[test] +fn simultaneous_compute_submissions_share_one_pipeline_build() { + let context = context(); + let source = fixture("output[id] = input[id] ^ 5u;"); + let start = std::sync::Barrier::new(4); + std::thread::scope(|scope| { + let workers: Vec<_> = (0..4) + .map(|input| { + let (context, source, start) = (&context, &source, &start); + scope.spawn(move || { + start.wait(); + let token = native(context.submit_words(source, "fixture", &[input])); + let result = native(context.wait(token)); + assert_eq!(result.output, [input ^ 5]); + usize::from(!pipeline_was_reused(&result)) + }) + }) + .collect(); + let builds: usize = workers + .into_iter() + .map(|worker| worker.join().unwrap()) + .sum(); + assert_eq!(builds, 1); + }); +} + #[test] fn errors_propagate() { let context = context(); @@ -413,3 +538,52 @@ kernel void fixture(device const uint *input [[buffer(0)]], } } } + +#[test] +#[ignore = "manual GPU timing run"] +fn compute_pipeline_reuse_benchmark() { + const WARMUPS: usize = 10; + const SAMPLES: usize = 101; + let warm_context = context(); + let device = warm_context.device_name(); + let source = fixture("output[id] = input[id] * 7u + 3u;"); + let input = mixing_input(131); + let expected: Vec<_> = input + .iter() + .map(|word| word.wrapping_mul(7).wrapping_add(3)) + .collect(); + let mut timings = [[[0.0; SAMPLES]; 4]; 2]; + + for round in 0..WARMUPS + SAMPLES { + let cold_context = context(); + // Alternate order so neither measurement always follows the other. + let contexts = [&cold_context, &warm_context]; + for index in [round % 2, (round + 1) % 2] { + let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input)); + assert_eq!(profile.output, expected, "context={index} round={round}"); + if round >= WARMUPS { + for (samples, seconds) in timings[index].iter_mut().zip([ + profile.library_seconds, + profile.pipeline_seconds, + profile.host_seconds, + profile.gpu_seconds, + ]) { + samples[round - WARMUPS] = seconds; + } + } + } + } + for (label, [mut library, mut pipeline, mut host, mut gpu]) in + ["fresh context", "repeated context"] + .into_iter() + .zip(timings) + { + println!( + "device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]", + timing_summary(&mut library), + timing_summary(&mut pipeline), + timing_summary(&mut host), + timing_summary(&mut gpu), + ); + } +} From 2f28a5adbb145799d9cac58ee8c50d497805dd86 Mon Sep 17 00:00:00 2001 From: Vedant Dadhich Date: Wed, 25 Nov 2026 01:37:53 +0530 Subject: [PATCH 3/4] Scripts: run GPU tests without GNU timeout stock macOS does not provide the timeout command used by scripts/test-gpu.sh. Add a Python 3 fallback that preserves duration parsing, process-group termination and exit status 124, while continuing to use GNU timeout when it is available. Signed-off-by: Vedant Dadhich --- CHANGELOG.md | 1 + README.md | 2 +- scripts/test-gpu.sh | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2efe1e..b071364 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ remains unsupported. ### Fixed - Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing. +- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### Added - Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302). diff --git a/README.md b/README.md index 82da167..5f5d38b 100644 --- a/README.md +++ b/README.md @@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac. scripts/test-gpu.sh ``` -The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. +The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable. ### Verify guest execution diff --git a/scripts/test-gpu.sh b/scripts/test-gpu.sh index 27a4f27..a9502cc 100755 --- a/scripts/test-gpu.sh +++ b/scripts/test-gpu.sh @@ -13,6 +13,43 @@ export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4} # allow slower hosts to raise it without editing the script. export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s} +# macOS does not ship GNU timeout. Python 3 is already a project requirement, +# so use a small POSIX-compatible fallback rather than making coreutils a +# prerequisite for the native suite. +if ! command -v timeout >/dev/null 2>&1; then + timeout() { + duration=$1 + shift + python3 - "$duration" "$@" <<'PY' +import os +import re +import signal +import subprocess +import sys + +text = sys.argv[1] +match = re.fullmatch(r"(\d+(?:\.\d+)?)([smh]?)", text) +if match is None: + print(f"timeout: invalid duration {text!r}", file=sys.stderr) + raise SystemExit(2) +seconds = float(match.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)] +try: + process = subprocess.Popen(sys.argv[2:], start_new_session=True) +except FileNotFoundError as error: + print(f"timeout: {error}", file=sys.stderr) + raise SystemExit(127) +try: + code = process.wait(timeout=seconds) +except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + print(f"timeout: command exceeded {seconds:g} seconds", file=sys.stderr) + raise SystemExit(124) +raise SystemExit(code) +PY + } +fi + cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \ --nocapture --test-threads=1 From a7fa8b0d65db0b020c6e1f1ce354449ad02b7ed5 Mon Sep 17 00:00:00 2001 From: katherinebytes Date: Tue, 24 Nov 2026 20:47:35 +0000 Subject: [PATCH 4/4] Retry the ARM64 CI run Signed-off-by: katherinebytes