victory-gta6: this fork's changes on top of VIctory main (ffe310e)
World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI (Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README describes the state, the changes and the credits. Based on VIctory by Marvisak and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as a reference. No game files are included. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
45c6e80601
commit
6fa814fba5
61 files changed
+32259
-1274
No files matched your search
@@ -0,0 +1,696 @@
|
||||
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
|
||||
//! instruction returns for one ray and one node. The emitter lowers the
|
||||
//! instruction to the same arithmetic in the same order
|
||||
//! (`emit/intersect.rs`), so its code can be compared against this dword
|
||||
//! for dword.
|
||||
//!
|
||||
//! The instruction tests one ray against one 64-byte node of a bounding
|
||||
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
|
||||
//! transforms, culling, the hit distance `numerator / denominator`) is the
|
||||
//! program's own code.
|
||||
//!
|
||||
//! # Node pointers
|
||||
//!
|
||||
//! A node pointer's low three bits are the node's kind, the rest its byte
|
||||
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
|
||||
//! base address of the descriptor (40 bits in dword 0 and the low byte of
|
||||
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
|
||||
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
|
||||
//! with base 0 for every structure and adds `address >> 3` itself.
|
||||
//!
|
||||
//! | kind | node |
|
||||
//! |---|---|
|
||||
//! | 0-3 | triangle 0-3 of a triangle node |
|
||||
//! | 4 | box node, 16-bit floats (64 bytes) |
|
||||
//! | 5 | box node, 32-bit floats (128 bytes) |
|
||||
//! | 6 | instance: not read by the instruction |
|
||||
//! | 7 | procedural primitive: not read by the instruction |
|
||||
//!
|
||||
//! # Box nodes
|
||||
//!
|
||||
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
|
||||
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
|
||||
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
|
||||
//! 112-127 are not read). The result is the pointers of the children whose
|
||||
//! box the ray enters before its extent, nearest entry first when the
|
||||
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
|
||||
//!
|
||||
//! # Triangle nodes
|
||||
//!
|
||||
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
|
||||
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
|
||||
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
|
||||
//! input triangle's second vertex at the former, its third at the latter
|
||||
//! and its first at the remaining one, so I and J are the weights of the
|
||||
//! input triangle's second and third vertices). Triangle `k` of the node
|
||||
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
|
||||
//! keeps fewer triangles in a node uses the bytes of the unused vertices
|
||||
//! for its own data.
|
||||
//!
|
||||
//! With the descriptor's triangle return mode set (bit 120) the result is
|
||||
//! the hit distance's numerator, its denominator, and the numerators of I
|
||||
//! and J over the same denominator, as floats. The denominator is positive
|
||||
//! for a triangle whose vertices run clockwise seen from the ray's origin
|
||||
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
|
||||
//! The ray's extent is not tested for triangles.
|
||||
//!
|
||||
//! # Where this comes from
|
||||
//!
|
||||
//! The node formats, the descriptor bits and the tests are those of the
|
||||
//! public software emulation of this instruction in the open-source Vulkan
|
||||
//! driver for this GPU family (box test and sorting network as there; the
|
||||
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
|
||||
//! JCGT 2013), and agree with what Grand Theft Auto VI's own structure
|
||||
//! builder writes and its trace programs read. Not known from either: how
|
||||
//! the console rounds, which of two boxes entered at the same distance it
|
||||
//! returns first, and what it returns for a ray exactly through an edge
|
||||
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
|
||||
//! a triangle miss; the title's programs do not read it).
|
||||
|
||||
/// The result dword for a box the ray misses, or a child that is not there.
|
||||
pub const NONE: u32 = 0xffff_ffff;
|
||||
|
||||
/// The node's vertices that make triangle 0-3, by the triangle's own
|
||||
/// vertex numbers 0-2.
|
||||
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
|
||||
|
||||
/// Descriptor dword 1: boxes are returned nearest first.
|
||||
pub const BOX_SORT: u32 = 1 << 31;
|
||||
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
|
||||
/// a triangle id and a hit status, which nothing here produces).
|
||||
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
|
||||
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
|
||||
/// structure.
|
||||
pub const DESCRIPTOR_TYPE: u32 = 8;
|
||||
|
||||
/// The ray as the instruction takes it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub extent: f32,
|
||||
pub origin: [f32; 3],
|
||||
pub direction: [f32; 3],
|
||||
/// What the program computed as `1 / direction`.
|
||||
pub inverse: [f32; 3],
|
||||
}
|
||||
|
||||
impl Ray {
|
||||
/// A ray with the inverse direction a program computes by division.
|
||||
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
|
||||
Self {
|
||||
extent,
|
||||
origin,
|
||||
direction,
|
||||
inverse: direction.map(|d| 1.0 / d),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of the node a pointer names.
|
||||
pub fn kind(pointer: u64) -> u32 {
|
||||
(pointer & 7) as u32
|
||||
}
|
||||
|
||||
/// The byte address of the node `pointer` names, for a descriptor whose
|
||||
/// first two dwords are `word0` and `word1`.
|
||||
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
|
||||
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
|
||||
base.wrapping_add((pointer >> 3) << 6)
|
||||
}
|
||||
|
||||
/// What the instruction returns for the node at `words` (its first 28
|
||||
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
|
||||
/// of this `kind`, with box sorting as `sort` says and the triangle return
|
||||
/// mode set.
|
||||
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
match kind & 7 {
|
||||
4 => boxes(&children(words), &boxes16(words), ray, sort),
|
||||
5 => boxes(&children(words), &boxes32(words), ray, sort),
|
||||
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
|
||||
_ => MISS.map(f32::to_bits),
|
||||
}
|
||||
}
|
||||
|
||||
/// A box node's four child pointers.
|
||||
pub fn children(words: &[u32; 28]) -> [u32; 4] {
|
||||
[words[0], words[1], words[2], words[3]]
|
||||
}
|
||||
|
||||
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
|
||||
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| {
|
||||
std::array::from_fn(|k| {
|
||||
let half = 6 * b + k;
|
||||
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The four boxes of a 32-bit box node.
|
||||
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
|
||||
}
|
||||
|
||||
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
|
||||
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
|
||||
/// 0x042).
|
||||
pub fn vertex_map(k: u32) -> u32 {
|
||||
let v = TRIANGLE_VERTICES[(k & 3) as usize];
|
||||
v[0] | v[1] << 4 | v[2] << 8
|
||||
}
|
||||
|
||||
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
|
||||
/// the one neither barycentric weighs, then I's, then J's.
|
||||
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
|
||||
let id = words[15] >> (8 * k);
|
||||
let (i, j) = (id & 3, id >> 2 & 3);
|
||||
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
|
||||
// what this arithmetic lands on (a vertex of the node), as the emitted
|
||||
// code does.
|
||||
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
|
||||
[first, i, j].map(|n| {
|
||||
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
|
||||
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
|
||||
})
|
||||
}
|
||||
|
||||
/// The box test: child pointers of the boxes the ray enters, `NONE` for
|
||||
/// the others; sorted by entry distance when `sort`, in child order
|
||||
/// otherwise.
|
||||
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
// An infinite inverse (a direction component of 0) would turn an
|
||||
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
|
||||
// the emitted code: a NaN becomes the lower bound, where `clamp` would
|
||||
// keep it.)
|
||||
#[allow(clippy::manual_clamp)]
|
||||
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
|
||||
let mut ids = [NONE; 4];
|
||||
let mut distances = [f32::INFINITY; 4];
|
||||
for (n, b) in boxes.iter().enumerate() {
|
||||
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
|
||||
for a in 0..3 {
|
||||
let low = (b[a] - ray.origin[a]) * inverse[a];
|
||||
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
|
||||
near[a] = low.min(high);
|
||||
far[a] = low.max(high);
|
||||
}
|
||||
let enter = near[0].max(near[1]).max(near[2]);
|
||||
let leave = far[0].min(far[1]).min(far[2]);
|
||||
// A box whose minimum x is NaN is switched off.
|
||||
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
|
||||
ids[n] = children[n];
|
||||
distances[n] = enter;
|
||||
}
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
if distances[b] < distances[a] {
|
||||
distances.swap(a, b);
|
||||
ids.swap(a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// What a triangle the ray misses returns.
|
||||
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
|
||||
|
||||
/// The triangle test: the hit distance's numerator, the denominator, and
|
||||
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
|
||||
/// Watertight: the vertices are sheared so the ray runs along its largest
|
||||
/// axis, and the signs of the three edge functions decide, so a ray
|
||||
/// between two triangles that share an edge cannot miss both. Any NaN
|
||||
/// misses, and so does a triangle seen edge-on.
|
||||
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
|
||||
let d = ray.direction;
|
||||
let size = d.map(f32::abs);
|
||||
// The largest axis, and the other two in an order that keeps the
|
||||
// triangle's winding.
|
||||
let kz = if size[0] >= size[1] {
|
||||
if size[0] >= size[2] { 0 } else { 2 }
|
||||
} else if size[1] >= size[2] {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
|
||||
if d[kz] < 0.0 {
|
||||
std::mem::swap(&mut kx, &mut ky);
|
||||
}
|
||||
let sz = ray.inverse[kz];
|
||||
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
|
||||
let sheared = |v: &[f32; 3]| {
|
||||
let r = [
|
||||
v[0] - ray.origin[0],
|
||||
v[1] - ray.origin[1],
|
||||
v[2] - ray.origin[2],
|
||||
];
|
||||
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
|
||||
};
|
||||
let (ax, ay, az) = sheared(&p[0]);
|
||||
let (bx, by, bz) = sheared(&p[1]);
|
||||
let (cx, cy, cz) = sheared(&p[2]);
|
||||
let u = cx * by - cy * bx;
|
||||
let v = ax * cy - ay * cx;
|
||||
let w = bx * ay - by * ax;
|
||||
let behind = u < 0.0 || v < 0.0 || w < 0.0;
|
||||
let before = u > 0.0 || v > 0.0 || w > 0.0;
|
||||
let det = u + (v + w);
|
||||
let t = (u * az + v * bz) + w * cz;
|
||||
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
|
||||
if !(behind && before) && ahead {
|
||||
[t, det, v, w]
|
||||
} else {
|
||||
MISS
|
||||
}
|
||||
}
|
||||
|
||||
/// A 16-bit float as a 32-bit one (exact).
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
let sign = u32::from(h >> 15) << 31;
|
||||
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
|
||||
let bits = match exponent {
|
||||
0 if mantissa == 0 => sign,
|
||||
0 => {
|
||||
// Subnormal: normalise.
|
||||
let shift = mantissa.leading_zeros() - 21;
|
||||
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
|
||||
}
|
||||
0x1f => sign | 0xff << 23 | mantissa << 13,
|
||||
e => sign | (e + 112) << 23 | mantissa << 13,
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The smallest 16-bit float not below `x` (`up`) or not above it.
|
||||
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
|
||||
let mut best: Option<u16> = None;
|
||||
for h in 0..=0xffffu16 {
|
||||
let f = half_to_f32(h);
|
||||
if f.is_nan() || if up { f < x } else { f > x } {
|
||||
continue;
|
||||
}
|
||||
best = match best {
|
||||
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
|
||||
_ => Some(h),
|
||||
};
|
||||
}
|
||||
best.expect("a half")
|
||||
}
|
||||
|
||||
/// A 32-bit box node.
|
||||
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
w[4 + 6 * b + k] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A 16-bit box node holding `boxes` rounded outward.
|
||||
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
let half = 6 * b + k;
|
||||
let h = if x.is_nan() {
|
||||
0x7e00
|
||||
} else {
|
||||
f32_to_half(*x, k >= 3)
|
||||
};
|
||||
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A triangle node: up to five vertices, and the dword at byte 60.
|
||||
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
for (n, v) in vertices.iter().enumerate() {
|
||||
for (c, x) in v.iter().enumerate() {
|
||||
w[3 * n + c] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w[15] = id;
|
||||
w
|
||||
}
|
||||
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
|
||||
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
|
||||
std::array::from_fn(|k| b[k] + by[k % 3])
|
||||
}
|
||||
|
||||
const OFF: [f32; 6] = [f32::NAN; 6];
|
||||
|
||||
#[test]
|
||||
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
|
||||
// The 64-bit form as the title uses it: base 0, the structure's
|
||||
// address folded into the pointer.
|
||||
let structure = 0x12_3456_7800u64;
|
||||
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
|
||||
assert_eq!(kind(pointer), 5);
|
||||
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
|
||||
// The 32-bit form: the base in the descriptor.
|
||||
let word0 = (structure >> 8) as u32;
|
||||
let word1 = (structure >> 40) as u32 | BOX_SORT;
|
||||
assert_eq!(
|
||||
node_address(word0, word1, 0x1000 >> 3 | 4),
|
||||
structure + 0x1000
|
||||
);
|
||||
// A base past 4 GiB of 256-byte units.
|
||||
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halves_convert_exactly() {
|
||||
assert_eq!(half_to_f32(0x3c00), 1.0);
|
||||
assert_eq!(half_to_f32(0xc000), -2.0);
|
||||
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
|
||||
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x7bff), 65504.0);
|
||||
assert!(half_to_f32(0x7e00).is_nan());
|
||||
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
|
||||
// Outward rounding of the test helper.
|
||||
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
|
||||
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boxes_are_returned_nearest_first_and_misses_last() {
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
|
||||
let node = box32(
|
||||
children,
|
||||
[
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
// Without sorting: child order, the miss in its place.
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &ray, false),
|
||||
[0x105, 0x20c, NONE, 0x400]
|
||||
);
|
||||
// The extent cuts the far ones off (entered at 9, 19, 29).
|
||||
let short = Ray {
|
||||
extent: 19.5,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &short, true),
|
||||
[0x20c, 0x400, NONE, NONE]
|
||||
);
|
||||
// An entry exactly at the extent is no hit.
|
||||
let exact = Ray {
|
||||
extent: 19.0,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
|
||||
// Backwards: nothing.
|
||||
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
|
||||
let node = box32(
|
||||
[8, 16, NONE, NONE],
|
||||
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
|
||||
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
|
||||
// Even with a tiny extent the box around the origin is a hit.
|
||||
let tiny = Ray {
|
||||
extent: 1e-6,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
|
||||
// Direction components of 0: the inverse is infinite.
|
||||
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert!(ray.inverse[1].is_infinite());
|
||||
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
|
||||
// would be a NaN; with the inverse held finite it is 0, and the ray
|
||||
// running along the face is inside.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
// Along the +y face it is outside: the face's plane is left at 0
|
||||
// and the box is entered at 4 (as the public emulation has it).
|
||||
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
|
||||
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
|
||||
// -0 gives -infinity.
|
||||
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
|
||||
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
|
||||
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_switched_off_and_a_missing_child_return_none() {
|
||||
let node = box32(
|
||||
[8, NONE, 24, 32],
|
||||
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
|
||||
);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
// Child 1 is hit but is not there: its pointer is what "none" is.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_distances_keep_child_order() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT; 4]);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_float_boxes_test_like_their_widened_values() {
|
||||
let boxes = [
|
||||
moved(UNIT, [30.0, 0.1, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.3]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.7, 0.0, 0.0]),
|
||||
];
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
let node = box16(children, boxes);
|
||||
let wide = boxes16(&node);
|
||||
for (w, b) in wide.iter().zip(&boxes) {
|
||||
for k in 0..3 {
|
||||
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
|
||||
}
|
||||
}
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
assert_eq!(
|
||||
intersect(&node, 4, &ray, true),
|
||||
intersect(&box32(children, wide), 5, &ray, true)
|
||||
);
|
||||
}
|
||||
|
||||
/// The hit a result describes: distance, I, J, front face.
|
||||
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
|
||||
let [t, det, i, j] = r.map(f32::from_bits);
|
||||
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
|
||||
}
|
||||
|
||||
/// Clockwise seen from the origin looking down +z in a left-handed
|
||||
/// system (x right, y up): the front face.
|
||||
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
|
||||
#[test]
|
||||
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!(t, 5.0);
|
||||
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
|
||||
assert_eq!((i, j), (0.25, 0.25));
|
||||
assert!(front);
|
||||
// Near vertex 1: I near 1.
|
||||
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert!(i > 0.85 && j < 0.1, "{i} {j}");
|
||||
// From behind: the same weights, the back face.
|
||||
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
|
||||
// An unnormalised direction: the distance is in its units.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
|
||||
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triangle_is_missed_beside_behind_and_edge_on() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let miss = MISS.map(f32::to_bits);
|
||||
// Beside it.
|
||||
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// It lies behind the origin.
|
||||
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// In its plane.
|
||||
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// A triangle with no area.
|
||||
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
|
||||
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&flat, 0, &ray, true), miss);
|
||||
// A vertex that is not a number, a direction of zero.
|
||||
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&nan, 0, &ray, true), miss);
|
||||
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &still, true), miss);
|
||||
// The extent is the program's to test: a far triangle is a hit.
|
||||
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
|
||||
assert!(hit(intersect(&node, 0, &short, true)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
|
||||
// Two triangles of a quad sharing the diagonal, wound alike.
|
||||
let quad = [
|
||||
[-1.0, -1.0, 4.0],
|
||||
[-1.0, 1.0, 4.0],
|
||||
[1.0, 1.0, 4.0],
|
||||
[1.0, -1.0, 4.0],
|
||||
];
|
||||
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
|
||||
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
|
||||
// A fan of rays crossing the diagonal, some exactly on it.
|
||||
for n in -40..=40 {
|
||||
let x = n as f32 / 64.0;
|
||||
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
|
||||
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
|
||||
// Aim at (ox, oy, 4).
|
||||
let s = 4.0 / d[2];
|
||||
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
|
||||
let a = hit(intersect(&first, 0, &ray, true));
|
||||
let b = hit(intersect(&second, 0, &ray, true));
|
||||
assert!(
|
||||
a.is_some() || b.is_some(),
|
||||
"a hole at {ox} {oy} along {d:?}"
|
||||
);
|
||||
for h in [a, b].into_iter().flatten() {
|
||||
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
|
||||
// What the title's builder does with an input triangle (a, b, c)
|
||||
// and an id byte: a at the vertex neither field names, b at I's,
|
||||
// c at J's.
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
|
||||
let mut stored = [[0f32; 3]; 3];
|
||||
stored[(3 - i - j) as usize] = a;
|
||||
stored[i as usize] = b;
|
||||
stored[j as usize] = c;
|
||||
let node = triangles(&stored, i | j << 2);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
|
||||
}
|
||||
// The higher bits of the byte (opaque and the like) change nothing.
|
||||
let node = triangles(&[a, b, c], 9 | 0x80);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let far = [50.0, 50.0, 50.0];
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for k in 1..4u32 {
|
||||
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
|
||||
let mut vertices = [far; 5];
|
||||
let at = TRIANGLE_VERTICES[k as usize];
|
||||
vertices[at[0] as usize] = a;
|
||||
vertices[at[1] as usize] = b;
|
||||
vertices[at[2] as usize] = c;
|
||||
// Triangle 0's byte would be malformed here; only byte k counts.
|
||||
let node = triangles(&vertices, 9 << (8 * k));
|
||||
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
|
||||
}
|
||||
// A pair as the title's builder stores it: the second triangle's
|
||||
// own vertex at node vertex 3, named by I.
|
||||
let d = [2.0, 2.0, 5.0];
|
||||
// Input triangles (a, b, c) and (a, d, b): they share a and b.
|
||||
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
|
||||
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
|
||||
let got = triangle_vertices(&node, 1);
|
||||
assert_eq!(got, [b, d, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_and_procedural_nodes_return_a_triangle_miss() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
for k in [6, 7] {
|
||||
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
|
||||
// The same triangle and ray turned so the ray's largest axis is each
|
||||
// of the three, forwards and backwards. Both turns are rotations,
|
||||
// so the facing stays.
|
||||
let turn = |v: [f32; 3], axis: usize, flip: bool| {
|
||||
let mut r = v;
|
||||
for _ in 0..axis {
|
||||
r = [r[2], r[0], r[1]];
|
||||
}
|
||||
if flip {
|
||||
// Half a turn about the axis after the largest one's next.
|
||||
let largest = (2 + axis) % 3;
|
||||
r[largest] = -r[largest];
|
||||
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
|
||||
}
|
||||
r
|
||||
};
|
||||
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
|
||||
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
|
||||
for axis in 0..3 {
|
||||
for flip in [false, true] {
|
||||
let p = TRIANGLE.map(|v| turn(v, axis, flip));
|
||||
let r = Ray::new(
|
||||
turn(ray.origin, axis, flip),
|
||||
turn(ray.direction, axis, flip),
|
||||
100.0,
|
||||
);
|
||||
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
|
||||
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
|
||||
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
|
||||
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ impl SigElement {
|
||||
18 => 68,
|
||||
19 => 67,
|
||||
20 => 69,
|
||||
28 => 23, // barycentrics
|
||||
30 => 25, // cull primitive
|
||||
_ => 0,
|
||||
}
|
||||
@@ -114,10 +115,27 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The most a mesh shader's outputs may take, in bytes (D3D12).
|
||||
pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024;
|
||||
|
||||
/// A mesh shader's output size as the DXIL validator measures it against
|
||||
/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element
|
||||
/// and primitive element, times the maxima rounded up to multiples of 32.
|
||||
pub(crate) fn mesh_output_bytes(
|
||||
vertex: &[SigElement],
|
||||
primitive: &[SigElement],
|
||||
max_vertices: u32,
|
||||
max_primitives: u32,
|
||||
) -> u64 {
|
||||
let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>();
|
||||
let align = |n: u32| u64::from(n).next_multiple_of(32);
|
||||
4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives))
|
||||
}
|
||||
|
||||
/// A resource bound by register, as `PSV0` lists it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Binding {
|
||||
/// PSV resource type: 1 sampler, 2 CBV.
|
||||
/// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV.
|
||||
pub kind: u32,
|
||||
pub space: u32,
|
||||
pub register: u32,
|
||||
@@ -126,7 +144,7 @@ pub(crate) struct Binding {
|
||||
}
|
||||
|
||||
pub(crate) struct Psv<'a> {
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute.
|
||||
pub stage: u8,
|
||||
/// Vertex: writes `SV_Position`. Pixel: writes depth.
|
||||
pub flag: bool,
|
||||
@@ -136,6 +154,9 @@ pub(crate) struct Psv<'a> {
|
||||
pub prims: &'a [SigElement],
|
||||
/// Mesh: its state and the group-shared bytes it declares.
|
||||
pub mesh: Option<(super::shader::Mesh, u32)>,
|
||||
/// Geometry (triangles in, triangle strips out on stream 0): its
|
||||
/// maximum vertex count. `flag`: writes `SV_Position`.
|
||||
pub geometry: Option<u32>,
|
||||
pub bindings: &'a [Binding],
|
||||
/// Compute: thread-group size and required wave size.
|
||||
pub threads: [u32; 3],
|
||||
@@ -189,6 +210,15 @@ pub(crate) fn psv(p: &Psv) -> Vec<u8> {
|
||||
info[27] = mesh.topology;
|
||||
info[30] = p.prims.len() as u8;
|
||||
}
|
||||
if let Some(max_vertices) = p.geometry {
|
||||
// Input primitive (3: triangles), output topology (5: triangle
|
||||
// strips), stream mask, position written; the vertex maximum.
|
||||
info[0..4].copy_from_slice(&3u32.to_le_bytes());
|
||||
info[4..8].copy_from_slice(&5u32.to_le_bytes());
|
||||
info[8..12].copy_from_slice(&1u32.to_le_bytes());
|
||||
info[12] = u8::from(p.flag);
|
||||
info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes());
|
||||
}
|
||||
out.extend(info);
|
||||
u32s(&mut out, &[p.bindings.len() as u32]);
|
||||
if !p.bindings.is_empty() {
|
||||
|
||||
@@ -68,6 +68,16 @@ impl Host {
|
||||
let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1");
|
||||
// SAFETY: plain D3D12/DXGI calls with valid out pointers.
|
||||
unsafe {
|
||||
// `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a
|
||||
// refused pipeline's error then carries.
|
||||
if std::env::var_os("VICTORY_D3D12_DEBUG").is_some() {
|
||||
let mut debug: Option<ID3D12Debug> = None;
|
||||
if D3D12GetDebugInterface(&mut debug).is_ok()
|
||||
&& let Some(debug) = debug
|
||||
{
|
||||
debug.EnableDebugLayer();
|
||||
}
|
||||
}
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
if warp {
|
||||
let factory: IDXGIFactory4 =
|
||||
@@ -132,21 +142,23 @@ impl Host {
|
||||
ShaderVisibility: vis,
|
||||
})
|
||||
.collect();
|
||||
let mut views: Vec<(u8, bool)> = stages
|
||||
// By slot, then kind: 0 CBV, 1 SRV, 2 UAV.
|
||||
let mut views: Vec<(u8, u8)> = stages
|
||||
.iter()
|
||||
.flat_map(|(s, _)| {
|
||||
let cbvs = s.root_cbvs.iter().map(|&r| (r, false));
|
||||
cbvs.chain(s.root_srvs.iter().map(|&r| (r, true)))
|
||||
let cbvs = s.root_cbvs.iter().map(|&r| (r, 0));
|
||||
let srvs = s.root_srvs.iter().map(|&r| (r, 1));
|
||||
cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2)))
|
||||
})
|
||||
.collect();
|
||||
views.sort_unstable();
|
||||
views.dedup();
|
||||
for (slot, srv) in views {
|
||||
for (slot, kind) in views {
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: if srv {
|
||||
D3D12_ROOT_PARAMETER_TYPE_SRV
|
||||
} else {
|
||||
D3D12_ROOT_PARAMETER_TYPE_CBV
|
||||
ParameterType: match kind {
|
||||
1 => D3D12_ROOT_PARAMETER_TYPE_SRV,
|
||||
2 => D3D12_ROOT_PARAMETER_TYPE_UAV,
|
||||
_ => D3D12_ROOT_PARAMETER_TYPE_CBV,
|
||||
},
|
||||
Anonymous: D3D12_ROOT_PARAMETER1_0 {
|
||||
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
|
||||
@@ -233,7 +245,34 @@ impl Host {
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the description points at live data.
|
||||
unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(err)
|
||||
unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e))
|
||||
}
|
||||
|
||||
/// The error with the debug layer's messages since the last call, if
|
||||
/// the layer is on (`VICTORY_D3D12_DEBUG`).
|
||||
fn explained(&self, e: windows::core::Error) -> String {
|
||||
let mut text = err(e);
|
||||
let Ok(queue) = self.device.cast::<ID3D12InfoQueue>() else {
|
||||
return text;
|
||||
};
|
||||
// SAFETY: each message is read into a buffer of the size the queue
|
||||
// asks for, aligned for the message header.
|
||||
unsafe {
|
||||
for i in 0..queue.GetNumStoredMessages() {
|
||||
let mut len = 0usize;
|
||||
let _ = queue.GetMessage(i, None, &mut len);
|
||||
let mut buffer = vec![0u64; len.div_ceil(8)];
|
||||
let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
|
||||
if queue.GetMessage(i, Some(message), &mut len).is_ok() {
|
||||
let m = &*message;
|
||||
let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1));
|
||||
text.push_str(" | ");
|
||||
text.push_str(&String::from_utf8_lossy(bytes));
|
||||
}
|
||||
}
|
||||
queue.ClearStoredMessages();
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A graphics pipeline from a vertex and a pixel shader, with float or
|
||||
@@ -255,6 +294,18 @@ impl Host {
|
||||
root: &ID3D12RootSignature,
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
) -> Result<ID3D12PipelineState, String> {
|
||||
self.pipeline_with_gs(root, vs, None, ps)
|
||||
}
|
||||
|
||||
/// As [`Host::pipeline_with`], with a geometry shader between the two
|
||||
/// (the rectangle stage, `rect_list_gs`).
|
||||
pub fn pipeline_with_gs(
|
||||
&self,
|
||||
root: &ID3D12RootSignature,
|
||||
vs: &[u8],
|
||||
gs: Option<&[u8]>,
|
||||
ps: &[u8],
|
||||
) -> Result<ID3D12PipelineState, String> {
|
||||
let inputs = sig(vs, FourCC::ISG1)?;
|
||||
let names: Vec<CString> = inputs
|
||||
@@ -287,6 +338,10 @@ impl Host {
|
||||
pShaderBytecode: ps.as_ptr().cast(),
|
||||
BytecodeLength: ps.len(),
|
||||
},
|
||||
GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: gs.as_ptr().cast(),
|
||||
BytecodeLength: gs.len(),
|
||||
}),
|
||||
SampleMask: u32::MAX,
|
||||
RasterizerState: D3D12_RASTERIZER_DESC {
|
||||
FillMode: D3D12_FILL_MODE_SOLID,
|
||||
@@ -528,6 +583,8 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
//! The console's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
|
||||
//! that tests one ray against one node of the title's own structures.
|
||||
//!
|
||||
//! [`crate::bvh`] says what the instruction computes and is the reference:
|
||||
//! the code made here does the same float operations in the same order
|
||||
//! (DXIL float operations carry no fast-math flags, so the host may not
|
||||
//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
|
||||
//! the card against the reference.
|
||||
//!
|
||||
//! The title's nodes are in title memory, named by address: they are read
|
||||
//! through the host's copies of title memory ([`Lower::memory`]), one look
|
||||
//! in its directory per node (two for a 128-byte box node).
|
||||
//!
|
||||
//! Shape of the code, under the instruction's lane guard:
|
||||
//!
|
||||
//! ```text
|
||||
//! kind = pointer & 7
|
||||
//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
|
||||
//! four slab tests; the sorting network
|
||||
//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
|
||||
//! other (6, 7): a triangle miss
|
||||
//! ```
|
||||
//!
|
||||
//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
|
||||
//! box node, 16 for a 16-bit one, 10 for a triangle.
|
||||
|
||||
use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
|
||||
use crate::bvh;
|
||||
use crate::resource::BvhNodes;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
|
||||
/// heap slot holding a raw buffer, and the title address of its first
|
||||
/// byte. (The card tests have no host to keep copies of title memory
|
||||
/// and their directory.)
|
||||
pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
|
||||
const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Where the instruction's node is.
|
||||
#[derive(Clone, Copy)]
|
||||
enum NodeAt {
|
||||
/// At this byte of a raw buffer of the host.
|
||||
Buffer { handle: V, byte: V },
|
||||
/// In title memory: the raw view of the host copy holding the node's
|
||||
/// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
|
||||
/// and the node's address, for the second half of a 128-byte node.
|
||||
Memory { handle: V, byte: V, low: V, high: V },
|
||||
}
|
||||
|
||||
/// The ray operands, as floats.
|
||||
struct Ray {
|
||||
extent: V,
|
||||
origin: [V; 3],
|
||||
direction: [V; 3],
|
||||
inverse: [V; 3],
|
||||
}
|
||||
|
||||
impl<'a> Lower<'a> {
|
||||
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
|
||||
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
|
||||
let Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
dmask,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
..
|
||||
} = &inst.fields
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
|
||||
return Err("a ray-tracing node test with 16-bit operands or a partial result");
|
||||
}
|
||||
let wide = inst.name() == "image_bvh64_intersect_ray";
|
||||
// Operand VGPRs in order: the node pointer (two dwords in the
|
||||
// 64-bit form), the ray's extent, origin, direction and inverse
|
||||
// direction.
|
||||
let mut regs = Vec::new();
|
||||
for a in addr {
|
||||
if let Operand::Vector { reg, dwords } = *a {
|
||||
regs.extend((0..dwords).map(|k| reg + k));
|
||||
}
|
||||
}
|
||||
if regs.len() != if wide { 12 } else { 11 } {
|
||||
return Err("a ray-tracing node test's operands");
|
||||
}
|
||||
let Operand::Vector { reg: dst, .. } = *data else {
|
||||
return Err("a ray-tracing node test's result");
|
||||
};
|
||||
let site = (b, i);
|
||||
let nodes = self
|
||||
.x
|
||||
.res
|
||||
.bvh
|
||||
.iter()
|
||||
.find(|n| n.0 == site)
|
||||
.map(|n| n.1)
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let (sort, barycentrics) = match nodes {
|
||||
BvhNodes::Resource => (true, true),
|
||||
BvhNodes::Memory { word1, word3 } => (
|
||||
word1 & bvh::BOX_SORT != 0,
|
||||
word3 & bvh::RETURN_BARYCENTRICS != 0,
|
||||
),
|
||||
};
|
||||
if !barycentrics {
|
||||
// Mode 0 returns a triangle id and a hit status in the last two
|
||||
// dwords; no program of the title asks for it.
|
||||
return Err("a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
let guard = self.guard(b, i)?;
|
||||
let mut x = Vec::with_capacity(regs.len());
|
||||
for &r in ®s {
|
||||
let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
|
||||
x.push(self.i32_of(v)?);
|
||||
}
|
||||
let pointer = x[0];
|
||||
let pointer_high = wide.then(|| x[1]);
|
||||
let f: Vec<V> = x[1 + usize::from(wide)..]
|
||||
.iter()
|
||||
.map(|&v| self.as_float(v))
|
||||
.collect();
|
||||
let ray = Ray {
|
||||
extent: f[0],
|
||||
origin: [f[1], f[2], f[3]],
|
||||
direction: [f[4], f[5], f[6]],
|
||||
inverse: [f[7], f[8], f[9]],
|
||||
};
|
||||
let c = self.cur;
|
||||
let at = match nodes {
|
||||
BvhNodes::Resource => {
|
||||
let src = self
|
||||
.descriptors
|
||||
.get(&(site, false))
|
||||
.copied()
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let handle = self.handle(site, src, false, (11, 0))?;
|
||||
// (pointer >> 3) << 6 from the buffer's start.
|
||||
let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
|
||||
let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
|
||||
let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
|
||||
NodeAt::Buffer { handle, byte }
|
||||
}
|
||||
BvhNodes::Memory { .. } => {
|
||||
let Operand::Scalar { code, .. } = *rsrc else {
|
||||
return Err("a ray-tracing structure descriptor not in SGPRs");
|
||||
};
|
||||
let mut words = [pointer; 2];
|
||||
for (k, w) in words.iter_mut().enumerate() {
|
||||
let v = inst
|
||||
.read(Reg::S(code + k as u8))
|
||||
.ok_or("an unread operand")?;
|
||||
*w = self.i32_of(v)?;
|
||||
}
|
||||
let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
|
||||
// One look for the node's copy, before the branches: a
|
||||
// node is 64 bytes on 64, so its first half lies in one
|
||||
// 64 KiB page whatever its kind.
|
||||
let (handle, byte) = self.bvh_memory(low, high, guard);
|
||||
NodeAt::Memory {
|
||||
handle,
|
||||
byte,
|
||||
low,
|
||||
high,
|
||||
}
|
||||
}
|
||||
};
|
||||
let zero = self.s.m.i32(0);
|
||||
let gate = self.begin_guarded(guard);
|
||||
let head = self.cur;
|
||||
let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
|
||||
let kind = self.s.m.bin(head, Bin::And, pointer, k7);
|
||||
let pair = self.s.m.bin(head, Bin::And, pointer, k6);
|
||||
let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
|
||||
let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
|
||||
let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(is_box, box_block, leaf_block));
|
||||
self.s
|
||||
.m
|
||||
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
|
||||
self.cur = box_block;
|
||||
let boxes = self.bvh_boxes(at, kind, &ray, sort);
|
||||
let box_end = self.cur;
|
||||
self.s.m.terminate(box_end, Term::Br(join));
|
||||
self.cur = triangle_block;
|
||||
let triangle = self.bvh_triangle(at, kind, &ray);
|
||||
let triangle_end = self.cur;
|
||||
self.s.m.terminate(triangle_end, Term::Br(join));
|
||||
self.cur = join;
|
||||
// Kinds 6 and 7 (an instance, a procedural primitive): not known
|
||||
// what the console returns; the title's programs do not read it.
|
||||
let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
|
||||
let i32t = self.s.t.i32;
|
||||
let mut results = Vec::with_capacity(4);
|
||||
for k in 0..4 {
|
||||
let phi = self.s.m.phi(join, i32t);
|
||||
self.s.m.set_phi(
|
||||
phi,
|
||||
vec![
|
||||
(boxes[k], box_end),
|
||||
(triangle[k], triangle_end),
|
||||
(other[k], leaf_block),
|
||||
],
|
||||
);
|
||||
results.push((phi, zero));
|
||||
}
|
||||
let results = self.end_guarded(gate, &results);
|
||||
for (k, &r) in results.iter().enumerate() {
|
||||
self.write(inst, Reg::V(dst + k as u8), r, guard);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Title memory at `low`/`high` for a node's bytes: the raw view of the
|
||||
/// host copy holding the address and the byte in that view
|
||||
/// ([`Lower::memory`]: a page the host has no copy of reads zeros and
|
||||
/// is left for the host to fetch, for lanes that run).
|
||||
fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
|
||||
#[cfg(test)]
|
||||
if let Some((slot, base)) = TEST_MEMORY.get() {
|
||||
// The buffer at heap slot `slot` holds the bytes from title
|
||||
// address `base` on; any other address reads past its end,
|
||||
// which is zeros.
|
||||
let c = self.cur;
|
||||
let slot = self.s.m.i32(slot);
|
||||
let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
|
||||
let (base_low, base_high) =
|
||||
(self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
|
||||
let at = self.s.m.bin(c, Bin::Sub, low, base_low);
|
||||
let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
|
||||
let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
|
||||
let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
|
||||
let outside = self.s.m.i32(0xffff_ff00);
|
||||
let at = self.s.m.select(c, inside, at, outside);
|
||||
return (handle, at);
|
||||
}
|
||||
self.memory(low, high, guard)
|
||||
}
|
||||
|
||||
/// `count` dwords of the node from its byte `base` + `offset` (`base`
|
||||
/// computed, `offset` fixed; none of the node's bytes past 127), read
|
||||
/// four at a time.
|
||||
fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
|
||||
let c = self.cur;
|
||||
let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
|
||||
// The second half of a 128-byte node may lie in the next 64 KiB
|
||||
// page, which may be in another copy: its own look, made once.
|
||||
let mut second = None;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for start in (0..count).step_by(4) {
|
||||
let n = (count - start).min(4);
|
||||
let node_byte = offset + 4 * start;
|
||||
let (handle, mut byte) = match at {
|
||||
NodeAt::Buffer { handle, byte } => (handle, byte),
|
||||
NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
|
||||
NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
|
||||
let (low, high) = self.address_plus(low, high, 64);
|
||||
// Every lane in this block runs the instruction.
|
||||
let (handle, byte) = self.bvh_memory(low, high, None);
|
||||
let k64 = self.s.m.i32(64);
|
||||
(handle, self.s.m.bin(c, Bin::Sub, byte, k64))
|
||||
}),
|
||||
};
|
||||
if let Some(b) = base {
|
||||
byte = self.s.m.bin(c, Bin::Add, byte, b);
|
||||
}
|
||||
let k = self.s.m.i32(node_byte);
|
||||
let byte = self.s.m.bin(c, Bin::Add, byte, k);
|
||||
let mask = self.s.m.i8((1u8 << n) - 1);
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"rawBufferLoad.f32",
|
||||
Attr::ReadOnly,
|
||||
self.s.t.res_ret,
|
||||
139,
|
||||
&[handle, byte, undef, mask, align],
|
||||
);
|
||||
for k in 0..n {
|
||||
let f = self.s.m.extract(c, r, k);
|
||||
out.push(self.as_int(f));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node's title address, [`bvh::node_address`]: the descriptor's
|
||||
/// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
|
||||
/// `(pointer >> 3) << 6`.
|
||||
fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
|
||||
let c = self.cur;
|
||||
let i64t = self.s.m.int(64);
|
||||
let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
|
||||
let base_high = self.s.m.bin(c, Bin::And, word1, byte);
|
||||
let base = self.join64(word0, base_high);
|
||||
let k8 = self.s.m.int_const(i64t, 8);
|
||||
let base = self.s.m.bin(c, Bin::Shl, base, k8);
|
||||
let p = self.join64(pointer, pointer_high.unwrap_or(zero));
|
||||
let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
|
||||
let p = self.s.m.bin(c, Bin::LShr, p, k3);
|
||||
let p = self.s.m.bin(c, Bin::Shl, p, k6);
|
||||
let a = self.s.m.bin(c, Bin::Add, base, p);
|
||||
self.s.flags |= flags::INT64;
|
||||
self.split64(a)
|
||||
}
|
||||
|
||||
/// The box test ([`bvh::boxes`]): four result dwords. Starts in the
|
||||
/// current block and leaves `self.cur` at the block it ends in.
|
||||
fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
|
||||
let head = self.cur;
|
||||
let children = self.bvh_node_words(at, None, 0, 4);
|
||||
let k5 = self.s.m.i32(5);
|
||||
let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
|
||||
let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let join = self.s.m.new_block();
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(wide, wide_block, half_block));
|
||||
// 32-bit floats: 24 dwords from byte 16.
|
||||
self.cur = wide_block;
|
||||
let k16 = self.s.m.i32(16);
|
||||
let words = self.bvh_node_words(at, None, 16, 24);
|
||||
let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
|
||||
self.s.m.terminate(wide_block, Term::Br(join));
|
||||
// 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
|
||||
// of a dword first.
|
||||
self.cur = half_block;
|
||||
let words = self.bvh_node_words(at, None, 16, 12);
|
||||
let f32t = self.s.t.f32;
|
||||
let mut halves = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let mut h = words[n / 2];
|
||||
if n % 2 == 1 {
|
||||
h = self.s.m.bin(half_block, Bin::LShr, h, k16);
|
||||
}
|
||||
// The conversion reads the low 16 bits.
|
||||
halves.push(self.s.op(
|
||||
half_block,
|
||||
"legacyF16ToF32",
|
||||
Attr::ReadNone,
|
||||
f32t,
|
||||
131,
|
||||
&[h],
|
||||
));
|
||||
}
|
||||
self.s.m.terminate(half_block, Term::Br(join));
|
||||
self.cur = join;
|
||||
let mut coords = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let phi = self.s.m.phi(join, f32t);
|
||||
self.s
|
||||
.m
|
||||
.set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
|
||||
coords.push(phi);
|
||||
}
|
||||
// The inverse direction held finite ([`bvh::boxes`]).
|
||||
let (most, least) = (
|
||||
self.s.m.f32(f32::MAX.to_bits()),
|
||||
self.s.m.f32((-f32::MAX).to_bits()),
|
||||
);
|
||||
let inverse = ray.inverse.map(|x| {
|
||||
let x = self.binary(35, x, least);
|
||||
self.binary(36, x, most)
|
||||
});
|
||||
let c = join;
|
||||
let (none, infinity, fzero) = (
|
||||
self.s.m.i32(bvh::NONE),
|
||||
self.s.m.f32(f32::INFINITY.to_bits()),
|
||||
self.s.m.f32(0),
|
||||
);
|
||||
let mut ids = [none; 4];
|
||||
let mut distances = [infinity; 4];
|
||||
for n in 0..4 {
|
||||
let bx = &coords[6 * n..6 * n + 6];
|
||||
let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
|
||||
for a in 0..3 {
|
||||
let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
|
||||
let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
|
||||
let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
|
||||
let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
|
||||
near[a] = self.binary(36, low, high);
|
||||
far[a] = self.binary(35, low, high);
|
||||
}
|
||||
let enter = self.binary(35, near[0], near[1]);
|
||||
let enter = self.binary(35, enter, near[2]);
|
||||
let leave = self.binary(36, far[0], far[1]);
|
||||
let leave = self.binary(36, leave, far[2]);
|
||||
let from = self.binary(35, enter, fzero);
|
||||
// Ordered compares: a NaN anywhere is a miss.
|
||||
let through = self.s.m.cmp(c, pred::OGE, leave, from);
|
||||
let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
|
||||
let off = self.is_nan_f32(bx[0]);
|
||||
let on = self.s.m.bool(true);
|
||||
let on = self.s.m.bin(c, Bin::Xor, off, on);
|
||||
let hit = self.s.m.bin(c, Bin::And, through, before);
|
||||
let hit = self.s.m.bin(c, Bin::And, hit, on);
|
||||
ids[n] = self.s.m.select(c, hit, children[n], none);
|
||||
distances[n] = self.s.m.select(c, hit, enter, infinity);
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
|
||||
let (da, db) = (distances[a], distances[b]);
|
||||
distances[a] = self.s.m.select(c, swap, db, da);
|
||||
distances[b] = self.s.m.select(c, swap, da, db);
|
||||
let (ia, ib) = (ids[a], ids[b]);
|
||||
ids[a] = self.s.m.select(c, swap, ib, ia);
|
||||
ids[b] = self.s.m.select(c, swap, ia, ib);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
|
||||
/// four result dwords, made in the current block.
|
||||
fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
|
||||
let c = self.cur;
|
||||
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
|
||||
// The triangle's byte of the dword at byte 60: which of its
|
||||
// vertices barycentric I and J weigh.
|
||||
let id = self.bvh_node_words(at, None, 60, 1)[0];
|
||||
let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
|
||||
let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
|
||||
let id = self.s.m.bin(c, Bin::LShr, id, shift);
|
||||
let i = self.s.m.bin(c, Bin::And, id, k3);
|
||||
let j = self.s.m.bin(c, Bin::LShr, id, k2);
|
||||
let j = self.s.m.bin(c, Bin::And, j, k3);
|
||||
let first = self.s.m.bin(c, Bin::Sub, k3, i);
|
||||
let first = self.s.m.bin(c, Bin::Sub, first, j);
|
||||
let first = self.s.m.bin(c, Bin::And, first, k3);
|
||||
// The node's vertices the triangle is made of, four bits each.
|
||||
let (k0, k1) = (k(self, 0), k(self, 1));
|
||||
let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
|
||||
let (is0, is1, is2) = (
|
||||
self.s.m.cmp(c, pred::EQ, kind, k0),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k1),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k2),
|
||||
);
|
||||
let map = self.s.m.select(c, is2, maps[2], maps[3]);
|
||||
let map = self.s.m.select(c, is1, maps[1], map);
|
||||
let map = self.s.m.select(c, is0, maps[0], map);
|
||||
let mut p = Vec::with_capacity(3);
|
||||
for n in [first, i, j] {
|
||||
let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
|
||||
let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
|
||||
let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
|
||||
let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
|
||||
let words = self.bvh_node_words(at, Some(byte), 0, 3);
|
||||
// Relative to the ray's origin.
|
||||
let r: Vec<V> = (0..3)
|
||||
.map(|a| {
|
||||
let f = self.as_float(words[a]);
|
||||
self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
|
||||
})
|
||||
.collect();
|
||||
p.push([r[0], r[1], r[2]]);
|
||||
}
|
||||
// The ray's largest axis z, and x and y after it in an order that
|
||||
// keeps the winding.
|
||||
let fzero = self.s.m.f32(0);
|
||||
let size = ray.direction.map(|d| self.unary(6, d));
|
||||
let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
|
||||
let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
|
||||
let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
|
||||
let z0 = self.s.m.bin(c, Bin::And, xy, xz);
|
||||
let on = self.s.m.bool(true);
|
||||
let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
|
||||
let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
|
||||
// Component (kz + n) % 3 of `q`.
|
||||
let pick = |l: &mut Self, q: [V; 3], n: usize| {
|
||||
let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
|
||||
l.s.m.select(c, z0, q[n % 3], rest)
|
||||
};
|
||||
let dz = pick(self, ray.direction, 0);
|
||||
let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
|
||||
// (x, y, z) of `q`: the two after the largest axis, swapped for a
|
||||
// ray that runs backwards along it.
|
||||
let axes = |l: &mut Self, q: [V; 3]| {
|
||||
let (x, y) = (pick(l, q, 1), pick(l, q, 2));
|
||||
[
|
||||
l.s.m.select(c, backwards, y, x),
|
||||
l.s.m.select(c, backwards, x, y),
|
||||
pick(l, q, 0),
|
||||
]
|
||||
};
|
||||
let d = axes(self, ray.direction);
|
||||
let sz = pick(self, ray.inverse, 0);
|
||||
let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
|
||||
let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
|
||||
let mut sheared = Vec::with_capacity(3);
|
||||
for r in p {
|
||||
let r = axes(self, r);
|
||||
let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
|
||||
let x = self.s.m.bin(c, Bin::Sub, r[0], x);
|
||||
let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
|
||||
let y = self.s.m.bin(c, Bin::Sub, r[1], y);
|
||||
let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
|
||||
sheared.push((x, y, z));
|
||||
}
|
||||
let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
|
||||
unreachable!()
|
||||
};
|
||||
// p * q - r * s.
|
||||
let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
|
||||
let a = l.s.m.bin(c, Bin::Mul, p, q);
|
||||
let b = l.s.m.bin(c, Bin::Mul, r, s);
|
||||
l.s.m.bin(c, Bin::Sub, a, b)
|
||||
};
|
||||
let u = cross(self, cx, by, cy, bx);
|
||||
let v = cross(self, ax, cy, ay, cx);
|
||||
let w = cross(self, bx, ay, by, ax);
|
||||
let any = |l: &mut Self, p: u8| {
|
||||
let a = l.s.m.cmp(c, p, u, fzero);
|
||||
let b = l.s.m.cmp(c, p, v, fzero);
|
||||
let d = l.s.m.cmp(c, p, w, fzero);
|
||||
let a = l.s.m.bin(c, Bin::Or, a, b);
|
||||
l.s.m.bin(c, Bin::Or, a, d)
|
||||
};
|
||||
let behind = any(self, pred::OLT);
|
||||
let before = any(self, pred::OGT);
|
||||
let outside = self.s.m.bin(c, Bin::And, behind, before);
|
||||
let inside = self.s.m.bin(c, Bin::Xor, outside, on);
|
||||
let det = self.s.m.bin(c, Bin::Add, v, w);
|
||||
let det = self.s.m.bin(c, Bin::Add, u, det);
|
||||
let t = self.s.m.bin(c, Bin::Mul, u, az);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
// The distance is not negative: the numerator has the
|
||||
// denominator's sign (or is 0). Ordered compares: a denominator
|
||||
// of 0 or a NaN is a miss.
|
||||
let front = self.s.m.cmp(c, pred::OGT, det, fzero);
|
||||
let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
|
||||
let front = self.s.m.bin(c, Bin::And, front, front_ahead);
|
||||
let back = self.s.m.cmp(c, pred::OLT, det, fzero);
|
||||
let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
|
||||
let back = self.s.m.bin(c, Bin::And, back, back_ahead);
|
||||
let ahead = self.s.m.bin(c, Bin::Or, front, back);
|
||||
let hit = self.s.m.bin(c, Bin::And, inside, ahead);
|
||||
let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
|
||||
let out = [t, det, v, w];
|
||||
std::array::from_fn(|n| {
|
||||
let f = self.s.m.select(c, hit, out[n], miss[n]);
|
||||
self.as_int(f)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! The ray-tracing node test end to end: a synthetic compute program that
|
||||
//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
|
||||
//! lowered to DXIL, validated by `dxil.dll` when present, run on the host
|
||||
//! GPU and WARP, and compared dword for dword with the CPU reference
|
||||
//! ([`crate::bvh`]).
|
||||
//!
|
||||
//! The nodes are in a raw buffer. Two ways to name it are run: the
|
||||
//! buffer's descriptor from the program's table (a resource of the host,
|
||||
//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
|
||||
//! descriptor of numbers over title memory with the structure's address in
|
||||
//! the node pointer or in the descriptor. These tests have no host that
|
||||
//! keeps copies of title memory and their directory, so for the second
|
||||
//! they put a stand-in under the node reader
|
||||
//! (`lower::intersect::TEST_MEMORY`); without it the same program reads
|
||||
//! through the directory, which is only checked to lower and validate.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::lower::intersect::TEST_MEMORY;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::bvh::{self, Ray, tests as nodes};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::resource::BvhNodes;
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Threads of one group, each with its own record.
|
||||
const THREADS: u32 = 32;
|
||||
/// Bytes of a thread's record: the node pointer (two dwords), the ray's
|
||||
/// extent, origin, direction and inverse direction, and whether the
|
||||
/// thread runs the instruction.
|
||||
const RECORD: u32 = 64;
|
||||
/// Where the nodes start in the buffer.
|
||||
const NODES: u32 = THREADS * RECORD;
|
||||
/// What the result registers hold before the instruction.
|
||||
const BEFORE: [u32; 4] = [1, 2, 3, 4];
|
||||
|
||||
/// How the program names the nodes' memory.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Descriptor {
|
||||
/// The buffer's descriptor from the table.
|
||||
Table,
|
||||
/// Numbers, as the title builds it: dwords 0 and 1 (the base address
|
||||
/// in 256-byte units and the box sorting bit); the size and the rest of
|
||||
/// the flags as the title sets them.
|
||||
Numbers(u32, u32),
|
||||
}
|
||||
|
||||
/// The descriptor the title builds for the 64-bit form: the whole address
|
||||
/// space, sorted boxes, barycentrics returned.
|
||||
const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
|
||||
|
||||
/// The program: per thread, the record's twelve operand dwords in v1-v12,
|
||||
/// the instruction's result in v13-v16 (under a lane mask of the threads
|
||||
/// whose record says so), stored to the UAV at 16 bytes a thread.
|
||||
fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
|
||||
let mut w = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x3428_0086, // v_lshlrev_b32 v20, 6, v0
|
||||
0xE038_1000,
|
||||
0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
|
||||
0xE038_1010,
|
||||
0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
|
||||
0xE038_1020,
|
||||
0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
|
||||
0xE030_1030,
|
||||
0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
|
||||
];
|
||||
for k in 0..4u32 {
|
||||
// v_mov_b32 v13+k, 1+k
|
||||
w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
|
||||
}
|
||||
let rsrc = match descriptor {
|
||||
Descriptor::Table => 8,
|
||||
Descriptor::Numbers(word0, word1) => {
|
||||
// s_mov_b32 s24, word0
|
||||
w.extend([0xBE98_03FF, word0]);
|
||||
if word1 == bvh::BOX_SORT {
|
||||
// As the title makes it.
|
||||
w.push(0xBE99_0B81); // s_brev_b32 s25, 1
|
||||
} else {
|
||||
w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
|
||||
}
|
||||
w.extend([
|
||||
0xBE9A_03C1, // s_mov_b32 s26, -1
|
||||
0xBE9B_03FF,
|
||||
0x8900_03FF, // s_mov_b32 s27, 0x890003ff
|
||||
]);
|
||||
24
|
||||
}
|
||||
};
|
||||
w.extend([
|
||||
0xBE94_037E, // s_mov_b32 s20, exec_lo
|
||||
0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
|
||||
]);
|
||||
let first = 0x0000_0D01 | (rsrc >> 2) << 16;
|
||||
if wide {
|
||||
// image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
|
||||
} else {
|
||||
// image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
|
||||
}
|
||||
w.extend([
|
||||
0xBEFE_0314, // s_mov_b32 exec_lo, s20
|
||||
0x342A_0084, // v_lshlrev_b32 v21, 4, v0
|
||||
0xE078_1000,
|
||||
0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
]);
|
||||
w
|
||||
}
|
||||
|
||||
fn native(words: &[u32]) -> NativeProgram {
|
||||
let table = |kind, at| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: at,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 22,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [THREADS, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowers the program; the DXIL is validated when the validator is there.
|
||||
fn build(
|
||||
wide: bool,
|
||||
descriptor: Descriptor,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
let native = native(&program(wide, descriptor));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
Ok((shader, res))
|
||||
}
|
||||
|
||||
/// One thread's test: a node (by its index in the node list), the kind its
|
||||
/// pointer carries, and the ray; `None` leaves the thread masked out.
|
||||
type Case = Option<(usize, u32, Ray)>;
|
||||
|
||||
/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
|
||||
/// where each node starts, in dwords from the first node.
|
||||
struct Scene {
|
||||
words: Vec<u32>,
|
||||
starts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
words: Vec::new(),
|
||||
starts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a node of `dwords` (16 or 32) and returns its index.
|
||||
fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
|
||||
self.starts.push(self.words.len());
|
||||
let mut padded = [0u32; 32];
|
||||
padded[..28].copy_from_slice(&node);
|
||||
// Bytes the instruction must not read as part of the node: what
|
||||
// follows a 64-byte node, and a box node's last 16 bytes.
|
||||
for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
|
||||
*w = 0x7fc0_dead;
|
||||
}
|
||||
self.words.extend(&padded[..dwords]);
|
||||
self.starts.len() - 1
|
||||
}
|
||||
|
||||
/// The pointer of node `n` with `kind`, counted from the first node.
|
||||
fn pointer(&self, n: usize, kind: u32) -> u32 {
|
||||
(4 * self.starts[n] as u32) >> 3 | kind
|
||||
}
|
||||
|
||||
/// What the instruction reads of node `n`.
|
||||
fn node(&self, n: usize) -> [u32; 28] {
|
||||
std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A small generator of repeatable numbers.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self
|
||||
.0
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) as u32
|
||||
}
|
||||
|
||||
/// A float in -1..1 in steps of 1/4096 (exactly representable).
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() % 8193) as f32 / 4096.0 - 1.0
|
||||
}
|
||||
|
||||
fn vector(&mut self, scale: f32) -> [f32; 3] {
|
||||
[
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The scene and batches of cases over it.
|
||||
fn scene() -> (Scene, Vec<Vec<Case>>) {
|
||||
let mut s = Scene::new();
|
||||
let mut g = Numbers(0x5eed);
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
let moved =
|
||||
|b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
|
||||
let off = [f32::NAN; 6];
|
||||
let mut box_nodes = Vec::new();
|
||||
// The boxes of the reference's own tests, in both widths.
|
||||
let lined = [
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
];
|
||||
let ids = [0x105, 0x20c, 0x304, 0x400];
|
||||
box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
|
||||
// Boxes around the origin, one switched off, one child missing.
|
||||
let around = [
|
||||
UNIT,
|
||||
moved(UNIT, [0.5, 0.5, 0.5]),
|
||||
off,
|
||||
[-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
|
||||
];
|
||||
let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
|
||||
box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
|
||||
// Random boxes.
|
||||
for n in 0..6 {
|
||||
let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
|
||||
let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
|
||||
std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
|
||||
});
|
||||
let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
|
||||
if n % 2 == 0 {
|
||||
box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
|
||||
} else {
|
||||
box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
|
||||
}
|
||||
}
|
||||
// Triangles: one of the reference's tests, a pair as the title's
|
||||
// builder stores it, all four triangles of a full node with turned
|
||||
// ids, random ones.
|
||||
let mut triangle_nodes = Vec::new();
|
||||
let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
|
||||
let pair = s.add(
|
||||
nodes::triangles(
|
||||
&[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
|
||||
9 | 0x80 | 6 << 8,
|
||||
),
|
||||
16,
|
||||
);
|
||||
triangle_nodes.extend([(pair, 0), (pair, 1)]);
|
||||
let five = [
|
||||
[-3.0, -1.0, 6.0],
|
||||
[-1.0, 2.0, 6.5],
|
||||
[1.0, -1.0, 6.0],
|
||||
[3.0, 2.0, 6.5],
|
||||
[5.0, -1.0, 7.0],
|
||||
];
|
||||
// I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
|
||||
let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
|
||||
triangle_nodes.extend((0..4).map(|k| (full, k)));
|
||||
for _ in 0..5 {
|
||||
let c = g.vector(6.0);
|
||||
let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
|
||||
let d = g.vector(3.0);
|
||||
[c[0] + d[0], c[1] + d[1], c[2] + d[2]]
|
||||
});
|
||||
triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
|
||||
}
|
||||
let mut cases: Vec<Case> = Vec::new();
|
||||
// Rays of the reference's tests against the lined-up boxes.
|
||||
for &(n, kind) in &box_nodes[..2] {
|
||||
for (origin, direction, extent) in [
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.5),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.0),
|
||||
([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
|
||||
([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [0.0; 3], 1000.0),
|
||||
] {
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Random rays at every box node, half of them aimed at a box.
|
||||
for &(n, kind) in &box_nodes {
|
||||
let words = s.node(n);
|
||||
let boxes = if kind == 5 {
|
||||
bvh::boxes32(&words)
|
||||
} else {
|
||||
bvh::boxes16(&words)
|
||||
};
|
||||
for k in 0..12 {
|
||||
let origin = g.vector(12.0);
|
||||
let direction = if k % 2 == 0 {
|
||||
let b = boxes[(k / 2) % 4];
|
||||
if b[0].is_nan() {
|
||||
g.vector(1.0)
|
||||
} else {
|
||||
std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
|
||||
}
|
||||
} else {
|
||||
g.vector(1.0)
|
||||
};
|
||||
let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Rays at every triangle: aimed inside, at an edge, at a vertex, past
|
||||
// it, from both sides, along each axis.
|
||||
for &(n, kind) in &triangle_nodes {
|
||||
let p = bvh::triangle_vertices(&s.node(n), kind);
|
||||
let at = |w: [f32; 3]| -> [f32; 3] {
|
||||
std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
|
||||
};
|
||||
for (k, w) in [
|
||||
[0.5, 0.25, 0.25],
|
||||
[0.125, 0.75, 0.125],
|
||||
[0.5, 0.5, 0.0],
|
||||
[0.0, 0.5, 0.5],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.75, 0.75, -0.5],
|
||||
[-0.25, 0.5, 0.75],
|
||||
[0.25, 0.25, 0.5],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let target = at(w);
|
||||
let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
|
||||
let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
|
||||
if k == 7 {
|
||||
// The triangle lies behind.
|
||||
direction = direction.map(|d| -d);
|
||||
}
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
for axis in 0..3 {
|
||||
for sign in [1.0f32, -1.0] {
|
||||
let target = at([0.25, 0.5, 0.25]);
|
||||
let mut origin = target;
|
||||
origin[axis] -= 8.0 * sign;
|
||||
let mut direction = [0.0; 3];
|
||||
direction[axis] = sign;
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Kinds the instruction does not read, and threads masked out.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
cases.extend([
|
||||
Some((triangle_nodes[0].0, 6, ray)),
|
||||
Some((triangle_nodes[0].0, 7, ray)),
|
||||
None,
|
||||
Some((
|
||||
box_nodes[0].0,
|
||||
5,
|
||||
Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
)),
|
||||
None,
|
||||
]);
|
||||
let batches = cases
|
||||
.chunks(THREADS as usize)
|
||||
.map(<[Case]>::to_vec)
|
||||
.collect();
|
||||
(s, batches)
|
||||
}
|
||||
|
||||
/// The buffer for one batch: the threads' records, then the nodes. Node
|
||||
/// pointers count from `base` before the first node, in bytes.
|
||||
fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
|
||||
let mut data = vec![0u32; (NODES / 4) as usize];
|
||||
for (t, case) in batch.iter().enumerate() {
|
||||
let Some((n, kind, ray)) = case else { continue };
|
||||
let r = &mut data[t * (RECORD / 4) as usize..][..13];
|
||||
let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
|
||||
(r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
|
||||
r[2] = ray.extent.to_bits();
|
||||
for a in 0..3 {
|
||||
r[3 + a] = ray.origin[a].to_bits();
|
||||
r[6 + a] = ray.direction[a].to_bits();
|
||||
r[9 + a] = ray.inverse[a].to_bits();
|
||||
}
|
||||
r[12] = 1;
|
||||
}
|
||||
data.extend(&scene.words);
|
||||
data
|
||||
}
|
||||
|
||||
fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
|
||||
match case {
|
||||
Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
|
||||
None => BEFORE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tests' title memory for this thread until dropped.
|
||||
struct Memory;
|
||||
|
||||
impl Memory {
|
||||
fn at(base: u64) -> Self {
|
||||
// Heap slot 0: the buffer of records and nodes.
|
||||
TEST_MEMORY.set(Some((0, base)));
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
TEST_MEMORY.set(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs every batch on the hardware adapter and WARP and compares with
|
||||
/// the reference. `pointers` is what node pointers count from, in bytes
|
||||
/// before the first node.
|
||||
fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
|
||||
let (shader, res) = build(wide, descriptor).expect("the program lowers");
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
let (scene, batches) = scene();
|
||||
// The reference must see a bit of everything, or the comparison
|
||||
// proves little.
|
||||
let all: Vec<&Case> = batches.iter().flatten().collect();
|
||||
let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
|
||||
let boxes = |hits: usize| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 4 | 5, _)))
|
||||
&& r.iter().filter(|&&x| x != bvh::NONE).count() == hits
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let triangles = |hit: bool| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
|
||||
})
|
||||
.count()
|
||||
};
|
||||
assert!(
|
||||
boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
|
||||
"box cases"
|
||||
);
|
||||
assert!(
|
||||
triangles(true) > 30 && triangles(false) > 30,
|
||||
"triangle cases"
|
||||
);
|
||||
// Sorting must matter to some case, or the unsorted run proves nothing.
|
||||
assert!(
|
||||
all.iter()
|
||||
.any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
|
||||
"no case tells sorted from unsorted"
|
||||
);
|
||||
let _one = super::valu_tests::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 {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
|
||||
for (b, batch) in batches.iter().enumerate() {
|
||||
let data = buffer(&scene, batch, pointers);
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(vec![0; 5]))],
|
||||
views: &[
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::RawUav(4 * THREADS),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
for t in 0..THREADS as usize {
|
||||
let case = batch.get(t).copied().flatten();
|
||||
let want = match batch.get(t) {
|
||||
Some(c) => expected(&scene, c, sort),
|
||||
// A thread past the batch: its record is zeros, so it
|
||||
// is masked out.
|
||||
None => BEFORE,
|
||||
};
|
||||
let got = &out[0][4 * t..4 * t + 4];
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
|
||||
got,
|
||||
got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
|
||||
want,
|
||||
want.map(f32::from_bits),
|
||||
);
|
||||
}
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "no SM 6.6 device available");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
// Pointers count from the buffer's start.
|
||||
run(true, Descriptor::Table, u64::from(NODES), true);
|
||||
assert_eq!(
|
||||
build(true, Descriptor::Table).unwrap().1.bvh[0].1,
|
||||
BvhNodes::Resource
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
run(false, Descriptor::Table, u64::from(NODES), true);
|
||||
}
|
||||
|
||||
/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
|
||||
const BASE: u64 = 0x12_3456_7800;
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's way: one descriptor for all of memory, the structure's
|
||||
// address folded into a 64-bit pointer.
|
||||
let _memory = Memory::at(BASE);
|
||||
run(true, WHOLE, BASE + u64::from(NODES), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's other way: the structure's address in the descriptor
|
||||
// (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
|
||||
// an address past 2^40 bytes, and without box sorting.
|
||||
let base = 0x312_3456_7800u64;
|
||||
let structure = base + u64::from(NODES);
|
||||
let _memory = Memory::at(base);
|
||||
let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
|
||||
run(false, descriptor, 0, false);
|
||||
// And sorted.
|
||||
let descriptor = Descriptor::Numbers(
|
||||
(structure >> 8) as u32,
|
||||
(structure >> 40) as u32 | bvh::BOX_SORT,
|
||||
);
|
||||
run(false, descriptor, 0, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
|
||||
for wide in [true, false] {
|
||||
let native = native(&program(wide, WHOLE));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
// The flags the title sets: sorted boxes, barycentrics, a
|
||||
// ray-tracing structure. No resource is taken for it: the buffer
|
||||
// loads' and the store's descriptors are all there is.
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
assert_eq!(
|
||||
res.bvh[0].1,
|
||||
BvhNodes::Memory {
|
||||
word1: 0x8000_0000,
|
||||
word3: 0x8900_03ff
|
||||
}
|
||||
);
|
||||
assert_eq!(res.descriptors.len(), 5);
|
||||
// Without the tests' stand-in the nodes are read as the title's
|
||||
// programs will read them: through the host's directory of title
|
||||
// memory. The program lowers and validates, and asks the host for
|
||||
// the directory and for the list of pages it found no copy of.
|
||||
let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
|
||||
assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
|
||||
assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
|
||||
// Triangle return mode 0 (bit 24 of dword 3 clear): the last two
|
||||
// result dwords would be a triangle id and a hit status.
|
||||
let mut words = program(true, WHOLE);
|
||||
let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
|
||||
words[flags] = 0x8800_03FF;
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let r = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
match r {
|
||||
Err(ShaderError::Unsupported { what, .. }) => {
|
||||
assert_eq!(what, "a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
other => panic!("{:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
+3923
-405
File diff suppressed because it is too large.
Load diff
@@ -50,10 +50,9 @@
|
||||
//! descriptors (1,024 world compute programs, ray-tracing material
|
||||
//! resolves) read raw views this way.
|
||||
//!
|
||||
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
|
||||
//! atomically is declared a 32-bit unsigned single-channel view; the
|
||||
//! host's view at that index must be an R32 integer view (64-bit atomics
|
||||
//! stop the translation). Global loads from a root SRV read it raw.
|
||||
//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT
|
||||
//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter
|
||||
//! require SM 6.6 atomic support on typed and descriptor-heap resources.
|
||||
//!
|
||||
//! Entry points: [`translate`] (container bytes as the title passes them
|
||||
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
|
||||
@@ -74,16 +73,26 @@
|
||||
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
|
||||
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
|
||||
//! console never exports them).
|
||||
//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a
|
||||
//! rectangle from three vertices; the host has no such topology. A
|
||||
//! pipeline the title makes for rectangles (topology type 19) gets a
|
||||
//! geometry shader of ours between the translated vertex and pixel
|
||||
//! shaders and draws triangle lists with the title's own vertex counts.
|
||||
//! It binds nothing.
|
||||
|
||||
mod bitcode;
|
||||
mod container;
|
||||
#[cfg(all(test, windows))]
|
||||
mod diff_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod intersect_tests;
|
||||
#[cfg(all(windows, any(test, feature = "host")))]
|
||||
pub mod host;
|
||||
mod lower;
|
||||
mod rect;
|
||||
mod sampler;
|
||||
mod shader;
|
||||
mod threading;
|
||||
#[cfg(windows)]
|
||||
pub mod validator;
|
||||
#[cfg(all(test, windows))]
|
||||
@@ -97,7 +106,13 @@ use crate::native::{HwStage, NativeProgram, RootType};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
pub use sampler::StaticSampler;
|
||||
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
|
||||
pub use lower::set_host_max_wave;
|
||||
pub use rect::rect_list_gs;
|
||||
pub use shader::{
|
||||
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
|
||||
SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
|
||||
set_view_heap_limit,
|
||||
};
|
||||
|
||||
/// The loop limit without an override: 2^20.
|
||||
pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
|
||||
@@ -122,6 +137,33 @@ pub fn loop_limit() -> u32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Which of a translated program's group barriers wait for the whole
|
||||
/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
|
||||
/// fence and lose the wait. A wait that some thread of the group never
|
||||
/// reaches is undefined on the host, and NVIDIA's wait is for every
|
||||
/// thread: the group stands until Windows resets the card. (The console's
|
||||
/// barrier is the wave's, whatever lanes are live, and a wave that ended
|
||||
/// is not waited for.) `VICTORY_GROUP_SYNC`:
|
||||
/// - unset or `2`: every barrier waits, as before.
|
||||
/// - `1`: the title's `s_barrier` waits only in a block every lane runs,
|
||||
/// in a program no lane can be cut out of at the iteration limit.
|
||||
/// - `0`: no barrier waits, neither the title's nor the ones the
|
||||
/// translation adds (wave64 programs in two host waves exchange through
|
||||
/// them, so such programs compute wrong values). For one run that tells
|
||||
/// whether a barrier is what stops the card: with it no run can stand in
|
||||
/// a barrier.
|
||||
///
|
||||
/// Part of the translation: the shader cache keys on it (`victory-gpu`'s
|
||||
/// does).
|
||||
pub fn group_sync() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
|
||||
Some("0") => 0,
|
||||
Some("1") => 1,
|
||||
_ => 2,
|
||||
})
|
||||
}
|
||||
|
||||
/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
|
||||
/// unreadable or 0. Pure, for testing.
|
||||
fn parse_loop_limit(value: Option<&str>) -> u32 {
|
||||
@@ -156,6 +198,11 @@ pub struct HostShader {
|
||||
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
|
||||
/// [`ROOT_CBV_SPACE`].
|
||||
pub root_srvs: Vec<u8>,
|
||||
/// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
|
||||
/// [`ROOT_CBV_SPACE`].
|
||||
pub root_uavs: Vec<u8>,
|
||||
/// Heap descriptors that can be selected from root state at bind time.
|
||||
pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
|
||||
}
|
||||
|
||||
impl HostShader {
|
||||
@@ -204,7 +251,7 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
offset: 0,
|
||||
what: "a container without a vertex, pixel, compute or mesh program",
|
||||
})?;
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let p = crate::spill::build(&native)?;
|
||||
// Structurisation first: tracing per-lane descriptors needs it (its
|
||||
// failure is reported after the earlier stages').
|
||||
let st = structure::structure(&p);
|
||||
@@ -223,6 +270,139 @@ pub fn emit(
|
||||
io: &io::Io,
|
||||
res: &resource::Resources,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let original = emit_program(c, native, p, st, io, res);
|
||||
// A console wave64 compute program on a host of 32-lane waves that
|
||||
// still needs 64 lanes, or whose cross-lane code sits where not every
|
||||
// lane runs: once more with its early-outs left out
|
||||
// ([`ir::without_early_outs`]), which is what usually keeps the whole
|
||||
// body from being a block every lane runs.
|
||||
let stuck = match &original {
|
||||
Ok((_, wave)) => *wave == Some(64),
|
||||
Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"),
|
||||
Err(_) => false,
|
||||
};
|
||||
if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
|
||||
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
|
||||
let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
|
||||
if why {
|
||||
match r {
|
||||
Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
|
||||
Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
|
||||
}
|
||||
}
|
||||
};
|
||||
let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
|
||||
// Each host wave as a wave of its own (`lower::with_local_waves`),
|
||||
// for programs still stopped where not every lane runs.
|
||||
let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
|
||||
// Where the wave operations are the allocation idiom
|
||||
// ([`lower::wave_local`]) that is exact. Other programs are taken
|
||||
// the same way last of all, each half-wave giving its own results
|
||||
// (approximate: a tile-wide result becomes two half-tile ones);
|
||||
// `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
|
||||
let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
|
||||
let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
|
||||
Ok(()) => true,
|
||||
Err((offset, what)) => {
|
||||
if why {
|
||||
eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
|
||||
}
|
||||
false
|
||||
}
|
||||
};
|
||||
// The program in two other forms: without its early-outs, and
|
||||
// without any branch that only skips code no lane is left for.
|
||||
let form = |p: Option<ir::Program>| {
|
||||
p.and_then(|p| {
|
||||
let st = structure::structure(&p).ok()?;
|
||||
let io = io::raise(&p, native).ok()?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
|
||||
Some((p, st, io, res))
|
||||
})
|
||||
};
|
||||
let forms = [
|
||||
("without early-outs", form(ir::without_early_outs(p))),
|
||||
("without skips", form(ir::without_skips(p))),
|
||||
];
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f {
|
||||
let again = emit_program(c, native, p, st, io, res);
|
||||
report(name, &again);
|
||||
if done(&again) {
|
||||
return again.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
if local_on {
|
||||
// exact first (every form), then approximate
|
||||
for exact in [true, false] {
|
||||
if !exact && strict {
|
||||
break;
|
||||
}
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f
|
||||
&& idiom(p, st) == exact
|
||||
{
|
||||
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
|
||||
report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
if idiom(p, st) == exact {
|
||||
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
|
||||
report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Last: every mask and lane read per host wave.
|
||||
if !strict {
|
||||
for (name, f) in &forms {
|
||||
if let Some((p, st, io, res)) = f {
|
||||
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
|
||||
report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
|
||||
report("local waves (APPROXIMATE, any mask)", &local);
|
||||
if done(&local) {
|
||||
return local.map(|(shader, _)| shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let original = original.map(|(shader, _)| shader);
|
||||
// Retry unsupported programs only. Threading can separate an unknown
|
||||
// register value from its apparent use on a mutually exclusive path.
|
||||
if !matches!(original, Err(ShaderError::Unsupported { .. })) {
|
||||
return original;
|
||||
}
|
||||
let edges = threading::constant_edges(p, st);
|
||||
if edges.is_empty() {
|
||||
return original;
|
||||
}
|
||||
let p = ir::thread_edges(p, &edges)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let io = io::raise(&p, native)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
|
||||
}
|
||||
|
||||
/// The translated program, and the wave size it requires of the host.
|
||||
fn emit_program(
|
||||
c: &Container,
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
st: &structure::Structured,
|
||||
io: &io::Io,
|
||||
res: &resource::Resources,
|
||||
) -> Result<(HostShader, Option<u32>), ShaderError> {
|
||||
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
match c.part(fourcc) {
|
||||
Some(part) => signature(part.data),
|
||||
@@ -241,6 +421,8 @@ pub fn emit(
|
||||
// Constant, as DXC declares it (the AMD compiler crashed on a
|
||||
// front face without a mode).
|
||||
(13, _) => 1,
|
||||
// Until a read says which mode (`lower`).
|
||||
(28, _) => 2,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
@@ -289,7 +471,8 @@ pub fn emit(
|
||||
prims,
|
||||
mesh_stride,
|
||||
})?;
|
||||
Ok(HostShader {
|
||||
let wave_size = l.wave_size;
|
||||
let shader = HostShader {
|
||||
stage: native.stage,
|
||||
dxil: l.dxil,
|
||||
user_data: l.user_data,
|
||||
@@ -308,7 +491,10 @@ pub fn emit(
|
||||
samplers: l.samplers,
|
||||
root_cbvs: l.root_cbvs,
|
||||
root_srvs: l.root_srvs,
|
||||
})
|
||||
root_uavs: l.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
Ok((shader, wave_size))
|
||||
}
|
||||
|
||||
/// The rows of an `ISG1`/`OSG1` part.
|
||||
@@ -358,6 +544,7 @@ fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
68 => 18,
|
||||
69 => 20,
|
||||
70 => 15,
|
||||
23 => 28, // barycentrics
|
||||
25 => 30, // cull primitive
|
||||
_ => {
|
||||
return Err(ShaderError::Unsupported {
|
||||
@@ -486,11 +673,12 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
|
||||
/// opaque and keyed by the unchanged low dword, so building its lane bit
|
||||
/// needed the mask's own value: lowering recursed until the stack
|
||||
/// overflowed, which takes the whole process down (found by
|
||||
/// random-input testing). Now the instruction fails like any other that
|
||||
/// random-input testing). Now that low dword, seen with two high
|
||||
/// dwords, has no mask, and the instruction fails like any other that
|
||||
/// cannot be expressed: its result is missing, and only a side effect
|
||||
/// that uses it would stop the translation.
|
||||
#[test]
|
||||
@@ -520,6 +708,108 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wave64 compute program: `body`, then a store of v1 to a UAV.
|
||||
fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
|
||||
use crate::native::RootParam;
|
||||
use crate::{ResourceType, RootType, UsedResource};
|
||||
// s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
|
||||
let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
|
||||
words.extend_from_slice(body);
|
||||
// v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
|
||||
// s_endpgm
|
||||
words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: true,
|
||||
vgprs: 4,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2,
|
||||
threads: [64, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
|
||||
let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
|
||||
let io = io::raise(&p, &native).unwrap();
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let container = crate::dxbc::build(&[]);
|
||||
let c = Container::parse(&container).unwrap();
|
||||
emit(&c, &native, &p, &st, &io, &res).map(|_| ())
|
||||
}
|
||||
|
||||
/// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
|
||||
/// or `exec_hi`): lanes 32-63 took the mask the low dword was first
|
||||
/// written with (the compare's, EXEC's on entry). Now the store refuses;
|
||||
/// without the write it translates.
|
||||
#[test]
|
||||
fn a_mask_whose_high_dword_is_rewritten_is_refused() {
|
||||
// v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
|
||||
let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
|
||||
// The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
|
||||
let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
|
||||
// v_mov_b32 v1, 7
|
||||
let mov = [0x7E02_0287];
|
||||
for body in [&select[..], &carry, &mov] {
|
||||
stores_v1(body).unwrap();
|
||||
}
|
||||
// s_mov_b32 vcc_hi, 0 after the compare.
|
||||
let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
|
||||
let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
|
||||
// s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
|
||||
// s_mov_b64 s[2:3], exec.
|
||||
let exec_hi = [0xBEFF_0380, 0x7E02_0287];
|
||||
let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
|
||||
for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
|
||||
assert!(stores_v1(body).is_err(), "{body:x?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
|
||||
/// names. It stopped as "LDS the program does not allocate" (sticky lips)
|
||||
/// or "an LDS operation" (the checkerboard shadow masks).
|
||||
#[test]
|
||||
fn a_backward_permute_reads_the_lane_its_address_names() {
|
||||
// v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
|
||||
stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
|
||||
}
|
||||
|
||||
/// A carry-in reading a join of compares after a divergent branch. A
|
||||
/// lane that skipped the inner compare has VCC clear there (VOPC clears
|
||||
/// inactive lanes), not the first compare's bit, so the join is no
|
||||
/// per-lane phi: lowering refuses it.
|
||||
#[test]
|
||||
fn a_carry_in_from_a_divergent_join_is_refused() {
|
||||
let body = [
|
||||
0x7E04_028B, // v_mov_b32 v2, 11
|
||||
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
|
||||
0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
|
||||
0xBF88_0001, // s_cbranch_execz 1
|
||||
0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
|
||||
0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
|
||||
0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
|
||||
];
|
||||
let e = stores_v1(&body).unwrap_err().to_string();
|
||||
assert!(e.contains("a carry-in from an untracked mask"), "{e}");
|
||||
}
|
||||
|
||||
/// A pixel shader writing a constant colour.
|
||||
#[cfg(windows)]
|
||||
fn constant_color() -> Vec<u8> {
|
||||
@@ -565,6 +855,8 @@ mod tests {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
let file = |var: &str, stage| {
|
||||
std::env::var(var).ok().map(|p| super::HostShader {
|
||||
@@ -575,6 +867,8 @@ mod tests {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
})
|
||||
};
|
||||
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
|
||||
@@ -746,4 +1040,528 @@ mod tests {
|
||||
// Translated or refused with a reason; it must not panic.
|
||||
let _ = super::emit(&c, &native, &p, &st, &io, &res);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valu_div_f32_sequence_executes_on_gpu() {
|
||||
let words: &[u32] = &[
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x340E_0083, // v_lshlrev_b32 v7, 3, v0
|
||||
0xE034_1000,
|
||||
0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
|
||||
0xD56D_6A03,
|
||||
0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
|
||||
0xD56D_1008,
|
||||
0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
|
||||
0x7E08_5503, // v_rcp_f32 v4, v3
|
||||
0xD54B_0005,
|
||||
0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
|
||||
0xD54B_0004,
|
||||
0x0412_0905, // v_fma_f32 v4, v5, v4, v4
|
||||
0x100A_0908, // v_mul_f32 v5, v8, v4
|
||||
0xD54B_0006,
|
||||
0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
|
||||
0xD56F_0004,
|
||||
0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
|
||||
0xD55F_0001,
|
||||
0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0xE070_1000,
|
||||
0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
let native = super::NativeProgram {
|
||||
stage: super::HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 9,
|
||||
layout: vec![
|
||||
crate::RootParam {
|
||||
root: crate::RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
crate::RootParam {
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![
|
||||
crate::UsedResource {
|
||||
kind: crate::ResourceType::Srv,
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
crate::UsedResource {
|
||||
kind: crate::ResourceType::Uav,
|
||||
root: crate::RootType::Table,
|
||||
table_offset_dwords: 8,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
io: crate::native::StageIo::Cs(crate::native::ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [7, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
|
||||
let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
|
||||
let io = crate::io::raise(&p, &native).unwrap();
|
||||
let st = crate::structure::structure(&p).unwrap();
|
||||
let l = super::lower::lower(&super::lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.unwrap();
|
||||
let mut dxil = l.dxil;
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::validator::Validator::load(
|
||||
super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut dxil).unwrap();
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Ok(host) = super::host::Host::new(false) {
|
||||
let cs = super::HostShader {
|
||||
stage: super::HwStage::Cs,
|
||||
dxil,
|
||||
user_data: l.user_data,
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: l.root_cbvs,
|
||||
root_srvs: l.root_srvs,
|
||||
root_uavs: l.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
let (root, pso) = host.compute_pipeline(&cs).unwrap();
|
||||
let inputs: Vec<u32> = [
|
||||
7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35,
|
||||
]
|
||||
.into_iter()
|
||||
.map(f32::to_bits)
|
||||
.collect();
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&super::host::Dispatch {
|
||||
roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
|
||||
views: &[
|
||||
super::host::View::Buffer {
|
||||
data: &inputs,
|
||||
stride: super::host::Stride::Raw,
|
||||
},
|
||||
super::host::View::RawUav(64),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
|
||||
assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
|
||||
assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
|
||||
assert!(
|
||||
(got[2] - 1e-35).abs() <= 1e-40,
|
||||
"lane 2 got {:?} ({:#x})",
|
||||
got[2],
|
||||
out[0][2]
|
||||
);
|
||||
assert!(
|
||||
(got[3] - 10.0).abs() < 1e-5,
|
||||
"lane 3 got {:?} ({:#x})",
|
||||
got[3],
|
||||
out[0][3]
|
||||
);
|
||||
assert_eq!(out[0][4], 0xFFC0_0000);
|
||||
assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
|
||||
assert!(
|
||||
(got[6] - (-1.0)).abs() < 1e-6,
|
||||
"lane 6 got {:?} ({:#x})",
|
||||
got[6],
|
||||
out[0][6]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod atomic_tests {
|
||||
use super::*;
|
||||
use crate::native::{ComputeIo, RootParam, StageIo};
|
||||
|
||||
#[test]
|
||||
fn heap_texture_atomic_widths() {
|
||||
// A synthetic compute shader loads a 2D UAV from a root table,
|
||||
// compares or adds at (0, 0), then uses the returned register(s).
|
||||
for (opcode, mask, wide) in [
|
||||
(16u32, 3, false),
|
||||
(16, 15, true),
|
||||
(17, 1, false),
|
||||
(17, 3, true),
|
||||
] {
|
||||
let words = [
|
||||
0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
|
||||
0xF40C_0200,
|
||||
0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
|
||||
0x7E00_0280,
|
||||
0x7E02_0280, // v0, v1 = coordinates
|
||||
0x7E04_0281,
|
||||
0x7E06_0282,
|
||||
0x7E08_0283,
|
||||
0x7E0A_0284, // v2..v5 = 1..4
|
||||
0xF000_2008 | opcode << 18 | mask << 8,
|
||||
0x0002_0200,
|
||||
// Use the old value in a second atomic at the same location.
|
||||
0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
|
||||
0x0002_0200,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 6,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2,
|
||||
threads: [32, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, false, native.vgprs).unwrap();
|
||||
let bytes = crate::dxbc::build(&[]);
|
||||
let shader = emit(
|
||||
&Container::parse(&bytes).unwrap(),
|
||||
&native,
|
||||
&p,
|
||||
&structure::structure(&p).unwrap(),
|
||||
&io::raise(&p, &native).unwrap(),
|
||||
&resource::track(&p, &native.layout, native.stage, None).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let container = Container::parse(&shader.dxil).unwrap();
|
||||
let features = u64::from_le_bytes(
|
||||
container
|
||||
.part(FourCC::SFI0)
|
||||
.unwrap()
|
||||
.data
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
|
||||
assert_eq!(features & required, if wide { required } else { 0 });
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
v.validate(&mut shader.dxil.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod barycentric_tests {
|
||||
use super::container::SigElement;
|
||||
use super::*;
|
||||
use crate::native::{PsInput, StageIo, Usage};
|
||||
|
||||
/// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
|
||||
const PERSP_CENTER: u32 = 1 << 1;
|
||||
const LINEAR_CENTER: u32 = 1 << 5;
|
||||
|
||||
/// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
|
||||
fn exp_mrt0(r: u32) -> [u32; 2] {
|
||||
[0xF800_180F, r * 0x0101_0101]
|
||||
}
|
||||
|
||||
/// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
|
||||
fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
|
||||
3 << 25 | dst << 17 | b << 9 | (256 + a)
|
||||
}
|
||||
|
||||
fn element(name: &str, kind: u8, row: u32) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index: 0,
|
||||
kind,
|
||||
comp: 9,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols: 4,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a pixel program with the input VGPRs `input_addr`
|
||||
/// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
|
||||
fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ps {
|
||||
inputs: vec![PsInput {
|
||||
usage: 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 mut target = element("SV_Target", 16, 0);
|
||||
target.usage = 15;
|
||||
let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
|
||||
let osg1 = container::signature(&[target], false);
|
||||
let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, None)?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let st = structure::structure(&p)?;
|
||||
emit(&c, &native, &p, &st, &io, &res)
|
||||
}
|
||||
|
||||
/// The translation's `SFI0` features and `ISG1` rows.
|
||||
fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
|
||||
let c = Container::parse(&shader.dxil).unwrap();
|
||||
let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
|
||||
(
|
||||
u64::from_le_bytes(sfi0),
|
||||
signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn validate(shader: &HostShader) {
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
v.validate(&mut shader.dxil.clone()).unwrap();
|
||||
}
|
||||
let _ = shader;
|
||||
}
|
||||
|
||||
/// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
|
||||
/// plain floats: they are channels y and z of `SV_Barycentrics`, the
|
||||
/// weights of vertices 1 and 2.
|
||||
#[test]
|
||||
fn barycentrics_read_as_values_are_sv_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
|
||||
assert_eq!(bary.len(), 1, "{inputs:?}");
|
||||
assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
|
||||
// Not packed: the validator wants packing location -1.
|
||||
assert_eq!(bary[0].row, None);
|
||||
// Only y and z (I and J) are read.
|
||||
let isg1 = Container::parse(&shader.dxil).unwrap();
|
||||
let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
|
||||
let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
|
||||
assert!(rw.contains(&0b110), "{rw:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Two kinds of barycentrics read directly: one element per mode.
|
||||
#[test]
|
||||
fn two_barycentric_modes_get_two_elements() {
|
||||
// v0-v1 perspective i, j; v2-v3 linear i, j.
|
||||
let [e0, e1] = exp_mrt0(4);
|
||||
let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
|
||||
let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
|
||||
let (_, inputs) = parts(&shader);
|
||||
let mut indices: Vec<u32> = inputs
|
||||
.iter()
|
||||
.filter(|e| e.kind == 28)
|
||||
.map(|e| e.index)
|
||||
.collect();
|
||||
indices.sort();
|
||||
assert_eq!(indices, [0, 1], "{inputs:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// I and J only fed to `v_interp_*` stay host interpolation: no
|
||||
/// barycentrics are declared.
|
||||
#[test]
|
||||
fn interpolation_alone_declares_no_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_eq!(features & 0x2_0000, 0);
|
||||
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Both: the attribute is interpolated and J is used as a value.
|
||||
#[test]
|
||||
fn interpolation_and_a_barycentric_value_together() {
|
||||
let [e0, e1] = exp_mrt0(3);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
v_add_f32(3, 2, 1), // v3 = attribute + j
|
||||
e0,
|
||||
e1,
|
||||
0xBF81_0000,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0);
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
/// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
|
||||
fn texcoord_mode(shader: &HostShader) -> u8 {
|
||||
let c = Container::parse(&shader.dxil).unwrap();
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
let row = [1, 0, 0x44, 0, 3];
|
||||
let at = psv.windows(5).position(|w| w == row).unwrap();
|
||||
psv[at + 5]
|
||||
}
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
/// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
|
||||
/// the attribute's vertices: TEXCOORD0 becomes constant, read with
|
||||
/// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
|
||||
#[test]
|
||||
fn computed_barycentrics_read_the_vertices() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// Weights from constants alone: the vertices, no `SV_Barycentrics`.
|
||||
#[test]
|
||||
fn constant_weights_need_no_barycentrics() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0x7E06_02F0, // v_mov_b32 v3, 0.5
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (features, inputs) = parts(&shader);
|
||||
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
|
||||
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// The same attribute interpolated with the loaded i and j and with a
|
||||
/// computed j: both from its vertices, the first weighed with
|
||||
/// `SV_Barycentrics`.
|
||||
#[test]
|
||||
fn computed_and_loaded_barycentrics_on_one_attribute() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
|
||||
0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
|
||||
0x1006_02F0, // v_mul_f32 v3, 0.5, v1
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
|
||||
v_add_f32(2, 2, 4),
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
let (_, inputs) = parts(&shader);
|
||||
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
}
|
||||
|
||||
/// P10 of an attribute the program interpolates is P1 - P0.
|
||||
#[test]
|
||||
fn p10_of_an_interpolated_attribute() {
|
||||
let [e0, e1] = exp_mrt0(2);
|
||||
let words = [
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
|
||||
v_add_f32(2, 2, 4),
|
||||
e0,
|
||||
e1,
|
||||
S_ENDPGM,
|
||||
];
|
||||
let shader = pixel(&words, PERSP_CENTER).unwrap();
|
||||
assert_eq!(texcoord_mode(&shader), 1);
|
||||
validate(&shader);
|
||||
// Alone, what the hardware holds is not known.
|
||||
let [e0, e1] = exp_mrt0(4);
|
||||
let words = [0xC812_0000, e0, e1, S_ENDPGM];
|
||||
assert!(pixel(&words, PERSP_CENTER).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! The geometry shader that completes the console's rectangle lists (list
|
||||
//! topology 17, pipeline topology type 19). A rectangle comes as three
|
||||
//! vertices, three corners of a screen-aligned rectangle; the hardware
|
||||
//! draws the whole rectangle and continues every vertex shader output
|
||||
//! linearly into the fourth corner. The host has no such topology: the
|
||||
//! draw goes out as a triangle list with this shader behind the translated
|
||||
//! vertex shader, so vertex counts, vertex numbers, indices and indirect
|
||||
//! arguments stay the title's, and each rectangle arrives here as one
|
||||
//! triangle.
|
||||
//!
|
||||
//! Which vertex is the corner between the other two varies: Grand Theft
|
||||
//! Auto VI's full-screen rectangles come as top left, bottom left, bottom
|
||||
//! right (the second), its tiled lighting as top left, bottom left, top
|
||||
//! right (the first). The corner is the vertex that shares x with one of
|
||||
//! the others and y with the other; the fourth vertex lies opposite it,
|
||||
//! `a + b - corner` for the position and every float output. That holds
|
||||
//! for three vertices with one positive w (then it is the same in clip
|
||||
//! space and on the screen, whatever the interpolation mode); three that
|
||||
//! differ in w, or are not such corners, stay the triangle they make.
|
||||
//!
|
||||
//! Flat values are the first vertex's: both triangles start with it (the
|
||||
//! halves on either side of the diagonal through it, turning as the three
|
||||
//! vertices do), which is the vertex the host takes a flat input from, and
|
||||
//! the fourth vertex's integer outputs are the first vertex's.
|
||||
//!
|
||||
//! shortcut: that the console takes a rectangle's flat values from its
|
||||
//! first vertex follows from the hardware's provoking-vertex setting for
|
||||
//! triangles; it is not measured on a rectangle.
|
||||
|
||||
use super::bitcode::{Attr, Bin, Term, V, pred};
|
||||
use super::container::SigElement;
|
||||
use super::shader::{Geometry, Shader};
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::{Container, FourCC};
|
||||
|
||||
/// Vertices emitted per rectangle: two triangles.
|
||||
const VERTICES: u32 = 6;
|
||||
|
||||
/// The scalars a geometry shader may emit per invocation (vertices times
|
||||
/// output components).
|
||||
const MAX_SCALARS: u32 = 1024;
|
||||
|
||||
/// The geometry shader (a DXIL container) for rectangle lists drawn with
|
||||
/// the translated vertex shader `vs` and, if the pipeline has one, the
|
||||
/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its
|
||||
/// inputs and outputs are the vertex shader's outputs, register for
|
||||
/// register, so it links with both. A pixel shader that declares a
|
||||
/// primitive id gets the rectangle's number, which the host leaves to the
|
||||
/// geometry stage when there is one.
|
||||
pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
|
||||
let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> {
|
||||
let c = Container::parse(dxil)?;
|
||||
match c.part(fourcc) {
|
||||
Some(part) => super::signature(part.data),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
};
|
||||
let outputs = sig(vs, FourCC::OSG1)?;
|
||||
let wanted = match ps {
|
||||
Some(ps) => sig(ps, FourCC::ISG1)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
build(outputs, &wanted)
|
||||
}
|
||||
|
||||
/// [`rect_list_gs`] from the vertex shader's outputs and the pixel
|
||||
/// shader's inputs.
|
||||
fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> {
|
||||
let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
|
||||
if outputs.iter().any(|e| e.row.is_none()) {
|
||||
return Err(unsupported("a rectangle list output without a register"));
|
||||
}
|
||||
let Some(position) = outputs
|
||||
.iter()
|
||||
.position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4)
|
||||
else {
|
||||
return Err(unsupported("a rectangle list without a four-component position"));
|
||||
};
|
||||
for e in &mut outputs {
|
||||
// Interpolation as `emit_program` declares a vertex shader's
|
||||
// outputs; a geometry shader's inputs carry the same modes.
|
||||
e.interp = match (e.kind, e.comp) {
|
||||
(3, _) => 4,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
e.usage = (1 << e.cols) - 1;
|
||||
}
|
||||
let mut s = Shader::new(false);
|
||||
s.geometry = Some(Geometry {
|
||||
max_vertices: VERTICES,
|
||||
});
|
||||
s.inputs = outputs.clone();
|
||||
// The primitive id the pixel shader declares, as one more output.
|
||||
let wanted = ps_inputs
|
||||
.iter()
|
||||
.find(|e| e.kind == 10 && e.row.is_some())
|
||||
.filter(|_| !outputs.iter().any(|o| o.kind == 10));
|
||||
let primitive = match wanted {
|
||||
Some(e) => {
|
||||
// Alone in its columns, and in a row of constant elements.
|
||||
let clash = outputs.iter().any(|o| {
|
||||
let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols;
|
||||
o.row == e.row && (o.interp != 1 || overlap)
|
||||
});
|
||||
if clash {
|
||||
return Err(unsupported(
|
||||
"a rectangle list whose primitive id shares a register with a vertex output",
|
||||
));
|
||||
}
|
||||
outputs.push(SigElement {
|
||||
interp: 1,
|
||||
usage: (1 << e.cols) - 1,
|
||||
..e.clone()
|
||||
});
|
||||
Some(outputs.len() - 1)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum();
|
||||
if scalars * VERTICES > MAX_SCALARS {
|
||||
return Err(unsupported(
|
||||
"a rectangle list with more output components than a geometry shader emits",
|
||||
));
|
||||
}
|
||||
s.outputs = outputs;
|
||||
let b = s.entry;
|
||||
|
||||
// Every input of the three vertices: [element][column][vertex].
|
||||
let mut corners: Vec<Vec<[V; 3]>> = Vec::new();
|
||||
for id in 0..s.inputs.len() {
|
||||
let mut columns = Vec::new();
|
||||
for col in 0..s.inputs[id].cols {
|
||||
columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex)));
|
||||
}
|
||||
corners.push(columns);
|
||||
}
|
||||
|
||||
// One positive w, and no two vertices in one place.
|
||||
let (x, y, w) = (
|
||||
corners[position][0],
|
||||
corners[position][1],
|
||||
corners[position][3],
|
||||
);
|
||||
let zero = s.m.f32(0);
|
||||
let mut plain = s.m.cmp(b, pred::OGT, w[0], zero);
|
||||
for &other in &w[1..] {
|
||||
let one_w = same(&mut s, other, w[0]);
|
||||
plain = both(&mut s, plain, one_w);
|
||||
}
|
||||
for (i, j) in [(0, 1), (0, 2), (1, 2)] {
|
||||
let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j]));
|
||||
let together = both(&mut s, same_x, same_y);
|
||||
let apart = not(&mut s, together);
|
||||
plain = both(&mut s, plain, apart);
|
||||
}
|
||||
// corner[i]: vertex i is the corner between the other two (the first
|
||||
// that shares x with one of them and y with the other).
|
||||
let mut corner: Vec<V> = Vec::new();
|
||||
for i in 0..3 {
|
||||
let (a, c) = ((i + 1) % 3, (i + 2) % 3);
|
||||
let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c]));
|
||||
let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a]));
|
||||
let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya));
|
||||
let shares = either(&mut s, one, other);
|
||||
let mut here = both(&mut s, shares, plain);
|
||||
for &found in &corner {
|
||||
let earlier = not(&mut s, found);
|
||||
here = both(&mut s, here, earlier);
|
||||
}
|
||||
corner.push(here);
|
||||
}
|
||||
|
||||
// What the six emitted vertices carry: [element][column][vertex].
|
||||
let mut emitted: Vec<Vec<[V; 6]>> = Vec::new();
|
||||
for (id, columns) in corners.iter().enumerate() {
|
||||
let float = s.inputs[id].comp == 9;
|
||||
let mut out = Vec::new();
|
||||
for &[p0, p1, p2] in columns {
|
||||
// The fourth vertex: `a + b - corner`. Integers (flat), and
|
||||
// three vertices without a corner, keep the first vertex's
|
||||
// value; the second triangle of the latter is then empty.
|
||||
let mut fourth = p0;
|
||||
if float {
|
||||
for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let sum = s.m.bin(b, Bin::Add, a, c);
|
||||
let opposite = s.m.bin(b, Bin::Sub, sum, at);
|
||||
fourth = s.m.select(b, corner[k], opposite, fourth);
|
||||
}
|
||||
}
|
||||
// Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1,
|
||||
// v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1).
|
||||
let third = s.m.select(b, corner[0], fourth, p2);
|
||||
let fifth = s.m.select(b, corner[1], p2, fourth);
|
||||
let sixth = s.m.select(b, corner[0], p2, p1);
|
||||
let sixth = s.m.select(b, corner[1], fourth, sixth);
|
||||
out.push([p0, p1, third, p0, fifth, sixth]);
|
||||
}
|
||||
emitted.push(out);
|
||||
}
|
||||
|
||||
// The rectangle's number: the triangle's, three vertices a rectangle.
|
||||
let mut number = None;
|
||||
if let Some(id) = primitive {
|
||||
let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]);
|
||||
number = Some((id, n));
|
||||
}
|
||||
let stream = s.m.i8(0);
|
||||
for vertex in 0..VERTICES as usize {
|
||||
for (id, columns) in emitted.iter().enumerate() {
|
||||
let name = if s.outputs[id].comp == 9 {
|
||||
"storeOutput.f32"
|
||||
} else {
|
||||
"storeOutput.i32"
|
||||
};
|
||||
for (col, values) in columns.iter().enumerate() {
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col as u8),
|
||||
values[vertex],
|
||||
];
|
||||
s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
if let Some((id, n)) = number {
|
||||
let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n];
|
||||
s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]);
|
||||
// The strip ends after the first triangle.
|
||||
if vertex == 2 {
|
||||
s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
Ok(s.finish())
|
||||
}
|
||||
|
||||
/// Column `col` of input `id` at vertex `vertex` of the triangle.
|
||||
fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V {
|
||||
let (name, ty) = if s.inputs[id].comp == 9 {
|
||||
("loadInput.f32", s.t.f32)
|
||||
} else {
|
||||
("loadInput.i32", s.t.i32)
|
||||
};
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col),
|
||||
s.m.i32(vertex),
|
||||
];
|
||||
let entry = s.entry;
|
||||
s.op(entry, name, Attr::ReadNone, ty, 4, &args)
|
||||
}
|
||||
|
||||
/// Two floats are equal.
|
||||
fn same(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.cmp(entry, pred::OEQ, a, b)
|
||||
}
|
||||
|
||||
fn both(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::And, a, b)
|
||||
}
|
||||
|
||||
fn either(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::Or, a, b)
|
||||
}
|
||||
|
||||
fn not(s: &mut Shader, a: V) -> V {
|
||||
let (entry, on) = (s.entry, s.m.bool(true));
|
||||
s.m.bin(entry, Bin::Xor, a, on)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index,
|
||||
kind,
|
||||
comp,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A position, a float interpolant and an integer one.
|
||||
fn outputs() -> Vec<SigElement> {
|
||||
vec![
|
||||
element("SV_Position", 0, 3, 9, 0, 4),
|
||||
element("TEXCOORD", 0, 0, 9, 1, 4),
|
||||
element("TEXCOORD", 1, 0, 5, 2, 2),
|
||||
]
|
||||
}
|
||||
|
||||
/// The stage is a geometry shader of triangles in and six strip
|
||||
/// vertices out, with the vertex shader's outputs on both sides and
|
||||
/// the primitive id the pixel shader declares; the validator, where
|
||||
/// there is one, accepts it.
|
||||
#[test]
|
||||
fn the_rectangle_stage_is_a_geometry_shader() {
|
||||
let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)];
|
||||
let gs = build(outputs(), &wanted).unwrap();
|
||||
let c = Container::parse(&gs).unwrap();
|
||||
// Program version: geometry (2), shader model 6.6.
|
||||
assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]);
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
// Triangles in, triangle strips out, stream 0, a position.
|
||||
assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]);
|
||||
// Geometry stage, six vertices, three inputs, four outputs.
|
||||
assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]);
|
||||
let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap();
|
||||
let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1));
|
||||
assert_eq!(ins.len(), 3);
|
||||
assert_eq!(outs.len(), 4);
|
||||
for (i, o) in ins.iter().zip(&outs) {
|
||||
assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row));
|
||||
assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp));
|
||||
}
|
||||
assert_eq!((outs[3].kind, outs[3].row), (10, Some(3)));
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut gs.clone()).unwrap();
|
||||
let plain = build(outputs(), &[]).unwrap();
|
||||
v.validate(&mut plain.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused with a reason: no position, a primitive id in a register a
|
||||
/// vertex output has, more components than six vertices may carry.
|
||||
#[test]
|
||||
fn rectangle_stages_that_cannot_be_made_are_refused() {
|
||||
assert!(build(outputs()[1..].to_vec(), &[]).is_err());
|
||||
let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)];
|
||||
assert!(build(outputs(), &taken).is_err());
|
||||
let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)];
|
||||
many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4)));
|
||||
assert!(build(many, &[]).is_err());
|
||||
}
|
||||
|
||||
/// A vertex shader that passes a position and a float4 through, and a
|
||||
/// pixel shader that writes the float4.
|
||||
#[cfg(windows)]
|
||||
fn pass_through() -> (super::super::HostShader, super::super::HostShader) {
|
||||
let position = SigElement {
|
||||
interp: 4,
|
||||
usage: 15,
|
||||
..element("SV_Position", 0, 3, 9, 0, 4)
|
||||
};
|
||||
let coord = SigElement {
|
||||
interp: 2,
|
||||
usage: 15,
|
||||
..element("TEXCOORD", 0, 0, 9, 1, 4)
|
||||
};
|
||||
let mut vs = Shader::new(false);
|
||||
vs.inputs = vec![
|
||||
SigElement {
|
||||
usage: 15,
|
||||
..element("POSITION", 0, 0, 9, 0, 4)
|
||||
},
|
||||
SigElement {
|
||||
interp: 0,
|
||||
..coord.clone()
|
||||
},
|
||||
];
|
||||
vs.outputs = vec![position.clone(), coord.clone()];
|
||||
let mut ps = Shader::new(true);
|
||||
ps.inputs = vec![
|
||||
SigElement {
|
||||
usage: 0,
|
||||
..position
|
||||
},
|
||||
coord,
|
||||
];
|
||||
ps.outputs = vec![SigElement {
|
||||
usage: 15,
|
||||
..element("SV_Target", 0, 16, 9, 0, 4)
|
||||
}];
|
||||
// Vertex: output id from input id. Pixel: target 0 from input 1.
|
||||
for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] {
|
||||
let b = s.entry;
|
||||
for &(from, to) in copies {
|
||||
for col in 0..4 {
|
||||
let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
|
||||
let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
|
||||
let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v];
|
||||
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
}
|
||||
let host = |stage, s: Shader| super::super::HostShader {
|
||||
stage,
|
||||
dxil: s.finish(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
(
|
||||
host(crate::native::HwStage::Vs, vs),
|
||||
host(crate::native::HwStage::Ps, ps),
|
||||
)
|
||||
}
|
||||
|
||||
/// Three corners of the whole target, the corner between the other two
|
||||
/// first (as the tiled lighting sends its tiles), second (as
|
||||
/// full-screen rectangles come) or third: with the stage every texel
|
||||
/// is drawn and the interpolant continues into the fourth corner's
|
||||
/// half; without it part of the target is not drawn.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn rectangles_are_drawn_whole() {
|
||||
use super::super::host::{Draw, Host};
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 device; skipped");
|
||||
return;
|
||||
};
|
||||
let (vs, ps) = pass_through();
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut vs.dxil.clone()).unwrap();
|
||||
v.validate(&mut ps.dxil.clone()).unwrap();
|
||||
}
|
||||
let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap();
|
||||
let root = host.root_signature(&vs, &ps).unwrap();
|
||||
// Position (z 0.5, w 1) and an interpolant that is the position.
|
||||
let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0];
|
||||
for (name, corners) in [
|
||||
("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]),
|
||||
("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]),
|
||||
("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]),
|
||||
] {
|
||||
let vertices = corners.map(vertex).concat();
|
||||
let draw = |gs: Option<&[u8]>| {
|
||||
let pso = host
|
||||
.pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil)
|
||||
.unwrap();
|
||||
let d = Draw {
|
||||
roots: Vec::new(),
|
||||
textures: &[],
|
||||
samplers: &[],
|
||||
vertices: &vertices,
|
||||
stride: 32,
|
||||
size: (8, 8),
|
||||
mesh_groups: 0,
|
||||
};
|
||||
host.draw(&root, &pso, &d).unwrap()
|
||||
};
|
||||
let whole = draw(Some(&gs[..]));
|
||||
for (i, texel) in whole.iter().enumerate() {
|
||||
let (x, y) = ((i % 8) as f32, (i / 8) as f32);
|
||||
let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0];
|
||||
assert!(
|
||||
texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4),
|
||||
"{name}: texel {i} is {texel:?}, not {want:?}"
|
||||
);
|
||||
}
|
||||
let half = draw(None);
|
||||
let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count();
|
||||
assert!(missing >= 24, "{name}: only {missing} texels need the stage");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,73 @@ pub const SAMPLER_SPACE: u32 = 0;
|
||||
/// `t<root parameter index>` in this space.
|
||||
pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
|
||||
/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
|
||||
/// reads buffers through descriptors it picks from the view heap at an
|
||||
/// index it computes (SM 6.6 dynamic resources): a raw buffer of
|
||||
/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
|
||||
/// element of the buffer view at heap slot `i` (0: none or not a buffer).
|
||||
/// The console's descriptor holds that stride and its hardware multiplies
|
||||
/// the element index by it; the program's code does not say it, and the
|
||||
/// used-resource list only names what tables hold. A shader that has this
|
||||
/// root SRV also tells the host that the buffer views of the whole heap
|
||||
/// must be ready when it runs, not only those its tables name.
|
||||
pub const SLOT_STRIDES: u8 = 255;
|
||||
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
|
||||
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
|
||||
|
||||
/// Title memory by address (`resource::MEMORY`): console code reads and
|
||||
/// writes through raw 40-bit addresses it takes from root constants,
|
||||
/// descriptors and other memory (the ray-tracing structure builder and the
|
||||
/// programs that walk its structures). The host keeps copies of the title
|
||||
/// memory shaders use; a shader with such an access finds the copy by the
|
||||
/// address:
|
||||
///
|
||||
/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
|
||||
/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
|
||||
/// address space: the number of the host copy holding that page (0: none
|
||||
/// yet) and the page's byte offset in that copy;
|
||||
/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
|
||||
/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
|
||||
/// reads zeros and drops writes;
|
||||
/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
|
||||
/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
|
||||
/// host reads afterwards to make those copies for the frames to come.
|
||||
pub const SLOT_MEMORY: u8 = 254;
|
||||
/// See [`SLOT_MEMORY`].
|
||||
pub const SLOT_FAULTS: u8 = 253;
|
||||
/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
|
||||
pub const MEMORY_PAGES: u32 = 1 << 21;
|
||||
/// Dwords of the [`SLOT_FAULTS`] buffer.
|
||||
pub const MEMORY_FAULTS: u32 = 4096;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the view
|
||||
/// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
|
||||
pub const USER_MEMORY_BASE: u32 = 0x100;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the low
|
||||
/// 32 bits of the title address of the buffer view at dword `dword` of the
|
||||
/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
|
||||
/// its bits from 32 up. (Console code reads the address out of a buffer
|
||||
/// descriptor and uses it as a pointer.)
|
||||
pub const USER_VIEW_ADDRESS: u32 = 0x101;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the
|
||||
/// bytes (0 to 15) by which the raw view the host binds for the root view
|
||||
/// of root parameter `slot` begins before the title's address. A raw view
|
||||
/// begins on 16 bytes of its host buffer; the console's root views begin
|
||||
/// anywhere (the structure builder's counters sit at addresses ending in
|
||||
/// 4 and c). The shader adds the dword to every byte offset through that
|
||||
/// view. Asked for every root UAV, and for the root SRVs of programs with
|
||||
/// a spilled user-data table.
|
||||
pub const USER_VIEW_BIAS: u32 = 0x103;
|
||||
|
||||
/// `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 BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
pub const ATOMIC_TYPED64: u64 = 1 << 27;
|
||||
pub const ATOMIC_HEAP64: u64 = 1 << 32;
|
||||
pub const RESOURCE_HEAP: u64 = 1 << 30;
|
||||
pub const SAMPLER_HEAP: u64 = 1 << 31;
|
||||
}
|
||||
@@ -45,6 +105,25 @@ pub(crate) struct Mesh {
|
||||
pub topology: u8,
|
||||
}
|
||||
|
||||
/// What a geometry shader declares: triangles in, triangle strips out on
|
||||
/// stream 0, one instance.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Geometry {
|
||||
pub max_vertices: u32,
|
||||
}
|
||||
|
||||
/// The null slot a host view heap keeps at its end when the title's heap did not fit in it
|
||||
/// (0: no limit). Shaders translated while it is set read that slot for any view index at or
|
||||
/// past it: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
|
||||
/// larger) hung its GPU on reads past the end (GPU-based validation: "descriptor heap index
|
||||
/// out of bounds"), which AMD's driver forgives.
|
||||
static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
|
||||
pub fn set_view_heap_limit(null_slot: u32) {
|
||||
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) struct Shader {
|
||||
pub m: Module,
|
||||
pub t: Types,
|
||||
@@ -55,6 +134,8 @@ pub(crate) struct Shader {
|
||||
pub prims: Vec<SigElement>,
|
||||
/// A mesh shader (`threads` is its thread-group size).
|
||||
pub mesh: Option<Mesh>,
|
||||
/// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
|
||||
pub geometry: Option<Geometry>,
|
||||
/// Dwords of user data the shader reads (0: no user-data buffer).
|
||||
pub user_data: u32,
|
||||
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
|
||||
@@ -65,6 +146,8 @@ pub(crate) struct Shader {
|
||||
pub root_cbvs: Vec<(u8, V)>,
|
||||
/// Root SRVs (raw buffers) read, likewise.
|
||||
pub root_srvs: Vec<(u8, V)>,
|
||||
/// Root UAVs (raw buffers) read or written, likewise.
|
||||
pub root_uavs: Vec<(u8, V)>,
|
||||
pub flags: u64,
|
||||
/// Heap handles made with a non-uniform index.
|
||||
pub nonuniform_handles: u32,
|
||||
@@ -115,11 +198,13 @@ impl Shader {
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh: None,
|
||||
geometry: None,
|
||||
user_data: 0,
|
||||
samplers: 0,
|
||||
cmp_samplers: 0,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
flags: 0,
|
||||
nonuniform_handles: 0,
|
||||
threads: None,
|
||||
@@ -236,6 +321,31 @@ impl Shader {
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root UAV (a raw buffer) of root parameter `slot`:
|
||||
/// `u<slot>` in [`ROOT_CBV_SPACE`].
|
||||
pub fn root_uav_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11 | 0x1000, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_uavs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of immediate sampler `n` (a comparison sampler when its
|
||||
/// bit in `cmp_samplers` is set).
|
||||
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
|
||||
@@ -286,6 +396,25 @@ impl Shader {
|
||||
nonuniform: bool,
|
||||
props: (u32, u32),
|
||||
) -> V {
|
||||
// a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
|
||||
let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
// (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
|
||||
let index = if !sampler && limit != 0 {
|
||||
let null = self.m.i32(limit);
|
||||
let i32t = self.t.i32;
|
||||
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null])
|
||||
} else if sampler {
|
||||
// A sampler heap has at most 2,048 samplers on any host: an
|
||||
// index past that (a number read from memory the host has not
|
||||
// got yet) stays inside the largest heap there is.
|
||||
// shortcut: not the bound heap's own count, which a title
|
||||
// heap smaller than 2,048 would need.
|
||||
let last = self.m.i32(2047);
|
||||
let i32t = self.t.i32;
|
||||
self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last])
|
||||
} else {
|
||||
index
|
||||
};
|
||||
self.flags |= if sampler {
|
||||
flags::SAMPLER_HEAP
|
||||
} else {
|
||||
@@ -318,6 +447,7 @@ impl Shader {
|
||||
|| self.samplers > 0
|
||||
|| !self.root_cbvs.is_empty()
|
||||
|| !self.root_srvs.is_empty()
|
||||
|| !self.root_uavs.is_empty()
|
||||
{
|
||||
let empty = self.m.md_str("");
|
||||
let mut cbvs = None;
|
||||
@@ -401,6 +531,43 @@ impl Shader {
|
||||
}
|
||||
srvs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut uavs = None;
|
||||
if !self.root_uavs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let no = self.m.bool(false);
|
||||
let no = self.m.md_value(no);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
|
||||
// Id, variable, name, space, lower bound, range size,
|
||||
// shape (11: raw buffer), globally coherent, counter,
|
||||
// rasterizer ordered, no extra properties.
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(no),
|
||||
Some(no),
|
||||
Some(no),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 7,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
uavs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut samplers = None;
|
||||
if self.samplers > 0 {
|
||||
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
|
||||
@@ -430,11 +597,12 @@ impl Shader {
|
||||
}
|
||||
samplers = Some(self.m.md_node(list));
|
||||
}
|
||||
resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs.
|
||||
resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
|
||||
bindings.sort_by_key(|b| match b.kind {
|
||||
2 => 0,
|
||||
1 => 1,
|
||||
7 => 3,
|
||||
_ => 2,
|
||||
});
|
||||
}
|
||||
@@ -468,6 +636,11 @@ impl Shader {
|
||||
});
|
||||
}
|
||||
}
|
||||
// A geometry shader lists four streams: the other three have
|
||||
// no outputs.
|
||||
if self.geometry.is_some() {
|
||||
view.extend([0, 0, 0]);
|
||||
}
|
||||
let arr = self.m.array(view.len() as u32, self.t.i32);
|
||||
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
|
||||
let arr = self.m.aggregate(arr, &elems);
|
||||
@@ -488,8 +661,8 @@ impl Shader {
|
||||
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).
|
||||
// Entry properties: shader flags (tag 0), geometry state (1),
|
||||
// thread-group size (4), wave size (11).
|
||||
let mut props = Vec::new();
|
||||
if self.flags != 0 {
|
||||
props.push(i32c(&mut self, 0));
|
||||
@@ -497,6 +670,13 @@ impl Shader {
|
||||
let f = self.m.int_const(i64t, self.flags as i64);
|
||||
props.push(self.m.md_value(f));
|
||||
}
|
||||
if let Some(g) = self.geometry {
|
||||
// Input primitive (3: triangles), maximum vertices, stream
|
||||
// mask, output topology (5: triangle strips), instances.
|
||||
props.push(i32c(&mut self, 1));
|
||||
let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
|
||||
props.push(self.m.md_node(state.to_vec()));
|
||||
}
|
||||
if let Some(threads) = self.threads {
|
||||
let t = threads.map(|n| Some(i32c(&mut self, n)));
|
||||
let t = self.m.md_node(t.to_vec());
|
||||
@@ -543,9 +723,10 @@ impl Shader {
|
||||
let version = self.m.md_node(vec![Some(one), Some(six)]);
|
||||
self.m.named_md("dx.version", vec![version]);
|
||||
self.m.named_md("dx.valver", vec![version]);
|
||||
// Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh.
|
||||
// Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
|
||||
let (name, kind) = match (self.threads, self.pixel) {
|
||||
_ if self.mesh.is_some() => ("ms", 13u32),
|
||||
_ if self.geometry.is_some() => ("gs", 2),
|
||||
(Some(_), _) => ("cs", 5u32),
|
||||
(None, true) => ("ps", 0),
|
||||
(None, false) => ("vs", 1),
|
||||
@@ -578,12 +759,21 @@ impl Shader {
|
||||
if self.flags & flags::INT64 != 0 {
|
||||
features |= 0x8000;
|
||||
}
|
||||
if self.flags & flags::BARYCENTRICS != 0 {
|
||||
features |= 0x2_0000;
|
||||
}
|
||||
if self.flags & flags::RESOURCE_HEAP != 0 {
|
||||
features |= 0x200_0000;
|
||||
}
|
||||
if self.flags & flags::SAMPLER_HEAP != 0 {
|
||||
features |= 0x400_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_TYPED64 != 0 {
|
||||
features |= 0x40_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_HEAP64 != 0 {
|
||||
features |= 0x1000_0000;
|
||||
}
|
||||
let sfi0 = features.to_le_bytes();
|
||||
let isg1 = container::signature(&self.inputs, true);
|
||||
let osg1 = container::signature(&self.outputs, false);
|
||||
@@ -599,6 +789,7 @@ impl Shader {
|
||||
outputs: &self.outputs,
|
||||
prims: &self.prims,
|
||||
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
|
||||
geometry: self.geometry.map(|g| g.max_vertices),
|
||||
bindings: &bindings,
|
||||
threads: self.threads.unwrap_or_default(),
|
||||
wave_size: self.wave_size,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Jump threading for uniform diamonds. One arm can set a flag that fixes
|
||||
//! the join's next branch. Registers recycled on that arm then never reach
|
||||
//! the other successor, even if an ordinary SSA phi joins their values.
|
||||
use crate::gfx10::{Fields, Operand, Valu};
|
||||
use crate::ir::{Exit, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn plain(v: &Valu) -> bool {
|
||||
v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& v.opsel == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0
|
||||
&& v.sdwa.is_none()
|
||||
&& v.dpp.is_none()
|
||||
}
|
||||
|
||||
fn immediate(op: Operand) -> Option<u32> {
|
||||
match op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(n) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
|
||||
let mut constants = HashMap::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if inst.name() == "v_mov_b32"
|
||||
&& st.guards[b][i].is_none()
|
||||
&& let Fields::Valu(v) = &inst.fields
|
||||
&& plain(v)
|
||||
&& let [src] = v.src.as_slice()
|
||||
&& let Some(word) = immediate(*src)
|
||||
&& let [(_, dst)] = inst.writes.as_slice()
|
||||
{
|
||||
constants.insert(*dst, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges = Vec::new();
|
||||
for (join, block) in p.blocks.iter().enumerate() {
|
||||
let LaneExit::Branch {
|
||||
when,
|
||||
taken,
|
||||
not_taken,
|
||||
} = st.exits[join]
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if when == Bool::TRUE || when == Bool::FALSE {
|
||||
continue;
|
||||
}
|
||||
// Keep memory accesses and wave operations at their original
|
||||
// reconvergence point. Only duplicate scalar ALU and comparisons.
|
||||
if !block.insts.iter().all(|i| match &i.fields {
|
||||
Fields::Sop { .. } => true,
|
||||
Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
|
||||
Fields::Valu(_) => i.name().starts_with("v_cmp_"),
|
||||
_ => false,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = block.preds.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
// A triangle has a direct edge from the fork to the join. A full
|
||||
// diamond has an unconditional jump at the end of each arm.
|
||||
let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
|
||||
&[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
|
||||
_ => None,
|
||||
};
|
||||
let fork = match (arm_from(*a), arm_from(*b)) {
|
||||
(Some(f), Some(g)) if f == g => f,
|
||||
(_, Some(f)) if f == *a => f,
|
||||
(Some(f), _) if f == *b => f,
|
||||
_ => continue,
|
||||
};
|
||||
if fork == join || a == b {
|
||||
continue;
|
||||
}
|
||||
let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
|
||||
continue;
|
||||
};
|
||||
if !st
|
||||
.bools
|
||||
.support(entry)
|
||||
.iter()
|
||||
.all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (edge, &pred) in block.preds.iter().enumerate() {
|
||||
let value = |v: Value| {
|
||||
let input = block
|
||||
.phis
|
||||
.iter()
|
||||
.find(|p| p.value == v)
|
||||
.map_or(v, |p| p.args[edge]);
|
||||
constants.get(&input).copied()
|
||||
};
|
||||
// Restrict the branch's decision diagram to known comparisons.
|
||||
// Unknown tests stop the proof. Keep the original join for the
|
||||
// other arm, which may still go either way.
|
||||
let mut cond = when;
|
||||
while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
|
||||
let Some(inst) = block
|
||||
.insts
|
||||
.iter()
|
||||
.find(|i| i.writes.iter().any(|&(_, v)| v == id))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let Fields::Valu(v) = &inst.fields else { break };
|
||||
let [left, right] = v.src.as_slice() else {
|
||||
break;
|
||||
};
|
||||
let operand = |op| match op {
|
||||
Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
|
||||
_ => immediate(op),
|
||||
};
|
||||
let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
|
||||
break;
|
||||
};
|
||||
if !plain(v) {
|
||||
break;
|
||||
}
|
||||
let yes = match inst.name() {
|
||||
"v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
|
||||
"v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
|
||||
_ => break,
|
||||
};
|
||||
cond = if yes { hi } else { lo };
|
||||
}
|
||||
if cond == Bool::TRUE || cond == Bool::FALSE {
|
||||
edges.push((
|
||||
pred,
|
||||
join,
|
||||
if cond == Bool::TRUE { taken } else { not_taken },
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ir;
|
||||
use crate::structure;
|
||||
|
||||
// s8 initially holds a descriptor address. One arm overwrites it with
|
||||
// a buffer load and sets v1. Only that arm can use s8 as the stored value.
|
||||
const WORDS: [u32; 19] = [
|
||||
0xbe810380, // s1 = 0 (table address high)
|
||||
0xf4080200, 0xfa000000, // load SRV into s[8:11]
|
||||
0xf4080300, 0xfa000020, // load UAV into s[12:15]
|
||||
0x7e020280, // v1 = 0
|
||||
0xbf068002, 0xbf850003, // if s2 == 0, jump to join
|
||||
0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
|
||||
0x7e020281, // v1 = 1
|
||||
0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
|
||||
0x7e060208, 0xbf820001, // v3 = s8, jump to store
|
||||
0x7e060293, // constant: v3 = 19
|
||||
0xe0700000, 0x80030300, // store v3 at byte 0
|
||||
0xbf810000, // end
|
||||
];
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
ir::build(
|
||||
&words
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect::<Vec<_>>(),
|
||||
false,
|
||||
4,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_buffer_load_reaches_the_numeric_read() {
|
||||
let p = program(&WORDS);
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let edges = constant_edges(&p, &st);
|
||||
assert_eq!(edges, [(0, 2, 4)]);
|
||||
let p = ir::thread_edges(&p, &edges).unwrap();
|
||||
let load = &p.blocks[1].insts[0];
|
||||
assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
|
||||
assert_eq!(
|
||||
p.blocks[0].exit,
|
||||
Exit::Branch {
|
||||
taken: 6,
|
||||
not_taken: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(p.blocks[6].exit, Exit::Jump(4));
|
||||
assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_unknown_flags_and_divergent_forks_alone() {
|
||||
let mut words = WORDS;
|
||||
words[5] = 0x7e020202; // v1 = s2
|
||||
words[10] = 0x7e020203; // v1 = s3
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
let mut words = WORDS;
|
||||
words[6] = 0x7d840080; // compare 0 with lane-dependent v0
|
||||
words[7] = 0xbf870003; // branch on VCC
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//!
|
||||
//! Covers RDNA2 hardware semantics that differ from naive DXIL lowering:
|
||||
//! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16`
|
||||
//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`.
|
||||
//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS
|
||||
//! float atomics `ds_min_f32`/`ds_max_f32`.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
@@ -43,9 +44,33 @@ const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
|
||||
|
||||
/// VOP3 `op vdst, src0, src1, src2` (no modifiers).
|
||||
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false)
|
||||
}
|
||||
|
||||
/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
const fn vop3_mod(
|
||||
op: u16,
|
||||
vdst: u8,
|
||||
src0: u16,
|
||||
src1: u16,
|
||||
src2: u16,
|
||||
abs: u8,
|
||||
neg: u8,
|
||||
omod: u8,
|
||||
clamp: bool,
|
||||
) -> [u32; 2] {
|
||||
[
|
||||
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
|
||||
0x35 << 26
|
||||
| (op as u32 & 0x3FF) << 16
|
||||
| (clamp as u32) << 15
|
||||
| (abs as u32 & 7) << 8
|
||||
| vdst as u32,
|
||||
(neg as u32 & 7) << 29
|
||||
| (omod as u32 & 3) << 27
|
||||
| (src0 as u32 & 0x1FF)
|
||||
| (src1 as u32 & 0x1FF) << 9
|
||||
| (src2 as u32 & 0x1FF) << 18,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -69,6 +94,12 @@ const fn vgpr(n: u8) -> u16 {
|
||||
/// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in
|
||||
/// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0.
|
||||
fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
build_cs(body, 1, 0)
|
||||
}
|
||||
|
||||
/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0`
|
||||
/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512).
|
||||
fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
|
||||
let mut words = Vec::new();
|
||||
// s[4:5] = descriptor table address (heap index 0 -> byte offset 0).
|
||||
words.push(s_mov_b32(5, 0x80)); // inline constant 0
|
||||
@@ -116,8 +147,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
|
||||
threads: [1, 1, 1],
|
||||
rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4
|
||||
threads: [threads, 1, 1],
|
||||
}),
|
||||
code,
|
||||
};
|
||||
@@ -148,6 +179,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
};
|
||||
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
@@ -172,11 +205,20 @@ pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()
|
||||
fn run_cases(
|
||||
shader: &HostShader,
|
||||
cases: &[[u32; 4]],
|
||||
check: impl FnMut(&str, usize, [u32; 4], u32),
|
||||
) {
|
||||
run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check);
|
||||
}
|
||||
|
||||
fn run_cases_on(
|
||||
shader: &HostShader,
|
||||
cases: &[[u32; 4]],
|
||||
devices: &[(&str, bool)],
|
||||
mut check: impl FnMut(&str, usize, [u32; 4], u32),
|
||||
) {
|
||||
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)] {
|
||||
for &(label, warp) in devices {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
@@ -209,7 +251,7 @@ fn run_cases(
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
|
||||
assert!(ran > 0, "no SM 6.6 device available ({devices:?})");
|
||||
}
|
||||
|
||||
fn is_f16_nan(bits: u16) -> bool {
|
||||
@@ -868,6 +910,286 @@ fn bfe_signed_and_unsigned_match_rdna2() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f16_omod_applies_before_clamp() {
|
||||
// VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp]
|
||||
let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false));
|
||||
let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false));
|
||||
let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false));
|
||||
let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true));
|
||||
|
||||
// f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800
|
||||
run_cases(
|
||||
&mul2,
|
||||
&[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2");
|
||||
},
|
||||
);
|
||||
run_cases(
|
||||
&mul4,
|
||||
&[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4");
|
||||
},
|
||||
);
|
||||
run_cases(
|
||||
&div2,
|
||||
&[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00)
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2");
|
||||
},
|
||||
);
|
||||
// Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00),
|
||||
// whereas clamp before div:2 would give 0.5 (0x3800).
|
||||
let clamp_cases: &[(u16, u16, u16)] = &[
|
||||
(0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75
|
||||
(0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0
|
||||
(0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0
|
||||
];
|
||||
let inputs: Vec<[u32; 4]> = clamp_cases
|
||||
.iter()
|
||||
.map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0])
|
||||
.collect();
|
||||
run_cases(&div2_clamp, &inputs, |backend, i, _, got| {
|
||||
let want = clamp_cases[i].2;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}",
|
||||
got as u16,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() {
|
||||
// VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52)
|
||||
// VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53)
|
||||
let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false));
|
||||
let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false));
|
||||
let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false));
|
||||
let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false));
|
||||
|
||||
let u16_cases: &[(u16, u16)] = &[
|
||||
(0xBC00, 0), // -1.0 -> 0
|
||||
(0xFC00, 0), // -inf -> 0
|
||||
(0x7E00, 0), // NaN -> 0
|
||||
(0x57BC, 123), // 123.75 -> 123
|
||||
(0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504
|
||||
(0x7C00, 0xFFFF), // +inf -> 65535 (saturated)
|
||||
];
|
||||
let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
|
||||
run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| {
|
||||
let want = u16_cases[i].1;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}",
|
||||
inp[0], got as u16,
|
||||
);
|
||||
});
|
||||
run_cases(
|
||||
&cvt_u16_abs,
|
||||
&[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|");
|
||||
},
|
||||
);
|
||||
|
||||
let i16_cases: &[(u16, u16)] = &[
|
||||
(0xFC00, 0x8000), // -inf -> -32768
|
||||
(0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped)
|
||||
(0xD7BC, (-123i16) as u16), // -123.75 -> -123
|
||||
(0x7E00, 0), // NaN -> 0
|
||||
(0x57BC, 123), // 123.75 -> 123
|
||||
(0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped)
|
||||
(0x7C00, 0x7FFF), // +inf -> 32767
|
||||
];
|
||||
let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
|
||||
run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| {
|
||||
let want = i16_cases[i].1;
|
||||
assert_eq!(
|
||||
got as u16, want,
|
||||
"{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}",
|
||||
inp[0], got as u16,
|
||||
);
|
||||
});
|
||||
run_cases(
|
||||
&cvt_i16_neg,
|
||||
&[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768
|
||||
|backend, i, _, got| {
|
||||
let want = [(-123i16) as u16, 0x8000][i];
|
||||
assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}");
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const S_BARRIER: u32 = 0xBF8A_0000;
|
||||
|
||||
/// VOP2 `op vdst, src0, vsrc1`.
|
||||
const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 {
|
||||
(op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
/// DS `op vdst, addr, data0` at offset 0.
|
||||
const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] {
|
||||
[
|
||||
0x36 << 26 | (op as u32) << 18,
|
||||
(vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32,
|
||||
]
|
||||
}
|
||||
|
||||
const DS_WRITE_B32: u8 = 0x0D;
|
||||
const DS_MIN_F32: u8 = 0x12;
|
||||
const DS_MAX_F32: u8 = 0x13;
|
||||
const DS_MIN_RTN_F32: u8 = 0x32;
|
||||
const DS_MAX_RTN_F32: u8 = 0x33;
|
||||
const DS_READ_B32: u8 = 0x36;
|
||||
|
||||
/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding
|
||||
/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept:
|
||||
/// an sNaN, data first, then memory, is written quieted; otherwise a NaN
|
||||
/// loses to a number (two quiet NaNs give the data); numbers compare as
|
||||
/// floats with -0 below +0.
|
||||
fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 {
|
||||
let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000;
|
||||
let snan = |x: u32| nan(x) && x & 0x40_0000 == 0;
|
||||
let key = |x: u32| {
|
||||
let b = x as i32;
|
||||
if b < 0 { b ^ 0x7FFF_FFFF } else { b }
|
||||
};
|
||||
if snan(data) {
|
||||
return data | 0x40_0000;
|
||||
}
|
||||
if snan(old) {
|
||||
return old | 0x40_0000;
|
||||
}
|
||||
match (nan(data), nan(old)) {
|
||||
(true, true) | (false, true) => return data,
|
||||
(true, false) => return old,
|
||||
(false, false) => {}
|
||||
}
|
||||
let take = if max {
|
||||
key(data) > key(old)
|
||||
} else {
|
||||
key(data) < key(old)
|
||||
};
|
||||
if take { data } else { old }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ds_min_max_f32_order_floats_and_return_the_old_value() {
|
||||
let values = [
|
||||
0.0f32,
|
||||
-0.0,
|
||||
1.0,
|
||||
-1.0,
|
||||
2.5,
|
||||
-2.5,
|
||||
1e-30,
|
||||
-1e-30,
|
||||
f32::from_bits(1), // denormal
|
||||
f32::from_bits(0x8000_0001),
|
||||
f32::INFINITY,
|
||||
f32::NEG_INFINITY,
|
||||
f32::MAX,
|
||||
f32::MIN,
|
||||
];
|
||||
// Quiet and signalling NaNs of both signs, in memory and as data.
|
||||
let nans = [
|
||||
0x7FC0_0000u32,
|
||||
0xFFC0_0000,
|
||||
0x7F80_0001,
|
||||
0xFFA0_0000,
|
||||
0x7FBF_FFFF,
|
||||
];
|
||||
let bits: Vec<u32> = values.iter().map(|v| v.to_bits()).chain(nans).collect();
|
||||
let mut cases: Vec<[u32; 4]> = Vec::new();
|
||||
for &old in &bits {
|
||||
for &data in &bits {
|
||||
cases.push([old, data, 0, 0]);
|
||||
}
|
||||
}
|
||||
for (rtn, plain, max, what) in [
|
||||
(DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"),
|
||||
(DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"),
|
||||
] {
|
||||
// v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value
|
||||
// (rtn) or the dword afterwards (read back).
|
||||
let mut returns_old = vec![vop1(0x001, 5, 0x80)];
|
||||
returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
returns_old.extend(ds(rtn, 0, 5, 2));
|
||||
let mut returns_new = vec![vop1(0x001, 5, 0x80)];
|
||||
returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
returns_new.extend(ds(plain, 0, 5, 2));
|
||||
returns_new.extend(ds(DS_READ_B32, 0, 5, 0));
|
||||
for (body, old_result) in [(returns_old, true), (returns_new, false)] {
|
||||
// One thread with LDS declares WaveSize(32), which WARP's
|
||||
// pipeline creation refuses: hardware only (the 64-thread test
|
||||
// below runs on WARP too).
|
||||
let shader = build_cs(&body, 1, 512);
|
||||
run_cases_on(
|
||||
&shader,
|
||||
&cases,
|
||||
&[("hardware", false)],
|
||||
|backend, _, inp, got| {
|
||||
let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1]));
|
||||
let want = if old_result {
|
||||
inp[0]
|
||||
} else {
|
||||
lds_min_max_ref(inp[0], inp[1], max)
|
||||
};
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})",
|
||||
inp[0],
|
||||
inp[1],
|
||||
if old_result {
|
||||
"old value"
|
||||
} else {
|
||||
"dword after"
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ds_min_max_f32_are_atomic_across_waves() {
|
||||
// 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then
|
||||
// every thread applies (thread - 32) as a float; v0 = LDS[0].
|
||||
for (op, max, init, want) in [
|
||||
(DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32),
|
||||
(DS_MAX_F32, true, 100.0, 100.0),
|
||||
(DS_MIN_F32, false, f32::INFINITY, -32.0),
|
||||
(DS_MIN_F32, false, -0.0, -32.0),
|
||||
] {
|
||||
let mut body = vec![vop1(0x001, 5, 0x80)];
|
||||
body.extend(ds(DS_WRITE_B32, 0, 5, 1));
|
||||
body.push(S_BARRIER);
|
||||
body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3
|
||||
body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32
|
||||
body.extend(ds(op, 0, 5, 6));
|
||||
body.push(S_BARRIER);
|
||||
body.extend(ds(DS_READ_B32, 0, 5, 0));
|
||||
let shader = build_cs(&body, 64, 512);
|
||||
run_cases(
|
||||
&shader,
|
||||
&[[init.to_bits(), 0, 32, 0]],
|
||||
|backend, _, _, got| {
|
||||
assert_eq!(
|
||||
f32::from_bits(got),
|
||||
want,
|
||||
"{backend}: {} from {init} over 64 threads",
|
||||
if max { "max" } else { "min" },
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v_cmp_class_f16_matches_rdna2() {
|
||||
// v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6
|
||||
|
||||
@@ -82,6 +82,8 @@ fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
|
||||
@@ -35,7 +35,9 @@ pub(crate) enum Op {
|
||||
impl Op {
|
||||
fn of(name: &str) -> Option<Op> {
|
||||
Some(match name {
|
||||
"v_add_nc_u32" => Op::AddU,
|
||||
// the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into
|
||||
// the high one) is the 32-bit sum of the low dwords
|
||||
"v_add_nc_u32" | "v_add_co_u32" => Op::AddU,
|
||||
"v_add_f32" => Op::AddF,
|
||||
"v_min_u32" => Op::MinU,
|
||||
"v_max_u32" => Op::MaxU,
|
||||
@@ -253,11 +255,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
let Some(k) = lo else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = if name == "s_mov_b64" {
|
||||
exec = (if name == "s_mov_b64" {
|
||||
k
|
||||
} else {
|
||||
exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF
|
||||
};
|
||||
(exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF)
|
||||
}) & all;
|
||||
continue;
|
||||
}
|
||||
if inst.write(Reg::S(EXEC + 1)).is_some() {
|
||||
@@ -268,7 +270,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = exec & 0xFFFF_FFFF | k << 32;
|
||||
exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all;
|
||||
continue;
|
||||
}
|
||||
if let Fields::Sop { src, .. } = &inst.fields {
|
||||
@@ -494,15 +496,18 @@ fn constant(inst: &Inst) -> Option<u64> {
|
||||
let Fields::Sop { src, .. } = &inst.fields else {
|
||||
return None;
|
||||
};
|
||||
let wide = inst.name() == "s_mov_b64";
|
||||
match *src.first()? {
|
||||
Operand::Const(c) => {
|
||||
Operand::Scalar { code: NULL, .. } => Some(0),
|
||||
Operand::Const(c @ 128..=208) => {
|
||||
let x = crate::resource::inline(c)?;
|
||||
Some(if (x as i32) < 0 {
|
||||
u64::MAX
|
||||
Some(if wide {
|
||||
i64::from(x as i32) as u64
|
||||
} else {
|
||||
u64::from(x)
|
||||
})
|
||||
}
|
||||
Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from),
|
||||
Operand::Literal(x) => Some(u64::from(x)),
|
||||
_ => None,
|
||||
}
|
||||
@@ -577,7 +582,8 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
};
|
||||
}
|
||||
// Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive).
|
||||
let mut found: Option<(Op, Value, Value, u32, bool)> = None;
|
||||
let mut meta: Option<(Value, Value, u32, bool)> = None;
|
||||
let mut op_found: Option<Op> = None;
|
||||
for (l, &s) in lanes.iter().enumerate() {
|
||||
let below = (1u64 << l) - 1;
|
||||
let (op, src, mask, ident, set) = match s {
|
||||
@@ -592,28 +598,40 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
Sym::K(_) if l == 0 => continue,
|
||||
_ => return None,
|
||||
};
|
||||
let inclusive = set == below | 1 << l;
|
||||
let inclusive = set == below | (1u64 << l);
|
||||
if !inclusive && set != below {
|
||||
return None;
|
||||
}
|
||||
let op = match (op, found) {
|
||||
(Some(o), _) => o,
|
||||
(None, Some(f)) => f.0,
|
||||
(None, None) => continue,
|
||||
};
|
||||
let me = (op, src, mask, ident, inclusive);
|
||||
match found {
|
||||
None => found = Some(me),
|
||||
Some(f) if f == me => {}
|
||||
if l == 0 && !inclusive {
|
||||
return None;
|
||||
}
|
||||
if op.is_none() && set.count_ones() != 1 {
|
||||
return None;
|
||||
}
|
||||
let lane_meta = (src, mask, ident, inclusive);
|
||||
match meta {
|
||||
None => meta = Some(lane_meta),
|
||||
Some(prev) if prev == lane_meta => {}
|
||||
_ => return None,
|
||||
}
|
||||
if let Some(o) = op {
|
||||
match op_found {
|
||||
None => op_found = Some(o),
|
||||
Some(prev) if prev == o => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
let (op, src, mask, ident, inclusive) = found?;
|
||||
if let Sym::K(k) = lanes[0]
|
||||
&& (inclusive || k != ident)
|
||||
{
|
||||
let (src, mask, ident, inclusive) = meta?;
|
||||
let op = op_found?;
|
||||
if !op.identity(ident) {
|
||||
return None;
|
||||
}
|
||||
match lanes[0] {
|
||||
Sym::K(k) if !inclusive && k == ident => {}
|
||||
Sym::Red { .. } if inclusive => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(Shape::Prefix(op, src, mask, ident, inclusive))
|
||||
}
|
||||
|
||||
@@ -621,6 +639,45 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 {
|
||||
0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32
|
||||
}
|
||||
|
||||
const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 {
|
||||
(0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 {
|
||||
(op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 {
|
||||
(row_mask as u32) << 28
|
||||
| (bank_mask as u32) << 24
|
||||
| (bound_ctrl as u32) << 19
|
||||
| (ctrl as u32) << 8
|
||||
| vsrc0 as u32
|
||||
}
|
||||
|
||||
const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
[
|
||||
0xD400_0000 | (op as u32) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18),
|
||||
]
|
||||
}
|
||||
|
||||
fn build(words: &[u32], wave64: bool) -> Program {
|
||||
let code: Vec<u8> = words
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(std::iter::once(S_ENDPGM))
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
crate::ir::build(&code, wave64, 256).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dpp_lanes_follow_the_isa() {
|
||||
// row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16.
|
||||
@@ -676,4 +733,220 @@ mod tests {
|
||||
Some(Shape::Active(Op::AddU, x, m, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_decodes_width_and_inline_kinds() {
|
||||
let b64 = 0x04;
|
||||
let b32 = 0x03;
|
||||
let check = |words: &[u32], wave64: bool| -> Option<u64> {
|
||||
let p = build(words, wave64);
|
||||
constant(&p.blocks[0].insts[0])
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 194)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFFE)
|
||||
);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 196)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFFC)
|
||||
);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 208)], true),
|
||||
Some(0xFFFF_FFFF_FFFF_FFF0)
|
||||
);
|
||||
assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX));
|
||||
assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0));
|
||||
assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None);
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b64, 255), 0x1234_5678], true),
|
||||
Some(0x1234_5678)
|
||||
);
|
||||
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE));
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000));
|
||||
assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0));
|
||||
assert_eq!(
|
||||
check(&[sop1(EXEC, b32, 255), 0x1234_5678], false),
|
||||
Some(0x1234_5678)
|
||||
);
|
||||
assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() {
|
||||
for wave64 in [false, true] {
|
||||
let mut w = Vec::new();
|
||||
let save_op = if wave64 { 0x25 } else { 0x3D };
|
||||
let mov_exec = if wave64 { 0x04 } else { 0x03 };
|
||||
let push_exec = |w: &mut Vec<u32>, k: u8| w.push(sop1(EXEC, mov_exec, k));
|
||||
let push_exec_lit = |w: &mut Vec<u32>, lit: u32| {
|
||||
w.push(sop1(EXEC, mov_exec, 255));
|
||||
w.push(lit);
|
||||
};
|
||||
|
||||
w.push(sop1(0, save_op, 193));
|
||||
w.extend(vop3(1, 0x101, 128, 256, 0));
|
||||
for shift in [1u16, 2, 4, 8] {
|
||||
w.push(vop2(1, 0x25, 0xFA, 1));
|
||||
w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false));
|
||||
}
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 15, 0));
|
||||
push_exec_lit(&mut w, 0xFFFF_0000);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
|
||||
if wave64 {
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 31, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0x0000_FFFF);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 47, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0xFFFF_0000);
|
||||
w.push(vop2(1, 0x25, 2, 1));
|
||||
}
|
||||
|
||||
push_exec(&mut w, 193);
|
||||
w.push(vop1(3, 0x01, 257));
|
||||
w.push(vop1(3, 0x01, 0xFA));
|
||||
w.push(dpp16(1, 0x111, 0xF, 0xF, false));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 15, 0));
|
||||
push_exec_lit(&mut w, 0x0001_0000);
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
|
||||
if wave64 {
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 31, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 129));
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
|
||||
w.extend(vop3(2, 0x360, 257, 128 + 47, 0));
|
||||
w.push(sop1(EXEC, 0x03, 128));
|
||||
w.push(sop1(EXEC + 1, 0x03, 255));
|
||||
w.push(0x0001_0000);
|
||||
w.push(vop1(3, 0x01, 2));
|
||||
}
|
||||
|
||||
push_exec(&mut w, 193);
|
||||
w.push(vop1(2, 0x01, 128));
|
||||
w.push(vop1(5, 0x01, 135));
|
||||
push_exec(&mut w, 194);
|
||||
w.push(vop1(2, 0x01, 259));
|
||||
w.push(vop1(4, 0x01, 0xFA));
|
||||
w.push(dpp16(5, 0xE4, 0xF, 0xF, false));
|
||||
w.push(sop1(EXEC, mov_exec, 0));
|
||||
|
||||
let p = build(&w, wave64);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let saved = insts[0].write(Reg::S(0)).unwrap();
|
||||
let v0_in = p
|
||||
.inputs
|
||||
.iter()
|
||||
.find_map(|&(r, v)| (r == Reg::V(0)).then_some(v))
|
||||
.unwrap();
|
||||
let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap();
|
||||
let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
assert_eq!(
|
||||
sec.shapes.get(&v2_val),
|
||||
Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false))
|
||||
);
|
||||
assert_eq!(sec.shapes.get(&v4_val), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() {
|
||||
let w = [
|
||||
sop1(0, 0x3D, 193),
|
||||
vop1(1, 0x01, 135),
|
||||
sop1(EXEC, 0x04, 193),
|
||||
vop1(2, 0x01, 0xFA),
|
||||
dpp16(1, 0xE4, 0xF, 0xF, false),
|
||||
sop1(EXEC + 1, 0x03, 193),
|
||||
vop1(3, 0x01, 0xFA),
|
||||
dpp16(1, 0xE4, 0xF, 0xF, false),
|
||||
sop1(EXEC, 0x03, 0),
|
||||
];
|
||||
let p = build(&w, false);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let v2_val = insts[3].write(Reg::V(2)).unwrap();
|
||||
let v3_val = insts[5].write(Reg::V(3)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7)));
|
||||
assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_lane_prefix_soundness() {
|
||||
let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4));
|
||||
let red = |op: Option<Op>, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red {
|
||||
op,
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
};
|
||||
|
||||
for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] {
|
||||
let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 };
|
||||
|
||||
let mut valid_inc: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l)))
|
||||
.collect();
|
||||
valid_inc[0] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(
|
||||
per_lane(&valid_inc, all),
|
||||
Some(Shape::Prefix(Op::AddU, v0, m0, 0, true))
|
||||
);
|
||||
|
||||
let mut valid_exc: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l)))
|
||||
.collect();
|
||||
valid_exc[0] = Sym::K(0);
|
||||
valid_exc[1] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(
|
||||
per_lane(&valid_exc, all),
|
||||
Some(Shape::Prefix(Op::AddU, v0, m0, 0, false))
|
||||
);
|
||||
|
||||
let mut mixed_other_src = valid_exc.clone();
|
||||
mixed_other_src[0] = red(None, v_other, m0, 0, 1);
|
||||
assert_eq!(per_lane(&mixed_other_src, all), None);
|
||||
|
||||
let mut mixed_same_src = valid_exc.clone();
|
||||
mixed_same_src[0] = red(None, v0, m0, 0, 1);
|
||||
assert_eq!(per_lane(&mixed_same_src, all), None);
|
||||
|
||||
let mut exc_bad_lane1_src = valid_exc.clone();
|
||||
exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1);
|
||||
assert_eq!(per_lane(&exc_bad_lane1_src, all), None);
|
||||
|
||||
let mut exc_bad_lane1_set = valid_exc.clone();
|
||||
exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11);
|
||||
assert_eq!(per_lane(&exc_bad_lane1_set, all), None);
|
||||
|
||||
for bad0 in [
|
||||
red(None, v0, m0, 1, 1),
|
||||
red(None, v_other, m0, 0, 1),
|
||||
red(None, v0, m_other, 0, 1),
|
||||
red(None, v0, m0, 0, 0),
|
||||
Sym::K(0),
|
||||
] {
|
||||
let mut bad_inc = valid_inc.clone();
|
||||
bad_inc[0] = bad0;
|
||||
assert_eq!(per_lane(&bad_inc, all), None);
|
||||
}
|
||||
|
||||
let mut bad_ident: Vec<Sym> = (0..wave)
|
||||
.map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l)))
|
||||
.collect();
|
||||
bad_ident[0] = red(None, v0, m0, 1, 1);
|
||||
assert_eq!(per_lane(&bad_ident, all), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,9 @@ use super::{Encoding, Instruction};
|
||||
pub enum Operand {
|
||||
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
|
||||
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
|
||||
/// 126/127 `exec_lo`/`exec_hi`.
|
||||
/// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the
|
||||
/// IR names scalars parked in VGPR lanes by the codes from 128 up
|
||||
/// (`crate::ir::PARKED`).
|
||||
Scalar {
|
||||
code: u8,
|
||||
dwords: u8,
|
||||
|
||||
+144
-18
@@ -33,7 +33,7 @@
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, Operand};
|
||||
use crate::ir::{Inst, Program, Reg, Value};
|
||||
use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
|
||||
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
|
||||
use crate::resource::Site;
|
||||
|
||||
@@ -138,6 +138,11 @@ pub enum Interp {
|
||||
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
|
||||
/// 1 for P20, 2 for P0 (the provoking vertex).
|
||||
Vertex { attribute: Attribute, vertex: u8 },
|
||||
/// A half of an interpolation whose i or j is computed rather than
|
||||
/// loaded: each half evaluates as the hardware does, from the
|
||||
/// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
|
||||
/// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
|
||||
Weighted { attribute: Attribute },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -238,13 +243,52 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
|
||||
(loaded, &[][..], &[][..])
|
||||
}
|
||||
(StageIo::Ms(ms), HwStage::Ms) => {
|
||||
let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1);
|
||||
// The group input, and the phis that may carry it past a join.
|
||||
let mut group: Vec<Value> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|i| i.0 == Reg::V(5))
|
||||
.map(|i| i.1)
|
||||
.collect();
|
||||
// No lane is active over the EXEC-zero edge of s_cbranch_execz or
|
||||
// _execnz, the same case as a partial-EXEC write below.
|
||||
let no_lanes = |q: usize, b: usize| match (
|
||||
p.blocks[q].insts.last().map(Inst::name),
|
||||
p.blocks[q].exit,
|
||||
) {
|
||||
(Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
|
||||
taken == b && not_taken != b
|
||||
}
|
||||
(Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
|
||||
not_taken == b && taken != b
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
while let Some(v) = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
|
||||
.find_map(|(b, f)| {
|
||||
let mut args = f.args.iter().zip(&p.blocks[b].preds);
|
||||
let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
|
||||
(carried && !group.contains(&f.value)).then_some(f.value)
|
||||
})
|
||||
{
|
||||
group.push(v);
|
||||
}
|
||||
// The group input holds the same value in every lane only as the
|
||||
// first lane reads it; a VGPR write reads its old value too.
|
||||
// first lane reads it. A write to v5 reads its old value too, which
|
||||
// only lanes outside EXEC keep.
|
||||
// shortcut: writes that may keep the old v5 in active lanes
|
||||
// (v_fmac_f32's accumulator, a 16-bit half or d16 load,
|
||||
// v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
|
||||
// partial-EXEC writes pass; check those too if a mesh program
|
||||
// writes v5 that way.
|
||||
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
|
||||
group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g)))
|
||||
i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
|
||||
&& i.name() != "v_readfirstlane_b32"
|
||||
&& i.write(Reg::V(5)).is_none()
|
||||
&& (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
|
||||
});
|
||||
if let Some(i) = per_lane {
|
||||
return Err(unsupported(
|
||||
@@ -352,7 +396,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
|
||||
&barycentric,
|
||||
)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
io.interps.push((site, interp.with(attribute)));
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
}
|
||||
@@ -368,7 +412,7 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
|
||||
let interp = halves
|
||||
.pair(&v.src[0], read(2), read(1), &barycentric)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
io.interps.push((site, interp.with(attribute)));
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
},
|
||||
@@ -439,22 +483,39 @@ fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// An interpolation before its attribute is known.
|
||||
/// An interpolation before its attribute is known: `barycentric` none
|
||||
/// when i or j is computed.
|
||||
struct Pair {
|
||||
barycentric: Barycentric,
|
||||
barycentric: Option<Barycentric>,
|
||||
first: Vec<Site>,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
fn with(self, attribute: Attribute) -> Interp {
|
||||
Interp::Interpolated {
|
||||
attribute,
|
||||
barycentric: self.barycentric,
|
||||
first: self.first,
|
||||
match self.barycentric {
|
||||
Some(barycentric) => Interp::Interpolated {
|
||||
attribute,
|
||||
barycentric,
|
||||
first: self.first,
|
||||
},
|
||||
None => Interp::Weighted { attribute },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records interpolation `pair` at `site`, and its first halves too when
|
||||
/// they evaluate on their own (computed barycentrics).
|
||||
fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
|
||||
if pair.barycentric.is_none() {
|
||||
for &f in &pair.first {
|
||||
if !io.interps.iter().any(|(s, _)| *s == f) {
|
||||
io.interps.push((f, Interp::Weighted { attribute }));
|
||||
}
|
||||
}
|
||||
}
|
||||
io.interps.push((site, pair.with(attribute)));
|
||||
}
|
||||
|
||||
/// Finds the first halves of interpolations.
|
||||
struct Halves<'a> {
|
||||
p: &'a Program,
|
||||
@@ -465,7 +526,9 @@ struct Halves<'a> {
|
||||
impl Halves<'_> {
|
||||
/// The interpolation whose second half reads the first half's result
|
||||
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
|
||||
/// must read the same attribute channel and the same kind's i.
|
||||
/// must read the same attribute channel. With j and every first half's
|
||||
/// i loaded as one kind's, the pair interpolates with that kind;
|
||||
/// otherwise each half evaluates on its own (`Interp::Weighted`).
|
||||
fn pair(
|
||||
&self,
|
||||
attr: &Operand,
|
||||
@@ -479,8 +542,9 @@ impl Halves<'_> {
|
||||
&mut Vec::new(),
|
||||
&mut first,
|
||||
)?;
|
||||
let Some((kind, 1)) = barycentric(j) else {
|
||||
return Err("an interpolation with computed barycentrics");
|
||||
let mut kind = match barycentric(j) {
|
||||
Some((kind, 1)) => Some(kind),
|
||||
_ => None,
|
||||
};
|
||||
for &(b, i) in &first {
|
||||
let inst = &self.p.blocks[b].insts[i];
|
||||
@@ -499,8 +563,8 @@ impl Halves<'_> {
|
||||
if a != *attr {
|
||||
return Err("interpolation halves of different attributes");
|
||||
}
|
||||
if barycentric(i) != Some((kind, 0)) {
|
||||
return Err("an interpolation with computed barycentrics");
|
||||
if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
|
||||
kind = None;
|
||||
}
|
||||
}
|
||||
Ok(Pair {
|
||||
@@ -634,6 +698,33 @@ mod tests {
|
||||
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computed_barycentrics_evaluate_each_half() {
|
||||
// i scaled before the first half: both halves stand on their own.
|
||||
let p = program(&[
|
||||
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
S_ENDPGM,
|
||||
]);
|
||||
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
|
||||
let attribute = Attribute {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
channel: 0,
|
||||
high: false,
|
||||
};
|
||||
let mut interps = io.interps.clone();
|
||||
interps.sort_by_key(|i| i.0);
|
||||
assert_eq!(
|
||||
interps,
|
||||
[
|
||||
((0, 1), Interp::Weighted { attribute }),
|
||||
((0, 2), Interp::Weighted { attribute }),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_inputs_and_primitive_export() {
|
||||
let mesh = |words: &[u32]| {
|
||||
@@ -669,6 +760,41 @@ mod tests {
|
||||
assert_eq!(io.exports[0].target, Target::Primitive);
|
||||
// The group input is uniform only as the first lane reads it.
|
||||
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
|
||||
// Also as an operand of a write to v5, or after a join.
|
||||
let per_lane: [&[u32]; 5] = [
|
||||
&[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
|
||||
&[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
|
||||
&[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
|
||||
&[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
|
||||
&[
|
||||
0xBF06_8001, // s_cmp_eq_u32 s1, 0
|
||||
0xBF85_0001, // s_cbranch_scc1 -> 0xc
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x7E02_0305, // 0xc: v_mov_b32 v1, v5
|
||||
S_ENDPGM,
|
||||
],
|
||||
];
|
||||
let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
|
||||
assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
|
||||
// Overwriting v5 reads the group input only for lanes outside EXEC:
|
||||
// v_mov_b32 v5, 0; v_mov_b32 v1, v5.
|
||||
assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
|
||||
// Skipping that write with s_cbranch_execz is the same case: under the
|
||||
// same mask, the read sees only the 0.
|
||||
let reuse = [
|
||||
0x7E04_0505, // v_readfirstlane_b32 s2, v5
|
||||
0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x14
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x24
|
||||
0x7E02_0305, // v_mov_b32 v1, v5
|
||||
0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
|
||||
S_ENDPGM,
|
||||
];
|
||||
assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+433
-18
@@ -19,7 +19,9 @@ use crate::ShaderError;
|
||||
use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
|
||||
|
||||
/// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs,
|
||||
/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC.
|
||||
/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from
|
||||
/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`):
|
||||
/// no machine instruction names them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Reg {
|
||||
S(u8),
|
||||
@@ -30,6 +32,8 @@ pub enum Reg {
|
||||
pub const VCC: u8 = 106;
|
||||
pub const M0: u8 = 124;
|
||||
pub const EXEC: u8 = 126;
|
||||
/// The first scalar code past the machine's (0-127): see [`Reg`].
|
||||
pub const PARKED: u8 = 128;
|
||||
|
||||
/// An SSA value: the content of one register dword (SCC: one bit).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -123,7 +127,7 @@ impl Inst {
|
||||
/// count. Fails on instructions the IR cannot express yet
|
||||
/// ([`ShaderError::Unsupported`]).
|
||||
pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> {
|
||||
let list = gfx10::decode(code)?;
|
||||
let mut list = gfx10::decode(code)?;
|
||||
let lanes = 1 + u8::from(wave64);
|
||||
let isa = |offset, reason| ShaderError::Isa { offset, reason };
|
||||
|
||||
@@ -145,6 +149,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
}
|
||||
leaders.sort_unstable();
|
||||
leaders.dedup();
|
||||
let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs);
|
||||
let block_at = |offset: usize| {
|
||||
leaders
|
||||
.binary_search(&offset)
|
||||
@@ -164,13 +169,21 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
let next_offsets: Vec<Option<usize>> = (0..list.len())
|
||||
.map(|i| list.get(i + 1).map(|n| n.offset))
|
||||
.collect();
|
||||
for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) {
|
||||
for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() {
|
||||
let b = leaders.partition_point(|&l| l <= machine.offset) - 1;
|
||||
let name = machine.name().ok_or(ShaderError::Unsupported {
|
||||
offset: machine.offset,
|
||||
what: "unknown opcode",
|
||||
})?;
|
||||
let fields = machine.fields(wave64);
|
||||
let mut fields = machine.fields(wave64);
|
||||
// A move to or from a scalar parked in a VGPR lane (`unspill`): its register
|
||||
// codes may be ones the machine word cannot hold.
|
||||
if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0)
|
||||
&& let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields
|
||||
&& let Some(Operand::Scalar { code: from, .. }) = src.first_mut()
|
||||
{
|
||||
(*to, *from) = (parked[k].1, parked[k].2);
|
||||
}
|
||||
let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?);
|
||||
let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok());
|
||||
if ends {
|
||||
@@ -185,7 +198,13 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
Flow::Stop => Exit::End,
|
||||
};
|
||||
}
|
||||
if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
|
||||
if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
|
||||
// Lanes disabled in EXEC keep the old value.
|
||||
for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) {
|
||||
if !reads.contains(w) {
|
||||
reads.push(*w);
|
||||
}
|
||||
}
|
||||
let unset = |regs: Vec<Reg>| regs.into_iter().map(|r| (r, NONE)).collect();
|
||||
blocks[b].insts.push(Inst {
|
||||
machine,
|
||||
@@ -204,6 +223,230 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
}
|
||||
split_irreducible(&mut blocks)?;
|
||||
|
||||
Ok(rename(blocks, wave64, vgprs))
|
||||
}
|
||||
|
||||
/// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves.
|
||||
///
|
||||
/// When it runs out of SGPRs the console compiler saves one in a lane of a
|
||||
/// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later
|
||||
/// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one
|
||||
/// of those two forms with a constant lane is such a store: lane K of it is a
|
||||
/// scalar register by another name. Each (VGPR, lane) gets a register code
|
||||
/// the program does not use (the trap temporaries first, then SGPRs it never
|
||||
/// names, then codes from [`PARKED`] up, which no machine word can hold), and
|
||||
/// the save and the restore become `s_mov_b32` to and from it. Returns those
|
||||
/// moves (index in `list`, destination code, source code) in order, for
|
||||
/// `build` to put the codes into the decoded fields. They are then copies for
|
||||
/// every later stage: a parked descriptor is traced to its load, and nothing
|
||||
/// is left of a cross-lane operation, which a console wave run as two host
|
||||
/// waves could not do where not every lane runs (the lane may be in the other
|
||||
/// wave, or not running).
|
||||
/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit
|
||||
/// address) moves as a pair (`s_mov_b64`) when every save and every restore
|
||||
/// of the two lanes come together, so a parked lane mask comes back as the
|
||||
/// mask it is; otherwise its halves come back as two scalars.
|
||||
fn unspill(
|
||||
list: &mut [gfx10::Instruction],
|
||||
leaders: &[usize],
|
||||
wave64: bool,
|
||||
lanes: u8,
|
||||
vgprs: u16,
|
||||
) -> Vec<(usize, u8, u8)> {
|
||||
/// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K).
|
||||
fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> {
|
||||
let Fields::Valu(v) = fields else { return None };
|
||||
if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() {
|
||||
return None;
|
||||
}
|
||||
let lane = |op: &Operand| match *op {
|
||||
Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128),
|
||||
_ => None,
|
||||
};
|
||||
match (inst.name()?, v.dst?, v.src.as_slice()) {
|
||||
("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => {
|
||||
Some((true, reg, *code, lane(k)?))
|
||||
}
|
||||
("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => {
|
||||
Some((false, *reg, code, lane(k)?))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// VGPRs used by parking alone, the scalar codes the program uses, and
|
||||
// per instruction the scalar codes it writes.
|
||||
let mut stores = [false; 256];
|
||||
let mut other = [false; 256];
|
||||
let mut used = [false; 128];
|
||||
let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
|
||||
let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
|
||||
for inst in list.iter() {
|
||||
let Some(name) = inst.name() else { return Vec::new() };
|
||||
let fields = inst.fields(wave64);
|
||||
let park = parked(inst, &fields);
|
||||
let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut codes = Vec::new();
|
||||
if let Some((reads, writes)) = effects {
|
||||
for ® in &writes {
|
||||
if let Reg::S(c) = reg {
|
||||
codes.push(c);
|
||||
}
|
||||
}
|
||||
for reg in reads.into_iter().chain(writes) {
|
||||
match reg {
|
||||
Reg::S(c) => used[usize::from(c)] = true,
|
||||
Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true,
|
||||
Reg::V(r) => other[usize::from(r)] = true,
|
||||
Reg::Scc => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
parks.push(park);
|
||||
written.push(codes);
|
||||
}
|
||||
for (i, park) in parks.iter_mut().enumerate() {
|
||||
if park.is_some_and(|p| other[usize::from(p.1)]) {
|
||||
*park = None;
|
||||
}
|
||||
let _ = i;
|
||||
}
|
||||
if parks.iter().all(Option::is_none) {
|
||||
return Vec::new();
|
||||
}
|
||||
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
|
||||
// Lane pairs (register, lower lane) that always move together: each
|
||||
// save of the lower lane is followed, in the same block and before its
|
||||
// register changes, by the save of the next register into the next
|
||||
// lane; each restore of the lower lane is followed at once by the
|
||||
// restore of the next lane into the next register.
|
||||
// The second save may come any number of instructions after the first (the
|
||||
// compiler puts loads and constants between the two: five instructions later
|
||||
// in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask
|
||||
// is one dword, and a pair move of it with its neighbour would hide it.
|
||||
let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect();
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
// instruction -> the instruction that completes its pair
|
||||
let partner = |i: usize| -> Option<usize> {
|
||||
let (save, reg, code, lane) = parks[i]?;
|
||||
if save {
|
||||
let mut j = i + 1;
|
||||
while j < list.len() && !leader(j) {
|
||||
if parks[j] == Some((true, reg, code + 1, lane + 1)) {
|
||||
return Some(j);
|
||||
}
|
||||
if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1))
|
||||
|| written[j].contains(&code)
|
||||
|| written[j].contains(&(code + 1))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
None
|
||||
} else {
|
||||
let j = i + 1;
|
||||
(j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j)
|
||||
}
|
||||
};
|
||||
let mut pairs: Vec<(u8, u32)> = Vec::new();
|
||||
for &(reg, lane) in &slots {
|
||||
if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) {
|
||||
continue;
|
||||
}
|
||||
let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect();
|
||||
let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count();
|
||||
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
|
||||
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() {
|
||||
pairs.push((reg, lane));
|
||||
}
|
||||
}
|
||||
// Codes for the parked scalars: the trap temporaries (108..=123), then
|
||||
// user SGPRs the program never names, from the top, then the codes past
|
||||
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
|
||||
// parked one always exists). A material resolve program parks up to 63
|
||||
// scalars and leaves about 20 machine codes unused.
|
||||
let past = usize::from(PARKED);
|
||||
let mut free = [false; 256];
|
||||
for c in (0..105).chain(108..=123) {
|
||||
free[c] = !used[c];
|
||||
}
|
||||
free[past..255].fill(true);
|
||||
let mut codes: Vec<((u8, u32), u8)> = Vec::new();
|
||||
for &(reg, lane) in &pairs {
|
||||
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
|
||||
// Not enough spare codes: leave the program as it is.
|
||||
let Some(c) = at else { return Vec::new() };
|
||||
(free[c], free[c + 1]) = (false, false);
|
||||
codes.push(((reg, lane), c as u8));
|
||||
codes.push(((reg, lane + 1), c as u8 + 1));
|
||||
}
|
||||
for &slot in &slots {
|
||||
if codes.iter().any(|c| c.0 == slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
free[c] = false;
|
||||
codes.push((slot, c as u8));
|
||||
}
|
||||
let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1);
|
||||
let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
|
||||
list[i] = gfx10::Instruction {
|
||||
offset: list[i].offset,
|
||||
encoding,
|
||||
opcode,
|
||||
words: vec![word],
|
||||
};
|
||||
};
|
||||
// `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code
|
||||
// from `PARKED` up does not fit the word: s0 stands in for it there.
|
||||
let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 };
|
||||
let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src);
|
||||
const NOP: u32 = 0xBF80_0000;
|
||||
let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new();
|
||||
for i in 0..list.len() {
|
||||
let Some((save, reg, code, lane)) = parks[i] else {
|
||||
continue;
|
||||
};
|
||||
let Some(slot) = code_of(reg, lane) else { return Vec::new() };
|
||||
if pairs.contains(&(reg, lane)) {
|
||||
let Some(j) = partner(i) else { return Vec::new() };
|
||||
// A save moves the pair where its second half is saved; a
|
||||
// restore where its first half is restored.
|
||||
let (at, gone) = if save { (j, i) } else { (i, j) };
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
edits.push((at, Some((true, dst, src))));
|
||||
edits.push((gone, None));
|
||||
} else if lane > 0 && pairs.contains(&(reg, lane - 1)) {
|
||||
// the upper half of a pair: moved with the lower
|
||||
} else {
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
edits.push((i, Some((false, dst, src))));
|
||||
}
|
||||
}
|
||||
let mut moves = Vec::new();
|
||||
for (i, edit) in edits {
|
||||
match edit {
|
||||
Some((wide, dst, src)) => {
|
||||
put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src));
|
||||
moves.push((i, dst, src));
|
||||
}
|
||||
None => put(list, i, gfx10::Encoding::Sopp, 0, NOP),
|
||||
}
|
||||
}
|
||||
moves.sort_unstable();
|
||||
moves
|
||||
}
|
||||
|
||||
/// Rename register reads and writes after changing edges in a reducible graph.
|
||||
fn rename(mut blocks: Vec<Block>, wave64: bool, vgprs: u16) -> Program {
|
||||
let order = reverse_postorder(&blocks);
|
||||
let (live_in, live_out) = liveness(&blocks, &order);
|
||||
let mut values = 0u32;
|
||||
@@ -262,33 +505,193 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
}
|
||||
}
|
||||
remove_trivial_phis(&mut blocks, values);
|
||||
Ok(Program {
|
||||
Program {
|
||||
wave64,
|
||||
vgprs,
|
||||
blocks,
|
||||
inputs,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicate a join for each proven (predecessor, join, destination) edge.
|
||||
/// The instructions still execute on that path and define fresh SSA values.
|
||||
pub(crate) fn thread_edges(
|
||||
p: &Program,
|
||||
edges: &[(usize, usize, usize)],
|
||||
) -> Result<Program, ShaderError> {
|
||||
let mut blocks = p.blocks.clone();
|
||||
for block in &mut blocks {
|
||||
block.phis.clear();
|
||||
}
|
||||
for &(pred, join, dest) in edges {
|
||||
let mut copy = blocks[join].clone();
|
||||
copy.exit = Exit::Jump(dest);
|
||||
let target = blocks.len();
|
||||
match &mut blocks[pred].exit {
|
||||
Exit::Jump(t) => *t = target,
|
||||
Exit::Branch { taken, not_taken } => {
|
||||
if *taken == join {
|
||||
*taken = target;
|
||||
}
|
||||
if *not_taken == join {
|
||||
*not_taken = target;
|
||||
}
|
||||
}
|
||||
_ => unreachable!("threading an incoming edge"),
|
||||
}
|
||||
blocks.push(copy);
|
||||
}
|
||||
link(&mut blocks);
|
||||
split_irreducible(&mut blocks)?;
|
||||
Ok(rename(blocks, p.wave64, p.vgprs))
|
||||
}
|
||||
|
||||
/// The program without its early-outs: an `s_cbranch_execz` to a block that
|
||||
/// only ends the program (`if (!inBounds) return;`, the outermost branch of
|
||||
/// most compute programs) is left out, so the lanes that would have left
|
||||
/// walk the body with EXEC clear. Vector instructions and every effect are
|
||||
/// masked by EXEC already, as on the console, where the branch is taken
|
||||
/// only when no lane of the wave is left; scalar code has no effects. The
|
||||
/// body is then code every lane runs, which a console wave run as two host
|
||||
/// waves needs for the barriers of its exchanges and LDS accesses.
|
||||
/// `None` if the program has no such branch.
|
||||
pub(crate) fn without_early_outs(p: &Program) -> Option<Program> {
|
||||
let ends = |b: usize| {
|
||||
p.blocks[b].exit == Exit::End
|
||||
&& p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
|
||||
};
|
||||
let mut blocks = p.blocks.clone();
|
||||
let mut any = false;
|
||||
for block in &mut blocks {
|
||||
let Exit::Branch { taken, not_taken } = block.exit else {
|
||||
continue;
|
||||
};
|
||||
if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
|
||||
block.insts.pop();
|
||||
block.exit = Exit::Jump(not_taken);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
for block in &mut blocks {
|
||||
block.phis.clear();
|
||||
}
|
||||
link(&mut blocks);
|
||||
split_irreducible(&mut blocks).ok()?;
|
||||
Some(rename(blocks, p.wave64, p.vgprs))
|
||||
}
|
||||
|
||||
/// As [`without_early_outs`], and also without the branches that only skip a
|
||||
/// region when no lane is left for it: an `s_cbranch_execz` whose target is
|
||||
/// where the skipped code ends up anyway (`if (c) { ... }` with nothing
|
||||
/// else leaving the region). Every lane then walks the region with EXEC
|
||||
/// clear for those that would have skipped it, and LDS accesses and
|
||||
/// exchanges inside it are in code every lane runs.
|
||||
/// The console takes such a branch only when no lane of the wave is left,
|
||||
/// and then its scalar code does not run: a branch is kept if the code
|
||||
/// after it could see that (a scalar register or SCC that the region
|
||||
/// changes and the join merges with the value from before; EXEC aside,
|
||||
/// which is empty either way). `None` if nothing changes.
|
||||
pub(crate) fn without_skips(p: &Program) -> Option<Program> {
|
||||
let n = p.blocks.len();
|
||||
let ends = |b: usize| {
|
||||
p.blocks[b].exit == Exit::End
|
||||
&& p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
|
||||
};
|
||||
// The region a skip of `b` to `target` leaves out, if it is a pure skip.
|
||||
let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> {
|
||||
let mut inside = vec![false; n];
|
||||
let mut stack = vec![first];
|
||||
while let Some(x) = stack.pop() {
|
||||
if x == target || inside[x] {
|
||||
continue;
|
||||
}
|
||||
if x == b {
|
||||
return None; // a loop back to the branch
|
||||
}
|
||||
inside[x] = true;
|
||||
match p.blocks[x].exit {
|
||||
Exit::End | Exit::Indirect => return None,
|
||||
exit => stack.extend(exit.successors()),
|
||||
}
|
||||
}
|
||||
// entered only through the branch
|
||||
for x in (0..n).filter(|&x| inside[x]) {
|
||||
if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// the join sees no scalar the region changed
|
||||
let join = &p.blocks[target];
|
||||
for phi in &join.phis {
|
||||
let scalar = match phi.reg {
|
||||
Reg::S(c) => c != 126 && c != 127,
|
||||
Reg::Scc => true,
|
||||
Reg::V(_) => false,
|
||||
};
|
||||
if !scalar {
|
||||
continue;
|
||||
}
|
||||
let before: Vec<Value> =
|
||||
join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| *a).collect();
|
||||
let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| *a);
|
||||
if within.into_iter().any(|a| !before.contains(&a)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// other ways into the join than the branch and the region: not a plain `if`
|
||||
if join.preds.iter().any(|&q| q != b && !inside[q]) {
|
||||
return None;
|
||||
}
|
||||
Some(inside)
|
||||
};
|
||||
let mut blocks = p.blocks.clone();
|
||||
let mut any = false;
|
||||
for b in 0..n {
|
||||
let Exit::Branch { taken, not_taken } = p.blocks[b].exit else {
|
||||
continue;
|
||||
};
|
||||
if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
|
||||
continue;
|
||||
}
|
||||
if ends(taken) || skipped(b, taken, not_taken).is_some() {
|
||||
blocks[b].insts.pop();
|
||||
blocks[b].exit = Exit::Jump(not_taken);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
for block in &mut blocks {
|
||||
block.phis.clear();
|
||||
}
|
||||
link(&mut blocks);
|
||||
split_irreducible(&mut blocks).ok()?;
|
||||
Some(rename(blocks, p.wave64, p.vgprs))
|
||||
}
|
||||
|
||||
/// Placeholder before renaming.
|
||||
const NONE: Value = Value(u32::MAX);
|
||||
/// SGPR codes 0-127, SCC, VGPRs 0-255.
|
||||
const REGS: usize = 128 + 1 + 256;
|
||||
/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255.
|
||||
const REGS: usize = 256 + 1 + 256;
|
||||
type RegSet = [u64; REGS.div_ceil(64)];
|
||||
|
||||
fn index(reg: Reg) -> usize {
|
||||
match reg {
|
||||
Reg::S(c) => usize::from(c),
|
||||
Reg::Scc => 128,
|
||||
Reg::V(r) => 129 + usize::from(r),
|
||||
Reg::Scc => 256,
|
||||
Reg::V(r) => 257 + usize::from(r),
|
||||
}
|
||||
}
|
||||
|
||||
fn reg_at(i: usize) -> Reg {
|
||||
match i {
|
||||
0..128 => Reg::S(i as u8),
|
||||
128 => Reg::Scc,
|
||||
_ => Reg::V((i - 129) as u8),
|
||||
0..256 => Reg::S(i as u8),
|
||||
256 => Reg::Scc,
|
||||
_ => Reg::V((i - 257) as u8),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -662,6 +1065,16 @@ const DROPPED: &[&str] = &[
|
||||
/// Registers read, registers written.
|
||||
type Effects = (Vec<Reg>, Vec<Reg>);
|
||||
|
||||
/// The registers `inst` of `p` reads as operands: its reads without the old
|
||||
/// value of a VGPR it only writes.
|
||||
pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec<Reg> {
|
||||
let lanes = 1 + u8::from(p.wave64);
|
||||
effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map_or_else(Vec::new, |e| e.0)
|
||||
}
|
||||
|
||||
/// Registers an instruction reads and writes, one per dword, or `None` if
|
||||
/// the IR drops it.
|
||||
fn effects(
|
||||
@@ -818,6 +1231,7 @@ fn effects(
|
||||
indexed(d, &mut r)?;
|
||||
}
|
||||
}
|
||||
"v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)),
|
||||
_ => {}
|
||||
}
|
||||
if name.starts_with("v_interp_") || src_indexed || dst_indexed {
|
||||
@@ -930,8 +1344,6 @@ fn effects(
|
||||
}
|
||||
if vector {
|
||||
r.extend(mask(EXEC));
|
||||
// Lanes disabled in EXEC keep the old value.
|
||||
r.extend(w.iter().filter(|w| matches!(w, Reg::V(_))));
|
||||
}
|
||||
let mut seen = Vec::with_capacity(r.len());
|
||||
r.retain(|reg| {
|
||||
@@ -1008,10 +1420,13 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<Reg>) -> Result<(), ()> {
|
||||
Operand::Scalar { code, .. } if code == gfx10::NULL => {}
|
||||
Operand::Scalar { code, dwords } => {
|
||||
let end = u16::from(code) + u16::from(dwords);
|
||||
if end > 128 {
|
||||
// A machine operand ends within the machine's codes, a parked
|
||||
// scalar (`unspill`) within those past them.
|
||||
let limit = if code < PARKED { 128 } else { 256 };
|
||||
if end > limit {
|
||||
return Err(());
|
||||
}
|
||||
out.extend((code..end as u8).map(Reg::S));
|
||||
out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8)));
|
||||
}
|
||||
Operand::Vector { reg, dwords } => {
|
||||
if u16::from(reg) + u16::from(dwords) > 256 {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
|
||||
//! console-only intrinsics, so the GFX10 code is translated in general.
|
||||
|
||||
pub mod bvh;
|
||||
pub mod dxbc;
|
||||
pub mod dxil;
|
||||
pub mod emit;
|
||||
@@ -14,6 +15,7 @@ pub mod io;
|
||||
pub mod ir;
|
||||
pub mod native;
|
||||
pub mod resource;
|
||||
pub mod spill;
|
||||
pub mod structure;
|
||||
|
||||
pub use dxbc::{Container, FourCC, Part};
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,380 @@
|
||||
//! The spilled user-data table of a compute program.
|
||||
//!
|
||||
//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
|
||||
//! root signature that needs more dwords than that keeps none of its
|
||||
//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
|
||||
//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
|
||||
//! the parameter the layout declares at user-data index N (16 or above) is
|
||||
//! at byte `4 * (N - 16)` of that table. The code reads it with
|
||||
//! `s_load_dword*` through that pointer. (Every compute program of the
|
||||
//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
|
||||
//! kind; measured there: 118 of 118 such loads land on a declared parameter.)
|
||||
//!
|
||||
//! [`user_data`] rewrites those loads away: each dword they read becomes the
|
||||
//! entry value of the SGPR its user-data index names, as if the parameter
|
||||
//! had arrived in a register. Resource tracking and lowering then treat a
|
||||
//! spilled parameter like any other (the host binds user data by root slot
|
||||
//! and dword, not by register).
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, NULL, Operand};
|
||||
use crate::ir::{self, Program, Reg, Value};
|
||||
use crate::native::{HwStage, NativeProgram, StageIo};
|
||||
|
||||
/// The user-data index of the table's first dword.
|
||||
const FIRST: u32 = 16;
|
||||
|
||||
/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
|
||||
/// of a spilled user-data table rewritten ([`user_data`]).
|
||||
pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
|
||||
let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
user_data(&mut p, native);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Whether `native` is a compute program that keeps its root parameters in
|
||||
/// a spilled user-data table (see the module): the entries no register
|
||||
/// holds, as (first user-data index, dwords), if the table starts at index
|
||||
/// 16 and the program has the two registers of its address.
|
||||
fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
|
||||
let StageIo::Cs(cs) = &native.io else {
|
||||
return None;
|
||||
};
|
||||
if native.stage != HwStage::Cs {
|
||||
return None;
|
||||
}
|
||||
let registers = u32::from(cs.user_sgprs());
|
||||
let spilled: Vec<(u32, u32)> = native
|
||||
.layout
|
||||
.iter()
|
||||
.filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
|
||||
.map(|e| (u32::from(e.user_data), e.sgprs))
|
||||
.collect();
|
||||
// Only the one arrangement seen: the table starts at index 16.
|
||||
(spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
|
||||
}
|
||||
|
||||
/// Whether `native` reads its root parameters from a spilled user-data
|
||||
/// table. (In Grand Theft Auto VI exactly the compute programs of the
|
||||
/// console's ray-tracing structure builder do.)
|
||||
pub fn is_spilled(native: &NativeProgram) -> bool {
|
||||
spilled(native).is_some()
|
||||
}
|
||||
|
||||
/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
|
||||
/// how many loads it replaced. Nothing changes unless the program is a
|
||||
/// compute program whose layout has entries past its user SGPRs, the first
|
||||
/// at index 16. A load is left alone (and resource tracking then refuses it
|
||||
/// as before) when its offset is not a constant on a dword, or when a dword
|
||||
/// it reads and the program uses is in no layout entry.
|
||||
pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
|
||||
let Some(spilled) = spilled(native) else {
|
||||
return 0;
|
||||
};
|
||||
let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
|
||||
let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
// The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
|
||||
let mut lows = vec![low];
|
||||
let mut highs: Vec<Value> = Vec::new();
|
||||
let mut raw_highs = vec![high];
|
||||
// Instructions that only form the pointer: dropped when nothing reads
|
||||
// them any more.
|
||||
let mut forming: Vec<(usize, usize)> = Vec::new();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Sop { dst, src, .. } = &inst.fields else {
|
||||
continue;
|
||||
};
|
||||
let Some(Operand::Scalar { code: d, .. }) = *dst else {
|
||||
continue;
|
||||
};
|
||||
let Some(out) = inst.write(Reg::S(d)) else {
|
||||
continue;
|
||||
};
|
||||
let read = |op: &Operand| match *op {
|
||||
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
|
||||
_ => None,
|
||||
};
|
||||
let found = match (inst.name(), &src[..]) {
|
||||
("s_mov_b32", [s]) => match read(s) {
|
||||
Some(v) if lows.contains(&v) => Some(&mut lows),
|
||||
Some(v) if highs.contains(&v) => Some(&mut highs),
|
||||
Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
|
||||
_ => None,
|
||||
},
|
||||
("s_and_b32", [x, y]) => {
|
||||
let masked = |a: &Operand, m: &Operand| {
|
||||
matches!(*m, Operand::Literal(0xff))
|
||||
&& read(a).is_some_and(|v| raw_highs.contains(&v))
|
||||
};
|
||||
(masked(x, y) || masked(y, x)).then_some(&mut highs)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(set) = found
|
||||
&& !set.contains(&out)
|
||||
{
|
||||
set.push(out);
|
||||
forming.push((b, i));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if highs.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Values some instruction or phi reads.
|
||||
let mut read_somewhere = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
let mut next = p
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| i.1)
|
||||
.chain(p.blocks.iter().flat_map(|b| {
|
||||
b.phis
|
||||
.iter()
|
||||
.map(|phi| phi.value)
|
||||
.chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
|
||||
}))
|
||||
.map(|v| v.0 + 1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Each load through the pointer: its dwords become entry values.
|
||||
let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
|
||||
let mut gone: Vec<(usize, usize)> = Vec::new();
|
||||
let mut inputs = p.inputs.clone();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
'insts: for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Smem {
|
||||
data: Some(Operand::Scalar { code: first, .. }),
|
||||
base: Operand::Scalar { code: base, .. },
|
||||
offset,
|
||||
soffset,
|
||||
..
|
||||
} = inst.fields
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !inst.name().starts_with("s_load_dword")
|
||||
|| !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
|
||||
|| offset < 0
|
||||
|| offset % 4 != 0
|
||||
|| !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
|
||||
|| !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut dwords = Vec::new();
|
||||
for &(reg, v) in &inst.writes {
|
||||
let Reg::S(code) = reg else {
|
||||
continue 'insts;
|
||||
};
|
||||
let Some(k) = code.checked_sub(first) else {
|
||||
continue 'insts;
|
||||
};
|
||||
let index = FIRST + offset as u32 / 4 + u32::from(k);
|
||||
let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
|
||||
if !declared {
|
||||
if read_somewhere.contains(&v) {
|
||||
continue 'insts;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// SGPR codes end at 105; no root signature reaches there.
|
||||
let Ok(code) = u8::try_from(index) else {
|
||||
continue 'insts;
|
||||
};
|
||||
if code > 105 {
|
||||
continue 'insts;
|
||||
}
|
||||
dwords.push((Reg::S(code), v));
|
||||
}
|
||||
for (reg, v) in dwords {
|
||||
let value = match inputs.iter().find(|e| e.0 == reg) {
|
||||
Some(e) => e.1,
|
||||
None => {
|
||||
let value = Value(next);
|
||||
next += 1;
|
||||
inputs.push((reg, value));
|
||||
value
|
||||
}
|
||||
};
|
||||
replaced.insert(v, value);
|
||||
}
|
||||
gone.push((b, i));
|
||||
}
|
||||
}
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
p.inputs = inputs;
|
||||
let renamed = |v: &mut Value| {
|
||||
if let Some(&to) = replaced.get(v) {
|
||||
*v = to;
|
||||
}
|
||||
};
|
||||
for block in &mut p.blocks {
|
||||
for phi in &mut block.phis {
|
||||
phi.args.iter_mut().for_each(renamed);
|
||||
}
|
||||
for inst in &mut block.insts {
|
||||
inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
|
||||
}
|
||||
}
|
||||
// The loads go, then what only formed the pointer (last first, so a
|
||||
// copy goes before what it copied).
|
||||
let mut drop = gone.clone();
|
||||
loop {
|
||||
let read_somewhere = {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if !drop.contains(&(b, i)) {
|
||||
used.extend(inst.reads.iter().map(|r| r.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
used
|
||||
};
|
||||
let before = drop.len();
|
||||
for &site in &forming {
|
||||
let inst = &p.blocks[site.0].insts[site.1];
|
||||
if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
|
||||
drop.push(site);
|
||||
}
|
||||
}
|
||||
if drop.len() == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (b, block) in p.blocks.iter_mut().enumerate() {
|
||||
let mut i = 0;
|
||||
block.insts.retain(|_| {
|
||||
i += 1;
|
||||
!drop.contains(&(b, i - 1))
|
||||
});
|
||||
}
|
||||
// The pointer's registers are no inputs once nothing reads them.
|
||||
let mut read = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
p.inputs
|
||||
.retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
|
||||
gone.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::{ComputeIo, RootParam, RootType};
|
||||
|
||||
fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
|
||||
RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A compute program with `registers` user SGPRs and the group id after
|
||||
/// them.
|
||||
fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 256,
|
||||
layout,
|
||||
used: vec![],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: registers << 1 | 1 << 7,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
|
||||
// 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
|
||||
const TABLE: [u32; 8] = [
|
||||
0x8703_FF01,
|
||||
0x0000_00FF,
|
||||
0xBE82_0300,
|
||||
0xF400_0141,
|
||||
0xFA00_0010,
|
||||
0xF404_0001,
|
||||
0xFA00_0000,
|
||||
0xBF81_0000,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn loads_of_the_spilled_table_become_entry_registers() {
|
||||
let n = native(
|
||||
&TABLE,
|
||||
4,
|
||||
vec![
|
||||
param(RootType::Descriptor, 16, 2, 0),
|
||||
param(RootType::Descriptor, 18, 2, 1),
|
||||
param(RootType::Constants, 20, 16, 2),
|
||||
],
|
||||
);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 2);
|
||||
let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
|
||||
assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
|
||||
// The pointer is gone with the loads; byte 0x10 is index 20, the
|
||||
// first root constant, and bytes 0-7 are the first root view.
|
||||
let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
|
||||
regs.sort();
|
||||
assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_in_registers_are_left_alone() {
|
||||
// The same code where s0 and s1 are a root view the layout declares.
|
||||
let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
let before = p.clone();
|
||||
assert_eq!(user_data(&mut p, &n), 0);
|
||||
assert_eq!(p, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_used_dword_no_parameter_declares_keeps_its_load() {
|
||||
// As above with `s_mov_b32 s6, s5` before the end: the dword at
|
||||
// byte 0x10 (index 20) is read, and here nothing declares it.
|
||||
let mut words = TABLE.to_vec();
|
||||
words.insert(7, 0xBE86_0305);
|
||||
let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 1);
|
||||
let loads = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.insts)
|
||||
.filter(|i| i.name().starts_with("s_load_"))
|
||||
.count();
|
||||
assert_eq!(loads, 1);
|
||||
// The pointer is still read, by the load that stays.
|
||||
assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,16 @@ const TERMINAL: u32 = u32::MAX;
|
||||
const MAX_NODES: usize = 1 << 21;
|
||||
/// Case splits [`Bools::meet`] makes before it gives up.
|
||||
const MAX_MEET: usize = 1 << 16;
|
||||
/// Conditions [`Meets`] keeps; past that, they are searched anew.
|
||||
const MAX_MEETS: usize = 1 << 18;
|
||||
|
||||
/// What [`Bools::meet`] found out about one [`Bools`], for its later calls:
|
||||
/// the conditions no lane satisfies, and the case splits it took to find
|
||||
/// that out of each.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Meets {
|
||||
none: Map<Box<[u32]>, usize>,
|
||||
}
|
||||
|
||||
impl Bools {
|
||||
fn new() -> Self {
|
||||
@@ -227,32 +237,99 @@ impl Bools {
|
||||
/// `b` where `holds`, its negation where not. Yes when the search grows
|
||||
/// too large to finish.
|
||||
pub fn meet(&self, all: &[(Bool, bool)]) -> bool {
|
||||
let mut budget = MAX_MEET;
|
||||
self.meet_in(all.to_vec(), &mut budget)
|
||||
self.meet_seen(all, &mut Meets::default())
|
||||
}
|
||||
|
||||
fn meet_in(&self, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool {
|
||||
let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE };
|
||||
if all.iter().any(fails) {
|
||||
return false;
|
||||
/// [`Self::meet`], which looks up in `seen` what earlier calls on these
|
||||
/// `Bools` found out and adds what it finds. The answer is the one
|
||||
/// `meet` gives.
|
||||
pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool {
|
||||
self.meet_within(all, MAX_MEET, seen)
|
||||
}
|
||||
|
||||
/// [`Self::meet_seen`] with `budget` case splits.
|
||||
fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool {
|
||||
let mut work = all
|
||||
.iter()
|
||||
.map(|&(b, holds)| b.0 << 1 | u32::from(holds))
|
||||
.collect();
|
||||
self.meet_in(0, &mut work, &mut budget, seen)
|
||||
}
|
||||
|
||||
/// The search of [`Self::meet`] for the conditions `work[at..]` (a node
|
||||
/// doubled, plus one where it must hold), which it takes off `work`.
|
||||
///
|
||||
/// The search is a case split on the top variable, and the cofactors of
|
||||
/// a few large functions come down to the same conditions over and over
|
||||
/// (a block's reach under a mask and under its negation share most of
|
||||
/// their nodes), so splitting each anew is exponential where the
|
||||
/// distinct conditions are few. `seen` keeps the conditions that no lane
|
||||
/// satisfies with the case splits it took to find that out: meeting
|
||||
/// them again takes those splits off the budget at once. A search
|
||||
/// therefore gives up exactly where one that split everything anew
|
||||
/// would (nothing below such conditions ends it early, so it either
|
||||
/// makes all those splits or runs out among them), and gives the same
|
||||
/// answer.
|
||||
fn meet_in(
|
||||
&self,
|
||||
at: usize,
|
||||
work: &mut Vec<u32>,
|
||||
budget: &mut usize,
|
||||
seen: &mut Meets,
|
||||
) -> bool {
|
||||
// Constants either fail or say nothing.
|
||||
let mut kept = at;
|
||||
for i in at..work.len() {
|
||||
let (b, holds) = (work[i] >> 1, work[i] & 1 != 0);
|
||||
if b > Bool::TRUE.0 {
|
||||
work[kept] = work[i];
|
||||
kept += 1;
|
||||
} else if (b == Bool::TRUE.0) != holds {
|
||||
work.truncate(at);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
|
||||
if all.is_empty() || *budget == 0 {
|
||||
work.truncate(kept);
|
||||
if kept == at || *budget == 0 {
|
||||
work.truncate(at);
|
||||
return true;
|
||||
}
|
||||
// As a set: neither order nor repeats change the search.
|
||||
work[at..].sort_unstable();
|
||||
let mut end = at + 1;
|
||||
for i in at + 1..kept {
|
||||
if work[i] != work[end - 1] {
|
||||
work[end] = work[i];
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
work.truncate(end);
|
||||
if let Some(&splits) = seen.none.get(&work[at..]) {
|
||||
let within = splits <= *budget;
|
||||
*budget = budget.saturating_sub(splits);
|
||||
work.truncate(at);
|
||||
return !within;
|
||||
}
|
||||
let before = *budget;
|
||||
*budget -= 1;
|
||||
let top = |b: Bool| self.nodes[b.0 as usize].0;
|
||||
let v = all.iter().map(|&(b, _)| top(b)).min().expect("not empty");
|
||||
[false, true].into_iter().any(|value| {
|
||||
let next = all
|
||||
.iter()
|
||||
.map(|&(b, holds)| {
|
||||
let (lo, hi) = self.split(b, v);
|
||||
(if value { hi } else { lo }, holds)
|
||||
})
|
||||
.collect();
|
||||
self.meet_in(next, budget)
|
||||
})
|
||||
let top = |code: u32| self.nodes[(code >> 1) as usize].0;
|
||||
let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty");
|
||||
let mut found = false;
|
||||
for value in [false, true] {
|
||||
for i in at..end {
|
||||
let (lo, hi) = self.split(Bool(work[i] >> 1), v);
|
||||
work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1);
|
||||
}
|
||||
if self.meet_in(end, work, budget, seen) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found && seen.none.len() < MAX_MEETS {
|
||||
seen.none.insert(work[at..end].into(), before - *budget);
|
||||
}
|
||||
work.truncate(at);
|
||||
found
|
||||
}
|
||||
|
||||
fn implies(&mut self, a: Bool, b: Bool) -> bool {
|
||||
@@ -351,8 +428,12 @@ pub struct Structured {
|
||||
pub highs: HashMap<Value, Value>,
|
||||
/// Masks (low dwords) set only in lanes whose EXEC bit is set where
|
||||
/// they are written: every such lane reaches the writing block, so a
|
||||
/// ballot there gives the mask as data.
|
||||
/// ballot there gives the mask as data. No split low dword, as in
|
||||
/// `masks`.
|
||||
pub active: HashSet<Value>,
|
||||
/// Incoming lane boolean per predecessor edge (in block predecessor order)
|
||||
/// for each [`Atom::Phi`] id.
|
||||
pub phi_masks: HashMap<Value, Vec<Bool>>,
|
||||
}
|
||||
|
||||
impl Structured {
|
||||
@@ -371,11 +452,15 @@ pub fn structure(program: &Program) -> Result<Structured, ShaderError> {
|
||||
loop {
|
||||
let execs = l.masks_in_order();
|
||||
let cond = l.paths()?;
|
||||
let wrong = l.wrong_joins(&cond);
|
||||
if wrong.is_empty() {
|
||||
let (wrong, new_derived) = l.check_joins(&cond);
|
||||
if l.b.overflow {
|
||||
return Err(TOO_LARGE);
|
||||
}
|
||||
if wrong.is_empty() && new_derived.is_empty() {
|
||||
return l.finish(&execs, &cond);
|
||||
}
|
||||
l.unresolved.extend(wrong);
|
||||
l.derived_phis.extend(new_derived);
|
||||
l.reset();
|
||||
}
|
||||
}
|
||||
@@ -397,16 +482,26 @@ struct Lanes<'a> {
|
||||
phis: Map<Value, (usize, usize)>,
|
||||
/// Mask joins found wrong when resolved to a constant: atoms instead.
|
||||
unresolved: HashSet<Value>,
|
||||
/// Phi ids whose joins depend on EXEC or VALU results (including along
|
||||
/// back edges), carried across resets so their joins stay in `masks`.
|
||||
derived_phis: HashSet<Value>,
|
||||
b: Bools,
|
||||
/// Masks derived from EXEC and VALU results.
|
||||
masks: Map<Key, Bool>,
|
||||
/// Other values read as masks: constants, uniform selects, opaque ones.
|
||||
other: Map<Key, Bool>,
|
||||
/// Pairs read as masks that `mask` does not see: carry-ins, and pairs
|
||||
/// joins take over back edges.
|
||||
seen: Vec<Key>,
|
||||
/// For branches: SCC of a mask operation ("some lane is set") as the
|
||||
/// lane's own bit.
|
||||
scc_lane: Map<Value, Bool>,
|
||||
/// Joins resolved to a constant, to check once all edges are known.
|
||||
joins: Vec<Join>,
|
||||
/// [`Atom::Phi`] joins created in the current pass, resolved in
|
||||
/// `check_joins` and exported in `finish`.
|
||||
phi_joins: Vec<PhiJoin>,
|
||||
phi_join_ids: HashSet<Value>,
|
||||
/// Per block: what a lane knows on entry, over forward edges only.
|
||||
first: Vec<Bool>,
|
||||
/// Per block ending in a branch: when a lane takes it.
|
||||
@@ -422,6 +517,16 @@ struct Join {
|
||||
/// The phi value naming the join.
|
||||
id: Value,
|
||||
value: bool,
|
||||
derived: bool,
|
||||
args: Vec<Key>,
|
||||
}
|
||||
|
||||
/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are
|
||||
/// resolved once every block (including loop back edges) has been visited.
|
||||
struct PhiJoin {
|
||||
block: usize,
|
||||
id: Value,
|
||||
derived: bool,
|
||||
args: Vec<Key>,
|
||||
}
|
||||
|
||||
@@ -468,11 +573,15 @@ impl<'a> Lanes<'a> {
|
||||
defs,
|
||||
phis,
|
||||
unresolved: HashSet::new(),
|
||||
derived_phis: HashSet::new(),
|
||||
b: Bools::new(),
|
||||
masks: Map::default(),
|
||||
other: Map::default(),
|
||||
seen: Vec::new(),
|
||||
scc_lane: Map::default(),
|
||||
joins: Vec::new(),
|
||||
phi_joins: Vec::new(),
|
||||
phi_join_ids: HashSet::new(),
|
||||
first: vec![Bool::FALSE; blocks.len()],
|
||||
when: vec![None; blocks.len()],
|
||||
active: HashSet::new(),
|
||||
@@ -483,8 +592,11 @@ impl<'a> Lanes<'a> {
|
||||
self.b = Bools::new();
|
||||
self.masks.clear();
|
||||
self.other.clear();
|
||||
self.seen.clear();
|
||||
self.scc_lane.clear();
|
||||
self.joins.clear();
|
||||
self.phi_joins.clear();
|
||||
self.phi_join_ids.clear();
|
||||
self.first.fill(Bool::FALSE);
|
||||
self.when.fill(None);
|
||||
self.active.clear();
|
||||
@@ -557,28 +669,61 @@ impl<'a> Lanes<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Joins whose constant fails on some edge, given what lanes know.
|
||||
fn wrong_joins(&mut self, cond: &[Bool]) -> Vec<Value> {
|
||||
/// Joins whose constant fails on some edge, and joins that need another
|
||||
/// pass because a later edge turned out to derive from EXEC or VALU.
|
||||
fn check_joins(&mut self, cond: &[Bool]) -> (Vec<Value>, Vec<Value>) {
|
||||
let mut wrong = Vec::new();
|
||||
let mut new_derived = Vec::new();
|
||||
let mut seen_derived = HashSet::new();
|
||||
let mut j = 0;
|
||||
let mut p = 0;
|
||||
// Checking an argument can resolve another join; it is checked too.
|
||||
while j < self.joins.len() {
|
||||
let (block, id, value) = (self.joins[j].block, self.joins[j].id, self.joins[j].value);
|
||||
for (n, a) in self.joins[j].args.clone().into_iter().enumerate() {
|
||||
let (q, taken) = self.incoming[block][n];
|
||||
let e = self.edge(cond[q], q, taken);
|
||||
let mut m = self.mask(a).0;
|
||||
if !value {
|
||||
m = self.b.not(m);
|
||||
}
|
||||
if !self.b.implies(e, m) {
|
||||
wrong.push(id);
|
||||
break;
|
||||
while j < self.joins.len() || p < self.phi_joins.len() {
|
||||
while j < self.joins.len() {
|
||||
let (block, id, value, was_derived) = (
|
||||
self.joins[j].block,
|
||||
self.joins[j].id,
|
||||
self.joins[j].value,
|
||||
self.joins[j].derived,
|
||||
);
|
||||
let mut failed = false;
|
||||
for (n, a) in self.joins[j].args.clone().into_iter().enumerate() {
|
||||
let (q, taken) = self.incoming[block][n];
|
||||
let e = self.edge(cond[q], q, taken);
|
||||
let (mut m, d) = self.mask(a);
|
||||
if !was_derived
|
||||
&& d
|
||||
&& !self.derived_phis.contains(&id)
|
||||
&& seen_derived.insert(id)
|
||||
{
|
||||
new_derived.push(id);
|
||||
}
|
||||
if !value {
|
||||
m = self.b.not(m);
|
||||
}
|
||||
if !failed && !self.b.implies(e, m) {
|
||||
wrong.push(id);
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
while p < self.phi_joins.len() {
|
||||
let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived);
|
||||
for a in self.phi_joins[p].args.clone() {
|
||||
let (_, d) = self.mask(a);
|
||||
if !was_derived
|
||||
&& d
|
||||
&& !self.derived_phis.contains(&id)
|
||||
&& seen_derived.insert(id)
|
||||
{
|
||||
new_derived.push(id);
|
||||
}
|
||||
}
|
||||
p += 1;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
wrong
|
||||
(wrong, new_derived)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
@@ -586,6 +731,22 @@ impl<'a> Lanes<'a> {
|
||||
execs: &[Vec<Option<Bool>>],
|
||||
cond: &[Bool],
|
||||
) -> Result<Structured, ShaderError> {
|
||||
let phi_joins = std::mem::take(&mut self.phi_joins);
|
||||
let mut phi_masks = HashMap::with_capacity(phi_joins.len());
|
||||
for pj in phi_joins {
|
||||
let incoming: Vec<Bool> = pj
|
||||
.args
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(n, a)| {
|
||||
let (q, taken) = self.incoming[pj.block][n];
|
||||
let e = self.edge(cond[q], q, taken);
|
||||
let m = self.mask(a).0;
|
||||
self.b.given(m, e)
|
||||
})
|
||||
.collect();
|
||||
phi_masks.insert(pj.id, incoming);
|
||||
}
|
||||
let blocks = &self.p.blocks;
|
||||
let b = &mut self.b;
|
||||
let guards = blocks
|
||||
@@ -624,6 +785,20 @@ impl<'a> Lanes<'a> {
|
||||
if self.b.overflow {
|
||||
return Err(TOO_LARGE);
|
||||
}
|
||||
// Exports go by low dword. A low dword read with two high dwords
|
||||
// (one rewritten alone) names no one mask: it is left out, so
|
||||
// lowering refuses what reads it instead of taking the other
|
||||
// pair's lanes 32-63. Not where the low dword holds a number: see
|
||||
// the shortcut in `mask`.
|
||||
let (mut high, mut split) = (Map::default(), HashSet::new());
|
||||
let keys = self.masks.keys().chain(self.other.keys());
|
||||
for &(lo, hi) in keys.chain(&self.seen) {
|
||||
if *high.entry(lo).or_insert(hi) != hi {
|
||||
split.insert(lo);
|
||||
}
|
||||
}
|
||||
self.masks.retain(|k, _| !split.contains(&k.0));
|
||||
self.active.retain(|lo| !split.contains(lo));
|
||||
Ok(Structured {
|
||||
masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(),
|
||||
highs: self
|
||||
@@ -634,6 +809,7 @@ impl<'a> Lanes<'a> {
|
||||
.collect(),
|
||||
paired_masks: if self.p.wave64 { self.masks } else { Map::default() },
|
||||
active: self.active,
|
||||
phi_masks,
|
||||
bools: self.b,
|
||||
exits,
|
||||
guards,
|
||||
@@ -694,6 +870,12 @@ impl<'a> Lanes<'a> {
|
||||
})
|
||||
};
|
||||
let derived = exec_write(lo, k.0) || exec_write(hi, k.1);
|
||||
// shortcut: the atom names the pair by its low dword, and
|
||||
// lowering takes the high dword written beside it. For halves
|
||||
// written apart (two `s_mov_b32`) lanes 32-63 are wrong unless
|
||||
// lowering has no value for the low dword (EXEC, compares)
|
||||
// and refuses. Give the atom both dwords when such code
|
||||
// turns up.
|
||||
let m = m.unwrap_or_else(|| {
|
||||
let born = self.born(k.0);
|
||||
self.b.atom(Atom::Opaque(k.0), born)
|
||||
@@ -730,7 +912,7 @@ impl<'a> Lanes<'a> {
|
||||
.map(|n| (arg(lo, k.0, n), arg(hi, k.1, n)))
|
||||
.collect();
|
||||
let id = lo.map_or(k.1, |_| k.0);
|
||||
let mut derived = false;
|
||||
let mut derived = self.derived_phis.contains(&id);
|
||||
// (edge condition, mask) per forward edge; back edges come later.
|
||||
let mut forward = Vec::new();
|
||||
for (n, &a) in args.iter().enumerate() {
|
||||
@@ -740,6 +922,8 @@ impl<'a> Lanes<'a> {
|
||||
derived |= d;
|
||||
let e = self.edge(self.first[q], q, taken);
|
||||
forward.push((e, m));
|
||||
} else {
|
||||
self.seen.push(a);
|
||||
}
|
||||
}
|
||||
if forward.len() == args.len()
|
||||
@@ -760,6 +944,7 @@ impl<'a> Lanes<'a> {
|
||||
block,
|
||||
id,
|
||||
value,
|
||||
derived,
|
||||
args,
|
||||
});
|
||||
let m = if value { Bool::TRUE } else { Bool::FALSE };
|
||||
@@ -767,6 +952,14 @@ impl<'a> Lanes<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.phi_join_ids.insert(id) {
|
||||
self.phi_joins.push(PhiJoin {
|
||||
block,
|
||||
id,
|
||||
derived,
|
||||
args,
|
||||
});
|
||||
}
|
||||
let born = self.index[block];
|
||||
Some((self.b.atom(Atom::Phi(id), born), derived))
|
||||
}
|
||||
@@ -854,9 +1047,13 @@ impl<'a> Lanes<'a> {
|
||||
"cselect" => {
|
||||
let (a, c) = (arg(0, self)?, arg(1, self)?);
|
||||
let scc = inst.read(Reg::Scc)?;
|
||||
let born = self.born(scc);
|
||||
let u = self.b.atom(Atom::Uniform(scc), born);
|
||||
(self.b.ite(u, a, c), None)
|
||||
if self.clear_after_loop(scc) {
|
||||
(c, None)
|
||||
} else {
|
||||
let born = self.born(scc);
|
||||
let u = self.b.atom(Atom::Uniform(scc), born);
|
||||
(self.b.ite(u, a, c), None)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let (a, c) = (arg(0, self)?, arg(1, self)?);
|
||||
@@ -872,6 +1069,31 @@ impl<'a> Lanes<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether SCC value `scc` is clear wherever it is read: the instruction before an
|
||||
/// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not
|
||||
/// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)`
|
||||
/// with EXEC empty. A read inside the loop or behind another way out of it sees a
|
||||
/// join of this value, not the value itself.
|
||||
fn clear_after_loop(&self, scc: Value) -> bool {
|
||||
let Some(&(b, i)) = self.defs.get(&scc) else {
|
||||
return false;
|
||||
};
|
||||
let block = &self.p.blocks[b];
|
||||
let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else {
|
||||
return false;
|
||||
};
|
||||
let exec = writer.write(Reg::S(EXEC));
|
||||
let back = match block.exit {
|
||||
Exit::Branch { taken, .. } => self.index[taken] <= self.index[b],
|
||||
_ => false,
|
||||
};
|
||||
back && i + 2 == block.insts.len()
|
||||
&& exec.is_some()
|
||||
&& last.name() == "s_cbranch_execnz"
|
||||
&& last.read(Reg::S(EXEC)) == exec
|
||||
&& (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1)))
|
||||
}
|
||||
|
||||
fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option<Bool> {
|
||||
let b = &mut self.b;
|
||||
Some(match f {
|
||||
@@ -963,6 +1185,23 @@ impl<'a> Lanes<'a> {
|
||||
};
|
||||
self.scc_lane.insert(scc, m);
|
||||
}
|
||||
// `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar
|
||||
// condition, or EXEC itself): its SCC, "some lane is set", is each lane's own
|
||||
// bit. A branch on it then reads no ballot.
|
||||
if takes_mask
|
||||
&& name.starts_with("s_bcnt1_i32_b")
|
||||
&& let Some(scc) = inst.write(Reg::Scc)
|
||||
&& let [a] = &src[..]
|
||||
&& let Some((m, true)) = self.operand(inst, a)
|
||||
{
|
||||
let e = exec.unwrap_or(Bool::TRUE);
|
||||
let own = self.b.given(m, e);
|
||||
if self.b.implies(m, e)
|
||||
&& self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
self.scc_lane.insert(scc, own);
|
||||
}
|
||||
}
|
||||
}
|
||||
Fields::Valu(v) => {
|
||||
let exec = self.exec(inst);
|
||||
@@ -974,11 +1213,22 @@ impl<'a> Lanes<'a> {
|
||||
l.active.insert(k.0);
|
||||
};
|
||||
// A select reads a mask nothing else may: a join of compare
|
||||
// results is resolved here, as for EXEC.
|
||||
if name == "v_cndmask_b32"
|
||||
// results is resolved here, as for EXEC. A carry-in is only
|
||||
// recorded for `finish`: resolving its join would turn a
|
||||
// refusal into a per-lane phi, wrong after a divergent branch.
|
||||
if (name == "v_cndmask_b32" || name.contains("_co_ci_"))
|
||||
&& let Some(&Operand::Scalar { code, .. }) = v.src.get(2)
|
||||
&& code != NULL
|
||||
&& let Some(k) = self.key(|r| inst.read(r), code)
|
||||
{
|
||||
if name == "v_cndmask_b32" {
|
||||
self.mask(k);
|
||||
} else {
|
||||
self.seen.push(k);
|
||||
}
|
||||
}
|
||||
if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64")
|
||||
&& let Some(k) = self.key(|r| inst.read(r), VCC)
|
||||
{
|
||||
self.mask(k);
|
||||
}
|
||||
@@ -1112,6 +1362,102 @@ mod tests {
|
||||
s.guards.iter().flatten().filter(|g| g.is_some()).count()
|
||||
}
|
||||
|
||||
/// The search of [`Bools::meet`] with every case split made anew, as it
|
||||
/// was before [`Meets`].
|
||||
fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool {
|
||||
let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE };
|
||||
if all.iter().any(fails) {
|
||||
return false;
|
||||
}
|
||||
all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
|
||||
if all.is_empty() || *budget == 0 {
|
||||
return true;
|
||||
}
|
||||
*budget -= 1;
|
||||
let top = |x: Bool| b.nodes[x.0 as usize].0;
|
||||
let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty");
|
||||
[false, true].into_iter().any(|value| {
|
||||
let next = all
|
||||
.iter()
|
||||
.map(|&(x, holds)| {
|
||||
let (lo, hi) = b.split(x, v);
|
||||
(if value { hi } else { lo }, holds)
|
||||
})
|
||||
.collect();
|
||||
meet_anew(b, next, budget)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_search_that_remembers_answers_as_one_made_anew() {
|
||||
// Functions of 12 variables put together at random, and conditions
|
||||
// of two to five of them (repeats and constants among them), under
|
||||
// budgets that run out early, late and never: the answer, and where
|
||||
// no lane is found the budget left, are those of the search that
|
||||
// remembers nothing; with what one `Meets` gathered over all of
|
||||
// them, and with an empty one.
|
||||
let mut b = Bools::new();
|
||||
let mut state = 0x9E37_79B9_7F4A_7C15_u64;
|
||||
let mut random = move |n: usize| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state % n as u64) as usize
|
||||
};
|
||||
let mut f: Vec<Bool> = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect();
|
||||
f.extend([Bool::FALSE, Bool::TRUE]);
|
||||
for _ in 0..120 {
|
||||
let (x, y) = (f[random(f.len())], f[random(f.len())]);
|
||||
let made = match random(4) {
|
||||
0 => b.and(x, y),
|
||||
1 => b.or(x, y),
|
||||
2 => b.xor(x, y),
|
||||
_ => b.not(x),
|
||||
};
|
||||
f.push(made);
|
||||
}
|
||||
let mut seen = Meets::default();
|
||||
let (mut none, mut some, mut gave_up) = (0, 0, 0);
|
||||
for _ in 0..1500 {
|
||||
let all: Vec<(Bool, bool)> = (0..2 + random(4))
|
||||
.map(|_| (f[random(f.len())], random(2) == 0))
|
||||
.collect();
|
||||
for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] {
|
||||
let mut left = budget;
|
||||
let anew = meet_anew(&b, all.clone(), &mut left);
|
||||
for fresh in [false, true] {
|
||||
let mut empty = Meets::default();
|
||||
let seen = if fresh { &mut empty } else { &mut seen };
|
||||
let mut work = all
|
||||
.iter()
|
||||
.map(|&(x, holds)| x.0 << 1 | u32::from(holds))
|
||||
.collect();
|
||||
let mut mine = budget;
|
||||
let found = b.meet_in(0, &mut work, &mut mine, seen);
|
||||
assert_eq!(found, anew, "{all:?} within {budget}");
|
||||
assert!(work.is_empty());
|
||||
if !found {
|
||||
assert_eq!(mine, left, "{all:?} within {budget}");
|
||||
}
|
||||
}
|
||||
assert_eq!(b.meet_within(&all, budget, &mut seen), anew);
|
||||
if !anew {
|
||||
none += 1;
|
||||
} else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) {
|
||||
some += 1;
|
||||
} else {
|
||||
gave_up += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// All three outcomes came up, and searches were remembered.
|
||||
assert!(
|
||||
none > 100 && some > 100 && gave_up > 100,
|
||||
"{none} {some} {gave_up}"
|
||||
);
|
||||
assert!(seen.none.len() > 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divergent_if_becomes_a_lane_branch() {
|
||||
let p = build(
|
||||
@@ -1193,6 +1539,39 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning
|
||||
/// programs): the loop is left when no lane remains, so the select takes
|
||||
/// its second operand; it was a uniform atom whose value no lane has.
|
||||
#[test]
|
||||
fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() {
|
||||
let cnd = 256 | (256 << 9) | (3 << 18);
|
||||
let p = build(
|
||||
&[
|
||||
0xBE83_037E, // 0: s_mov_b32 s3, exec_lo
|
||||
0xBE9C_037E, // s_mov_b32 s28, exec_lo
|
||||
0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7
|
||||
0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7
|
||||
0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28
|
||||
0xBF89_FFFC, // s_cbranch_execnz -> 8
|
||||
0xBEFE_0303, // s_mov_b32 exec_lo, s3
|
||||
0x8503_807E, // s_cselect_b32 s3, exec_lo, 0
|
||||
0xD501_0001,
|
||||
cnd, // v_cndmask_b32 v1, v0, v0, s3
|
||||
S_ENDPGM,
|
||||
],
|
||||
false,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
let select = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.insts)
|
||||
.find(|i| i.name() == "s_cselect_b32")
|
||||
.expect("the select");
|
||||
let mask = select.write(Reg::S(3)).unwrap();
|
||||
assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_branches_stay_uniform() {
|
||||
let p = build(
|
||||
@@ -1212,6 +1591,57 @@ mod tests {
|
||||
assert_eq!(guarded(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() {
|
||||
for reader in [
|
||||
0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc
|
||||
0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
|
||||
] {
|
||||
let p = build(
|
||||
&[
|
||||
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
|
||||
0xBEEB_0380, // s_mov_b32 vcc_hi, 0
|
||||
reader,
|
||||
S_ENDPGM,
|
||||
],
|
||||
true,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap();
|
||||
assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo));
|
||||
// The reader sees (compare low dword, 0): lanes 32-63 are clear.
|
||||
// The mask exported for that low dword must not be the compare.
|
||||
assert_ne!(
|
||||
s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
|
||||
Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)),
|
||||
"{reader:#x}: vcc_hi was zeroed after the compare"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() {
|
||||
let p = build(
|
||||
&[
|
||||
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
|
||||
0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc
|
||||
0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1
|
||||
0xBEEB_0380, // s_mov_b32 vcc_hi, 0
|
||||
0xBF85_FFFC, // s_cbranch_scc1 -> 4
|
||||
S_ENDPGM,
|
||||
],
|
||||
true,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
// The select reads the loop header's join; over the back edge it
|
||||
// takes (compare low dword, 0), which only the join sees.
|
||||
let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap();
|
||||
assert_ne!(
|
||||
s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
|
||||
Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn irreducible_loops_are_split() {
|
||||
let p = build(
|
||||
@@ -1231,4 +1661,117 @@ mod tests {
|
||||
assert_eq!(p.blocks[1].preds, [2]);
|
||||
assert!(structure(&p).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_phi_joining_constant_and_compare_records_edge_bools() {
|
||||
let cnd = 258 | (259 << 9) | (2 << 18);
|
||||
let p = build(
|
||||
&[
|
||||
0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0
|
||||
0xBF85_0002, // 4: s_cbranch_scc1 -> 16
|
||||
0xBE82_0380, // 8: s_mov_b32 s2, 0
|
||||
0xBF82_0002, // 12: s_branch -> 24
|
||||
0xD4C2_0002,
|
||||
0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0
|
||||
0xD501_0001,
|
||||
cnd, // 24: v_cndmask_b32 v1, v2, v3, s2
|
||||
S_ENDPGM,
|
||||
],
|
||||
false,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
let phi = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.phis)
|
||||
.find(|phi| phi.reg == Reg::S(2))
|
||||
.expect("mask phi for s2");
|
||||
assert_eq!(
|
||||
s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)),
|
||||
Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE))
|
||||
);
|
||||
let edges = &s.phi_masks[&phi.value];
|
||||
assert_eq!(edges.len(), 2);
|
||||
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
|
||||
assert!(
|
||||
edges
|
||||
.iter()
|
||||
.any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
|
||||
"{edges:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() {
|
||||
let cnd = 258 | (259 << 9) | (2 << 18);
|
||||
let p = build(
|
||||
&[
|
||||
0xBE82_0480, // 0: s_mov_b64 s[2:3], 0
|
||||
0xBE84_0380, // 4: s_mov_b32 s4, 0
|
||||
0xD501_0001,
|
||||
cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3]
|
||||
0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0
|
||||
0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3]
|
||||
0x8004_8104, // 24: s_add_u32 s4, s4, 1
|
||||
0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
|
||||
0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8
|
||||
0xD501_0004,
|
||||
cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3]
|
||||
S_ENDPGM,
|
||||
],
|
||||
true,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
let phi = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.phis)
|
||||
.find(|phi| phi.reg == Reg::S(2))
|
||||
.expect("loop mask phi for s[2:3]");
|
||||
assert!(s.masks.contains_key(&phi.value));
|
||||
let edges = &s.phi_masks[&phi.value];
|
||||
assert_eq!(edges.len(), 2);
|
||||
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
|
||||
assert!(edges.iter().any(|&e| {
|
||||
let sup = s.bools.support(e);
|
||||
sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_)))
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_mask_phi_reset_to_constant_on_back_edge() {
|
||||
let cnd = 258 | (259 << 9) | (2 << 18);
|
||||
let p = build(
|
||||
&[
|
||||
0xD4C2_0002,
|
||||
0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0
|
||||
0xBE84_0380, // 8: s_mov_b32 s4, 0
|
||||
0xD501_0001,
|
||||
cnd, // 12: v_cndmask_b32 v1, v2, v3, s2
|
||||
0xBE82_0380, // 20: s_mov_b32 s2, 0
|
||||
0x8004_8104, // 24: s_add_u32 s4, s4, 1
|
||||
0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
|
||||
0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12
|
||||
S_ENDPGM,
|
||||
],
|
||||
false,
|
||||
);
|
||||
let s = structure(&p).unwrap();
|
||||
let phi = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.phis)
|
||||
.find(|phi| phi.reg == Reg::S(2))
|
||||
.expect("loop mask phi for s2");
|
||||
assert!(s.masks.contains_key(&phi.value));
|
||||
let edges = &s.phi_masks[&phi.value];
|
||||
assert_eq!(edges.len(), 2);
|
||||
assert!(edges.contains(&Bool::FALSE), "{edges:?}");
|
||||
assert!(
|
||||
edges
|
||||
.iter()
|
||||
.any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
|
||||
"{edges:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user