Skip to content
Merged
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
49 changes: 46 additions & 3 deletions crates/leonida-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -960,7 +960,7 @@ impl HostHeap {
));
let strides = (!sampler)
.then(|| {
let bytes = u64::from(leonida_shader::emit::SLOT_STRIDES_COUNT) * 4;
let bytes = u64::from(leonida_shader::emit::SLOT_STRIDES_DWORDS) * 4;
let (buffer, data) = host.upload_buffer(bytes)?;
// SAFETY: the buffer's whole mapping; a live buffer.
let gpu = unsafe {
Expand Down Expand Up @@ -1637,9 +1637,20 @@ impl HostHeap {
if let Some((_, _, data)) = &self.strides
&& index < leonida_shader::emit::SLOT_STRIDES_COUNT
{
use leonida_shader::emit::SLOT_VIEW_ADDRESSES;
let address = stride.and(view).and_then(buffer_range).map_or(0, |r| r.0);
let at = (SLOT_VIEW_ADDRESSES + 2 * index) as usize;
// SAFETY: inside the mapping; shaders read it while we write (a
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
// dword, either value is one the slot had; the address's two
// dwords can be seen half old, half new while the slot changes).
unsafe {
let words = *data as *mut u32;
words
.add(index as usize)
.write_volatile(stride.unwrap_or(0));
words.add(at).write_volatile(address as u32);
words.add(at + 1).write_volatile((address >> 32) as u32);
}
}
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
let was = if stride.is_some() {
Expand Down Expand Up @@ -3653,6 +3664,38 @@ mod tests {
assert_eq!(heap.dynamic(50), Some(4));
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
}

/// The table shaders pick buffers from the heap by holds each slot's
/// stride and, after the strides, the title address of its buffer view;
/// both follow the slot's writes.
#[test]
fn the_slot_table_holds_each_buffer_views_address() {
use leonida_shader::emit::SLOT_VIEW_ADDRESSES;
let Some(heap) = HostHeap::new(false, 8) else {
return; // no host GPU
};
let data = heap.strides.as_ref().map(|s| s.2).unwrap();
// SAFETY: dwords inside the table's mapping.
let word = |k: u32| unsafe { (data as *const u32).add(k as usize).read_volatile() };
let slot = |i: u32| (word(i), word(SLOT_VIEW_ADDRESSES + 2 * i), word(SLOT_VIEW_ADDRESSES + 2 * i + 1));
// 10 structured elements of 16 bytes from element 2, at an address no
// test and no title uses.
let at = 0x7fee_0000_0040u64;
let buffer = |at: u64| {
let mut desc = [0u32; 16];
(desc[1], desc[4], desc[6], desc[7]) = (1, 2, 10, 16);
(desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
View::Placed(false, [1; 14], desc)
};
assert!(heap.note_buffer(3, Some(&buffer(at)), false).is_empty());
assert_eq!(slot(3), (16, (at + 32) as u32, (at >> 32) as u32));
assert_eq!(slot(2), (0, 0, 0));
// Written again elsewhere, then emptied.
heap.note_buffer(3, Some(&buffer(at + 0x1000)), false);
assert_eq!(slot(3).1, (at + 0x1020) as u32);
heap.note_buffer(3, None, false);
assert_eq!(slot(3), (0, 0, 0));
}
}

#[cfg(test)]
Expand Down
47 changes: 45 additions & 2 deletions crates/leonida-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2749,6 +2749,9 @@ impl<'a> Lower<'a> {
use super::shader::USER_VIEW_ADDRESS;
let a = self.scalar.get(&site).copied()?;
let rp = *self.x.native.layout.get(a.param)?;
if rp.root == RootType::ResourceHeap && a.offset % 32 == 0 {
return self.slot_view_address(site);
}
if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
return None;
}
Expand Down Expand Up @@ -6573,6 +6576,42 @@ impl<'a> Lower<'a> {
Ok(Some(v))
}

/// The title address (low dword, bits from 32 up) of the buffer view the
/// scalar load at `site` reads from the view heap at an index it
/// computes: read from the host's table by heap slot
/// (`shader.rs` `SLOT_VIEW_ADDRESSES`), in the current block.
fn slot_view_address(&mut self, site: Site) -> Option<(V, V)> {
use super::shader::{SLOT_STRIDES, SLOT_STRIDES_COUNT, SLOT_VIEW_ADDRESSES};
let slot = self.heap_index(site, 0, false).ok()?;
let c = self.cur;
let i32t = self.s.t.i32;
// Inside the table whatever the index, as for the strides.
let last = self.s.m.i32(SLOT_STRIDES_COUNT - 1);
let slot = self
.s
.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
self.s.m.tag(slot, Tag::Clamp);
let three = self.s.m.i32(3);
let byte = self.s.m.bin(c, Bin::Shl, slot, three);
let start = self.s.m.i32(SLOT_VIEW_ADDRESSES * 4);
let byte = self.s.m.bin(c, Bin::Add, byte, start);
let h = self.s.root_srv_handle(SLOT_STRIDES);
let iu = self.s.m.undef(i32t);
let mask = self.s.m.i8(3);
let align = self.s.m.i32(4);
let r = self.s.op(
c,
"rawBufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
139,
&[h, byte, iu, mask, align],
);
let lo = self.s.m.extract(c, r, 0);
let hi = self.s.m.extract(c, r, 1);
Some((self.as_int(lo), self.as_int(hi)))
}

/// The heap index of a descriptor that may differ between lanes,
/// computed in the current block (or, chosen by control flow, at the
/// join).
Expand Down Expand Up @@ -11431,6 +11470,10 @@ fn interp_mode(kind: Barycentric) -> Option<u8> {
})
}

#[cfg(test)]
#[path = "view_address_tests.rs"]
mod view_address_tests;

#[cfg(test)]
mod tests {
use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
Expand Down Expand Up @@ -11598,7 +11641,7 @@ mod tests {

/// Lowers a compute program with the root parameters `layout` (in user
/// SGPRs from s0 on) and the used resources `used`.
fn lower_with(
pub(super) fn lower_with(
words: &[u32],
layout: Vec<RootParam>,
used: Vec<UsedResource>,
Expand Down Expand Up @@ -11646,7 +11689,7 @@ mod tests {
}

/// Root parameter `slot` in user SGPRs from `user_data` on.
fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
pub(super) fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
RootParam {
root,
table_offset_dwords: 0,
Expand Down
6 changes: 3 additions & 3 deletions crates/leonida-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ pub use sampler::StaticSampler;
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, view_heap_limit,
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY,
SLOT_STRIDES, SLOT_STRIDES_COUNT, SLOT_STRIDES_DWORDS, SLOT_VIEW_ADDRESSES, USER_DATA_SPACE,
USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit,
};

/// The loop limit without an override: 2^20.
Expand Down
10 changes: 9 additions & 1 deletion crates/leonida-shader/src/emit/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,16 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// 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.
/// Heap slots the [`SLOT_STRIDES`] buffer covers: heap indices are clamped to it.
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
/// The [`SLOT_STRIDES`] buffer goes on after its strides: from this dword, two
/// per heap slot `i` (dwords `SLOT_VIEW_ADDRESSES + 2 * i` and the next), the
/// title address of the buffer view at slot `i` (0: none or not a buffer).
/// Console code reads the address out of a descriptor it picks from the heap
/// and walks the memory behind it (the shadow-ray tracer's structures).
pub const SLOT_VIEW_ADDRESSES: u32 = SLOT_STRIDES_COUNT;
/// Dwords of the whole [`SLOT_STRIDES`] buffer: strides, then addresses.
pub const SLOT_STRIDES_DWORDS: u32 = 3 * SLOT_STRIDES_COUNT;

/// Title memory by address (`resource::MEMORY`): console code reads and
/// writes through raw 40-bit addresses it takes from root constants,
Expand Down
32 changes: 32 additions & 0 deletions crates/leonida-shader/src/emit/view_address_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! The address of a buffer view picked from the view heap, read from the
//! host's table by heap slot (`SLOT_VIEW_ADDRESSES`).
use super::tests::{lower_with, root};
use crate::native::RootType;

const S_ENDPGM: u32 = 0xBF81_0000;

#[test]
fn a_view_picked_from_the_heap_for_its_address_reads_it_from_the_host() {
// A buffer descriptor loaded from the heap (s0) at the slot a root
// constant (s1) names, its address alone copied to LDS.
let words = [
0x8F02_8501, // s_lshl_b32 s2, s1, 5
0xBE81_0380, // s_mov_b32 s1, 0
0xF408_0100,
0x0400_0000, // s_load_dwordx4 s[4:7], s[0:1], s2
0x7E02_0204, // v_mov_b32 v1, s4
0x7E04_0205, // v_mov_b32 v2, s5
0xD834_0000,
0x0000_0100, // ds_write_b32 v0, v1
0xD834_0000,
0x0000_0200, // ds_write_b32 v0, v2
S_ENDPGM,
];
let layout = vec![
root(RootType::ResourceHeap, 0, 0),
root(RootType::Constants, 1, 1),
];
let l = lower_with(&words, layout, vec![]).unwrap();
assert!(l.root_srvs.contains(&super::super::shader::SLOT_STRIDES));
}
50 changes: 50 additions & 0 deletions crates/leonida-shader/src/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -991,6 +991,18 @@ impl<'a> Lanes<'a> {
let args: Vec<Key> = (0..target.preds.len())
.map(|n| (arg(lo, k.0, n), arg(hi, k.1, n)))
.collect();
// A register holding a mask on one path and a dword read from memory
// on another is a number the compiler reuses: no lane mask comes back
// from a scalar load.
let loaded = |v: Value| {
self.defs
.get(&v)
.is_some_and(|&(b, i)| matches!(p.blocks[b].insts[i].fields, Fields::Smem { .. }))
};
if args.iter().any(|&(a, b)| loaded(a) || loaded(b)) {
let born = self.born(k.0);
return Some((self.b.atom(Atom::Opaque(k.0), born), false));
}
let id = lo.map_or(k.1, |_| k.0);
let mut derived = self.derived_phis.contains(&id);
// (edge condition, mask) per forward edge; back edges come later.
Expand Down Expand Up @@ -1759,6 +1771,44 @@ mod tests {
);
}

#[test]
fn a_register_joining_a_mask_with_loaded_data_is_no_mask() {
// s4 is a compare's mask on the branch taken, a dword read from a
// buffer on the other path; after the join it is masked as a number.
let p = build(
&[
0xD4C2_0004,
0x0002_0080, // v_cmp_eq_u32 s4, 0, v0
0xBF06_8000, // s_cmp_eq_u32 s0, 0
0xBF85_0002, // s_cbranch_scc1 +2
0xF420_0104,
0xFA00_0000, // s_buffer_load_dword s4, s[8:11], 0
0x8705_FF04,
0x001F_FFFF, // s_and_b32 s5, s4, 0x1fffff
0x7E02_0205, // v_mov_b32 v1, s5
S_ENDPGM,
],
false,
);
let s = structure(&p).unwrap();
let joined = p
.blocks
.iter()
.flat_map(|b| &b.phis)
.find(|phi| phi.reg == Reg::S(4))
.unwrap()
.value;
let and = p
.blocks
.iter()
.flat_map(|b| &b.insts)
.find(|i| i.name() == "s_and_b32")
.and_then(|i| i.write(Reg::S(5)))
.unwrap();
assert!(!s.masks.contains_key(&joined));
assert!(!s.masks.contains_key(&and));
}

#[test]
fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() {
let p = build(
Expand Down
18 changes: 18 additions & 0 deletions docs/fork-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ The status summary is in [README.md](../README.md).

## Newest (2026-11-26)

**R-7: buffer view addresses by view heap slot.**
The 5 `CS_TraceShadowRays_*` compute programs ("a descriptor read only as
data") load a buffer descriptor from the view heap at an index they compute
and only take its address, to walk the memory behind it. The host's table of
element strides by heap slot (`SLOT_STRIDES`) now goes on after its 2^21
strides with two dwords per slot, the title address of the slot's buffer view
(0: none or not a buffer, `SLOT_VIEW_ADDRESSES`), written with the stride
whenever the slot is. `view_address` reads it for a descriptor picked from
the heap, as it took the address from a user-data dword for one in a table.
The table's upload buffer grows from 8 to 24 MiB per view heap.
`CS_TraceShadowRays_FullAdaptive` then stopped on "a lane mask holding lanes
elsewhere read as data": the compiler reuses an SGPR that holds a compare's
mask on one path and a dword from `s_buffer_load` on the other, and masks the
join as a number. Structurisation took the join for a lane mask; a join with
an argument read by a scalar memory load is now no mask. With
`translate --list --validate` limited to these programs, all 5 translate and
validate.

**R-7: signature interpolation modes from the console's `PSV0`.**
The translated signatures took their interpolation modes from a table keyed
by type: every float linear, every integer constant. The console packs a
Expand Down