Compare commits

..
Author SHA1 Message Date
katherinebytes bd46504a97 Add a seeded CPU differential corpus
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 21:11:03 +00:00
11 changed files with 676 additions and 1557 deletions

No files matched your search

-4
View File
@@ -10,7 +10,6 @@ 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.
@@ -21,15 +20,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
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- 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).
+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. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
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.
### Verify guest execution
+3 -778
View File
@@ -5,14 +5,7 @@
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
//! document (format version 1). The text output does not change. Values the
//! benchmark cannot determine, such as the git revision outside a checkout,
//! are written as `null`. The benchmark cannot see build settings such as LTO,
//! so `XENORA_DBT_BENCH_BUILD_LABEL=<text>` records a label of your choosing
//! for them.
//!
//! Set `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` to compare
//! two such documents instead of running the benchmark. The comparison is
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//! are written as `null`.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
@@ -161,7 +154,6 @@ struct RunInfo {
revision: Option<String>,
dirty: Option<bool>,
debug_assertions: bool,
build_label: Option<String>,
guest_code_bytes: usize,
warmup: usize,
}
@@ -195,7 +187,6 @@ fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
.map(|status| !status.is_empty()),
debug_assertions: cfg!(debug_assertions),
build_label: non_empty(std::env::var("XENORA_DBT_BENCH_BUILD_LABEL").ok()),
guest_code_bytes,
warmup,
}
@@ -283,10 +274,7 @@ fn json_document(
),
(
"build",
json_object(&[
("debug_assertions", info.debug_assertions.to_string()),
("label", json_option(info.build_label.as_ref(), string)),
]),
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
),
(
"workload",
@@ -331,471 +319,7 @@ fn json_document(
])
}
/// A parsed JSON value. Numbers keep their source text, so integers compare exactly.
#[derive(Clone, Debug, PartialEq)]
enum Json {
Null,
Bool(bool),
Number(String),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>),
}
impl Json {
/// The value at a dotted path such as `host.cpu`, if every step is an object key.
fn get(&self, path: &str) -> Option<&Json> {
path.split('.').try_fold(self, |value, key| match value {
Json::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
})
}
}
const MAX_JSON_DEPTH: usize = 32;
/// Reads one JSON document (RFC 8259) and rejects anything after it.
fn parse_json(text: &str) -> Result<Json, String> {
let mut reader = JsonReader {
bytes: text.as_bytes(),
pos: 0,
};
let value = reader.value(0)?;
reader.skip_whitespace();
if reader.pos != reader.bytes.len() {
return reader.error("unexpected data after the document");
}
Ok(value)
}
struct JsonReader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl JsonReader<'_> {
fn error<T>(&self, what: &str) -> Result<T, String> {
Err(format!("{what} at byte {}", self.pos))
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.pos).copied()
}
fn skip_whitespace(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.pos += 1;
}
}
fn expect(&mut self, byte: u8) -> Result<(), String> {
if self.peek() == Some(byte) {
self.pos += 1;
Ok(())
} else {
self.error(&format!("expected '{}'", byte as char))
}
}
fn value(&mut self, depth: usize) -> Result<Json, String> {
if depth > MAX_JSON_DEPTH {
return self.error("nesting too deep");
}
self.skip_whitespace();
match self.peek() {
None => self.error("unexpected end of input"),
Some(b'n') => self.literal("null", Json::Null),
Some(b't') => self.literal("true", Json::Bool(true)),
Some(b'f') => self.literal("false", Json::Bool(false)),
Some(b'"') => Ok(Json::String(self.string()?)),
Some(b'[') => self.array(depth),
Some(b'{') => self.object(depth),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => self.error("unexpected character"),
}
}
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
if self.bytes[self.pos..].starts_with(word.as_bytes()) {
self.pos += word.len();
Ok(value)
} else {
self.error("invalid literal")
}
}
fn array(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'[')?;
let mut items = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b']') {
self.pos += 1;
return Ok(Json::Array(items));
}
loop {
items.push(self.value(depth + 1)?);
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b']') => {
self.pos += 1;
return Ok(Json::Array(items));
}
_ => return self.error("expected ',' or ']'"),
}
}
}
fn object(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'{')?;
let mut fields: Vec<(String, Json)> = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b'}') {
self.pos += 1;
return Ok(Json::Object(fields));
}
loop {
self.skip_whitespace();
let key = self.string()?;
if fields.iter().any(|(k, _)| *k == key) {
return self.error(&format!("duplicate key `{key}`"));
}
self.skip_whitespace();
self.expect(b':')?;
let value = self.value(depth + 1)?;
fields.push((key, value));
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b'}') => {
self.pos += 1;
return Ok(Json::Object(fields));
}
_ => return self.error("expected ',' or '}'"),
}
}
}
fn digits(&mut self) -> usize {
let start = self.pos;
while matches!(self.peek(), Some(b'0'..=b'9')) {
self.pos += 1;
}
self.pos - start
}
fn number(&mut self) -> Result<Json, String> {
let start = self.pos;
if self.peek() == Some(b'-') {
self.pos += 1;
}
match self.peek() {
Some(b'0') => self.pos += 1,
Some(b'1'..=b'9') => {
self.digits();
}
_ => return self.error("invalid number"),
}
if self.peek() == Some(b'.') {
self.pos += 1;
if self.digits() == 0 {
return self.error("invalid number");
}
}
if matches!(self.peek(), Some(b'e' | b'E')) {
self.pos += 1;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.pos += 1;
}
if self.digits() == 0 {
return self.error("invalid number");
}
}
// Only ASCII digits and signs were consumed.
Ok(Json::Number(
String::from_utf8_lossy(&self.bytes[start..self.pos]).into_owned(),
))
}
fn hex4(&mut self) -> Result<u32, String> {
let digits = self.bytes.get(self.pos..self.pos + 4);
let value = digits
.and_then(|d| std::str::from_utf8(d).ok())
.and_then(|d| u32::from_str_radix(d, 16).ok());
match value {
Some(value) if digits.is_some_and(|d| d.iter().all(u8::is_ascii_hexdigit)) => {
self.pos += 4;
Ok(value)
}
_ => self.error("invalid \\u escape"),
}
}
fn unicode_escape(&mut self) -> Result<char, String> {
let first = self.hex4()?;
let code = match first {
0xD800..=0xDBFF => {
if !self.bytes[self.pos..].starts_with(b"\\u") {
return self.error("unpaired surrogate");
}
self.pos += 2;
let second = self.hex4()?;
if !(0xDC00..=0xDFFF).contains(&second) {
return self.error("unpaired surrogate");
}
0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00)
}
0xDC00..=0xDFFF => return self.error("unpaired surrogate"),
code => code,
};
char::from_u32(code).map_or_else(|| self.error("invalid code point"), Ok)
}
fn string(&mut self) -> Result<String, String> {
self.expect(b'"')?;
let mut out = String::new();
loop {
// Copy the run up to the next quote, backslash or control byte. Those
// are ASCII, so the run never ends inside a multi-byte character.
let start = self.pos;
while matches!(self.peek(), Some(b) if b != b'"' && b != b'\\' && b >= 0x20) {
self.pos += 1;
}
match std::str::from_utf8(&self.bytes[start..self.pos]) {
Ok(run) => out.push_str(run),
Err(_) => return self.error("invalid UTF-8"),
}
match self.peek() {
Some(b'"') => {
self.pos += 1;
return Ok(out);
}
Some(b'\\') => {
self.pos += 1;
let escaped = self.peek();
self.pos += 1;
out.push(match escaped {
Some(b'"') => '"',
Some(b'\\') => '\\',
Some(b'/') => '/',
Some(b'b') => '\u{8}',
Some(b'f') => '\u{c}',
Some(b'n') => '\n',
Some(b'r') => '\r',
Some(b't') => '\t',
Some(b'u') => self.unicode_escape()?,
_ => {
self.pos -= 1;
return self.error("invalid escape");
}
});
}
Some(_) => return self.error("control character in string"),
None => return self.error("unterminated string"),
}
}
}
}
/// Fields that must be equal for two runs to be compared. A field listed in
/// `OPTIONAL_FIELDS` counts as `null` when a document does not have it.
const MATCHING_FIELDS: [&str; 15] = [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
];
/// Older version 1 documents predate the build label.
const OPTIONAL_FIELDS: [&str; 1] = ["build.label"];
/// Host fields that must be known: two unknown CPUs are not the same CPU.
const KNOWN_FIELDS: [&str; 3] = ["host.cpu", "host.os", "host.arch"];
const SERIES: [(&str, &str); 3] = [
("interpreter", "Interpreter"),
("cold_dbt", "Cold DBT"),
("warm_dbt", "Warm DBT"),
];
const COUNTERS: [&str; 8] = [
"blocks_compiled",
"cache_hits",
"cache_misses",
"native_bytes_emitted",
"dbt_dispatches",
"instructions_executed",
"interpreter_fallbacks",
"service_calls",
];
fn field<'a>(doc: &'a Json, path: &str) -> Result<&'a Json, String> {
match doc.get(path) {
Some(value) => Ok(value),
None if OPTIONAL_FIELDS.contains(&path) => Ok(&Json::Null),
None => Err(format!("missing field `{path}`")),
}
}
fn integer(doc: &Json, path: &str) -> Result<u128, String> {
match field(doc, path)? {
Json::Number(text) => text
.parse()
.map_err(|_| format!("`{path}` is not a non-negative integer")),
_ => Err(format!("`{path}` is not a number")),
}
}
fn text(doc: &Json, path: &str) -> String {
match doc.get(path) {
Some(Json::String(value)) => value.clone(),
Some(Json::Bool(value)) => value.to_string(),
Some(Json::Number(value)) => value.clone(),
// The build label is optional, so its absence is not an unknown value.
_ if OPTIONAL_FIELDS.contains(&path) => "none".to_owned(),
_ => "unknown".to_owned(),
}
}
fn duration(ns: u128) -> Duration {
Duration::from_nanos(u64::try_from(ns).unwrap_or(u64::MAX))
}
fn change(before: u128, after: u128) -> String {
if before == 0 {
return "n/a".to_owned();
}
format!(
"{:+.2}%",
(after as f64 - before as f64) / before as f64 * 100.0
)
}
fn source(doc: &Json) -> String {
let dirty = match doc.get("source.dirty") {
Some(Json::Bool(true)) => " with local changes",
Some(Json::Bool(false)) => "",
_ => ", local changes unknown",
};
format!("{}{dirty}", text(doc, "source.revision"))
}
/// Compares two exported documents. Returns the report lines, or why the runs
/// cannot be compared.
fn compare_documents(baseline: &Json, candidate: &Json) -> Result<Vec<String>, String> {
for doc in [baseline, candidate] {
if field(doc, "format_version")? != &Json::Number("1".to_owned()) {
return Err("only format version 1 is supported".to_owned());
}
}
for path in KNOWN_FIELDS {
for (name, doc) in [("baseline", baseline), ("candidate", candidate)] {
if field(doc, path)? == &Json::Null {
return Err(format!(
"`{path}` is unknown in the {name}, so the hosts cannot be shown to match"
));
}
}
}
for path in MATCHING_FIELDS {
if field(baseline, path)? != field(candidate, path)? {
return Err(format!(
"`{path}` differs: baseline {}, candidate {}",
text(baseline, path),
text(candidate, path)
));
}
}
let mut lines = vec![
format!("Baseline: {}", source(baseline)),
format!("Candidate: {}", source(candidate)),
format!(
"Host: {}, {} {}; debug assertions {}; build label {}",
text(baseline, "host.cpu"),
text(baseline, "host.os"),
text(baseline, "host.arch"),
text(baseline, "build.debug_assertions"),
text(baseline, "build.label"),
),
];
if field(baseline, "host.os_version")? != field(candidate, "host.os_version")? {
lines.push(format!(
"Note: OS version differs: baseline {}, candidate {}",
text(baseline, "host.os_version"),
text(candidate, "host.os_version")
));
}
for (key, label) in SERIES {
let path = |stat: &str| format!("timings.{key}.{stat}");
let before = integer(baseline, &path("median_ns"))?;
let after = integer(candidate, &path("median_ns"))?;
let spread = integer(baseline, &path("iqr_ns"))?.max(integer(candidate, &path("iqr_ns"))?);
let verdict = if before.abs_diff(after) > spread {
"larger than"
} else {
"within"
};
lines.push(format!(
"{label}: median {:?} -> {:?} ({}), {verdict} the larger IQR {:?}",
duration(before),
duration(after),
change(before, after),
duration(spread)
));
}
let mut counters_changed = false;
for counter in COUNTERS {
let path = format!("cold_dbt_metrics.{counter}");
let (before, after) = (integer(baseline, &path)?, integer(candidate, &path)?);
if before != after {
counters_changed = true;
lines.push(format!(
"Cold DBT {counter}: {before} -> {after} ({})",
change(before, after)
));
}
}
if !counters_changed {
lines.push("Cold DBT counters are identical".to_owned());
}
Ok(lines)
}
fn compare_files(spec: &str) -> Result<Vec<String>, String> {
let (baseline, candidate) = spec
.split_once(',')
.ok_or("expected <baseline.json>,<candidate.json>")?;
let read = |path: &str| {
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
parse_json(&text).map_err(|e| format!("{path}: {e}"))
};
compare_documents(&read(baseline)?, &read(candidate)?)
}
fn main() {
if let Ok(spec) = std::env::var("XENORA_DBT_BENCH_COMPARE") {
match compare_files(&spec) {
Ok(lines) => lines.iter().for_each(|line| println!("{line}")),
Err(reason) => {
eprintln!("dbt_bench: cannot compare: {reason}");
std::process::exit(1);
}
}
return;
}
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
@@ -970,7 +494,6 @@ mod tests {
revision: Some("0123abcd".to_owned()),
dirty: Some(false),
debug_assertions: false,
build_label: Some("fat-lto".to_owned()),
guest_code_bytes: 40_011,
warmup: 10,
}
@@ -1005,7 +528,7 @@ mod tests {
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
r#""build":{{"debug_assertions":false,"label":"fat-lto"}},"#,
r#""build":{{"debug_assertions":false}},"#,
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
@@ -1057,302 +580,4 @@ mod tests {
assert_eq!(s.iqr, Duration::from_micros(30));
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
}
// `cargo bench` builds this target with `--cfg test` but without `--test`,
// so this module is compiled with its #[test] functions removed and shared
// helpers look unused there.
#[allow(dead_code)]
fn comparable_document() -> super::Json {
super::parse_json(concat!(
r#"{"format_version":1,"benchmark":"dbt_bench","unix_time":1,"#,
r#""host":{"cpu":"Apple M5","os":"macos","os_version":"27.2.1","arch":"aarch64"},"#,
r#""source":{"revision":"aaaa","dirty":false},"#,
r#""build":{"debug_assertions":false,"label":null},"#,
r#""workload":{"name":"add_rax_chain","guest_instructions":10002,"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10},"#,
r#""timings":{"#,
r#""interpreter":{"samples":101,"median_ns":900000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":20000,"median_mips":11.1},"#,
r#""cold_dbt":{"samples":101,"median_ns":1100000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":40000,"median_mips":9.1},"#,
r#""warm_dbt":{"samples":101,"median_ns":22000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":500,"median_mips":454.6}},"#,
r#""cold_dbt_metrics":{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":0,"service_calls":0}}"#,
))
.expect("fixture parses")
}
/// Replaces the value at a dotted path, which must exist except for its last key.
#[allow(dead_code)]
fn set(doc: &mut super::Json, path: &str, value: super::Json) {
let (parent, key) = path.rsplit_once('.').map_or(("", path), |(p, k)| (p, k));
let mut node = doc;
for step in parent.split('.').filter(|s| !s.is_empty()) {
let super::Json::Object(fields) = node else {
panic!("{step} is not in an object")
};
node = &mut fields.iter_mut().find(|(k, _)| k == step).expect(step).1;
}
let super::Json::Object(fields) = node else {
panic!("{path} has no parent object")
};
match fields.iter_mut().find(|(k, _)| k == key) {
Some(entry) => entry.1 = value,
None => fields.push((key.to_owned(), value)),
}
}
#[test]
fn reader_accepts_json_values() {
use super::{Json, parse_json};
let doc = parse_json(
r#" { "a" : [1, -0.5, 2e3, 3E-2, true, false, null, {}, []], "s": "q\"b\\s\/n\n\té😀 Zażółć" } "#,
)
.unwrap();
assert_eq!(
doc.get("a"),
Some(&Json::Array(vec![
Json::Number("1".to_owned()),
Json::Number("-0.5".to_owned()),
Json::Number("2e3".to_owned()),
Json::Number("3E-2".to_owned()),
Json::Bool(true),
Json::Bool(false),
Json::Null,
Json::Object(vec![]),
Json::Array(vec![]),
]))
);
assert_eq!(
doc.get("s"),
Some(&Json::String("q\"b\\s/n\n\té😀 Zażółć".to_owned()))
);
assert_eq!(doc.get("a.b"), None);
assert_eq!(doc.get("missing"), None);
}
#[test]
fn reader_rejects_malformed_json() {
use super::parse_json;
let deep = "[".repeat(40) + &"]".repeat(40);
for bad in [
"",
"{",
r#"{"a":1,}"#,
r#"{"a" 1}"#,
r#"{"a":1,"a":2}"#,
"[1 2]",
"01",
"1.",
"-",
"1e",
"+1",
"tru",
r#""open"#,
"\"tab\tinside\"",
r#""\x""#,
r#""\u12g4""#,
r#""\u+123""#,
r#""\ud83d""#,
r#""\ude00""#,
r#""\ud83dA""#,
"{} {}",
deep.as_str(),
] {
assert!(parse_json(bad).is_err(), "accepted {bad:?}");
}
}
#[test]
fn exported_document_reads_back() {
use super::{DbtMetrics, Duration, Json, RunInfo, Summary, json_document, parse_json};
let summary = Summary {
samples: 7,
median: Duration::from_nanos(1_234_567),
min: Duration::from_nanos(1),
max: Duration::from_nanos(9),
p95: Duration::from_nanos(8),
p99: Duration::from_nanos(9),
iqr: Duration::from_nanos(3),
mips: 8.25,
};
let info = RunInfo {
unix_time: None,
cpu: Some("CPU \"x\" \\ \u{1}".to_owned()),
os: "macos",
os_version: None,
arch: "aarch64",
revision: None,
dirty: Some(true),
debug_assertions: true,
build_label: Some("é label".to_owned()),
guest_code_bytes: 5,
warmup: 2,
};
let metrics = DbtMetrics {
native_bytes_emitted: 42,
..DbtMetrics::default()
};
let doc = parse_json(&json_document(
&info, &summary, &summary, &summary, &metrics,
))
.unwrap();
let string = |s: &str| Some(Json::String(s.to_owned()));
assert_eq!(doc.get("host.cpu").cloned(), string("CPU \"x\" \\ \u{1}"));
assert_eq!(doc.get("build.label").cloned(), string("é label"));
assert_eq!(doc.get("host.os_version"), Some(&Json::Null));
assert_eq!(doc.get("source.dirty"), Some(&Json::Bool(true)));
assert_eq!(
doc.get("timings.cold_dbt.median_ns"),
Some(&Json::Number("1234567".to_owned()))
);
assert_eq!(
doc.get("cold_dbt_metrics.native_bytes_emitted"),
Some(&Json::Number("42".to_owned()))
);
}
#[test]
fn comparison_reports_changes_against_the_spread() {
use super::{Json, compare_documents};
let baseline = comparable_document();
let mut candidate = comparable_document();
set(
&mut candidate,
"source.revision",
Json::String("bbbb".to_owned()),
);
set(&mut candidate, "source.dirty", Json::Bool(true));
// 900 µs -> 846 µs is 54 µs, beyond the larger IQR of 20 µs.
set(
&mut candidate,
"timings.interpreter.median_ns",
Json::Number("846000".to_owned()),
);
// 1.1 ms -> 1.12 ms is 20 µs, within the larger IQR of 45 µs.
set(
&mut candidate,
"timings.cold_dbt.median_ns",
Json::Number("1120000".to_owned()),
);
set(
&mut candidate,
"timings.cold_dbt.iqr_ns",
Json::Number("45000".to_owned()),
);
set(
&mut candidate,
"cold_dbt_metrics.native_bytes_emitted",
Json::Number("290184".to_owned()),
);
set(
&mut candidate,
"host.os_version",
Json::String("27.3".to_owned()),
);
let lines = compare_documents(&baseline, &candidate).unwrap();
assert_eq!(
lines,
[
"Baseline: aaaa",
"Candidate: bbbb with local changes",
"Host: Apple M5, macos aarch64; debug assertions false; build label none",
"Note: OS version differs: baseline 27.2.1, candidate 27.3",
"Interpreter: median 900µs -> 846µs (-6.00%), larger than the larger IQR 20µs",
"Cold DBT: median 1.1ms -> 1.12ms (+1.82%), within the larger IQR 45µs",
"Warm DBT: median 22µs -> 22µs (+0.00%), within the larger IQR 500ns",
"Cold DBT native_bytes_emitted: 245168 -> 290184 (+18.36%)",
]
);
let same = compare_documents(&baseline, &baseline).unwrap();
assert_eq!(same.last().unwrap(), "Cold DBT counters are identical");
}
#[test]
fn comparison_rejects_every_mismatching_field() {
use super::{Json, compare_documents};
// Written out independently of MATCHING_FIELDS, so dropping a field
// there fails this test.
for path in [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
] {
let mut candidate = comparable_document();
let other = match path {
"build.debug_assertions" => Json::Bool(true),
"build.label" => Json::String("fat-lto".to_owned()),
// A valid but different version is refused as unsupported first.
"format_version" => Json::Number("2".to_owned()),
p if p.contains("samples")
|| p.starts_with("workload.") && p != "workload.name" =>
{
Json::Number("7".to_owned())
}
_ => Json::String("other".to_owned()),
};
set(&mut candidate, path, other);
let error = compare_documents(&comparable_document(), &candidate).expect_err(path);
assert!(
error.contains(path) || path == "format_version" && error.contains("version"),
"{path}: {error}"
);
}
}
#[test]
fn comparison_needs_known_hosts_and_matching_labels() {
use super::{Json, compare_documents};
for path in ["host.cpu", "host.os", "host.arch"] {
let mut unknown = comparable_document();
set(&mut unknown, path, Json::Null);
let error = compare_documents(&unknown, &unknown).expect_err(path);
assert!(error.contains("unknown in the baseline"), "{error}");
}
// A document written before the label existed counts as having no label.
let mut old = comparable_document();
let Json::Object(fields) = &mut old else {
unreachable!()
};
let build = &mut fields.iter_mut().find(|(k, _)| k == "build").unwrap().1;
let Json::Object(build) = build else {
unreachable!()
};
build.retain(|(k, _)| k != "label");
assert!(compare_documents(&old, &comparable_document()).is_ok());
let mut labelled = comparable_document();
set(
&mut labelled,
"build.label",
Json::String("fat-lto".to_owned()),
);
assert!(compare_documents(&old, &labelled).is_err());
assert!(compare_documents(&labelled, &labelled).is_ok());
let mut missing = comparable_document();
let Json::Object(fields) = &mut missing else {
unreachable!()
};
fields.retain(|(k, _)| k != "workload");
let error = compare_documents(&comparable_document(), &missing).unwrap_err();
assert!(error.contains("missing field `workload.name`"), "{error}");
}
}
-40
View File
@@ -430,46 +430,6 @@ 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(
+1 -21
View File
@@ -335,9 +335,6 @@ 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,
@@ -590,26 +587,9 @@ 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),
@@ -643,7 +623,7 @@ impl Emitter<'_> {
match op {
// INC and DEC leave CF unchanged.
Op::Inc | Op::Dec => {}
Op::Add | Op::Adc => {
Op::Add => {
asm.cset_32(X12, Condition::Cs);
asm.strb_uoff(X12, X19, CF);
}
-42
View File
@@ -164,45 +164,3 @@ 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}");
}
}
+644
View File
@@ -0,0 +1,644 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Seeded sequences of original x86-64 instructions for issue #74.
//!
//! Expected states follow the Intel SDM (Vol. 1, §§3.4.1 and 3.4.3,
//! Vol. 2, ADD, SUB, CMP, XOR, MOV, Jcc, CALL, RET, DEC, MOVDQU, PADDB,
//! PSUBW and PXOR, and Vol. 3A, §7.15, Page-Fault Exception). The oracles work from arithmetic operands, branch
//! predicates, array indices and vector lanes. They never decode the emitted
//! bytes or use Xenora's instruction or flag helpers.
//!
//! <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
//!
//! The x86 bytes run as guest code through a synthetic memory map and end at
//! Xenora's HLT sentinel. To replay a failure, use the printed test name and
//! XENORA_CPU_DIFFERENTIAL_CASE index. For example:
//!
//! ```sh
//! XENORA_CPU_DIFFERENTIAL_CASE=0 cargo test --locked -p xenora-loader \
//! --test cpu_differential seeded_register_sequences -- --exact
//! ```
//!
//! The seed and bytes are printed for reproducing the program outside this
//! harness as well.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
const CODE: u64 = 0x40_0000;
const DATA: u64 = 0x50_0000;
const DATA_LEN: usize = 192;
const STACK_TOP: u64 = DATA + DATA_LEN as u64;
const BUDGET: usize = 128;
const TEST_SEED: u64 = 0x74_da7a_c0de_ba5e;
// SplitMix64 with a fresh stream per case. Changing the corpus order does not
// affect replay of an existing index.
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut word = self.0;
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
word ^ (word >> 31)
}
fn below(&mut self, end: usize) -> usize {
(self.next() % end as u64) as usize
}
}
#[derive(Clone)]
struct State {
cpu: CpuState,
data: [u8; DATA_LEN],
af_defined: bool,
}
impl State {
fn seeded(random: &mut Random) -> Self {
let mut cpu = CpuState::new(CODE, STACK_TOP);
cpu.gpr = std::array::from_fn(|_| random.next());
cpu.set(Register::Rsp, STACK_TOP);
cpu.xmm =
std::array::from_fn(|_| (u128::from(random.next()) << 64) | u128::from(random.next()));
let flags = random.next();
cpu.flags = RFlags {
cf: flags & 1 != 0,
pf: flags & 2 != 0,
af: flags & 4 != 0,
zf: flags & 8 != 0,
sf: flags & 16 != 0,
of: flags & 32 != 0,
};
cpu.df = flags & 64 != 0;
cpu.fs_base = DATA;
cpu.gs_base = DATA + 64;
Self {
cpu,
data: std::array::from_fn(|_| random.next() as u8),
af_defined: true,
}
}
fn checkpoint(&mut self, trace: &mut Vec<Self>, offset: usize) {
self.cpu.rip = CODE + offset as u64;
trace.push(self.clone());
}
fn word(&self, offset: usize) -> u64 {
u64::from_le_bytes(self.data[offset..offset + 8].try_into().unwrap())
}
fn put_word(&mut self, offset: usize, value: u64) {
self.data[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
}
struct Case {
code: Vec<u8>,
initial: State,
// State after each attempted instruction, including the terminal instruction.
trace: Vec<State>,
native_only: bool,
exit: ExitReason,
}
impl Case {
fn memory(&self) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE,
self.code.len(),
MemoryPermissions::READ_EXECUTE,
&self.code,
)
.unwrap();
memory
.map_region_with_data(
DATA,
DATA_LEN,
MemoryPermissions::READ_WRITE,
&self.initial.data,
)
.unwrap();
memory
}
fn verify(&self, id: &str) {
let steps = self.trace.len();
assert!(steps < BUDGET);
let compare = |engine: &str,
result: ExecutionResult,
memory: &GuestMemory,
budget: usize,
offset: usize| {
let steps = (steps - offset).min(budget);
let expected = &self.trace[offset + steps - 1];
let label = || {
let start_rip = if offset == 0 {
self.initial.cpu.rip
} else {
self.trace[offset - 1].cpu.rip
};
format!(
"{id} {engine} from {start_rip:#x}, after {} guest steps, bytes {:02x?}",
offset + steps,
self.code
)
};
let finished = offset + steps == self.trace.len();
let exit = if finished {
self.exit
} else {
ExitReason::StepLimitExceeded
};
let retired = steps - usize::from(finished && self.exit != ExitReason::Halt);
assert_eq!(result.exit_reason, exit, "{}", label());
assert_eq!(result.instructions_executed, retired, "{}", label());
let mut actual = result.final_state;
if !expected.af_defined {
actual.flags.af = expected.cpu.flags.af;
}
assert_eq!(actual, expected.cpu, "{}", label());
let mut data = [0; DATA_LEN];
memory.read_bytes(DATA, &mut data).unwrap();
if let Some(index) = data.iter().zip(expected.data).position(|(&a, b)| a != b) {
panic!(
"{}: guest byte at {:#x}: got {:#04x}, expected {:#04x}",
label(),
DATA + index as u64,
data[index],
expected.data[index]
);
}
};
let mut stepped = DbtEngine::new(128 * 1024).unwrap();
let mut interpreted_memory = self.memory();
let mut translated_memory = self.memory();
let mut interpreted_cpu = self.initial.cpu.clone();
let mut translated_cpu = self.initial.cpu.clone();
// Check the first divergent retired instruction before testing full
// blocks. Each engine continues from its own state at every step.
for offset in 0..steps {
let result = Interpreter::new(interpreted_cpu, &mut interpreted_memory, 1).run();
interpreted_cpu = result.final_state.clone();
compare(
"interpreter (1 step)",
result,
&interpreted_memory,
1,
offset,
);
let result = stepped.run(&mut translated_cpu, &mut translated_memory, 1);
compare("DBT (1 step)", result, &translated_memory, 1, offset);
}
// Exercise native block lowering and then reuse those blocks with a
// fresh copy of the guest input and memory at the same addresses.
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
let mut memory = self.memory();
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
compare("interpreter", result, &memory, BUDGET, 0);
let mut run_full = |engine| {
let mut memory = self.memory();
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
compare(engine, result, &memory, BUDGET, 0);
dbt.metrics
};
let cold = run_full("DBT (cold)");
let cached = run_full("DBT (cached)");
assert!(cold.blocks_compiled > 0, "{id}");
assert_eq!(cold.blocks_compiled, cached.blocks_compiled, "{id}");
assert!(cached.cache_hits > cold.cache_hits, "{id}");
assert!(cached.dbt_dispatches > cold.dbt_dispatches, "{id}");
// These budgets cut the longer programs around a 16-instruction
// native block boundary, including a resume from the truncated block.
for budget in [15, 16, 17].into_iter().filter(|&budget| budget < steps) {
let mut memory = self.memory();
let mut cpu = self.initial.cpu.clone();
let result = dbt.run(&mut cpu, &mut memory, budget);
compare("DBT (limited)", result, &memory, budget, 0);
let result = dbt.run(&mut cpu, &mut memory, BUDGET);
compare("DBT (resumed)", result, &memory, BUDGET, budget);
}
if self.native_only {
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{id}");
assert_eq!(stepped.metrics.interpreter_fallbacks, 0, "{id}");
}
}
}
#[derive(Clone, Copy, Debug)]
enum Alu {
Add,
Sub,
Compare,
Xor,
Move,
}
impl Alu {
const OPS: [Self; 5] = [Self::Add, Self::Sub, Self::Compare, Self::Xor, Self::Move];
// SDM Vol. 2, §2.1 and the r/m,reg forms for each instruction. A bare
// REX prefix selects SPL/BPL/SIL/DIL instead of the high byte registers.
fn encode(self, code: &mut Vec<u8>, bits: u32, dst: usize, src: usize) {
if bits == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(bits == 64) << 3) | ((src as u8 >> 3) << 2) | (dst as u8 >> 3);
if rex != 0x40 || (bits == 8 && (src >= 4 || dst >= 4)) {
code.push(rex);
}
let byte_opcode = match self {
Self::Add => 0x00,
Self::Sub => 0x28,
Self::Compare => 0x38,
Self::Xor => 0x30,
Self::Move => 0x88,
};
code.extend([
byte_opcode | u8::from(bits != 8),
0xc0 | ((src as u8 & 7) << 3) | (dst as u8 & 7),
]);
}
fn expect(self, state: &mut State, bits: u32, dst: usize, src: usize) {
let mask = u64::MAX >> (64 - bits);
let left = state.cpu.gpr[dst] & mask;
let right = state.cpu.gpr[src] & mask;
let result = match self {
Self::Move => right,
Self::Xor => {
let result = left ^ right;
state.cpu.flags = result_flags(result, bits);
state.af_defined = false;
result
}
Self::Add | Self::Compare | Self::Sub => {
let (result, flags) = arithmetic(left, right, bits, matches!(self, Self::Add));
state.cpu.flags = flags;
state.af_defined = true;
result
}
};
if !matches!(self, Self::Compare) {
state.cpu.gpr[dst] = if bits >= 32 {
result
} else {
(state.cpu.gpr[dst] & !mask) | result
};
}
}
}
fn result_flags(result: u64, bits: u32) -> RFlags {
RFlags {
zf: result == 0,
sf: result >> (bits - 1) == 1,
pf: (result as u8).count_ones().is_multiple_of(2),
..RFlags::default()
}
}
// Carry, auxiliary carry and signed overflow are derived by separate
// widened calculations. The exact signed result determines overflow.
fn arithmetic(left: u64, right: u64, bits: u32, add: bool) -> (u64, RFlags) {
let modulus = 1i128 << bits;
let signed = |word: u64| {
let word = i128::from(word);
if word >= modulus / 2 {
word - modulus
} else {
word
}
};
let operation = |a: i128, b: i128| if add { a + b } else { a - b };
let wide = operation(i128::from(left), i128::from(right));
let result = wide.rem_euclid(modulus) as u64;
let mut flags = result_flags(result, bits);
flags.cf = !(0..modulus).contains(&wide);
let nibble = operation(i128::from(left & 15), i128::from(right & 15));
flags.af = !(0..16).contains(&nibble);
let signed_result = operation(signed(left), signed(right));
flags.of = !(-modulus / 2..modulus / 2).contains(&signed_result);
(result, flags)
}
fn seeded_cases(
test: &str,
family: u64,
count: usize,
make_case: impl Fn(usize, &mut Random) -> Case,
) {
let selected = std::env::var("XENORA_CPU_DIFFERENTIAL_CASE")
.ok()
.map(|text| {
let index = text
.parse::<usize>()
.expect("XENORA_CPU_DIFFERENTIAL_CASE must be a decimal case index");
assert!(index < count, "{test} has case indices 0..{count}");
index
});
for index in selected.map_or(0..count, |index| index..index + 1) {
let seed = TEST_SEED ^ (family << 48) ^ index as u64;
let case = make_case(index, &mut Random(seed));
case.verify(&format!(
"{test}: XENORA_CPU_DIFFERENTIAL_CASE={index} (seed {seed:#018x})"
));
}
}
#[test]
fn seeded_register_sequences() {
const WIDTHS: [u32; 4] = [8, 16, 32, 64];
seeded_cases("seeded_register_sequences", 1, 240, |index, random| {
let mixed_widths = index >= 160;
let bits = WIDTHS[index % 4];
let edges = [
0,
1,
15,
16,
(1u64 << (bits - 1)) - 1,
1 << (bits - 1),
u64::MAX,
];
let mut initial = State::seeded(random);
// Keep random high bits when the operand is narrower than the GPR.
let mask = u64::MAX >> (64 - bits);
for reg in [0, 1, 2, 3, 8, 9, 10, 11] {
let edge = edges[random.below(edges.len())];
initial.cpu.gpr[reg] = (initial.cpu.gpr[reg] & !mask) | (edge & mask);
}
let mut state = initial.clone();
let mut code = Vec::new();
let mut trace = Vec::new();
for step in 0..24 {
let bits = if mixed_widths {
WIDTHS[(index + step) % WIDTHS.len()]
} else {
bits
};
let op = Alu::OPS[random.below(Alu::OPS.len())];
let dst = random.below(16);
let src = random.below(16);
op.encode(&mut code, bits, dst, src);
op.expect(&mut state, bits, dst, src);
state.checkpoint(&mut trace, code.len());
}
code.push(0xf4);
state.checkpoint(&mut trace, code.len());
Case {
code,
initial,
trace,
native_only: !mixed_widths && bits >= 32,
exit: ExitReason::Halt,
}
});
}
fn branch_predicate(condition: usize, flags: RFlags) -> bool {
let base = [
flags.of,
flags.cf,
flags.zf,
flags.cf || flags.zf,
flags.sf,
flags.pf,
flags.sf != flags.of,
flags.zf || flags.sf != flags.of,
][condition / 2];
base ^ !condition.is_multiple_of(2)
}
#[test]
fn seeded_compare_branch_pairs() {
seeded_cases("seeded_compare_branch_pairs", 2, 128, |index, random| {
let condition = index % 16;
let taken = index / 16 % 2 != 0;
let bits = [32, 64][index / 32 % 2];
let near = index >= 64;
let sign = 1u64 << (bits - 1);
let boundary = [0, 1, 2, sign - 1, sign, sign | 1, (sign - 1) | sign];
let pairs = boundary
.into_iter()
.flat_map(|left| boundary.map(|right| (left, right)));
let eligible: Vec<_> = pairs
.filter(|&(left, right)| {
branch_predicate(condition, arithmetic(left, right, bits, false).1) == taken
})
.collect();
let (left, right) = eligible[random.below(eligible.len())];
let mut initial = State::seeded(random);
let mask = u64::MAX >> (64 - bits);
initial.cpu.gpr[0] = (initial.cpu.gpr[0] & !mask) | left;
initial.cpu.gpr[8] = (initial.cpu.gpr[8] & !mask) | right;
let mut state = initial.clone();
let mut code = Vec::new();
let mut trace = Vec::new();
Alu::Compare.encode(&mut code, bits, 0, 8);
Alu::Compare.expect(&mut state, bits, 0, 8);
let branch = code.len();
state.checkpoint(&mut trace, branch);
if near {
code.extend([0x0f, 0x80 + condition as u8, 3, 0, 0, 0]);
} else {
code.extend([0x70 + condition as u8, 3]);
}
// The two arms set distinct low bytes of RDX, then stop.
let fallthrough = code.len();
code.extend([0xb2, 0x31, 0xf4, 0xb2, 0x73, 0xf4]);
let arm = fallthrough + if taken { 3 } else { 0 };
state.checkpoint(&mut trace, arm);
state.cpu.gpr[2] = (state.cpu.gpr[2] & !255) | if taken { 0x73 } else { 0x31 };
state.checkpoint(&mut trace, arm + 2);
state.checkpoint(&mut trace, arm + 3);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_memory_loop_with_calls() {
seeded_cases("seeded_memory_loop_with_calls", 3, 64, |_, random| {
let count = random.below(8) + 1;
let input = random.below(8);
let output = 80 + random.below(8);
let mut initial = State::seeded(random);
initial.cpu.set(Register::Rcx, count as u64);
initial.cpu.set(Register::Rsi, DATA + input as u64);
initial.cpu.set(Register::Rdi, DATA + output as u64);
let code = vec![
0xe8, 10, 0, 0, 0, // 0: call sum
0x48, 0x89, 0x44, 0xcf, 0xf8, // 5: mov [rdi + rcx*8 - 8], rax
0xff, 0xc9, // 10: dec ecx
0x75, 0xf2, // 12: jnz start
0xf4, // 14: hlt
0x48, 0x03, 0x44, 0xce, 0xf8, // 15: sum: add rax, [rsi + rcx*8 - 8]
0xc3, // 20: ret
];
let mut state = initial.clone();
let mut trace = Vec::new();
let mut sum = state.cpu.get(Register::Rax);
for remaining in (1..=count).rev() {
state.put_word(DATA_LEN - 8, CODE + 5);
state.cpu.set(Register::Rsp, STACK_TOP - 8);
state.checkpoint(&mut trace, 15);
let index = (remaining - 1) * 8;
let (next, flags) = arithmetic(sum, initial.word(input + index), 64, true);
sum = next;
state.cpu.set(Register::Rax, sum);
state.cpu.flags = flags;
state.checkpoint(&mut trace, 20);
state.cpu.set(Register::Rsp, STACK_TOP);
state.checkpoint(&mut trace, 5);
state.put_word(output + index, sum);
state.checkpoint(&mut trace, 10);
let (counter, mut flags) = arithmetic(remaining as u64, 1, 32, false);
flags.cf = state.cpu.flags.cf; // DEC leaves carry intact.
state.cpu.set(Register::Rcx, counter);
state.cpu.flags = flags;
state.checkpoint(&mut trace, 12);
state.checkpoint(&mut trace, if counter == 0 { 14 } else { 0 });
}
state.checkpoint(&mut trace, 15);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_vector_load_arithmetic_store() {
seeded_cases("seeded_vector_load_arithmetic_store", 4, 64, |_, random| {
let mut initial = State::seeded(random);
let input = random.below(16);
let output = 64 + random.below(16);
initial.cpu.set(Register::Rsi, DATA + input as u64);
initial.cpu.set(Register::Rdi, DATA + output as u64);
let code = vec![
0xf3, 0x44, 0x0f, 0x6f, 0x0e, // 0: movdqu xmm9, [rsi]
0x66, 0x44, 0x0f, 0xfc, 0xca, // 5: paddb xmm9, xmm2
0x66, 0x45, 0x0f, 0xf9, 0xcf, // 10: psubw xmm9, xmm15
0x66, 0x44, 0x0f, 0xef, 0xc8, // 15: pxor xmm9, xmm0
0xf3, 0x44, 0x0f, 0x7f, 0x0f, // 20: movdqu [rdi], xmm9
0xf4,
];
let mut state = initial.clone();
let mut trace = Vec::new();
let mut lanes: [u8; 16] = initial.data[input..input + 16].try_into().unwrap();
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 5);
for (lane, addend) in lanes.iter_mut().zip(initial.cpu.xmm[2].to_le_bytes()) {
*lane = lane.wrapping_add(addend);
}
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 10);
let subtrahend = initial.cpu.xmm[15].to_le_bytes();
let (words, _) = lanes.as_chunks_mut::<2>();
let (subtrahends, _) = subtrahend.as_chunks::<2>();
for (word, &rhs) in words.iter_mut().zip(subtrahends) {
let left = u16::from_le_bytes(*word);
let right = u16::from_le_bytes(rhs);
*word = left.wrapping_sub(right).to_le_bytes();
}
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 15);
state.cpu.xmm[9] ^= initial.cpu.xmm[0];
state.checkpoint(&mut trace, 20);
state.data[output..output + 16].copy_from_slice(&state.cpu.xmm[9].to_le_bytes());
state.checkpoint(&mut trace, 25);
state.checkpoint(&mut trace, 26);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_precise_memory_faults() {
seeded_cases("seeded_precise_memory_faults", 5, 28, |index, random| {
// Both branch outcomes and both operand directions at each of the
// seven possible byte splits of an eight-byte operand.
let store = index.is_multiple_of(2);
let taken = (index / 2).is_multiple_of(2);
let split = index / 4 + 1;
let mut initial = State::seeded(random);
let output = random.below(32);
let value = initial.cpu.get(Register::Rax);
let rhs = if taken { value } else { value ^ (1 << 63) };
initial.cpu.set(Register::R8, rhs);
initial.cpu.set(Register::Rdi, DATA + output as u64);
initial.cpu.set(Register::Rsi, STACK_TOP - split as u64);
let code = vec![
0x48,
0x89,
0x07, // 0: mov [rdi], rax
0x4c,
0x39,
0xc0, // 3: cmp rax, r8
0x74,
0x03, // 6: je faulting_move
0x4d,
0x89,
0xd1, // 8: mov r9, r10
0x48,
if store { 0x89 } else { 0x8b },
0x06, // 11: mov [rsi], rax or mov rax, [rsi]
0xf4,
];
let mut state = initial.clone();
let mut trace = Vec::new();
state.put_word(output, value);
state.checkpoint(&mut trace, 3);
state.cpu.flags = arithmetic(value, rhs, 64, false).1;
state.checkpoint(&mut trace, 6);
if taken {
state.checkpoint(&mut trace, 11);
} else {
state.checkpoint(&mut trace, 8);
state.cpu.set(Register::R9, initial.cpu.get(Register::R10));
state.checkpoint(&mut trace, 11);
}
// The faulting instruction leaves RIP, registers and all mapped bytes
// intact. The preceding store and optional register move stay retired.
state.checkpoint(&mut trace, 11);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::MemoryFault(MemoryError::UnmappedAddress(STACK_TOP)),
}
});
}
-384
View File
@@ -1,384 +0,0 @@
// 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}");
}
}
}
+27 -76
View File
@@ -1,4 +1,4 @@
use std::collections::{BTreeMap, VecDeque};
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
@@ -37,16 +37,6 @@ 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>
@@ -158,9 +148,7 @@ 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.
@@ -183,8 +171,6 @@ 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.
@@ -261,7 +247,7 @@ struct SubmissionEntry {
/// Metal reports Completed or Error.
struct InFlightResources {
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: ComputePipeline,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
@@ -362,7 +348,6 @@ impl NativeCompute {
device,
queue,
submissions: Mutex::default(),
compute_pipelines: Mutex::default(),
})
})
}
@@ -916,7 +901,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
self.run_profiled_words(source, entry, input, Some(width))
}
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
/// Compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
@@ -926,7 +911,11 @@ 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 (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
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)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
@@ -974,8 +963,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
host_start: Instant,
) -> Result<Submission<'_>, MetalError> {
self.submissions().check_capacity()?;
let (pipeline, library_seconds, pipeline_seconds) =
self.prepare_compute_pipeline(source, entry)?;
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 limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
@@ -1112,67 +1108,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn prepare_compute_pipeline(
fn compute_pipeline(
&self,
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)
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
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(
@@ -1285,6 +1232,10 @@ 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,131 +356,6 @@ 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();
@@ -538,52 +413,3 @@ 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,43 +13,6 @@ 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