Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 112 additions & 5 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,14 +1117,54 @@ pub(super) fn toolchain_identity() -> &'static str {
})
}

/// FNV-1a 64 of the inputs that determine the DXIL.
fn fnv_add(h: &mut u64, bytes: &[u8]) {
for &b in bytes {
*h ^= b as u64;
*h = h.wrapping_mul(0x100_0000_01b3);
}
}

/// The optimisation level `compile_one` picks from the source length (-O3 / -O1 / -O0).
fn opt_bracket(src_len: usize) -> u8 {
if src_len > UNOPTIMISED_ABOVE {
2
} else if src_len > 1024 * 1024 {
1
} else {
0
}
}

/// FNV-1a 64 of the inputs that determine the DXIL. Whole-line `//` comments are left out: the
/// translator annotates every instruction, and the annotations of the per-program `v_nop`
/// literals at the start of each console program differ between programs with the same code
/// (38 % of a retail game's compiles were such copies). A comment line that ends in `\`, or follows
/// a line that does, is kept: line splicing would make it change the code.
fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] {
for b in part.bytes().chain([0u8]) {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
for part in ["xcl-dxc-key-v2", env!("CARGO_PKG_VERSION"), toolchain, profile, entry] {
fnv_add(&mut h, part.as_bytes());
fnv_add(&mut h, &[0]);
}
let mut spliced = false;
for line in src.split('\n') {
let continues = line.trim_end_matches('\r').ends_with('\\');
if spliced || continues || !line.trim_start().starts_with("//") {
fnv_add(&mut h, line.as_bytes());
fnv_add(&mut h, b"\n");
}
spliced = continues;
}
fnv_add(&mut h, &[0, opt_bracket(src.len())]);
h
}

/// The key before comments were left out: entries an older build wrote are still found by it.
fn legacy_cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] {
fnv_add(&mut h, part.as_bytes());
fnv_add(&mut h, &[0]);
}
h
}
Expand Down Expand Up @@ -1405,6 +1445,25 @@ fn store_error_file(file: &Path, key: u64, src_len: usize, reason: &str) {
}
}

/// An entry an older build wrote under the key that still hashed comments: linked to the current
/// name (copied where a link is not possible), so later runs and the startup proof find it there.
fn adopt_legacy_entry(dir: &Path, file: &Path, src: &str, entry: &str, profile: &str) -> Option<Vec<u8>> {
let legacy = legacy_cache_key_for_toolchain(src, entry, profile, toolchain_identity());
let legacy = dir.join(format!("{legacy:016x}.dxil"));
if legacy == file {
return None;
}
let b = cached_file(&legacy)?;
let _stall = crate::stall::span(crate::stall::StallKind::CacheIo);
if std::fs::hard_link(&legacy, file).is_err() && !file.is_file() {
let tmp = file.with_extension(format!("tmp{}-legacy", std::process::id()));
if std::fs::write(&tmp, &b).is_err() || std::fs::rename(&tmp, file).is_err() {
let _ = std::fs::remove_file(&tmp);
}
}
Some(b)
}

fn compile_cached_in_observed<F>(
dir: &Path,
src: &str,
Expand All @@ -1424,6 +1483,10 @@ where
counters.hits.fetch_add(1, Ordering::Relaxed);
return Ok((b, true));
}
if let Some(b) = adopt_legacy_entry(&dir, &file, src, entry, profile) {
counters.hits.fetch_add(1, Ordering::Relaxed);
return Ok((b, true));
}
if let Some(err) = cached_error_file(&err_file, key, src.len()) {
return Err(err);
}
Expand Down Expand Up @@ -1688,6 +1751,50 @@ mod cache_tests {
assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b"));
}

#[test]
fn cache_key_leaves_out_whole_line_comments_only() {
let key = |src: &str| cache_key_for_toolchain(src, "main", "ps_6_6", "toolchain");
// the per-program v_nop literal annotations of two programs with the same code
let a = key("void main() {\n // 0000: v_nop ; lit 0x1da031c7\n o0 = v0;\n}\n");
assert_eq!(a, key("void main() {\n // 0000: v_nop ; lit 0x0261bb7a\n o0 = v0;\n}\n"));
assert_ne!(a, key("void main() {\n // 0000: v_nop ; lit 0x1da031c7\n o0 = v1;\n}\n"));
// a comment after code on the same line still counts
assert_ne!(key("o0 = v0; // a\n"), key("o0 = v0; // b\n"));
// line splicing: a comment line ending in `\` swallows the next line, a spliced line is code
assert_ne!(key("// a \\\no0 = v0;\n"), key("// a\no0 = v0;\n"));
assert_ne!(key("#define X 1 \\\n// a\nY\n"), key("#define X 1 \\\n// b\nY\n"));
}

#[test]
fn cache_key_tracks_the_optimisation_level_the_length_picks() {
let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "toolchain");
let code = "o0 = v0;\n";
let padded = format!("// {}\n{code}", "x".repeat(1024 * 1024));
assert_eq!(opt_bracket(padded.len()), 1);
assert_ne!(key(code), key(&padded), "-O1 and -O3 DXIL must not share an entry");
assert_eq!(key(&format!("// a\n{code}")), key(code));
}

#[test]
fn entries_of_the_comment_hashing_key_are_adopted() {
let dir = std::env::temp_dir().join(format!("xcl-dxil-legacy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let src = "// 0000: v_nop ; lit 0x1da031c7\nlegacy source";
let legacy = legacy_cache_key_for_toolchain(src, "main", "cs_6_6", toolchain_identity());
let valid = synthetic_dxil(13);
std::fs::write(dir.join(format!("{legacy:016x}.dxil")), &valid).unwrap();

let (b, hit) = compile_cached_in_with(&dir, src, "main", "cs_6_6", || panic!("an older build's entry was compiled again")).unwrap();
assert!(hit);
assert_eq!(b, valid);
let current = dir.join(format!("{:016x}.dxil", cache_key(src, "main", "cs_6_6")));
assert_eq!(std::fs::read(&current).unwrap(), valid, "the entry is found under the current key from now on");
assert!(dir.join(format!("{legacy:016x}.dxil")).is_file(), "older builds keep finding it");

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn validates_dxil_cache_structure_and_rebuilds_corruption() {
let valid = synthetic_dxil(7);
Expand Down
Loading