Merge upstream main (8e79c80) into shader/per-lane-phi

main now has CI (clippy with -D warnings, then the workspace's tests) and
three new tests that call `resource::track`, which this branch gives a
fourth argument. No textual conflict, but the test target did not build:
those three calls (emit/lower.rs, twice in emit/mod.rs) now structure the
program first and pass it, as this branch's other callers do. Both of
CI's clippy commands are clean on the result.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
r4.andClaude Fable 5.2 committed 2026-11-24 11:10:23 +02:00
commit e09dbb6dae
28 files changed
+1308 -143

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
name: CI
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
jobs:
check:
runs-on: windows-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v5
# The version and components pinned in rust-toolchain.toml.
- run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
- name: Clippy
run: cargo clippy --workspace --all-targets --locked -- -D warnings
- name: Clippy, diagnostics build
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
# Includes xtask's repository_passes_policy, the asset-policy check.
- name: Tests
run: cargo test --workspace --locked
+2 -1
View File
@@ -180,6 +180,7 @@ fn show_config() -> Result<()> {
);
println!("game_dir : {}", status(&cfg.game_dir));
println!("cache_dir : {}", cfg.cache_dir.display());
println!("data_dir : {}", cfg.data_dir.display());
for t in &cfg.test_titles {
println!("test_title : {}", status(&Some(t.clone())));
}
@@ -187,7 +188,7 @@ fn show_config() -> Result<()> {
.game_dir
.iter()
.chain(&cfg.test_titles)
.chain([&cfg.cache_dir])
.chain([&cfg.cache_dir, &cfg.data_dir])
{
if let Err(e) = victory_core::ensure_outside_repo(p) {
println!("POLICY VIOLATION: {e}");
+10
View File
@@ -204,4 +204,14 @@ mod tests {
};
assert!(cfg.cache_subdir("x").is_err());
}
#[test]
fn data_inside_repo_is_refused() {
let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data");
let cfg = Config {
data_dir: inside,
..Default::default()
};
assert!(cfg.data_subdir("x").is_err());
}
}
+223 -28
View File
@@ -80,7 +80,12 @@ struct Bc7Ix {
/// The format's constant tables.
pub struct Tables {
freq: [[u32; BUCKETS]; MODELS],
start: [[u32; BUCKETS]; MODELS],
/// Each bucket's first slot; 65536 past the model's last, and one more
/// 65536 at the end so a bucket always has a next start.
start: [[u32; BUCKETS + 1]; MODELS],
/// Per model, the bucket of the first slot of each 256-slot window: the
/// search for a slot's bucket starts there and seldom moves on.
bucket: Box<[[u8; 256]; MODELS]>,
/// ceil(2^32 / freq): exact division for the offsets inside a bucket.
recip: [[u64; BUCKETS]; MODELS],
rank1: [u8; 256],
@@ -132,7 +137,8 @@ impl Tables {
}
let mut r = Reader(bytes);
let mut freq = [[0u32; BUCKETS]; MODELS];
let mut start = [[0u32; BUCKETS]; MODELS];
let mut start = [[0u32; BUCKETS + 1]; MODELS];
let mut bucket = Box::new([[0u8; 256]; MODELS]);
let mut recip = [[0u64; BUCKETS]; MODELS];
for m in 0..MODELS {
for f in &mut freq[m] {
@@ -153,6 +159,10 @@ impl Tables {
return Err(Error("a model does not tile 65536"));
}
start[m][used..].fill(1 << 16);
for (window, b) in bucket[m].iter_mut().enumerate() {
let first = (window as u32) << 8;
*b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8;
}
}
let rank1 = r.bytes();
let rank3a = r.bytes();
@@ -221,6 +231,7 @@ impl Tables {
Ok(Tables {
freq,
start,
bucket,
recip,
rank1,
rank3a,
@@ -342,33 +353,20 @@ impl Lane {
let start = &t.start[usize::from(self.model)];
let slot = x & 0xffff;
// The bucket: starts are ascending, and 65536 past the model's last.
let b = start[1..].iter().filter(|&&s| s <= slot).count();
// Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency
// are below 2^16, where the reciprocal divides exactly.
let sym = match b {
0 => 0,
1 => 1,
_ => {
let rec = t.recip[usize::from(self.model)][b];
(1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8
}
};
// Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1.
let (f, c) = if sym == 0 {
(freq[0] - 1, 1)
let b = bucket_of(t, self.model, slot);
// Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0
// is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency
// f[b] from start[b] on; offset and frequency are below 2^16, where
// the reciprocal divides exactly.
let (sym, f, rem) = if b == 0 {
(0, freq[0] - 1, slot.wrapping_sub(1))
} else {
let k = (8 - sym.leading_zeros()) as usize;
let f = freq[k];
(
f,
(u32::from(sym) - (1 << (k - 1)))
.wrapping_mul(f)
.wrapping_add(start[k])
& 0xffff,
)
let offset = slot - start[b];
let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32;
((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b])
};
self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot);
self.out = Some(sym);
self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem);
self.out = Some(sym as u8);
} else if self.left != 0 {
// At exactly 2^24 the lane neither reads nor decodes again; only a
// lane that has delivered its symbols may end up there.
@@ -385,6 +383,19 @@ impl Lane {
}
}
/// The bucket holding `slot` (below 65536): the last whose start is at or
/// below it. The window table gives the bucket of the window's first slot;
/// later buckets that start inside the window are stepped over.
#[inline]
fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize {
let start = &t.start[usize::from(model)];
let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]);
while start[b + 1] <= slot {
b += 1;
}
b
}
/// Decodes `per` symbols per block on every lane into `records` (one record
/// of `widths.len() * per` symbols per block), taking input from `fetch`
/// (given the lane that takes the byte) in the order of the schedule: each
@@ -409,6 +420,8 @@ fn lanes(
let stride = widths.len() * per;
let full = (1u32 << widths.len()) - 1;
let (mut pos, mut done, mut idle) = (0, 0u32, 0);
// Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on.
let mut at = 0;
while pos < blocks * per {
let (mut taken, mut moved) = (0, false);
for (j, lane) in lanes.iter_mut().enumerate() {
@@ -429,13 +442,18 @@ fn lanes(
if !lane.stalled
&& let Some(sym) = lane.out.take()
{
records[pos / per * stride + j * per + pos % per] = sym;
records[at + j * per] = sym;
done |= bit;
moved = true;
}
}
if done == full {
pos += 1;
at += if pos.is_multiple_of(per) {
stride - per + 1
} else {
1
};
done = 0;
moved = true;
}
@@ -1369,6 +1387,183 @@ mod tests {
}
}
/// The window table finds the bucket a scan of the starts finds, for
/// every slot of every model, in the shipped tables and in ours (whose
/// buckets are wide) and in tables whose buckets are one slot wide.
#[test]
fn bucket_lookup_matches_a_scan_of_the_starts() {
let mut narrow = tables();
for m in 0..MODELS {
// Buckets 1.. of one slot each where they fit; bucket 0 takes the rest.
let used = m / 16 + 2;
let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::<u32>();
for b in 0..used {
let f = if b == 0 { rest } else { 1 };
narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes());
}
}
for t in [
Tables::builtin().unwrap(),
Tables::parse(&tables()).unwrap(),
Tables::parse(&narrow).unwrap(),
] {
for model in 0..MODELS as u8 {
let start = &t.start[usize::from(model)];
for slot in 0..1u32 << 16 {
let scan = start[1..].iter().filter(|&&s| s <= slot).count();
assert_eq!(
bucket_of(&t, model, slot),
scan,
"model {model} slot {slot}"
);
}
}
}
}
/// One rANS decode as first written: scan for the bucket, divide for the
/// symbol, rebuild its frequency and start from the symbol.
fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) {
let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]);
let slot = x & 0xffff;
let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count();
let sym = match b {
0 => 0,
1 => 1,
_ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b],
} as u8;
let (f, c) = if sym == 0 {
(freq[0] - 1, 1)
} else {
let k = (8 - sym.leading_zeros()) as usize;
let f = freq[k];
(
f,
((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff,
)
};
(
sym,
(x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot),
)
}
/// A payload step decodes the symbol and state the first version did, for
/// every model and slot of the shipped tables and ours, at assorted states.
#[test]
fn payload_step_matches_the_reference_decode() {
for t in [
Tables::builtin().unwrap(),
Tables::parse(&tables()).unwrap(),
] {
for model in 0..MODELS as u8 {
for high in [0x100u32, 0x1234, 0xffff] {
for slot in 0..1u32 << 16 {
let x = high << 16 | slot;
if x <= LOW {
continue;
}
let mut lane = Lane {
phase: 3,
model,
x,
left: 1,
..Default::default()
};
lane.step(&t).unwrap();
let (sym, next) = reference_decode(&t, model, x);
assert_eq!(
(lane.out, lane.x),
(Some(sym), next),
"model {model} x {x:#x}"
);
}
}
}
}
}
/// Pseudo-random records that fit each lane's alphabet; BC7 keeps control
/// code 0 (mode 6), the only one the synthetic tables define.
fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec<Vec<u8>> {
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
(0..blocks)
.map(|_| {
let mut r: Vec<u8> = (0..widths.len() * per)
.map(|k| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let alphabet = 1u32 << (widths[k / per] + 1);
(seed as u32 % alphabet) as u8
})
.collect();
if bc7 {
r[30] = 0;
r[31] = 0;
}
r
})
.collect()
}
/// The fast paths decode exactly what one lane step at a time does, on
/// every format's lane layout, with short and long fragments.
#[test]
fn every_layout_round_trips_through_the_lanes() {
let t = Tables::parse(&tables()).unwrap();
let layouts: [(&[u8], usize); 6] = [
(&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1),
(&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2),
(&BC4_LANES, 1),
(&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2),
(&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2),
(&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2),
];
for (widths, per) in layouts {
for blocks in [1, 2, 17, 300, 1000] {
let records = random_records(widths, per, blocks, false);
let src = stream(&t, widths, per, &records);
let mut got = vec![0u8; records.concat().len()];
let mut next = src.iter().copied();
lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap();
assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks");
}
}
}
/// Decode throughput on synthetic streams (no game data):
/// `cargo test --release -p victory-formats bcpack_throughput -- --ignored --nocapture`.
#[test]
#[ignore = "benchmark"]
fn bcpack_throughput() {
let t = Tables::parse(&tables()).unwrap();
let cases: [(u8, &[u8], usize, usize); 3] = [
(1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8),
(4, &BC4_LANES, 1, 8),
(7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16),
];
for (bc, widths, per, block) in cases {
// One fragment per lane holds at most 65792 bytes.
let blocks = 1 << 14;
let records = random_records(widths, per, blocks, bc == 7);
let src = stream(&t, widths, per, &records);
let mut dst = vec![0u8; blocks * block];
decode(bc, &src, &mut dst, &t).unwrap();
let runs = 40;
let started = std::time::Instant::now();
for _ in 0..runs {
decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap();
}
let secs = started.elapsed().as_secs_f64() / f64::from(runs);
println!(
"BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block",
(blocks * block) as f64 / secs / 1e6,
secs * 1e9 / blocks as f64
);
}
}
/// Compares with reference outputs made outside the repository:
/// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a
/// directory of `<name>.bc<n>` packed chunks with `<name>.out` beside them.
+1 -1
View File
@@ -13,7 +13,7 @@
//! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`,
//! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`,
//! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile
//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on
//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on
//! RDNA2). addrlib carries this notice:
//!
//! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
+19 -3
View File
@@ -336,7 +336,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
}
return Some(out);
}
87..=93 => {
// B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below).
87 | 88 | 90..=93 => {
for y in 0..h {
for x in 0..w {
let p = px(x, y, 4);
@@ -345,7 +346,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
}
return Some(out);
}
23..=25 => (4, Box::new(move |b| {
23..=25 | 89 => (4, Box::new(move |b| {
let v = u32_at(b, 0);
[(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
})),
@@ -353,7 +354,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
let v = u32_at(b, 0);
[small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
})),
9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))),
33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
1..=2 => (16, Box::new(move |b| {
[0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
@@ -522,4 +524,18 @@ mod tests {
fn crc_matches_the_png_check_value() {
assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
}
/// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2,
/// not B8G8R8A8.
#[test]
fn unorm16_and_xr_bias_targets_decode_as_their_formats() {
// Red 0x8000 (a half-float -0), green 0x4000, blue 0.
let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff];
assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255]));
// Red 0x3ff, green 0x1ff, blue 0, alpha 3.
let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes();
assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255]));
// B8G8R8A8 still swaps to RGBA.
assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255]));
}
}
+12 -9
View File
@@ -85,15 +85,18 @@ impl Heap {
return None;
}
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
let h = self
.host
.get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count))
.as_ref()?;
let step = u64::from(increment(self.desc.kind)?);
for i in pending.drain(..) {
h.mirror(i, self.start + u64::from(i) * step, false);
}
Some(h)
// A recorder can take the fast path as soon as the OnceLock is
// initialized. Publish only after replaying the queued writes.
self.host
.get_or_init(|| {
let step = u64::from(increment(self.desc.kind)?);
let h = host::HostHeap::new(self.samplers(), self.desc.count)?;
for i in pending.drain(..) {
h.mirror(i, self.start + u64::from(i) * step, false);
}
Some(h)
})
.as_ref()
}
/// The descriptor index of `handle` in this heap, if it lies in it.
+11 -1
View File
@@ -244,6 +244,12 @@ impl State {
}
}
pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
*slot = VertexView::default();
}
}
pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
self.index = view.copied().unwrap_or_default();
}
@@ -1156,7 +1162,11 @@ fn describe(view: Option<&View>) -> String {
None => "no view".into(),
Some(v @ View::Shader(r, _)) => texture(*r as This)
.unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
// A buffer has no host texture: its title range, as for a shader view.
Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else(
|| format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)),
|t| format!("uav {t}"),
),
Some(View::Placed(u, r, d)) => format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
r[0],
+15 -3
View File
@@ -6,7 +6,7 @@
//! the table as a call.
//!
//! Each list records onto a host command list as its methods are called
//! (decision 0007); draw state lives in [`crate::draw`]. Methods not
//! (decision 0007); draw state lives in `crate::draw`. Methods not
//! written yet log once with their caller, so a run lists what to do next.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
@@ -446,6 +446,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
crate::resource::host_resource(dst),
crate::resource::host_resource(src),
) {
if crate::texture::title_written(from) {
crate::texture::upload(list, src, from);
}
ensure_state(list, dst, COPY_DEST);
ensure_state(list, src, COPY_SOURCE);
crate::texture::host_written(dst);
@@ -522,7 +525,9 @@ extern "system" fn copy_texture_region(
let Some((buffer, staging)) = list.upload(host, bytes) else {
return;
};
list.defer_copy(staging, data, bytes as usize);
// The list owns this mapped D3D12 upload buffer. Wine can report
// its address as MEM_FREE, so use the host-upload path.
list.defer_fill(staging, data, bytes as usize);
from.resource = buffer.as_raw().cast_const().cast();
from.footprint.offset = 0;
#[cfg(feature = "diagnostics")]
@@ -535,6 +540,9 @@ extern "system" fn copy_texture_region(
let Some(texture) = crate::resource::host_resource(src.resource) else {
return;
};
if crate::texture::title_written(texture) {
crate::texture::upload(list, src.resource, texture);
}
ensure_state(list, src.resource, COPY_SOURCE);
from.resource = texture.as_raw().cast_const().cast();
}
@@ -1007,7 +1015,11 @@ mod state {
views: *const VertexView,
) {
with_state(this, |_, s| {
s.set_vertex_buffers(start, items(views, count))
if views.is_null() {
s.clear_vertex_buffers(start, count);
} else {
s.set_vertex_buffers(start, items(views, count));
}
});
}
/// `(count, handles, one range, depth)`: with one range, the handles
+30 -1
View File
@@ -127,7 +127,19 @@ fn f32_to_half(v: f32) -> u16 {
return sign | 0x7c00; // too large: infinity
}
if exp <= 0 {
return sign; // too small: zero
if exp < -10 {
return sign; // below half the smallest subnormal: zero
}
// Half subnormals are `m * 2^-24`. An f32 in this range is still
// normal (exponent field >= 1), so its significand has the implicit
// leading 1; shift it into the half mantissa, rounding to even.
let sig = (1u32 << 23) | man;
let shift = (14 - exp) as u32;
let halfway = 1u32 << (shift - 1);
let q = sig >> shift;
let r = sig & ((1u32 << shift) - 1);
let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0));
return sign | m as u16;
}
// Rounded to nearest: a carry out of the mantissa is added into the
// exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00.
@@ -199,4 +211,21 @@ mod tests {
assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]);
assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
}
/// `half_to_f32` reads subnormals, so an f16 rectangle output must be
/// able to write them back instead of flushing every one to zero.
#[test]
fn half_subnormals_convert_in_both_directions() {
assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001);
assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001);
assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002);
assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff);
// Ties go to an even mantissa: 0/1 and 1/2.
assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000);
assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002);
// Below half the smallest subnormal, and normal values, are unchanged.
assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000);
assert_eq!(f32_to_half(1.5), 0x3e00);
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
//! atomically; an entry that does not read back is translated again.
//!
//! The entry is our own encoding of [`HostShader`]: a field added to it
//! must be added to [`encode`] and [`decode`] too (entries of older builds
//! must be added to `encode` and `decode` too (entries of older builds
//! are ignored anyway).
use std::path::PathBuf;
+13 -2
View File
@@ -210,7 +210,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
/// The runtime calls it (as `kernel_will_write`) before the title's kernel
/// reads into its own memory.
pub fn writing(at: usize, len: usize) {
open(&mut guards(), at, at + len);
// The length is the title's (`fread`'s size times count, saturated).
open(&mut guards(), at, at.saturating_add(len));
}
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
@@ -219,7 +220,7 @@ pub fn title_memory_remapped(at: usize, len: usize) {
let mut g = guards();
let blocks: Vec<usize> = g
.protected
.range(at / BLOCK..(at + len).div_ceil(BLOCK))
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
.copied()
.collect();
for block in blocks {
@@ -367,4 +368,14 @@ mod tests {
unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
title_memory_remapped(view, 2 * BLOCK);
}
/// A write or mapping that runs past the end of the address space (a
/// title's `fread` with a huge count) covers up to the end; the sum used
/// to overflow. Up there no test has guarded blocks.
#[test]
fn ranges_past_the_address_space_end_do_not_overflow() {
let top = usize::MAX - 16;
writing(top, PAGE);
title_memory_remapped(top, usize::MAX);
}
}
+9 -1
View File
@@ -471,7 +471,8 @@ impl Xma {
// The decoder writes the same words.
let mut slot = lock(&self.voices[index as usize]);
let size = context.field(0, 22, 5).max(1);
let read = (context.field(9, 0, 5) + blocks) % size;
// The count is the title's: reduced first, so the sum stays small.
let read = (context.field(9, 0, 5) + blocks % size) % size;
context.set_field(9, 0, 5, read);
if blocks > 0 {
context.set_field(1, 31, 1, 1);
@@ -1062,6 +1063,13 @@ mod tests {
assert_eq!(context.field(0, 20, 2), 0, "input used up");
assert_eq!(context.field(2, 26, 5), INPUT_INVALID);
// A count near `u32::MAX` wraps the read block like any other
// (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum
// used to overflow.
context.set_field(9, 0, 5, 3);
submit(ADVANCE_XMA_READ, &[1, u32::MAX]);
assert_eq!(context.field(9, 0, 5), 2);
submit(DISABLE_XMA, &[1]);
assert_eq!(produced(&xma()), None);
(m.release)(acp);
@@ -174,6 +174,15 @@ extern "system" fn window_proc(
end_title("window closed", Box::new(|| {}));
return 0;
}
// Alt or F10 puts a window into menu mode: the system runs a modal menu
// loop on the thread that owns the window, which is the title's. The
// title then stops (no frames, no input) until a key ends the loop, and
// nothing shows it, since the window has no menu bar; Grand Theft Auto
// VI aborts itself about half a minute later. A console has no window
// menu. The mouse still opens it from the title bar.
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize {
return 0;
}
// SAFETY: the procedure `hook` stored, called the way the system would.
unsafe {
let title = wm::GetPropW(hwnd, TITLE_PROC);
@@ -366,4 +375,64 @@ mod tests {
wm::DestroyWindow(hwnd);
}
}
thread_local! {
/// The system commands `recording` received, low four bits cleared.
static COMMANDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Stands in for a title's procedure: notes system commands and acts
/// on none of them (no menu loop, no minimising).
extern "system" fn recording(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
if message == wm::WM_SYSCOMMAND {
COMMANDS.with(|c| c.borrow_mut().push(wparam & 0xFFF0));
return 0;
}
// SAFETY: the system's default procedure, called as the system would.
unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) }
}
#[test]
fn the_keyboard_menu_never_reaches_the_title() {
let null = std::ptr::null_mut();
let hwnd = CreateWindowExW(
0,
w!("STATIC"),
w!("menu"),
0,
0,
0,
10,
10,
null,
null,
null,
std::ptr::null(),
);
assert!(!hwnd.is_null());
// SAFETY: our window, owned by this thread, so each message is
// handled before SendMessageW returns. `recording` stands in for the
// title's procedure and the original is put back before the window
// is destroyed.
unsafe {
let title = wm::GetPropW(hwnd, TITLE_PROC);
wm::SetPropW(hwnd, TITLE_PROC, recording as *const () as *mut c_void);
let command = |c: u32, key: u8| {
wm::SendMessageW(hwnd, wm::WM_SYSCOMMAND, c as usize, LPARAM::from(key))
};
command(wm::SC_KEYMENU, 0); // Alt or F10
command(wm::SC_KEYMENU, b' '); // Alt+Space
command(wm::SC_KEYMENU | 1, 0); // the low bits are the system's
command(wm::SC_MINIMIZE, 0);
wm::SetPropW(hwnd, TITLE_PROC, title);
wm::DestroyWindow(hwnd);
}
let seen = COMMANDS.with(|c| c.borrow().clone());
assert_eq!(seen, [wm::SC_MINIMIZE as usize]);
}
}
@@ -38,6 +38,8 @@ pub const IID_2026: Guid = Guid::new(
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
type This = *const Object;
/// The path titles get: the root of a virtual drive over the folder. On the
@@ -63,8 +65,11 @@ extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
}
}
/// A buffer too small for the path fails with `E_FAIL`, the documented
/// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`).
extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
match folder() {
Some(path) if size <= path.len() => E_FAIL,
Some(path) => put_string(&path, size, buffer, used),
None => NOT_SUPPORTED,
}
@@ -196,6 +201,7 @@ mod tests {
let (mut buffer, mut used) = ([0u8; 4], 0);
let get = method::<Get>(&OBJECT, 0x20);
assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK);
assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL);
let drive = std::str::from_utf8(&buffer[..3]).unwrap();
assert!(drive.ends_with(":\\"), "{drive}");
// Title file calls on it reach the folder.
+54 -3
View File
@@ -635,7 +635,9 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
return E_INVALIDARG;
}
let hr = status(block);
if hr == S_OK {
// Any nonnegative completion carries a result, not just S_OK: S_FALSE
// is a success code too and a provider may return data with it.
if hr >= 0 {
// SAFETY: checked non-null.
unsafe { out.write(words(block).1.load(Ordering::Acquire)) };
}
@@ -664,8 +666,8 @@ pub fn XAsyncGetResult(
}
let hr = status(block);
let size = words(block).1.load(Ordering::Acquire);
if hr != S_OK || size == 0 {
if hr == S_OK && !used.is_null() {
if hr < 0 || size == 0 {
if hr >= 0 && !used.is_null() {
// SAFETY: checked non-null.
unsafe { used.write(0) };
}
@@ -1132,6 +1134,55 @@ mod tests {
XTaskQueueCloseHandle(q);
}
#[test]
fn a_nonnegative_completion_still_returns_its_payload() {
const S_FALSE: HRESULT = 1;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data.
let data = unsafe { &*data };
match op {
OP_BEGIN => XAsyncSchedule(data.block, 0),
OP_DO_WORK => {
XAsyncComplete(data.block, S_FALSE, 8);
S_OK
}
OP_GET_RESULT => {
// SAFETY: the caller checked eight bytes.
unsafe { data.buffer.cast::<u64>().write(0x1234) };
S_OK
}
_ => S_OK,
}
}
let mut q = std::ptr::null();
assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK);
let mut block = AsyncBlock {
queue: q,
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
let identity = 0x77 as *const c_void;
assert_eq!(
XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)),
S_OK
);
assert!(XTaskQueueDispatch(q, WORK, 0));
assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE);
let mut size = 0;
assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE);
assert_eq!(size, 8);
let mut value = 0u64;
let mut used = 0;
assert_eq!(
XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used),
S_OK
);
assert_eq!((value, used), (0x1234, 8));
assert!(call(&raw mut block).is_none(), "the call ends with its result");
XTaskQueueCloseHandle(q);
}
#[test]
fn run_returns_the_work_result() {
extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {
+38 -2
View File
@@ -396,6 +396,21 @@ fn remaining(root: &Path) -> u64 {
.min(storage::disk_free(root))
}
/// Why an update writing `written` bytes, `replaced` of them over blobs it
/// replaces, does not fit: past the per-user quota (`used` bytes kept), or
/// past the host disk's `free` bytes, which is not the user's quota (the
/// new version is written before the old one goes, so nothing it replaces
/// counts there).
fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option<HRESULT> {
if written > QUOTA.saturating_sub(used) + replaced {
Some(QUOTA_EXCEEDED)
} else if written > free {
Some(OUT_OF_LOCAL_STORAGE)
} else {
None
}
}
fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT {
tracing::warn!(dir = %dir.display(), %e, "game save");
if e.kind() == std::io::ErrorKind::StorageFull {
@@ -449,8 +464,9 @@ impl Update {
changed.map(|(_, size)| size).sum()
});
let root = self.dir.parent().unwrap_or(&self.dir);
if written as u64 > remaining(root) + replaced {
return QUOTA_EXCEEDED;
let free = storage::disk_free(root);
if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) {
return hr;
}
let display = self.display.as_deref();
let display = display.or(current.as_ref().map(|v| v.display.as_str()));
@@ -789,6 +805,11 @@ extern "system" fn read_result(
) -> HRESULT {
let mut used = 0;
let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used);
// The documented error for a small buffer; the result stays for a
// retry with a larger one.
if hr == xasync::E_NOT_SUFFICIENT_BUFFER {
return BUFFER_TOO_SMALL;
}
if hr < 0 {
return hr;
}
@@ -948,6 +969,17 @@ mod tests {
}
}
/// The per-user quota and the host disk fail with their own errors.
#[test]
fn a_full_disk_is_not_the_quota() {
let mb = 1 << 20;
assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE));
assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED));
// Replacing a blob of the same size fits a full quota.
assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None);
assert_eq!(no_room(mb, 0, 0, mb), None);
}
fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT {
Update {
name: "Slot".into(),
@@ -1237,6 +1269,10 @@ mod tests {
);
let mut buffer = vec![0u64; size.div_ceil(8)];
let mut count = 0;
assert_eq!(
read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count),
BUFFER_TOO_SMALL
);
assert_eq!(
read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count),
S_OK
+1 -1
View File
@@ -4,7 +4,7 @@
//! CPU, so the machine code needs no translation. What differs is the
//! platform underneath, so the loader's job is to:
//!
//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark
//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark
//! it as a DLL, remove its entry point and import directory, and detach
//! its TLS callbacks, so the Windows loader maps it, relocates it,
//! allocates its static TLS and registers its unwind tables, but runs
+5 -4
View File
@@ -20,11 +20,12 @@ fn workspace_root() -> PathBuf {
}
/// Builds the fixture into its own target dir (the outer cargo holds the
/// lock on the main one while tests run).
/// lock on the main one while tests run), in the outer one's scratch folder
/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the
/// build.
fn build_probe() -> PathBuf {
let root = workspace_root();
let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml");
let target = root.join("target/fixtures");
let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml");
let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe");
let status = Command::new(env!("CARGO"))
.args(["build", "--quiet", "--manifest-path"])
.arg(&manifest)
+14
View File
@@ -103,6 +103,9 @@ pub(crate) mod pred {
pub const OGE: u8 = 3;
pub const OLT: u8 = 4;
pub const OLE: u8 = 5;
// Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg`
// lowers as OLT | OGT instead.
#[allow(dead_code)]
pub const ONE: u8 = 6;
pub const ORD: u8 = 7;
pub const UNO: u8 = 8;
@@ -291,6 +294,17 @@ impl Module {
self.constant(ty, Const::Aggregate(ids))
}
/// The value of an integer constant; `None` for anything else.
pub fn int_value(&self, v: V) -> Option<i64> {
match v {
V::Const(i) => match self.consts[i as usize].1 {
Const::Int(x) => Some(x),
_ => None,
},
_ => None,
}
}
/// Gives constant `old` the content of `new` (both stay valid).
pub fn replace_const(&mut self, old: V, new: V) {
if let (V::Const(o), V::Const(n)) = (old, new) {
@@ -161,6 +161,15 @@ pub(crate) fn psv(p: &Psv) -> Vec<u8> {
u32s(&mut out, &[48]);
let mut info = [0u8; 48];
info[0] = u8::from(p.flag);
if p.stage == 0 {
// PSInfo.SampleFrequency: an input interpolated per sample, or the
// sample index.
info[1] = u8::from(
p.inputs
.iter()
.any(|e| matches!(e.interp, 6 | 7) || e.kind == 12),
);
}
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
info[16..20].copy_from_slice(&min.to_le_bytes());
info[20..24].copy_from_slice(&max.to_le_bytes());
+349 -81
View File
@@ -931,8 +931,16 @@ impl<'a> Lower<'a> {
for &(reg, v) in &self.x.p.inputs {
let val = match reg {
Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
Reg::S(_) => match io_inputs.get(&v) {
Reg::S(n) => match io_inputs.get(&v) {
Some(&input) => self.input(input),
// Above the SGPRs the hardware initializes, a register
// holds what the last wave left, so no program depends
// on it: a read the paths only seem to allow (a branch
// past the write, taken only with one past the read)
// reads zero, as VGPRs do.
None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
Val::I32(self.s.m.i32(0))
}
None => Val::Missing("a hardware SGPR input"),
},
Reg::Scc => Val::Missing("SCC on entry"),
@@ -1233,6 +1241,19 @@ impl<'a> Lower<'a> {
}
}
/// GFX10 puts an inline f16 constant in the low half of the operand.
fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
match *op {
Operand::Const(c @ 240..=248) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
Ok(self.s.m.i32(h))
}
_ => self.operand(inst, op),
}
}
fn as_float(&mut self, x: V) -> V {
self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
}
@@ -1360,6 +1381,25 @@ impl<'a> Lower<'a> {
)
}
/// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
/// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
/// the compare and select DXIL specifies gives either zero.
fn max_min(&mut self, max: bool, a: V, b: V) -> V {
let c = self.cur;
let r = self.binary(if max { 35 } else { 36 }, a, b);
let (ia, ib) = (self.as_int(a), self.as_int(b));
let either = self.s.m.bin(c, Bin::Or, ia, ib);
let magnitude = self.s.m.i32(0x7FFF_FFFF);
let either = self.s.m.bin(c, Bin::And, either, magnitude);
let zero = self.s.m.i32(0);
let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
// Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
let op = if max { Bin::And } else { Bin::Or };
let sign = self.s.m.bin(c, op, ia, ib);
let signed = self.as_float(sign);
self.s.m.select(c, zeros, signed, r)
}
fn fmad(&mut self, a: V, b: V, c: V) -> V {
self.s.op(
self.cur,
@@ -3866,8 +3906,8 @@ impl<'a> Lower<'a> {
"v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
"v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
"v_mul_legacy_f32" => self.legacy_mul(a, bb),
"v_max_f32" => self.binary(35, a, bb),
_ => self.binary(36, a, bb),
"v_max_f32" => self.max_min(true, a, bb),
_ => self.max_min(false, a, bb),
};
float(self, r)
}
@@ -3917,12 +3957,12 @@ impl<'a> Lower<'a> {
let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
let r = match name {
"v_max3_f32" => {
let t = self.binary(35, a, bb);
self.binary(35, t, cc)
let t = self.max_min(true, a, bb);
self.max_min(true, t, cc)
}
"v_min3_f32" => {
let t = self.binary(36, a, bb);
self.binary(36, t, cc)
let t = self.max_min(false, a, bb);
self.max_min(false, t, cc)
}
_ => self.med3(a, bb, cc),
};
@@ -4281,15 +4321,9 @@ impl<'a> Lower<'a> {
_ => return Err("a byte select on a 16-bit operation"),
}
}
let x = match (op, self.src0) {
(_, Some(x)) if k == 0 => x,
(Operand::Const(c @ 240..=248), _) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
self.s.m.i32(h)
}
_ => self.operand(inst, &op)?,
let x = match self.src0 {
Some(x) if k == 0 => x,
_ => self.f16_operand(inst, &op)?,
};
let c = self.cur;
let x = if high {
@@ -4416,6 +4450,8 @@ impl<'a> Lower<'a> {
"v_min_i16",
"v_cvt_u16_f16",
"v_cvt_i16_f16",
"v_cvt_norm_i16_f16",
"v_cvt_norm_u16_f16",
];
let all = [FLOAT1, FLOAT2, FLOAT3, INT];
if !all.iter().any(|l| l.contains(&name))
@@ -4468,8 +4504,8 @@ impl<'a> Lower<'a> {
"v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
"v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
"v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
"v_max_f16" => self.binary(35, a, b),
_ => self.binary(36, a, b),
"v_max_f16" => self.max_min(true, a, b),
_ => self.max_min(false, a, b),
};
return float_result(self, r);
}
@@ -4499,12 +4535,12 @@ impl<'a> Lower<'a> {
// product is exact; the sum rounds twice).
"v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
"v_max3_f16" => {
let t = self.binary(35, a, b);
self.binary(35, t, acc)
let t = self.max_min(true, a, b);
self.max_min(true, t, acc)
}
"v_min3_f16" => {
let t = self.binary(36, a, b);
self.binary(36, t, acc)
let t = self.max_min(false, a, b);
self.max_min(false, t, acc)
}
_ => self.med3(a, b, acc),
};
@@ -4554,21 +4590,35 @@ impl<'a> Lower<'a> {
};
return float_result(self, r);
}
if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
if v.clamp || v.omod != 0 {
return Err("modifiers on a 16-bit integer operation");
}
let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
return self.write_half(inst, r, guard);
}
// 16-bit integers: computed on the low halves, the low 16 bits kept.
if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
return Err("modifiers on a 16-bit integer operation");
}
let r = match name {
"v_cvt_u16_f16" | "v_cvt_i16_f16" => {
// shortcut: converted through 32 bits, so out-of-range values
// wrap instead of saturating at 16 bits.
// Toward zero, saturating at the 16-bit range (infinities
// included); NaN gives 0. Clamped in f32 first, where every
// f16 is exact, so the conversion never leaves i32's range.
let a = self.half_fsrc(inst, 0)?;
let op = if name == "v_cvt_u16_f16" {
Cast::FpToUi
let (lo, hi) = if name == "v_cvt_u16_f16" {
(0.0f32, 65535.0f32)
} else {
Cast::FpToSi
(-32768.0, 32767.0)
};
self.s.m.cast(c, op, a, i32t)
let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
let t = self.binary(35, a, lo);
let t = self.binary(36, t, hi);
let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
let nan = self.s.m.cmp(c, pred::UNO, a, a);
let z = self.s.m.i32(0);
self.s.m.select(c, nan, z, r)
}
_ => {
let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
@@ -4618,24 +4668,92 @@ impl<'a> Lower<'a> {
self.write_half(inst, r, guard)
}
/// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
/// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
/// rounded to nearest even once from the exact product; NaN gives 0.
/// Worked on the f16's bits in integers, because in f32 the product
/// (up to 26 significant bits) would round before the rounding to an
/// integer.
fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
let c = self.cur;
let k = |l: &mut Self, x: u32| l.s.m.i32(x);
let mut h = self.half_src(inst, 0)?;
if v.abs & 1 != 0 {
let m = k(self, 0x7FFF);
h = self.s.m.bin(c, Bin::And, h, m);
}
if v.neg & 1 != 0 {
let m = k(self, 0x8000);
h = self.s.m.bin(c, Bin::Xor, h, m);
}
let scale = if signed { 0x7FFF } else { 0xFFFF };
let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
let mag_mask = k(self, 0x7FFF);
let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
let k15 = k(self, 15);
let neg = self.s.m.bin(c, Bin::LShr, h, k15);
let neg = self.s.m.cmp(c, pred::NE, neg, k0);
// |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
let man_mask = k(self, 0x3FF);
let man = self.s.m.bin(c, Bin::And, mag, man_mask);
let implicit = k(self, 0x400);
let normal = self.s.m.bin(c, Bin::Or, man, implicit);
let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
let m = self.s.m.select(c, sub, man, normal);
let k25 = k(self, 25);
let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
let k24 = k(self, 24);
let sh = self.s.m.select(c, sub, k24, s_norm);
let ks = k(self, scale);
let p = self.s.m.bin(c, Bin::Mul, m, ks);
let q = self.s.m.bin(c, Bin::LShr, p, sh);
let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
let rem = self.s.m.bin(c, Bin::And, p, low_mask);
let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
let above = self.s.m.cmp(c, pred::IUGT, rem, half);
let tie = self.s.m.cmp(c, pred::EQ, rem, half);
let odd = self.s.m.bin(c, Bin::And, q, k1);
let odd = self.s.m.cmp(c, pred::NE, odd, k0);
let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
let up = self.s.m.bin(c, Bin::Or, above, tie_up);
let r = self.s.m.select(c, up, k1, k0);
let r = self.s.m.bin(c, Bin::Add, q, r);
// |x| >= 1 (and infinity) saturates; NaN gives 0.
let one_h = k(self, 0x3C00);
let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
let r = self.s.m.select(c, big, ks, r);
let inf = k(self, 0x7C00);
let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
let r = self.s.m.select(c, nan, k0, r);
let r = if signed {
let n = self.s.m.bin(c, Bin::Sub, k0, r);
self.s.m.select(c, neg, n, r)
} else {
self.s.m.select(c, neg, k0, r)
};
let m16 = k(self, 0xFFFF);
Ok(self.s.m.bin(c, Bin::And, r, m16))
}
/// Half `high` of source `k` of a packed (VOP3P) operation, in the low
/// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
/// half the high result reads. Inline float constants are f16 values.
fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
/// half the high result reads. Packed integer instructions see the f32
/// bits of an inline float constant.
fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
let op = *v.src.get(k).ok_or("a missing operand")?;
let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
let x = match op {
Operand::Const(c @ 240..=248) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
// shortcut: taken to fill both halves.
self.s.m.i32(h | h << 16)
}
_ => self.operand(inst, &op)?,
let x = if float {
self.f16_operand(inst, &op)?
} else {
self.operand(inst, &op)?
};
let c = self.cur;
let x = if sel {
@@ -4671,7 +4789,7 @@ impl<'a> Lower<'a> {
for high in [false, true] {
let mut xs = Vec::new();
for k in 0..n {
let h = self.packed_src(inst, k, high)?;
let h = self.packed_src(inst, k, high, float)?;
if float {
let mut f = self
.s
@@ -4690,8 +4808,8 @@ impl<'a> Lower<'a> {
let mut f = match op {
"add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
"mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
"min_f16" => self.binary(36, xs[0], xs[1]),
"max_f16" => self.binary(35, xs[0], xs[1]),
"min_f16" => self.max_min(false, xs[0], xs[1]),
"max_f16" => self.max_min(true, xs[0], xs[1]),
// shortcut: FMad in f32, as v_fma_f16.
_ => self.fmad(xs[0], xs[1], xs[2]),
};
@@ -4973,24 +5091,22 @@ impl<'a> Lower<'a> {
_ => {
// A computed selector: each byte picked at run time.
let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
let i64t = self.s.m.int(64);
self.s.flags |= flags::INT64;
let wa = self.s.m.cast(c, Cast::ZExt, a, i64t);
let wb = self.s.m.cast(c, Cast::ZExt, b, i64t);
let k32 = self.s.m.int_const(i64t, 32);
let wa = self.s.m.bin(c, Bin::Shl, wa, k32);
let both = self.s.m.bin(c, Bin::Or, wa, wb);
let mut r = k(self, 0);
for i in 0..4u32 {
let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
let sel = self.s.m.bin(c, Bin::And, sel, ff);
// Bytes 0-7 of {src0, src1}.
let k3 = k(self, 3);
let bits = self.s.m.bin(c, Bin::Shl, sel, k3);
let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t);
let x = self.s.m.bin(c, Bin::LShr, both, bits);
let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
// Select a dword and a byte within it.
// Later selects handle codes 8 and above.
let four = k(self, 4);
let zero = k(self, 0);
let high = self.s.m.bin(c, Bin::And, sel, four);
let high = self.s.m.cmp(c, pred::NE, high, zero);
let word = self.s.m.select(c, high, a, b);
let three = k(self, 3);
let index = self.s.m.bin(c, Bin::And, sel, three);
let bits = self.s.m.bin(c, Bin::Shl, index, three);
let x = self.s.m.bin(c, Bin::LShr, word, bits);
let mut byte = self.s.m.bin(c, Bin::And, x, ff);
// 8-11: the sign of bytes 1, 3 of src1, then of src0.
for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
@@ -5214,26 +5330,35 @@ impl<'a> Lower<'a> {
} else {
(self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
};
let p = match op {
"f" => pred::FALSE,
"lt" => pred::OLT,
"eq" => pred::OEQ,
"le" => pred::OLE,
"gt" => pred::OGT,
"lg" => pred::ONE,
"ge" => pred::OGE,
"o" => pred::ORD,
"u" => pred::UNO,
"nge" => pred::ULT,
"nlg" => pred::UEQ,
"ngt" => pred::ULE,
"nle" => pred::UGT,
"neq" => pred::UNE,
"nlt" => pred::UGE,
"tru" => pred::TRUE,
_ => return Err(inst.name()),
};
self.s.m.cmp(c, p, a, b)
if op == "lg" {
// Ordered and not equal, false for a NaN, as `olt | ogt`.
// `fcmp one` means the same, but the AMD D3D12 driver
// runs it as unordered (true for a NaN) where NVIDIA
// and WARP do not; olt and ogt agree on all three.
let lt = self.s.m.cmp(c, pred::OLT, a, b);
let gt = self.s.m.cmp(c, pred::OGT, a, b);
self.s.m.bin(c, Bin::Or, lt, gt)
} else {
let p = match op {
"f" => pred::FALSE,
"lt" => pred::OLT,
"eq" => pred::OEQ,
"le" => pred::OLE,
"gt" => pred::OGT,
"ge" => pred::OGE,
"o" => pred::ORD,
"u" => pred::UNO,
"nge" => pred::ULT,
"nlg" => pred::UEQ,
"ngt" => pred::ULE,
"nle" => pred::UGT,
"neq" => pred::UNE,
"nlt" => pred::UGE,
"tru" => pred::TRUE,
_ => return Err(inst.name()),
};
self.s.m.cmp(c, p, a, b)
}
}
"u64" | "i64" => {
let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
@@ -5650,7 +5775,7 @@ impl<'a> Lower<'a> {
return Ok(());
}
let (op, sample) = match name {
"image_sample" => (60, true),
"image_sample" | "image_sample_o" => (60, true),
"image_sample_lz" | "image_sample_l" => (62, true),
"image_sample_b" => (61, true),
"image_sample_c_lz" => (65, true),
@@ -5795,6 +5920,25 @@ impl<'a> Lower<'a> {
args.extend(&cs);
match op {
60 => {
if offset_word {
// DXIL takes immediate offsets in -8..=7; the
// console's are 6-bit and may be computed.
let w = addr_val(self, 0)?;
let w = self
.s
.m
.int_value(w)
.ok_or("a sample offset that is not constant")?
as u32;
for (k, o) in os.iter_mut().enumerate().take(offsets) {
let x = (w >> (8 * k) & 0x3F) as i32;
let x = if x >= 32 { x - 64 } else { x };
if !(-8..=7).contains(&x) {
return Err("a sample offset past -8..7");
}
*o = self.s.m.i32(x as u32);
}
}
args.extend(&os);
args.push(fu);
self.s
@@ -6733,6 +6877,20 @@ impl<'a> Lower<'a> {
fn fill_phis(&mut self) -> Result<(), Stop> {
let p = self.x.p;
// A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that
// reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the
// lowering accepts what it refuses when the same value is read directly.
let mut work: Vec<Value> = self.read_phis.iter().copied().collect();
while let Some(v) = work.pop() {
let Some(&(b, i)) = self.phi_at.get(&v) else {
continue;
};
for &arg in &p.blocks[b].phis[i].args {
if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) {
work.push(arg);
}
}
}
for (v, b, i) in std::mem::take(&mut self.data_phis) {
let phi = &p.blocks[b].phis[i];
let bit = phi.reg == Reg::Scc;
@@ -6792,8 +6950,8 @@ mod tests {
const S_ENDPGM: u32 = 0xBF81_0000;
/// Lowers a compute program of constants: whether it translates.
fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> {
/// Whether a synthetic compute program translates with these input registers.
fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let native = NativeProgram {
stage: HwStage::Cs,
@@ -6802,7 +6960,7 @@ mod tests {
layout: vec![],
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: 0,
rsrc2,
threads: [1, 1, 1],
}),
code,
@@ -6914,10 +7072,91 @@ mod tests {
S_ENDPGM,
];
for words in [add, sub] {
lowers(&words).unwrap();
lowers(&words, 0).unwrap();
}
}
fn perm_features(selector: u32) -> u64 {
// Synthetic compute shader:
// v0 is the thread ID and can supply a dynamic selector.
// Store the result in LDS to keep the permutation live.
let words = [
0x7E02_02FFu32,
0x817F_34AB,
0x7E04_02FF,
0xFE01_56CD,
0xD744_0003,
257 | (258 << 9) | (selector << 18),
0x3408_0082,
0xD834_0000,
0x0000_0304,
S_ENDPGM,
];
let code: Vec<u8> = words.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: 1 << 15,
threads: [64, 1, 1],
}),
code,
};
let p = ir::build(&native.code, false, 256).unwrap();
assert!(p.blocks.iter()
.flat_map(|b| &b.insts)
.any(|i| i.name() == "v_perm_b32"));
let st = structure::structure(&p).unwrap();
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = io::raise(&p, &native).unwrap();
let emitted = lower(&Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: vec![],
outputs: vec![],
prims: vec![],
mesh_stride: 0,
}).unwrap();
let container =
crate::Container::parse(&emitted.dxil).unwrap();
let features =
container.part(crate::FourCC::SFI0).unwrap();
u64::from_le_bytes(features.data.try_into().unwrap())
}
#[test]
fn perm_constant_selector_needs_no_int64() {
assert_eq!(perm_features(128) & 0x8000, 0);
}
#[test]
fn perm_dynamic_selector_needs_no_int64() {
assert_eq!(
perm_features(256) & 0x8000,
0,
"dynamic v_perm_b32 must not require INT64"
);
}
#[test]
fn a_descriptor_selected_by_scc_picks_its_heap_index() {
// Two buffer descriptors loaded from the table at s0, one picked by
@@ -7049,10 +7288,39 @@ mod tests {
];
for head in bit_tests {
let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
lowers(&words).unwrap();
lowers(&words, 0).unwrap();
}
}
#[test]
fn a_missing_value_stays_missing_through_two_live_joins() {
let mut words = [
0xF490_0180,
0, // s_memtime s[6:7]
0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
0xBF85_0001, // skip the first overwrite
0xBE86_0380, // s_mov_b32 s6, 0
0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
0xBF85_0001, // skip the second overwrite
0xBE86_0381, // s_mov_b32 s6, 1
0xBF07_8006, // s_cmp_lg_u32 s6, 0
0xBF85_0001, // use the result to branch
0xBE83_0380,
S_ENDPGM,
];
let group_ids_xy = 3 << 7;
// Compare to a direct read so future timestamp support works in both cases.
let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
Ok(()) => None,
Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
Err(error) => panic!("{error}"),
};
let direct = [&words[..2], &words[8..]].concat();
assert_eq!(refusal(&words), refusal(&direct));
words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
lowers(&words, group_ids_xy).expect("dead timestamp");
}
#[test]
fn buffer_formats_by_number() {
// The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
+147
View File
@@ -246,6 +246,13 @@ pub fn emit(
_ => 0,
};
}
// With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
// wants the position centroid (or per sample), as DXC declares it then.
if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
for e in inputs.iter_mut().filter(|e| e.kind == 3) {
e.interp = 5;
}
}
// Per-primitive outputs are constant. The console never exports a
// primitive id or cull flag a mesh shader writes (it culls with the
// primitive export), so those rows are left out.
@@ -416,6 +423,68 @@ mod tests {
use super::*;
use crate::native::{ComputeIo, StageIo};
/// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
/// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
/// output signature has SV_StencilRef, and the feature bit
/// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
/// both against the module.
#[test]
fn a_stencil_export_declares_the_stencil_ref_feature() {
let words = [
0x7E00_02F2u32, // v_mov_b32 v0, 1.0
0x7E02_0285, // v_mov_b32 v1, 5
0xF800_1883,
0x0000_0100, // exp mrtz v0, v1, off, off done vm
0xBF81_0000,
];
let native = NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 2,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs: vec![],
input_addr: 0,
db_shader_control: 0,
patches: vec![],
},
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let el = |name: &str, kind, comp| SigElement {
name: name.into(),
index: 0,
kind,
comp,
interp: 0,
row: None,
col: 0,
cols: 1,
usage: 1,
half: false,
};
let osg1 =
container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
let c = Container::parse(&bytes).unwrap();
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let st = structure::structure(&p).unwrap();
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = io::raise(&p, &native).unwrap();
let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
// dxil.dll, where there is one, checks the flags against the module.
#[cfg(windows)]
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut out.dxil.clone()).unwrap();
}
let host = Container::parse(&out.dxil).unwrap();
let sfi0 = host.part(FourCC::SFI0).unwrap().data;
let features = u64::from_le_bytes(sfi0.try_into().unwrap());
assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
}
/// A wave64 compute program that writes only EXEC's high dword
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
/// opaque and keyed by the unchanged low dword, so building its lane bit
@@ -452,6 +521,7 @@ mod tests {
}
/// A pixel shader writing a constant colour.
#[cfg(windows)]
fn constant_color() -> Vec<u8> {
let mut s = Shader::new(true);
s.outputs.push(SigElement {
@@ -545,6 +615,83 @@ mod tests {
assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
}
/// A pixel shader interpolating at sample positions (PERSP_SAMPLE
/// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
/// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
/// whenever an input is interpolated per sample.
#[test]
fn sample_interpolated_inputs_set_psv_sample_frequency() {
let words = [
0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xF800_180F,
0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
0xBF81_0000,
];
let psv_of = |input_addr: u32| {
let native = super::NativeProgram {
stage: super::HwStage::Ps,
wave64: false,
vgprs: 4,
layout: vec![],
used: vec![],
io: crate::native::StageIo::Ps {
inputs: vec![crate::native::PsInput {
usage: crate::native::Usage::Generic,
row: 0,
mask: 0b1111,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 0,
}],
input_addr,
db_shader_control: 0,
patches: vec![],
},
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let el = |name: &str, kind, usage| SigElement {
name: name.into(),
index: 0,
kind,
comp: 9,
interp: 0,
row: Some(0),
col: 0,
cols: 4,
usage,
half: false,
};
let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
let bytes =
crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
let c = super::Container::parse(&bytes).unwrap();
let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let st = crate::structure::structure(&p).unwrap();
let res =
crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = crate::io::raise(&p, &native).unwrap();
let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
// dxil.dll, where there is one, checks PSV0 against the module.
#[cfg(windows)]
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut out.dxil.clone()).unwrap();
}
let host = super::Container::parse(&out.dxil).unwrap();
host.part(super::FourCC::PSV0).unwrap().data.to_vec()
};
// Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
let center = psv_of(1 << 1);
assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
let sample = psv_of(1 << 0);
assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
}
/// A pixel shader reading channel z of an input whose element starts at
/// w. Looking the channel up subtracted the element's first channel
/// before checking the channel lies in it, so in a build with overflow
+8
View File
@@ -16,6 +16,7 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
pub(crate) mod flags {
pub const RAW_BUFFERS: u64 = 1 << 4;
pub const STENCIL_REF: u64 = 1 << 11;
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
pub const WAVE_OPS: u64 = 1 << 19;
pub const INT64: u64 = 1 << 20;
@@ -483,6 +484,10 @@ impl Shader {
} else {
None
};
// A pixel shader with an SV_StencilRef output (as DXC collects it).
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
self.flags |= flags::STENCIL_REF;
}
// Entry properties: shader flags (tag 0), thread-group size (4),
// wave size (11).
let mut props = Vec::new();
@@ -561,6 +566,9 @@ impl Shader {
dxil.extend(&bitcode);
let mut features = 0u64;
if self.flags & flags::STENCIL_REF != 0 {
features |= 0x200;
}
if self.flags & flags::TYPED_UAV_LOADS != 0 {
features |= 0x800;
}
+1 -1
View File
@@ -1,6 +1,6 @@
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
//! offline batch. Translated shaders do not need it: they carry the
//! container hash we compute ([`super::container::hash`]).
//! container hash we compute (`container::hash`).
//!
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
@@ -167,6 +167,11 @@ fn run_cases(
cases: &[[u32; 4]],
mut check: impl FnMut(&str, usize, [u32; 4], u32),
) {
// One test at a time: with these tests on the hardware adapter and WARP
// from several test threads at once, now and then none of their
// dispatches ever completes and the test binary hangs.
static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
@@ -232,6 +237,27 @@ fn f16_to_f32(bits: u16) -> f32 {
f32::from_bits(f32_bits)
}
#[test]
fn packed_add_selects_halves_of_inline_constants() {
// Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves.
// The same GFX10 source field (248) has a different bit pattern for a
// packed floating-point and a packed integer instruction.
let cases = [
// v_pk_add_f16 v0, 0x3118, v1
([0xcc0f4000, 0x1a0202f8], 0x0000_3118),
// v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice)
([0xcc0f4000, 0x120202f8], 0x3118_3118),
// v_pk_add_u16 v0, 0x3e22f983, v1
([0xcc0a4000, 0x1a0202f8], 0x3e22_f983),
];
for (words, expected) in cases {
let shader = build_valu_cs(&words);
run_cases(&shader, &[[0; 4]], |backend, _, _, got| {
assert_eq!(got, expected, "{backend}: {words:08x?}");
});
}
}
#[test]
fn v_med3_f32_matches_rdna2_with_nan() {
// v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157)
@@ -280,6 +306,32 @@ fn v_med3_f32_matches_rdna2_with_nan() {
});
}
/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and
/// FMin compare and select, which can give either zero.
#[test]
fn max_and_min_order_negative_zero_below_positive_zero() {
let (pz, nz) = (0_u32, 0x8000_0000_u32);
// Each case has a -0 and a +0 among its first two operands.
let cases = [
[nz, pz, nz, 0],
[pz, nz, nz, 0],
[nz, pz, pz, 0],
[pz, nz, pz, 0],
];
let ops = [
("v_max_f32", 0x110, pz),
("v_min_f32", 0x10F, nz),
("v_max3_f32", 0x154, pz),
("v_min3_f32", 0x151, nz),
];
for (name, op, want) in ops {
let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
run_cases(&shader, &cases, |backend, _, inp, got| {
assert_eq!(got, want, "{backend}: {name} {inp:x?}");
});
}
}
#[test]
fn v_med3_f16_matches_rdna2_with_nan() {
// v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357)
@@ -321,6 +373,58 @@ fn v_med3_f16_matches_rdna2_with_nan() {
});
}
/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when
/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware).
#[test]
fn v_cmp_lg_is_false_for_nan() {
// v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3);
// v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101)
let nan = f32::NAN.to_bits();
let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits());
let f = f32::to_bits;
let f32_cases: &[([u32; 4], u32)] = &[
([f(1.0), f(2.0), 0, 0], 1),
([f(2.0), f(1.0), 0, 0], 1),
([f(1.0), f(1.0), 0, 0], 0),
([f(0.0), f(-0.0), 0, 0], 0),
([inf, ninf, 0, 0], 1),
([inf, inf, 0, 0], 0),
([nan, f(1.0), 0, 0], 0),
([f(1.0), nan, 0, 0], 0),
([nan, nan, 0, 0], 0),
([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN
];
let f16_cases: &[([u32; 4], u32)] = &[
([0x3C00, 0x4000, 0, 0], 1),
([0x4000, 0x3C00, 0, 0], 1),
([0x3C00, 0x3C00, 0, 0], 0),
([0x0000, 0x8000, 0, 0], 0),
([0x7C00, 0xFC00, 0, 0], 1),
([0x7E00, 0x3C00, 0, 0], 0),
([0x3C00, 0x7E00, 0, 0], 0),
([0x7E00, 0x7E00, 0, 0], 0),
([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN
([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read
];
for (op, what, cases) in [
(0x005u16, "v_cmp_lg_f32", f32_cases),
(0x0cd, "v_cmp_lg_f16", f16_cases),
] {
let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec();
body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20)));
let shader = build_valu_cs(&body);
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
run_cases(&shader, &inputs, |backend, i, inp, got| {
let want = cases[i].1;
assert_eq!(
got, want,
"{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}",
inp[0], inp[1],
);
});
}
}
#[test]
fn v_fract_f32_never_returns_one() {
// v_fract_f32 v0, v1 (VOP1 opcode 0x020)
@@ -421,6 +525,52 @@ fn v_fract_f16_never_returns_one() {
});
}
/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or
/// 65535, round the exact product to nearest even; NaN gives 0.
fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 {
let x = f16_to_f32(bits);
if x.is_nan() {
return 0;
}
let (lo, scale) = if signed {
(-1.0, 32767.0)
} else {
(0.0, 65535.0)
};
// f64 holds the product of an f16 and a 16-bit scale exactly.
let p = f64::from(x.clamp(lo, 1.0)) * scale;
p.round_ties_even() as i32 as u16
}
#[test]
fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() {
// Every 251st f16 pattern, plus the values where an f32 product would
// round before the rounding to an integer, ties, and the edges.
let mut bits: Vec<u16> = (0..=u16::MAX).step_by(251).collect();
bits.extend([
0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF,
0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01,
0x3A9B, 0xBA9B, 0x2E66, 0x1400,
]);
for (op, signed, what) in [
(0x063u16, true, "v_cvt_norm_i16_f16"),
(0x064, false, "v_cvt_norm_u16_f16"),
] {
// v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0.
let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let want = cvt_norm16_reference(bits[i], signed);
assert_eq!(
got,
u32::from(want),
"{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
bits[i],
);
});
}
}
#[test]
fn v_sin_and_v_cos_f32_reduce_large_turns() {
let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]);
@@ -521,6 +671,46 @@ fn v_sin_and_v_cos_f32_reduce_large_turns() {
});
}
#[test]
fn v_cvt_u16_and_i16_f16_saturate() {
// v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053).
let cases: &[(u16, u16, u16)] = &[
// (f16 input, u16 result, i16 result)
(0x0000, 0, 0), // 0
(0x8000, 0, 0), // -0
(0x3E00, 1, 1), // 1.5 -> 1 (toward zero)
(0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1
(0x57D0, 125, 125), // 125.0
(0x7800, 32768, 32767), // 32768 saturates i16
(0x77FF, 32752, 32752), // 32752, the largest f16 below 32768
(0xF800, 0, 0x8000), // -32768 fits i16
(0xF801, 0, 0x8000), // -32800 saturates i16
(0x7BFF, 65504, 32767), // max finite f16
(0xFBFF, 0, 0x8000), // -65504
(0x7C00, 0xFFFF, 32767), // +inf
(0xFC00, 0, 0x8000), // -inf
(0x7E00, 0, 0), // NaN
(0xFE00, 0, 0), // -NaN
(0x0001, 0, 0), // smallest subnormal
];
for (op, what, pick) in [
(0x052u16, "v_cvt_u16_f16", 0usize),
(0x053, "v_cvt_i16_f16", 1),
] {
let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let want = if pick == 0 { cases[i].1 } else { cases[i].2 };
assert_eq!(
got,
u32::from(want),
"{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
cases[i].0,
);
});
}
}
#[test]
fn v_sin_and_v_cos_f16_reduce_large_turns() {
let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]);
+7
View File
@@ -182,6 +182,9 @@ pub struct Io {
pub inputs: Vec<(Value, Input)>,
pub interps: Vec<(Site, Interp)>,
pub exports: Vec<Export>,
/// Compute: how many SGPRs the hardware initializes
/// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)).
pub initialized_sgprs: Option<u8>,
}
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
@@ -287,6 +290,10 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
let mut io = Io {
inputs: inputs.clone(),
initialized_sgprs: match &native.io {
StageIo::Cs(cs) => Some(cs.initialized_sgprs()),
_ => None,
},
..Io::default()
};
let defs: std::collections::HashMap<Value, Site> = p
+31
View File
@@ -319,6 +319,15 @@ impl ComputeIo {
(ids, take(10))
}
/// SGPRs the hardware initializes: the user SGPRs, the enabled system
/// ones, then the scratch wave offset when scratch is enabled (bit 0).
/// The ones above hold whatever the previous wave left.
pub fn initialized_sgprs(&self) -> u8 {
let (ids, info) = self.system_sgprs();
let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max();
end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8
}
/// Thread id components in v0, v1, v2 (1 to 3).
pub fn thread_id_vgprs(&self) -> u8 {
(self.rsrc2 >> 11 & 3) as u8 + 1
@@ -948,6 +957,28 @@ mod tests {
assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0));
}
#[test]
fn initialized_sgprs_covers_user_system_and_scratch() {
// 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6.
let cs = ComputeIo {
rsrc2: 0x1098A,
threads: [16, 16, 1],
};
assert_eq!(cs.initialized_sgprs(), 7);
// All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9.
let cs = ComputeIo {
rsrc2: 0x78C,
threads: [8, 8, 1],
};
assert_eq!(cs.initialized_sgprs(), 10);
// The same with scratch enabled adds the wave offset: s0..=s10.
let cs = ComputeIo {
rsrc2: 0x78D,
threads: [8, 8, 1],
};
assert_eq!(cs.initialized_sgprs(), 11);
}
#[test]
fn reads_every_native_blob() {
let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));