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

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

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

No files matched your search

+14
View File
@@ -103,6 +103,9 @@ pub(crate) mod pred {
pub const OGE: u8 = 3;
pub const OLT: u8 = 4;
pub const OLE: u8 = 5;
// Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg`
// lowers as OLT | OGT instead.
#[allow(dead_code)]
pub const ONE: u8 = 6;
pub const ORD: u8 = 7;
pub const UNO: u8 = 8;
@@ -291,6 +294,17 @@ impl Module {
self.constant(ty, Const::Aggregate(ids))
}
/// The value of an integer constant; `None` for anything else.
pub fn int_value(&self, v: V) -> Option<i64> {
match v {
V::Const(i) => match self.consts[i as usize].1 {
Const::Int(x) => Some(x),
_ => None,
},
_ => None,
}
}
/// Gives constant `old` the content of `new` (both stay valid).
pub fn replace_const(&mut self, old: V, new: V) {
if let (V::Const(o), V::Const(n)) = (old, new) {
@@ -161,6 +161,15 @@ pub(crate) fn psv(p: &Psv) -> Vec<u8> {
u32s(&mut out, &[48]);
let mut info = [0u8; 48];
info[0] = u8::from(p.flag);
if p.stage == 0 {
// PSInfo.SampleFrequency: an input interpolated per sample, or the
// sample index.
info[1] = u8::from(
p.inputs
.iter()
.any(|e| matches!(e.interp, 6 | 7) || e.kind == 12),
);
}
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
info[16..20].copy_from_slice(&min.to_le_bytes());
info[20..24].copy_from_slice(&max.to_le_bytes());
+349 -81
View File
@@ -931,8 +931,16 @@ impl<'a> Lower<'a> {
for &(reg, v) in &self.x.p.inputs {
let val = match reg {
Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
Reg::S(_) => match io_inputs.get(&v) {
Reg::S(n) => match io_inputs.get(&v) {
Some(&input) => self.input(input),
// Above the SGPRs the hardware initializes, a register
// holds what the last wave left, so no program depends
// on it: a read the paths only seem to allow (a branch
// past the write, taken only with one past the read)
// reads zero, as VGPRs do.
None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
Val::I32(self.s.m.i32(0))
}
None => Val::Missing("a hardware SGPR input"),
},
Reg::Scc => Val::Missing("SCC on entry"),
@@ -1233,6 +1241,19 @@ impl<'a> Lower<'a> {
}
}
/// GFX10 puts an inline f16 constant in the low half of the operand.
fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
match *op {
Operand::Const(c @ 240..=248) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
Ok(self.s.m.i32(h))
}
_ => self.operand(inst, op),
}
}
fn as_float(&mut self, x: V) -> V {
self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
}
@@ -1360,6 +1381,25 @@ impl<'a> Lower<'a> {
)
}
/// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
/// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
/// the compare and select DXIL specifies gives either zero.
fn max_min(&mut self, max: bool, a: V, b: V) -> V {
let c = self.cur;
let r = self.binary(if max { 35 } else { 36 }, a, b);
let (ia, ib) = (self.as_int(a), self.as_int(b));
let either = self.s.m.bin(c, Bin::Or, ia, ib);
let magnitude = self.s.m.i32(0x7FFF_FFFF);
let either = self.s.m.bin(c, Bin::And, either, magnitude);
let zero = self.s.m.i32(0);
let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
// Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
let op = if max { Bin::And } else { Bin::Or };
let sign = self.s.m.bin(c, op, ia, ib);
let signed = self.as_float(sign);
self.s.m.select(c, zeros, signed, r)
}
fn fmad(&mut self, a: V, b: V, c: V) -> V {
self.s.op(
self.cur,
@@ -3866,8 +3906,8 @@ impl<'a> Lower<'a> {
"v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
"v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
"v_mul_legacy_f32" => self.legacy_mul(a, bb),
"v_max_f32" => self.binary(35, a, bb),
_ => self.binary(36, a, bb),
"v_max_f32" => self.max_min(true, a, bb),
_ => self.max_min(false, a, bb),
};
float(self, r)
}
@@ -3917,12 +3957,12 @@ impl<'a> Lower<'a> {
let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
let r = match name {
"v_max3_f32" => {
let t = self.binary(35, a, bb);
self.binary(35, t, cc)
let t = self.max_min(true, a, bb);
self.max_min(true, t, cc)
}
"v_min3_f32" => {
let t = self.binary(36, a, bb);
self.binary(36, t, cc)
let t = self.max_min(false, a, bb);
self.max_min(false, t, cc)
}
_ => self.med3(a, bb, cc),
};
@@ -4281,15 +4321,9 @@ impl<'a> Lower<'a> {
_ => return Err("a byte select on a 16-bit operation"),
}
}
let x = match (op, self.src0) {
(_, Some(x)) if k == 0 => x,
(Operand::Const(c @ 240..=248), _) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
self.s.m.i32(h)
}
_ => self.operand(inst, &op)?,
let x = match self.src0 {
Some(x) if k == 0 => x,
_ => self.f16_operand(inst, &op)?,
};
let c = self.cur;
let x = if high {
@@ -4416,6 +4450,8 @@ impl<'a> Lower<'a> {
"v_min_i16",
"v_cvt_u16_f16",
"v_cvt_i16_f16",
"v_cvt_norm_i16_f16",
"v_cvt_norm_u16_f16",
];
let all = [FLOAT1, FLOAT2, FLOAT3, INT];
if !all.iter().any(|l| l.contains(&name))
@@ -4468,8 +4504,8 @@ impl<'a> Lower<'a> {
"v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
"v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
"v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
"v_max_f16" => self.binary(35, a, b),
_ => self.binary(36, a, b),
"v_max_f16" => self.max_min(true, a, b),
_ => self.max_min(false, a, b),
};
return float_result(self, r);
}
@@ -4499,12 +4535,12 @@ impl<'a> Lower<'a> {
// product is exact; the sum rounds twice).
"v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
"v_max3_f16" => {
let t = self.binary(35, a, b);
self.binary(35, t, acc)
let t = self.max_min(true, a, b);
self.max_min(true, t, acc)
}
"v_min3_f16" => {
let t = self.binary(36, a, b);
self.binary(36, t, acc)
let t = self.max_min(false, a, b);
self.max_min(false, t, acc)
}
_ => self.med3(a, b, acc),
};
@@ -4554,21 +4590,35 @@ impl<'a> Lower<'a> {
};
return float_result(self, r);
}
if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
if v.clamp || v.omod != 0 {
return Err("modifiers on a 16-bit integer operation");
}
let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
return self.write_half(inst, r, guard);
}
// 16-bit integers: computed on the low halves, the low 16 bits kept.
if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
return Err("modifiers on a 16-bit integer operation");
}
let r = match name {
"v_cvt_u16_f16" | "v_cvt_i16_f16" => {
// shortcut: converted through 32 bits, so out-of-range values
// wrap instead of saturating at 16 bits.
// Toward zero, saturating at the 16-bit range (infinities
// included); NaN gives 0. Clamped in f32 first, where every
// f16 is exact, so the conversion never leaves i32's range.
let a = self.half_fsrc(inst, 0)?;
let op = if name == "v_cvt_u16_f16" {
Cast::FpToUi
let (lo, hi) = if name == "v_cvt_u16_f16" {
(0.0f32, 65535.0f32)
} else {
Cast::FpToSi
(-32768.0, 32767.0)
};
self.s.m.cast(c, op, a, i32t)
let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
let t = self.binary(35, a, lo);
let t = self.binary(36, t, hi);
let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
let nan = self.s.m.cmp(c, pred::UNO, a, a);
let z = self.s.m.i32(0);
self.s.m.select(c, nan, z, r)
}
_ => {
let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
@@ -4618,24 +4668,92 @@ impl<'a> Lower<'a> {
self.write_half(inst, r, guard)
}
/// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
/// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
/// rounded to nearest even once from the exact product; NaN gives 0.
/// Worked on the f16's bits in integers, because in f32 the product
/// (up to 26 significant bits) would round before the rounding to an
/// integer.
fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
let c = self.cur;
let k = |l: &mut Self, x: u32| l.s.m.i32(x);
let mut h = self.half_src(inst, 0)?;
if v.abs & 1 != 0 {
let m = k(self, 0x7FFF);
h = self.s.m.bin(c, Bin::And, h, m);
}
if v.neg & 1 != 0 {
let m = k(self, 0x8000);
h = self.s.m.bin(c, Bin::Xor, h, m);
}
let scale = if signed { 0x7FFF } else { 0xFFFF };
let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
let mag_mask = k(self, 0x7FFF);
let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
let k15 = k(self, 15);
let neg = self.s.m.bin(c, Bin::LShr, h, k15);
let neg = self.s.m.cmp(c, pred::NE, neg, k0);
// |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
let man_mask = k(self, 0x3FF);
let man = self.s.m.bin(c, Bin::And, mag, man_mask);
let implicit = k(self, 0x400);
let normal = self.s.m.bin(c, Bin::Or, man, implicit);
let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
let m = self.s.m.select(c, sub, man, normal);
let k25 = k(self, 25);
let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
let k24 = k(self, 24);
let sh = self.s.m.select(c, sub, k24, s_norm);
let ks = k(self, scale);
let p = self.s.m.bin(c, Bin::Mul, m, ks);
let q = self.s.m.bin(c, Bin::LShr, p, sh);
let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
let rem = self.s.m.bin(c, Bin::And, p, low_mask);
let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
let above = self.s.m.cmp(c, pred::IUGT, rem, half);
let tie = self.s.m.cmp(c, pred::EQ, rem, half);
let odd = self.s.m.bin(c, Bin::And, q, k1);
let odd = self.s.m.cmp(c, pred::NE, odd, k0);
let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
let up = self.s.m.bin(c, Bin::Or, above, tie_up);
let r = self.s.m.select(c, up, k1, k0);
let r = self.s.m.bin(c, Bin::Add, q, r);
// |x| >= 1 (and infinity) saturates; NaN gives 0.
let one_h = k(self, 0x3C00);
let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
let r = self.s.m.select(c, big, ks, r);
let inf = k(self, 0x7C00);
let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
let r = self.s.m.select(c, nan, k0, r);
let r = if signed {
let n = self.s.m.bin(c, Bin::Sub, k0, r);
self.s.m.select(c, neg, n, r)
} else {
self.s.m.select(c, neg, k0, r)
};
let m16 = k(self, 0xFFFF);
Ok(self.s.m.bin(c, Bin::And, r, m16))
}
/// Half `high` of source `k` of a packed (VOP3P) operation, in the low
/// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
/// half the high result reads. Inline float constants are f16 values.
fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
/// half the high result reads. Packed integer instructions see the f32
/// bits of an inline float constant.
fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
let op = *v.src.get(k).ok_or("a missing operand")?;
let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
let x = match op {
Operand::Const(c @ 240..=248) => {
let h = [
0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
][usize::from(c - 240)];
// shortcut: taken to fill both halves.
self.s.m.i32(h | h << 16)
}
_ => self.operand(inst, &op)?,
let x = if float {
self.f16_operand(inst, &op)?
} else {
self.operand(inst, &op)?
};
let c = self.cur;
let x = if sel {
@@ -4671,7 +4789,7 @@ impl<'a> Lower<'a> {
for high in [false, true] {
let mut xs = Vec::new();
for k in 0..n {
let h = self.packed_src(inst, k, high)?;
let h = self.packed_src(inst, k, high, float)?;
if float {
let mut f = self
.s
@@ -4690,8 +4808,8 @@ impl<'a> Lower<'a> {
let mut f = match op {
"add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
"mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
"min_f16" => self.binary(36, xs[0], xs[1]),
"max_f16" => self.binary(35, xs[0], xs[1]),
"min_f16" => self.max_min(false, xs[0], xs[1]),
"max_f16" => self.max_min(true, xs[0], xs[1]),
// shortcut: FMad in f32, as v_fma_f16.
_ => self.fmad(xs[0], xs[1], xs[2]),
};
@@ -4973,24 +5091,22 @@ impl<'a> Lower<'a> {
_ => {
// A computed selector: each byte picked at run time.
let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
let i64t = self.s.m.int(64);
self.s.flags |= flags::INT64;
let wa = self.s.m.cast(c, Cast::ZExt, a, i64t);
let wb = self.s.m.cast(c, Cast::ZExt, b, i64t);
let k32 = self.s.m.int_const(i64t, 32);
let wa = self.s.m.bin(c, Bin::Shl, wa, k32);
let both = self.s.m.bin(c, Bin::Or, wa, wb);
let mut r = k(self, 0);
for i in 0..4u32 {
let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
let sel = self.s.m.bin(c, Bin::And, sel, ff);
// Bytes 0-7 of {src0, src1}.
let k3 = k(self, 3);
let bits = self.s.m.bin(c, Bin::Shl, sel, k3);
let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t);
let x = self.s.m.bin(c, Bin::LShr, both, bits);
let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
// Select a dword and a byte within it.
// Later selects handle codes 8 and above.
let four = k(self, 4);
let zero = k(self, 0);
let high = self.s.m.bin(c, Bin::And, sel, four);
let high = self.s.m.cmp(c, pred::NE, high, zero);
let word = self.s.m.select(c, high, a, b);
let three = k(self, 3);
let index = self.s.m.bin(c, Bin::And, sel, three);
let bits = self.s.m.bin(c, Bin::Shl, index, three);
let x = self.s.m.bin(c, Bin::LShr, word, bits);
let mut byte = self.s.m.bin(c, Bin::And, x, ff);
// 8-11: the sign of bytes 1, 3 of src1, then of src0.
for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
@@ -5214,26 +5330,35 @@ impl<'a> Lower<'a> {
} else {
(self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
};
let p = match op {
"f" => pred::FALSE,
"lt" => pred::OLT,
"eq" => pred::OEQ,
"le" => pred::OLE,
"gt" => pred::OGT,
"lg" => pred::ONE,
"ge" => pred::OGE,
"o" => pred::ORD,
"u" => pred::UNO,
"nge" => pred::ULT,
"nlg" => pred::UEQ,
"ngt" => pred::ULE,
"nle" => pred::UGT,
"neq" => pred::UNE,
"nlt" => pred::UGE,
"tru" => pred::TRUE,
_ => return Err(inst.name()),
};
self.s.m.cmp(c, p, a, b)
if op == "lg" {
// Ordered and not equal, false for a NaN, as `olt | ogt`.
// `fcmp one` means the same, but the AMD D3D12 driver
// runs it as unordered (true for a NaN) where NVIDIA
// and WARP do not; olt and ogt agree on all three.
let lt = self.s.m.cmp(c, pred::OLT, a, b);
let gt = self.s.m.cmp(c, pred::OGT, a, b);
self.s.m.bin(c, Bin::Or, lt, gt)
} else {
let p = match op {
"f" => pred::FALSE,
"lt" => pred::OLT,
"eq" => pred::OEQ,
"le" => pred::OLE,
"gt" => pred::OGT,
"ge" => pred::OGE,
"o" => pred::ORD,
"u" => pred::UNO,
"nge" => pred::ULT,
"nlg" => pred::UEQ,
"ngt" => pred::ULE,
"nle" => pred::UGT,
"neq" => pred::UNE,
"nlt" => pred::UGE,
"tru" => pred::TRUE,
_ => return Err(inst.name()),
};
self.s.m.cmp(c, p, a, b)
}
}
"u64" | "i64" => {
let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
@@ -5650,7 +5775,7 @@ impl<'a> Lower<'a> {
return Ok(());
}
let (op, sample) = match name {
"image_sample" => (60, true),
"image_sample" | "image_sample_o" => (60, true),
"image_sample_lz" | "image_sample_l" => (62, true),
"image_sample_b" => (61, true),
"image_sample_c_lz" => (65, true),
@@ -5795,6 +5920,25 @@ impl<'a> Lower<'a> {
args.extend(&cs);
match op {
60 => {
if offset_word {
// DXIL takes immediate offsets in -8..=7; the
// console's are 6-bit and may be computed.
let w = addr_val(self, 0)?;
let w = self
.s
.m
.int_value(w)
.ok_or("a sample offset that is not constant")?
as u32;
for (k, o) in os.iter_mut().enumerate().take(offsets) {
let x = (w >> (8 * k) & 0x3F) as i32;
let x = if x >= 32 { x - 64 } else { x };
if !(-8..=7).contains(&x) {
return Err("a sample offset past -8..7");
}
*o = self.s.m.i32(x as u32);
}
}
args.extend(&os);
args.push(fu);
self.s
@@ -6733,6 +6877,20 @@ impl<'a> Lower<'a> {
fn fill_phis(&mut self) -> Result<(), Stop> {
let p = self.x.p;
// A phi that only another read phi consumes is live too. Without this, a value with no DXIL form that
// reaches a read through two joins is taken for dead at the first join and replaced by zero below, and the
// lowering accepts what it refuses when the same value is read directly.
let mut work: Vec<Value> = self.read_phis.iter().copied().collect();
while let Some(v) = work.pop() {
let Some(&(b, i)) = self.phi_at.get(&v) else {
continue;
};
for &arg in &p.blocks[b].phis[i].args {
if self.phi_at.contains_key(&arg) && self.read_phis.insert(arg) {
work.push(arg);
}
}
}
for (v, b, i) in std::mem::take(&mut self.data_phis) {
let phi = &p.blocks[b].phis[i];
let bit = phi.reg == Reg::Scc;
@@ -6792,8 +6950,8 @@ mod tests {
const S_ENDPGM: u32 = 0xBF81_0000;
/// Lowers a compute program of constants: whether it translates.
fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> {
/// Whether a synthetic compute program translates with these input registers.
fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let native = NativeProgram {
stage: HwStage::Cs,
@@ -6802,7 +6960,7 @@ mod tests {
layout: vec![],
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: 0,
rsrc2,
threads: [1, 1, 1],
}),
code,
@@ -6914,10 +7072,91 @@ mod tests {
S_ENDPGM,
];
for words in [add, sub] {
lowers(&words).unwrap();
lowers(&words, 0).unwrap();
}
}
fn perm_features(selector: u32) -> u64 {
// Synthetic compute shader:
// v0 is the thread ID and can supply a dynamic selector.
// Store the result in LDS to keep the permutation live.
let words = [
0x7E02_02FFu32,
0x817F_34AB,
0x7E04_02FF,
0xFE01_56CD,
0xD744_0003,
257 | (258 << 9) | (selector << 18),
0x3408_0082,
0xD834_0000,
0x0000_0304,
S_ENDPGM,
];
let code: Vec<u8> = words.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: 1 << 15,
threads: [64, 1, 1],
}),
code,
};
let p = ir::build(&native.code, false, 256).unwrap();
assert!(p.blocks.iter()
.flat_map(|b| &b.insts)
.any(|i| i.name() == "v_perm_b32"));
let st = structure::structure(&p).unwrap();
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = io::raise(&p, &native).unwrap();
let emitted = lower(&Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: vec![],
outputs: vec![],
prims: vec![],
mesh_stride: 0,
}).unwrap();
let container =
crate::Container::parse(&emitted.dxil).unwrap();
let features =
container.part(crate::FourCC::SFI0).unwrap();
u64::from_le_bytes(features.data.try_into().unwrap())
}
#[test]
fn perm_constant_selector_needs_no_int64() {
assert_eq!(perm_features(128) & 0x8000, 0);
}
#[test]
fn perm_dynamic_selector_needs_no_int64() {
assert_eq!(
perm_features(256) & 0x8000,
0,
"dynamic v_perm_b32 must not require INT64"
);
}
#[test]
fn a_descriptor_selected_by_scc_picks_its_heap_index() {
// Two buffer descriptors loaded from the table at s0, one picked by
@@ -7049,10 +7288,39 @@ mod tests {
];
for head in bit_tests {
let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
lowers(&words).unwrap();
lowers(&words, 0).unwrap();
}
}
#[test]
fn a_missing_value_stays_missing_through_two_live_joins() {
let mut words = [
0xF490_0180,
0, // s_memtime s[6:7]
0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
0xBF85_0001, // skip the first overwrite
0xBE86_0380, // s_mov_b32 s6, 0
0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
0xBF85_0001, // skip the second overwrite
0xBE86_0381, // s_mov_b32 s6, 1
0xBF07_8006, // s_cmp_lg_u32 s6, 0
0xBF85_0001, // use the result to branch
0xBE83_0380,
S_ENDPGM,
];
let group_ids_xy = 3 << 7;
// Compare to a direct read so future timestamp support works in both cases.
let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
Ok(()) => None,
Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
Err(error) => panic!("{error}"),
};
let direct = [&words[..2], &words[8..]].concat();
assert_eq!(refusal(&words), refusal(&direct));
words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
lowers(&words, group_ids_xy).expect("dead timestamp");
}
#[test]
fn buffer_formats_by_number() {
// The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
+147
View File
@@ -246,6 +246,13 @@ pub fn emit(
_ => 0,
};
}
// With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
// wants the position centroid (or per sample), as DXC declares it then.
if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
for e in inputs.iter_mut().filter(|e| e.kind == 3) {
e.interp = 5;
}
}
// Per-primitive outputs are constant. The console never exports a
// primitive id or cull flag a mesh shader writes (it culls with the
// primitive export), so those rows are left out.
@@ -416,6 +423,68 @@ mod tests {
use super::*;
use crate::native::{ComputeIo, StageIo};
/// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
/// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
/// output signature has SV_StencilRef, and the feature bit
/// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
/// both against the module.
#[test]
fn a_stencil_export_declares_the_stencil_ref_feature() {
let words = [
0x7E00_02F2u32, // v_mov_b32 v0, 1.0
0x7E02_0285, // v_mov_b32 v1, 5
0xF800_1883,
0x0000_0100, // exp mrtz v0, v1, off, off done vm
0xBF81_0000,
];
let native = NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 2,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs: vec![],
input_addr: 0,
db_shader_control: 0,
patches: vec![],
},
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let el = |name: &str, kind, comp| SigElement {
name: name.into(),
index: 0,
kind,
comp,
interp: 0,
row: None,
col: 0,
cols: 1,
usage: 1,
half: false,
};
let osg1 =
container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
let c = Container::parse(&bytes).unwrap();
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let st = structure::structure(&p).unwrap();
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = io::raise(&p, &native).unwrap();
let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
// dxil.dll, where there is one, checks the flags against the module.
#[cfg(windows)]
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut out.dxil.clone()).unwrap();
}
let host = Container::parse(&out.dxil).unwrap();
let sfi0 = host.part(FourCC::SFI0).unwrap().data;
let features = u64::from_le_bytes(sfi0.try_into().unwrap());
assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
}
/// A wave64 compute program that writes only EXEC's high dword
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
/// opaque and keyed by the unchanged low dword, so building its lane bit
@@ -452,6 +521,7 @@ mod tests {
}
/// A pixel shader writing a constant colour.
#[cfg(windows)]
fn constant_color() -> Vec<u8> {
let mut s = Shader::new(true);
s.outputs.push(SigElement {
@@ -545,6 +615,83 @@ mod tests {
assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
}
/// A pixel shader interpolating at sample positions (PERSP_SAMPLE
/// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
/// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
/// whenever an input is interpolated per sample.
#[test]
fn sample_interpolated_inputs_set_psv_sample_frequency() {
let words = [
0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xF800_180F,
0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
0xBF81_0000,
];
let psv_of = |input_addr: u32| {
let native = super::NativeProgram {
stage: super::HwStage::Ps,
wave64: false,
vgprs: 4,
layout: vec![],
used: vec![],
io: crate::native::StageIo::Ps {
inputs: vec![crate::native::PsInput {
usage: crate::native::Usage::Generic,
row: 0,
mask: 0b1111,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 0,
}],
input_addr,
db_shader_control: 0,
patches: vec![],
},
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let el = |name: &str, kind, usage| SigElement {
name: name.into(),
index: 0,
kind,
comp: 9,
interp: 0,
row: Some(0),
col: 0,
cols: 4,
usage,
half: false,
};
let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
let bytes =
crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
let c = super::Container::parse(&bytes).unwrap();
let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let st = crate::structure::structure(&p).unwrap();
let res =
crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
let io = crate::io::raise(&p, &native).unwrap();
let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
// dxil.dll, where there is one, checks PSV0 against the module.
#[cfg(windows)]
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut out.dxil.clone()).unwrap();
}
let host = super::Container::parse(&out.dxil).unwrap();
host.part(super::FourCC::PSV0).unwrap().data.to_vec()
};
// Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
let center = psv_of(1 << 1);
assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
let sample = psv_of(1 << 0);
assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
}
/// A pixel shader reading channel z of an input whose element starts at
/// w. Looking the channel up subtracted the element's first channel
/// before checking the channel lies in it, so in a build with overflow
+8
View File
@@ -16,6 +16,7 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
pub(crate) mod flags {
pub const RAW_BUFFERS: u64 = 1 << 4;
pub const STENCIL_REF: u64 = 1 << 11;
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
pub const WAVE_OPS: u64 = 1 << 19;
pub const INT64: u64 = 1 << 20;
@@ -483,6 +484,10 @@ impl Shader {
} else {
None
};
// A pixel shader with an SV_StencilRef output (as DXC collects it).
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
self.flags |= flags::STENCIL_REF;
}
// Entry properties: shader flags (tag 0), thread-group size (4),
// wave size (11).
let mut props = Vec::new();
@@ -561,6 +566,9 @@ impl Shader {
dxil.extend(&bitcode);
let mut features = 0u64;
if self.flags & flags::STENCIL_REF != 0 {
features |= 0x200;
}
if self.flags & flags::TYPED_UAV_LOADS != 0 {
features |= 0x800;
}
+1 -1
View File
@@ -1,6 +1,6 @@
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
//! offline batch. Translated shaders do not need it: they carry the
//! container hash we compute ([`super::container::hash`]).
//! container hash we compute (`container::hash`).
//!
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
@@ -167,6 +167,11 @@ fn run_cases(
cases: &[[u32; 4]],
mut check: impl FnMut(&str, usize, [u32; 4], u32),
) {
// One test at a time: with these tests on the hardware adapter and WARP
// from several test threads at once, now and then none of their
// dispatches ever completes and the test binary hangs.
static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
@@ -232,6 +237,27 @@ fn f16_to_f32(bits: u16) -> f32 {
f32::from_bits(f32_bits)
}
#[test]
fn packed_add_selects_halves_of_inline_constants() {
// Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves.
// The same GFX10 source field (248) has a different bit pattern for a
// packed floating-point and a packed integer instruction.
let cases = [
// v_pk_add_f16 v0, 0x3118, v1
([0xcc0f4000, 0x1a0202f8], 0x0000_3118),
// v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice)
([0xcc0f4000, 0x120202f8], 0x3118_3118),
// v_pk_add_u16 v0, 0x3e22f983, v1
([0xcc0a4000, 0x1a0202f8], 0x3e22_f983),
];
for (words, expected) in cases {
let shader = build_valu_cs(&words);
run_cases(&shader, &[[0; 4]], |backend, _, _, got| {
assert_eq!(got, expected, "{backend}: {words:08x?}");
});
}
}
#[test]
fn v_med3_f32_matches_rdna2_with_nan() {
// v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157)
@@ -280,6 +306,32 @@ fn v_med3_f32_matches_rdna2_with_nan() {
});
}
/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and
/// FMin compare and select, which can give either zero.
#[test]
fn max_and_min_order_negative_zero_below_positive_zero() {
let (pz, nz) = (0_u32, 0x8000_0000_u32);
// Each case has a -0 and a +0 among its first two operands.
let cases = [
[nz, pz, nz, 0],
[pz, nz, nz, 0],
[nz, pz, pz, 0],
[pz, nz, pz, 0],
];
let ops = [
("v_max_f32", 0x110, pz),
("v_min_f32", 0x10F, nz),
("v_max3_f32", 0x154, pz),
("v_min3_f32", 0x151, nz),
];
for (name, op, want) in ops {
let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
run_cases(&shader, &cases, |backend, _, inp, got| {
assert_eq!(got, want, "{backend}: {name} {inp:x?}");
});
}
}
#[test]
fn v_med3_f16_matches_rdna2_with_nan() {
// v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357)
@@ -321,6 +373,58 @@ fn v_med3_f16_matches_rdna2_with_nan() {
});
}
/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when
/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware).
#[test]
fn v_cmp_lg_is_false_for_nan() {
// v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3);
// v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101)
let nan = f32::NAN.to_bits();
let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits());
let f = f32::to_bits;
let f32_cases: &[([u32; 4], u32)] = &[
([f(1.0), f(2.0), 0, 0], 1),
([f(2.0), f(1.0), 0, 0], 1),
([f(1.0), f(1.0), 0, 0], 0),
([f(0.0), f(-0.0), 0, 0], 0),
([inf, ninf, 0, 0], 1),
([inf, inf, 0, 0], 0),
([nan, f(1.0), 0, 0], 0),
([f(1.0), nan, 0, 0], 0),
([nan, nan, 0, 0], 0),
([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN
];
let f16_cases: &[([u32; 4], u32)] = &[
([0x3C00, 0x4000, 0, 0], 1),
([0x4000, 0x3C00, 0, 0], 1),
([0x3C00, 0x3C00, 0, 0], 0),
([0x0000, 0x8000, 0, 0], 0),
([0x7C00, 0xFC00, 0, 0], 1),
([0x7E00, 0x3C00, 0, 0], 0),
([0x3C00, 0x7E00, 0, 0], 0),
([0x7E00, 0x7E00, 0, 0], 0),
([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN
([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read
];
for (op, what, cases) in [
(0x005u16, "v_cmp_lg_f32", f32_cases),
(0x0cd, "v_cmp_lg_f16", f16_cases),
] {
let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec();
body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20)));
let shader = build_valu_cs(&body);
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
run_cases(&shader, &inputs, |backend, i, inp, got| {
let want = cases[i].1;
assert_eq!(
got, want,
"{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}",
inp[0], inp[1],
);
});
}
}
#[test]
fn v_fract_f32_never_returns_one() {
// v_fract_f32 v0, v1 (VOP1 opcode 0x020)
@@ -421,6 +525,52 @@ fn v_fract_f16_never_returns_one() {
});
}
/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or
/// 65535, round the exact product to nearest even; NaN gives 0.
fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 {
let x = f16_to_f32(bits);
if x.is_nan() {
return 0;
}
let (lo, scale) = if signed {
(-1.0, 32767.0)
} else {
(0.0, 65535.0)
};
// f64 holds the product of an f16 and a 16-bit scale exactly.
let p = f64::from(x.clamp(lo, 1.0)) * scale;
p.round_ties_even() as i32 as u16
}
#[test]
fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() {
// Every 251st f16 pattern, plus the values where an f32 product would
// round before the rounding to an integer, ties, and the edges.
let mut bits: Vec<u16> = (0..=u16::MAX).step_by(251).collect();
bits.extend([
0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF,
0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01,
0x3A9B, 0xBA9B, 0x2E66, 0x1400,
]);
for (op, signed, what) in [
(0x063u16, true, "v_cvt_norm_i16_f16"),
(0x064, false, "v_cvt_norm_u16_f16"),
] {
// v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0.
let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let want = cvt_norm16_reference(bits[i], signed);
assert_eq!(
got,
u32::from(want),
"{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
bits[i],
);
});
}
}
#[test]
fn v_sin_and_v_cos_f32_reduce_large_turns() {
let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]);
@@ -521,6 +671,46 @@ fn v_sin_and_v_cos_f32_reduce_large_turns() {
});
}
#[test]
fn v_cvt_u16_and_i16_f16_saturate() {
// v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053).
let cases: &[(u16, u16, u16)] = &[
// (f16 input, u16 result, i16 result)
(0x0000, 0, 0), // 0
(0x8000, 0, 0), // -0
(0x3E00, 1, 1), // 1.5 -> 1 (toward zero)
(0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1
(0x57D0, 125, 125), // 125.0
(0x7800, 32768, 32767), // 32768 saturates i16
(0x77FF, 32752, 32752), // 32752, the largest f16 below 32768
(0xF800, 0, 0x8000), // -32768 fits i16
(0xF801, 0, 0x8000), // -32800 saturates i16
(0x7BFF, 65504, 32767), // max finite f16
(0xFBFF, 0, 0x8000), // -65504
(0x7C00, 0xFFFF, 32767), // +inf
(0xFC00, 0, 0x8000), // -inf
(0x7E00, 0, 0), // NaN
(0xFE00, 0, 0), // -NaN
(0x0001, 0, 0), // smallest subnormal
];
for (op, what, pick) in [
(0x052u16, "v_cvt_u16_f16", 0usize),
(0x053, "v_cvt_i16_f16", 1),
] {
let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let want = if pick == 0 { cases[i].1 } else { cases[i].2 };
assert_eq!(
got,
u32::from(want),
"{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
cases[i].0,
);
});
}
}
#[test]
fn v_sin_and_v_cos_f16_reduce_large_turns() {
let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]);