Take the fix/amd-view-heap-clamp branch of triippywhale's fork (as one commit)

Every host view heap ends at a null slot that view indices past the heap
read (a host that takes large heaps gets 2^21 views; one that caps them
keeps the capped heap), the cache key includes that limit, and
v_permlane16/x16 are lowered.

Both forks lower v_cvt_f32_f64. The IEEE form with its test is the one in
use; this branch's flush-to-zero form is kept beside it, unused, and its
test is ignored until the console's float mode for the instruction is
checked.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-24 19:00:31 -05:00
1 parent 3bff182ef4
commit 31714deb2d
6 files changed
+302 -49

No files matched your search

+76 -37
View File
@@ -509,34 +509,52 @@ pub(crate) fn near_heaps(va: u64) -> String {
/// tiers 1 and 2; tier 3 hardware may take more.
const PORTABLE_VIEWS: u32 = 1_000_000;
/// Asks the host, once, whether it caps view heaps at [`PORTABLE_VIEWS`],
/// and if so tells the translator now (`set_view_heap_limit`) instead of
/// when the title's heap is made: a shader keeps the limit it was
/// translated with, and the title makes 25 pipelines (their
/// shaders translated at once) before it makes its view heap. Those would
/// read a view index past the heap unclamped, the read that hangs NVIDIA.
/// Called before a shader is translated.
/// shortcut: the limit is the capped heap's last slot whatever size the
/// title's heap turns out to have; a heap that fits is not capped and
/// keeps no null slot there (an index past it is as undefined as before).
/// The size of every host view heap on a host that takes more than
/// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000
/// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and
/// the last slot is the null slot every view index at or past it reads.
const UNCAPPED_VIEWS: u32 = 1 << 21;
/// Picks, once, the null slot at the end of every host view heap and tells
/// the translator now (`set_view_heap_limit`) instead of when the title's
/// heap is made: a shader keeps the limit it was translated with, and the
/// title makes 25 pipelines (their shaders translated at once) before it
/// makes its view heap. Called before a shader is translated and before a
/// view heap is made.
///
/// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`]
/// (NVIDIA) hung on a view index past the heap; one that does not (AMD
/// RDNA3, RX 7900 XT) took a page fault and removed the device on entering
/// the world: a compute program read view slot 16,777,088 (0xffff80) of a
/// heap of 1,507,328, past its end. Unclamped, that index is undefined on
/// any host.
pub(crate) fn probe_view_limit() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let Some(host) = host() else { return };
// SAFETY: plain heap creation; the heap is released at once.
let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe {
host.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: PORTABLE_VIEWS + 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
let fits = |count: u32| {
// SAFETY: plain heap creation; the heap is released at once.
let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe {
host.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: count,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
};
made.is_ok()
};
if made.is_err() {
tracing::info!("the host caps view heaps at {PORTABLE_VIEWS}: view indices are clamped from the first shader on");
victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1);
}
let views = if fits(UNCAPPED_VIEWS) {
UNCAPPED_VIEWS
} else {
PORTABLE_VIEWS
};
tracing::info!(
views,
"host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on"
);
victory_shader::emit::set_view_heap_limit(views - 1);
});
}
@@ -574,20 +592,41 @@ impl HostHeap {
}
};
let extra = if sampler { 0 } else { DYNAMIC };
let (heap, count, size) = match make(count + extra) {
Ok(heap) => (heap, count, count + extra),
Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
// shortcut: descriptors past the host's limit are left out; a title that reaches
// them needs remapping. The heap's last slot stays null, and shaders read it for
// any view index from there on (`set_view_heap_limit`): a read past the heap's
// end hung NVIDIA's GPU (the title's heap is a little over 1 000 000 views).
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}; views past it read a null slot");
victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1);
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra - 1, PORTABLE_VIEWS)
// A view heap ends at the null slot shaders clamp view indices to
// (`probe_view_limit`), whatever the title's own count: the title's
// slots, then the dynamic ones, then null up to and with that slot.
if !sampler {
probe_view_limit();
}
let null = if sampler {
0
} else {
victory_shader::emit::view_heap_limit()
};
let (heap, count, size) = if null == 0 {
match make(count + extra) {
Ok(heap) => (heap, count, count + extra),
Err(e) => {
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
return None;
}
}
Err(e) => {
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
return None;
} else {
let size = null + 1;
let fitted = if count + extra <= null {
count
} else {
// shortcut: descriptors past the host's limit are left out; a title that reaches
// them needs remapping. They read the null slot instead.
tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot");
null - extra
};
match make(size) {
Ok(heap) => (heap, fitted, size),
Err(e) => {
tracing::warn!(error = %e, count, size, "no host view heap");
return None;
}
}
};
// SAFETY: a live heap.
@@ -602,7 +641,7 @@ impl HostHeap {
let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
gpu,
u64::from(count + extra) * u64::from(step),
u64::from(size) * u64::from(step),
u64::from(step),
sampler,
));
+4
View File
@@ -54,6 +54,10 @@ fn build() -> &'static [u8; 32] {
match exe {
Ok(mut bytes) => {
bytes.extend_from_slice(&limit.to_le_bytes());
// So is the view heap's null slot (it differs by host GPU):
// a translation cached without the clamp must not be served.
crate::descriptor::host::probe_view_limit();
bytes.extend_from_slice(&victory_shader::emit::view_heap_limit().to_le_bytes());
// Which group barriers wait is part of the translation too.
bytes.push(victory_shader::emit::group_sync());
// So are the switches that pick the form of a wave64 program:
+107 -6
View File
@@ -7077,6 +7077,50 @@ impl<'a> Lower<'a> {
let r = self.s.m.cast(c, op, a, self.s.t.i32);
int(self, r)
}
"v_permlane16_b32" | "v_permlanex16_b32" => {
// Each lane reads src0 of a lane of its own 32-lane half,
// picked by nibble (lane & 15) of {src2, src1}: within its
// own row of 16 (`v_permlane16`) or the other row of its
// half (`v_permlanex16`). The pick stays inside a half, so a
// console wave of 64 run as two host waves of 32 needs no
// exchange.
// shortcut: a source lane with EXEC clear is read as the host
// gives it (the console keeps vdst unless op_sel's fetch
// inactive bit is set).
self.cross_lane(false)?;
let x = s(self, 0)?;
let (s1, s2) = (s(self, 1)?, s(self, 2)?);
let i32t = self.s.t.i32;
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let [k15, k8, k7, k2, k16, not31, not15] =
[15, 8, 7, 2, 16, !31, !15].map(|x| self.s.m.i32(x));
let low = self.s.m.bin(c, Bin::And, lane, k15);
// nibble `low` of the 64-bit selector: src1 holds lanes 0-7
let hi_word = self.s.m.cmp(c, pred::IUGE, low, k8);
let word = self.s.m.select(c, hi_word, s2, s1);
let n = self.s.m.bin(c, Bin::And, low, k7);
let sh = self.s.m.bin(c, Bin::Shl, n, k2);
let pick = self.s.m.bin(c, Bin::LShr, word, sh);
let pick = self.s.m.bin(c, Bin::And, pick, k15);
let row = if name == "v_permlanex16_b32" {
// the other row of this half
let half = self.s.m.bin(c, Bin::And, lane, not31);
let other = self.s.m.bin(c, Bin::And, lane, k16);
let other = self.s.m.bin(c, Bin::Xor, other, k16);
self.s.m.bin(c, Bin::Or, half, other)
} else {
self.s.m.bin(c, Bin::And, lane, not15)
};
let from = self.s.m.bin(c, Bin::Or, row, pick);
let r = self.read_lane(x, from);
int(self, r)
}
"v_cvt_f32_f64" => {
let (lo, hi) = self.f64_pair(inst, 0)?;
let bits = self.f64_to_f32_bits(lo, hi);
let r = self.as_float(bits);
float(self, r)
}
"v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
| "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
let mut a = s(self, 0)?;
@@ -7094,12 +7138,6 @@ impl<'a> Lower<'a> {
let r = self.s.m.cast(c, op, a, self.s.t.f32);
float(self, r)
}
"v_cvt_f32_f64" => {
let (lo, hi) = self.f64_pair(inst, 0)?;
let bits = self.f64_to_f32_bits(lo, hi);
let r = self.as_float(bits);
float(self, r)
}
"v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
// Each source is f32, or with op_sel_hi the low (op_sel: high)
// f16 half; neg_hi is the absolute value here.
@@ -7631,6 +7669,69 @@ impl<'a> Lower<'a> {
self.s.m.bin(c, Bin::Or, lo, hi)
}
/// The bits of the float nearest the double whose dwords are `lo` and
/// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
/// kept (a NaN stays quiet), a result below the smallest normal float
/// signed zero (flushed, as the console's default float mode does).
// The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
// float mode for this instruction is checked.
#[allow(dead_code)]
fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
let c = self.cur;
let k = |l: &mut Self, x: u32| l.s.m.i32(x);
let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
let sign_mask = k(self, 0x8000_0000);
let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
let e = self.s.m.bin(c, Bin::LShr, hi, k20);
let e_mask = k(self, 0x7ff);
let e = self.s.m.bin(c, Bin::And, e, e_mask);
// The top 23 bits of the 52-bit mantissa, and the 29 below them.
let m_mask = k(self, 0x000f_ffff);
let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
let m = self.s.m.bin(c, Bin::Or, mh, ml);
let rest_mask = k(self, 0x1fff_ffff);
let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
// Round to nearest even: up past half, or at half when odd.
let half = k(self, 0x1000_0000);
let one = k(self, 1);
let above = self.s.m.cmp(c, pred::IUGT, rest, half);
let at = self.s.m.cmp(c, pred::EQ, rest, half);
let odd = self.s.m.bin(c, Bin::And, m, one);
let zero = k(self, 0);
let odd = self.s.m.cmp(c, pred::NE, odd, zero);
let tie = self.s.m.bin(c, Bin::And, at, odd);
let up = self.s.m.bin(c, Bin::Or, above, tie);
let up = self.s.m.select(c, up, one, zero);
// Rebias the exponent (1023 → 127); a carry out of the mantissa
// steps the exponent, up to infinity.
let bias = k(self, 1023 - 127);
let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
let normal = self.s.m.bin(c, Bin::Add, ex, m);
let normal = self.s.m.bin(c, Bin::Add, normal, up);
let normal = self.s.m.bin(c, Bin::Or, normal, sign);
// Exponents out of the float's range (signed, after rebiasing).
let inf = k(self, 0x7f80_0000);
let inf = self.s.m.bin(c, Bin::Or, inf, sign);
let k255 = k(self, 255);
let big = self.s.m.cmp(c, pred::SGE, e32, k255);
let small = self.s.m.cmp(c, pred::SLE, e32, zero);
let r = self.s.m.select(c, big, inf, normal);
let r = self.s.m.select(c, small, sign, r);
// Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
let all = k(self, 0x7ff);
let special = self.s.m.cmp(c, pred::EQ, e, all);
let any = self.s.m.bin(c, Bin::Or, mh, ml);
let any = self.s.m.bin(c, Bin::Or, any, rest);
let nan = self.s.m.cmp(c, pred::NE, any, zero);
let quiet = k(self, 0x0040_0000);
let quiet = self.s.m.select(c, nan, quiet, zero);
let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
self.s.m.select(c, special, special_bits, r)
}
/// The low and high dwords of an i64.
fn split64(&mut self, x: V) -> (V, V) {
let c = self.cur;
+1 -1
View File
@@ -115,7 +115,7 @@ 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,
set_view_heap_limit, view_heap_limit,
};
/// The loop limit without an override: 2^20.
+10 -5
View File
@@ -113,11 +113,11 @@ 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.
/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while
/// it is set read that slot for any view index at or past it. A read past a heap's end is
/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD
/// RDNA3 took a page fault and removed the device.
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.
@@ -125,6 +125,11 @@ pub fn set_view_heap_limit(null_slot: u32) {
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
}
/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
pub fn view_heap_limit() -> u32 {
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) struct Shader {
pub m: Module,
pub t: Types,
@@ -308,6 +308,110 @@ fn packed_add_selects_halves_of_inline_constants() {
}
}
/// The float `v_cvt_f32_f64` gives for `x`: Rust's rounding (to nearest
/// even), with results below the smallest normal float flushed to signed
/// zero as the console's default float mode does.
fn cvt_f32_f64_reference(x: f64) -> u32 {
let r = x as f32;
if r.is_subnormal() || (r == 0.0 && x != 0.0) {
r.to_bits() & 0x8000_0000
} else {
r.to_bits()
}
}
#[test]
#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"]
fn v_cvt_f32_f64_rounds_to_nearest_even() {
// v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f)
let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]);
let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0
let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp
let values = [
0.0,
-0.0,
1.0,
-2.5,
std::f64::consts::PI,
1.0e-3,
123_456_789.123,
tie_even,
tie_odd,
1.0 + f64::from(f32::EPSILON) * 0.75,
f64::from(f32::MAX),
f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity
1.0e300,
-1.0e300,
1.0e-40, // a float denormal: flushed
-1.0e-300,
f64::from(f32::MIN_POSITIVE),
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
];
let inputs: Vec<[u32; 4]> = values
.iter()
.map(|x| {
let b = x.to_bits();
[b as u32, (b >> 32) as u32, 0, 0]
})
.collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let x = values[i];
if x.is_nan() {
assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN");
return;
}
let want = cvt_f32_f64_reference(x);
assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}");
});
}
/// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads
/// for `lane`, with selector dwords `s1` (lanes 0-7 of a row) and `s2`.
fn permlane_source(lane: u32, s1: u32, s2: u32, cross: bool) -> u32 {
let sel = u64::from(s1) | u64::from(s2) << 32;
let pick = (sel >> (4 * (lane & 15)) & 15) as u32;
let row = if cross {
(lane & !31) | ((lane & 16) ^ 16)
} else {
lane & !15
};
row | pick
}
#[test]
fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() {
// 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1);
// lane `read` of v1 into s12, then into v0 for the store.
let selectors: [(u32, u32); 3] = [
(0x7654_3210, 0xfedc_ba98), // identity within the row
(0x89ab_cdef, 0x0123_4567), // reversed
(0x1111_1111, 0xf0f0_f0f0), // repeats
];
for (op, cross) in [(0x377u16, false), (0x378, true)] {
for read in [0u8, 5, 15, 16, 22, 31] {
let mut body = Vec::new();
body.extend_from_slice(&vop3(op, 1, vgpr(0), sgpr(0), sgpr(1)));
// v_readlane_b32 s12, v1, read (inline constant 128 + read)
body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0));
body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12
let shader = build_cs(&body, 32, 0);
let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect();
// Cross-lane code declares WaveSize(32), which WARP's pipeline
// creation refuses: hardware only.
run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| {
let want = permlane_source(u32::from(read), inp[0], inp[1], cross);
assert_eq!(
got, want,
"{backend}: op {op:#x} selectors {:08x?}, lane {read}",
selectors[i]
);
});
}
}
}
#[test]
fn v_med3_f32_matches_rdna2_with_nan() {
// v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157)