Merge upstream main into task/329-gate-a1

Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
This commit is contained in:
zachdoxsee committed 2026-11-24 22:24:13 +01:00
commit e6fa931264
9 files changed
+778 -29

No files matched your search

+3
View File
@@ -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.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
@@ -20,10 +21,12 @@ remains unsupported.
- 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.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- 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.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### 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 process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
+1 -1
View File
@@ -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
+40
View File
@@ -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(
+21 -1
View File
@@ -361,6 +361,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,
@@ -613,9 +616,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),
@@ -649,7 +669,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);
}
+42
View File
@@ -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}");
}
}
+384
View File
@@ -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<u8> {
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}");
}
}
}
+76 -27
View File
@@ -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<ProtocolObject<dyn MTLComputePipelineState>>;
struct CachedPipeline {
source: Box<str>,
entry: Box<str>,
shader_validation: bool,
pipeline: ComputePipeline,
}
const BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -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<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
submissions: Mutex<SubmissionTable>,
// Least recently used first. In-flight submissions retain their own reference.
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
}
/// 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<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_pipeline: ComputePipeline,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
@@ -348,6 +362,7 @@ impl NativeCompute {
device,
queue,
submissions: Mutex::default(),
compute_pipelines: Mutex::default(),
})
})
}
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> 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<float, access::sample> tex [[texture(0)]],
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
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<float, access::sample> tex [[texture(0)]],
host_start: Instant,
) -> Result<Submission<'_>, 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<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
fn prepare_compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, 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<dyn MTLComputePipelineState>,
) -> 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",
+174
View File
@@ -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::<Vec<_>>()
.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),
);
}
}
+37
View File
@@ -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