Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crates/xcl/src/gpu/desc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,18 @@ pub fn image_d3d12(t: &Image) -> Option<(D3D12_RESOURCE_DESC, D3D12_SHADER_RESOU
Some((res, v))
}

/// S# word 2 fields that make [`sampler_d3d12`]'s filter blend: XY_MAG_FILTER [21:20] and
/// XY_MIN_FILTER [23:22] other than point (linear or anisotropic), MIP_FILTER [27:26] linear.
pub const SAMPLER_XY_FILTER: u32 = 0x00F0_0000;
pub const SAMPLER_MIP_FILTER: u32 = 0x0C00_0000;
pub const SAMPLER_MIP_LINEAR: u32 = 0x0800_0000;

/// Whether a sample through the S# with word 2 `w2` can return a blend of texels or mips
/// rather than one texel (the host filter [`sampler_d3d12`] makes is not MIN_MAG_MIP_POINT).
pub fn sampler_filters(w2: u32) -> bool {
w2 & SAMPLER_XY_FILTER != 0 || w2 & SAMPLER_MIP_FILTER == SAMPLER_MIP_LINEAR
}

/// D3D12 sampler from an S#. Border colours from the console's table (type 3) become
/// transparent black. `comparison` selects the comparison variant (image_*_c).
pub fn sampler_d3d12(w: &[u32; 4], comparison: bool) -> D3D12_SAMPLER_DESC {
Expand Down
65 changes: 56 additions & 9 deletions crates/xcl/src/gpu/dxil/lower_image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use super::lower::{err, LResult, Lw, VAR_VGPR};
use super::module::{BinOp, Pred, Value};
use super::ops::{AtomicOp, CompType, Sampler, TexKind, Texture};
use super::ops_core::op;
use crate::gpu::desc;
use crate::gpu::rdna2::{self, Decoded};

/// Upper bound on valid SRV indices in the shared shader-visible view heap
Expand Down Expand Up @@ -1047,6 +1048,12 @@ impl Lw {
let act = self.act();
let valid = self.valid_tsharp(tw0, tw1, tw3);
let run = self.land(act, valid);
// the T#'s format, for D16 reads of UNORM / SNORM texels (`d16_fmt`)
let ifmt = self.lshrc(tw1, 20);
let ifmt = self.andc(ifmt, 0x1FF);
let c77 = self.c(77);
let ifmt = self.umin(ifmt, c77);
let finfo = self.fmt_info(ifmt);
let z0 = self.c(0);
let safe_tw0 = self.sel(valid, tw0, z0);
let comps: Vec<u64> = (0..4).filter(|c| dmask >> c & 1 == 1).collect();
Expand Down Expand Up @@ -1303,12 +1310,45 @@ impl Lw {
};
let n = if gather { 4 } else { comps.len() };
let sel: Vec<usize> = (0..n).map(|k| if gather { k } else { comps[k] as usize }).collect();
// D16: a gather or a sample whose sampler cannot filter returns texels, codes of the
// format (`d16_fmt`); a filtered sample is a blend of them, not a code, and keeps the
// host's value (truncated, as d16_fmt's float channels).
enum Filters {
No,
Yes,
/// whether the S# filters, read when the shader runs
Dynamic(Value),
}
let filters = match self.static_samplers.get(&d.pc).copied() {
_ if gather || !d16 => Filters::No,
Some(w) if desc::sampler_filters(w[2]) => Filters::Yes,
Some(_) => Filters::No,
None => {
let s2 = self.sreg(ssamp + 2);
let xy = self.andc(s2, desc::SAMPLER_XY_FILTER);
let xy = self.cmpc(Pred::Ne, xy, 0);
let mip = self.andc(s2, desc::SAMPLER_MIP_FILTER);
let mip = self.cmpc(Pred::Eq, mip, desc::SAMPLER_MIP_LINEAR);
Filters::Dynamic(self.lor(xy, mip))
}
};
let vals: Vec<Value> = sel
.iter()
.map(|&c| {
if d16 {
// f32tof16(asfloat(e))
self.s.f32_to_f16(r[c])
// f32tof16(asfloat(e)); UNORM / SNORM rounded once (`d16_fmt`). A
// gather's four values are of the one component DMASK names.
let comp = if gather { comps.first().copied().unwrap_or(0) as u32 } else { c as u32 };
let sel = self.c(4 + comp);
match filters {
Filters::No => self.d16_fmt(rb[c], sel, finfo),
Filters::Yes => self.f16_rtz(r[c]),
Filters::Dynamic(fl) => {
let texel = self.d16_fmt(rb[c], sel, finfo);
let host = self.f16_rtz(r[c]);
self.sel(fl, host, texel)
}
}
} else {
rb[c]
}
Expand Down Expand Up @@ -1456,7 +1496,7 @@ impl Lw {
}
}
if ms {
return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act, run);
return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act, run, finfo);
}
match base {
"load" | "load_mip" => {
Expand Down Expand Up @@ -1519,8 +1559,8 @@ impl Lw {
.iter()
.map(|&c| {
let x = r[c as usize];
let fx = self.f(x);
let h = self.s.f32_to_f16(fx);
let sel = self.c(4 + c as u32);
let h = self.d16_fmt(x, sel, finfo);
let lo = self.andc(x, 0xFFFF);
let fl = self.cmpc(Pred::Eq, cls, 0);
self.sel(fl, h, lo)
Expand Down Expand Up @@ -1616,7 +1656,7 @@ impl Lw {
/// DMASK component of the four samples fragment .. fragment + 3 (a gather of samples).
/// Samples past the resource's count read 0 (made explicit: D3D leaves them undefined).
#[allow(clippy::too_many_arguments)]
fn mimg_msaa(&mut self, base: &str, ic: &[Value], tw0: Value, kind: TexKind, cls: Value, comps: &[u64], vdata: u64, d16: bool, act: Value, run: Value) -> LResult<()> {
fn mimg_msaa(&mut self, base: &str, ic: &[Value], tw0: Value, kind: TexKind, cls: Value, comps: &[u64], vdata: u64, d16: bool, act: Value, run: Value, finfo: Value) -> LResult<()> {
let nc = kind.coords();
let frag = ic[nc];
let coords = ic[..nc].to_vec();
Expand Down Expand Up @@ -1662,11 +1702,18 @@ impl Lw {
} else {
comps.iter().map(|&c| self.rd(tmps[0][c as usize])).collect()
};
// the component of each value: msaa_load's are all of one
let comp_of: Vec<u32> = if base == "msaa_load" {
vec![comps.first().copied().unwrap_or(0) as u32; raw.len()]
} else {
comps.iter().map(|&c| c as u32).collect()
};
let vals: Vec<Value> = if d16 {
raw.iter()
.map(|&x| {
let fx = self.f(x);
let h = self.s.f32_to_f16(fx);
.zip(comp_of)
.map(|(&x, comp)| {
let sel = self.c(4 + comp);
let h = self.d16_fmt(x, sel, finfo);
let lo = self.andc(x, 0xFFFF);
let fl = self.cmpc(Pred::Eq, cls, 0);
self.sel(fl, h, lo)
Expand Down
95 changes: 89 additions & 6 deletions crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,89 @@ impl Lw {
self.s.m.set_insert_before_term(prev_ins);
r
}
/// A D16 format load's non-integer channel `s` (decoded f32 bits) of DST_SEL `sel` as f16.
/// UNORM / SNORM data is `code / (2^w - 1)`, rounded once to nearest as RDNA2 does: its
/// binary expansion repeats the w-bit code, so its first 32 bits decide the rounding (a tie
/// cannot happen). Other channels truncate (`f16_rtz`), as RDNA2 does, whatever the host's
/// `legacyF32ToF16` rounds to.
pub(crate) fn d16_fmt(&mut self, s: Value, sel: Value, info: Value) -> Value {
let f = self.f(s);
let plain = self.f16_rtz(f);
let ty = self.lshrc(info, 3);
let ty = self.andc(ty, 7);
let four = self.c(4);
let k = self.sub(sel, four);
let k = self.andc(k, 3);
let six = self.c(6);
let k6 = self.mul(k, six);
let eight = self.c(8);
let shift = self.add(k6, eight);
let w = self.bin(BinOp::LShr, info, shift);
let w = self.andc(w, 63);
let snorm = self.cmpc(Pred::Eq, ty, 1);
let one = self.c(1);
let wm1 = self.sub(w, one);
let we = self.sel(snorm, wm1, w);
let dmax = self.bin(BinOp::Shl, one, we);
let dmax = self.sub(dmax, one);
// the code, back from the decoded value (within 2 ULP of exact)
let zf = self.fc(0.0);
let onef = self.fc(1.0);
let a = self.fabs(f);
let u = self.fmax(f, zf);
let a = self.sel(snorm, a, u);
let a = self.fmin(a, onef);
let df = self.uitof(dmax);
let y = self.fmul(a, df);
let y = self.un(crate::gpu::dxil::ops_core::op::ROUND_NE, y);
let y = self.ftoui(y);
// first 32 bits of y / dmax
let y64 = self.zext64(y);
let k32 = self.c64(32);
let y64 = self.bin(BinOp::Shl, y64, k32);
let d64 = self.zext64(dmax);
let p = self.bin(BinOp::UDiv, y64, d64);
let p = self.trunc32(p);
let lz = self.lzcnt(p);
let fourteen = self.c(14);
let e = self.sub(fourteen, lz);
// normal: 11 bits after the leading one and the round bit
let pn = self.bin(BinOp::Shl, p, lz);
let b = self.lshrc(pn, 20);
let half_ = self.lshrc(b, 1);
let rb = self.andc(b, 1);
let m = self.add(half_, rb);
let em1 = self.sub(e, one);
let eh = self.shlc(em1, 10);
let normal = self.add(eh, m);
// subnormal
let s8 = self.lshrc(p, 8);
let r7 = self.lshrc(p, 7);
let r7 = self.andc(r7, 1);
let sub = self.add(s8, r7);
let is_normal = self.cmp(Pred::SGe, e, one);
let h = self.sel(is_normal, normal, sub);
let zero = self.c(0);
let y0 = self.cmpc(Pred::Eq, y, 0);
let h = self.sel(y0, zero, h);
let full = self.cmp(Pred::UGe, y, dmax);
let h = self.selc(full, 0x3C00, h);
let neg = self.fcmp(Pred::FOLt, f, zf);
let sbit = self.c(0x8000);
let sgn = self.land(snorm, neg);
let sgn = self.sel(sgn, sbit, zero);
let h = self.or(h, sgn);
// which channels: UNORM / SNORM (ty 0 / 1) of 2..16 bits, a component (sel >= 4)
let is_norm = self.cmpc(Pred::ULe, ty, 1);
let comp = self.cmpc(Pred::UGe, sel, 4);
let w_lo = self.cmpc(Pred::UGe, w, 2);
let w_hi = self.cmpc(Pred::ULe, w, 16);
let use_n = self.land(is_norm, comp);
let use_n = self.land(use_n, w_lo);
let use_n = self.land(use_n, w_hi);
self.sel(use_n, h, plain)
}

fn fmt_desc(&mut self, d3: Value, mtbuf_fmt: Option<u32>) -> FmtDesc {
let key = (d3, mtbuf_fmt);
if let Some(&cached) = self.fmt_desc_cache.get(&key) {
Expand Down Expand Up @@ -1312,8 +1395,8 @@ impl Lw {
if let Some((_, _, high)) = d16_format {
let cur0 = self.vreg(vdata);
let lo16 = self.andc(s_val, 0xFFFF);
let sf = self.f(s_val);
let h16 = self.s.f32_to_f16(sf);
let sel0 = self.andc(d3, 7);
let h16 = self.d16_fmt(s_val, sel0, c1.desc.info);
let h = self.sel(c1.desc.isint, lo16, h16);
if high {
let h = self.shlc(h, 16);
Expand Down Expand Up @@ -1357,8 +1440,9 @@ impl Lw {
let half = |lw: &mut Lw, comp: u64| -> Value {
let s = decode_sel(lw, comp);
let lo = lw.andc(s, 0xFFFF);
let sf = lw.f(s);
let h = lw.s.f32_to_f16(sf);
let sel = lw.lshrc(d3, 3 * comp as u32);
let sel = lw.andc(sel, 7);
let h = lw.d16_fmt(s, sel, desc.info);
lw.sel(desc.isint, lo, h)
};
for i in 0..count {
Expand All @@ -1385,8 +1469,7 @@ impl Lw {
let sel = lw.andc(sel, 7);
let s = lw.dst_sel(&c, sel, desc.isint);
let lo = lw.andc(s, 0xFFFF);
let sf = lw.f(s);
let h = lw.s.f32_to_f16(sf);
let h = lw.d16_fmt(s, sel, desc.info);
lw.sel(desc.isint, lo, h)
};
for i in 0..count {
Expand Down
69 changes: 64 additions & 5 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::fmt::Write as _;

use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER};
use super::upper_lanes::Read;
use crate::gpu::desc;
use crate::gpu::dxbc::SigElement;
use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant};

Expand Down Expand Up @@ -2194,7 +2195,8 @@ impl Em {
if let Some((_, components, high)) = d16_format {
let half = |component: u64| {
let selected = format!("dst_sel({t}_c, ({d3} >> {}u) & 7u, {t}_int)", 3 * component);
format!("select({t}_int, {selected} & 0xFFFFu, f32tof16(asfloat({selected})))")
let sel = format!("(({d3} >> {}u) & 7u)", 3 * component);
format!("select({t}_int, {selected} & 0xFFFFu, d16_fmt({selected}, {sel}, {t}_info))")
};
let mut assigns = Vec::new();
if high {
Expand Down Expand Up @@ -2634,6 +2636,7 @@ impl Em {
// indexing `ResourceDescriptorHeap` (valid XCL T#: type >= 8, BASE_ADDRESS_HI cleared,
// SRV index < (1 << 21) - 1 so `tw0 + 1` stays in bounds without wrapping).
self.line(&format!("bool {t}_ok = (({tw3} >> 28) >= 8u) && ((({tw1}) & 0xFFu) == 0u) && (({tw0}) < {}u);", crate::gpu::dxil::lower_image::VIEW_HEAP_MAX_SRV));
self.line(&format!("uint {t}_finfo = FMT_INFO[min(({tw1} >> 20) & 0x1FFu, 77u)];"));
let comps: Vec<u64> = (0..4).filter(|c| dmask >> c & 1 == 1).collect();
// write the selected result components (`r` is a uint4 of raw bits); D16 packs halves
let write_result = |s: &mut Self, r: &str, n: usize, sel: &dyn Fn(usize) -> u64, half: &dyn Fn(&str) -> String| {
Expand All @@ -2655,7 +2658,18 @@ impl Em {
}
}
};
let f16 = |e: &str| format!("f32tof16(asfloat({e}))");
// UNORM / SNORM rounded once (`d16_fmt`); the component is the swizzle letter of `e`
let finfo = format!("{t}_finfo");
let comp_of = |e: &str| match e.chars().last() {
Some('x') => 0,
Some('y') => 1,
Some('z') => 2,
_ => 3,
};
let f16 = {
let finfo = finfo.clone();
move |e: &str| format!("d16_fmt({e}, {}u, {finfo})", 4 + comp_of(e))
};

if sampling {
if matches!(dim, 6 | 7) {
Expand Down Expand Up @@ -2815,7 +2829,29 @@ impl Em {
let n = if gather { 4 } else { comps.len() };
let comps2 = comps.clone();
let sel = move |k: usize| if gather { k as u64 } else { comps2[k] };
write_result(self, &format!("{t}_r"), n, &sel, &f16);
// D16: a gather or a sample whose sampler cannot filter returns texels, codes of the
// format (`d16_fmt`); a filtered sample is a blend of them, not a code, and keeps the
// host's value (truncated, as d16_fmt's float channels).
let point = match self.static_ss.get(&d.pc) {
_ if gather || !d16 => "true".to_string(),
Some(w) => (!desc::sampler_filters(w[2])).to_string(),
None => {
let s2 = self.sreg(ssamp + 2);
self.line(&format!(
"bool {t}_pt = (({s2}) & {:#X}u) == 0u && (({s2}) & {:#X}u) != {:#X}u;",
desc::SAMPLER_XY_FILTER,
desc::SAMPLER_MIP_FILTER,
desc::SAMPLER_MIP_LINEAR
));
format!("{t}_pt")
}
};
let half = move |e: &str| match point.as_str() {
"true" => f16(e),
"false" => format!("f16_rtz(asfloat({e}))"),
p => format!("select({p}, {}, f16_rtz(asfloat({e})))", f16(e)),
};
write_result(self, &format!("{t}_r"), n, &sel, &half);
return Ok(());
}

Expand Down Expand Up @@ -2843,7 +2879,7 @@ impl Em {
"uint4 {t}_r = ({t}_ok ? asuint(float4({t}_T.CalculateLevelOfDetail({t}_S, {coord}), {t}_T.CalculateLevelOfDetailUnclamped({t}_S, {coord}), 0.0f, 0.0f)) : uint4(0u, 0u, 0u, 0u));"
));
let comps2 = comps.clone();
write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &f16);
write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &|e: &str| format!("f32tof16(asfloat({e}))"));
return Ok(());
}

Expand Down Expand Up @@ -2931,7 +2967,7 @@ impl Em {
));
}
let cls = format!("{t}_cls");
let half = move |e: &str| format!("(({cls} == 0u) ? f32tof16(asfloat({e})) : ({e} & 0xFFFFu))");
let half = move |e: &str| format!("(({cls} == 0u) ? d16_fmt({e}, {}u, {finfo}) : ({e} & 0xFFFFu))", 4 + comp_of(e));
let comps2 = comps.clone();
write_result(self, &format!("{t}_r"), comps.len(), &move |k| comps2[k], &half);
}
Expand Down Expand Up @@ -5944,6 +5980,29 @@ void st_bytes(uint a, uint4 r, uint n) {
st_part(b, m << s, r.x << s);
if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s));
}
// code / (2^w - 1) as f16, rounded once to nearest (RDNA2's D16 of UNORM / SNORM data): the
// binary expansion repeats the w-bit code, so p (its first 32 bits) decides the rounding, and a
// tie cannot happen. f32tof16 of the decoded f32 rounds twice, the second time toward zero.
uint norm16_rep(uint y, uint w) {
uint d = (1u << w) - 1u;
if (y == 0u) return 0u;
if (y >= d) return 0x3C00u;
uint p = (uint)(((uint64_t)y << 32) / (uint64_t)d);
uint lz = 31u - firstbithigh(p);
int e = 14 - (int)lz;
if (e >= 1) { uint b = (p << lz) >> 20; return ((uint)(e - 1) << 10) + (b >> 1) + (b & 1u); }
return (p >> 8) + ((p >> 7) & 1u);
}
// a D16 format load's non-integer channel x (decoded f32 bits) of DST_SEL sel
uint d16_fmt(uint x, uint sel, uint info) {
uint ty = (info >> 3) & 7u;
uint w = (info >> (8u + 6u * ((sel - 4u) & 3u))) & 63u;
if (ty > 1u || sel < 4u || w < 2u || w > 16u) return f16_rtz(asfloat(x));
float f = asfloat(x);
if (ty == 0u) return norm16_rep((uint)round(saturate(f) * (float)((1u << w) - 1u)), w);
uint h = norm16_rep((uint)round(min(abs(f), 1.0f) * (float)((1u << (w - 1u)) - 1u)), w - 1u);
return h | select(f < 0.0f, 0x8000u, 0u);
}
uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); }
"#;

Expand Down
Loading
Loading