Shaders: per-lane descriptors chosen by control flow

A waterfall loop whose descriptor dwords are VGPR phis stopped with "a
descriptor read from the first lane of a phi" (294 programs of the
title on #307, all at if/else joins of two s_load_dwordx4 descriptors
copied into VGPRs). An EXEC if/else leaves two phis per dword: the
flow block's joins an arm's dwords with what lanes that skipped the arm
held before (inputs, unrelated loads and arithmetic in the title), the
join after the other arm picks per path. Only lanes that never read the
descriptor bring those other values, so tracing every edge fails.

Tracing (resource::track now takes the program's per-lane form):
- per-lane phis of one block are traced on each edge into it that the
  lanes accessing the descriptor can take, from structure's lane
  conditions (new Structured::reach, the exits' conditions, and
  Bools::meet, a read-only satisfiability check); the trace starts from
  what holds in the access's block. Edges no such lane takes are None
  in the new Source::LanePhi { block, args };
- every per-lane write it follows (v_mov_b32 copies, v_cndmask_b32,
  global_load_dword*) must run in all those lanes: a guarded one fails
  with "a per-lane descriptor written where some lanes may keep the old
  one". On #307 an else arm without its s_cbranch_execz traced as the
  second descriptor for every lane;
- a loop header's phi fails with "a descriptor read from the first lane
  of a phi at a loop header", words defined after the join with "a
  descriptor partly joined by control flow"; without the per-lane form
  (structurisation failed) the join is refused.

Lowering computes each traced edge's heap index at its predecessor's end
(through lane_heap_index, so loads, per-lane loads, choices and nested
joins work), joins them with a phi (0 on untaken edges) and makes the
handle non-uniform. The waterfall compares need no change.

Tests: the if/else of two loaded image descriptors, a join of a per-lane
load and a v_cndmask choice, nested arms choosing a buffer descriptor
with lanes that skip both and do not load (pruned only by the access's
condition), a loop header phi, and an unskipped else arm. On #307's head
the three join programs fail with "...of a phi" and the unskipped arm is
traced as one descriptor for all lanes. On an RTX 5070 and WARP, each
lane reads its own arm's texture or buffer; the shaders pass dxil.dll
1.8.2502.11. Reversing the phi's inputs fails validation, flipping the
heap index fails the GPU check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
r4.andClaude Opus 5.5 committed 2026-11-24 06:59:46 +02:00
1 parent 52c1a51900
commit 59ecbf4b93
8 files changed
+1114 -66

No files matched your search

+8 -3
View File
@@ -333,7 +333,11 @@ fn translate(
Ok(program) => {
t.translated += 1;
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
let res = match resource::track(&program, &p.layout, p.stage) {
// Per-lane descriptors are traced on the per-lane form; its
// failure is listed after the resources' and I/O's.
let structured = structure::structure(&program);
let lanes = structured.as_ref().ok();
let res = match resource::track(&program, &p.layout, p.stage, lanes) {
Ok(r) => {
tally_resources(&p, &r, t);
Some(r)
@@ -368,7 +372,7 @@ fn translate(
Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
}
}
let structured = match structure::structure(&program) {
let structured = match structured {
Ok(s) => {
tally_structured(&program, &s, t);
Some(s)
@@ -562,7 +566,8 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
}
resource::Source::Phi { .. }
| resource::Source::Select { .. }
| resource::Source::Lanes { .. } => {
| resource::Source::Lanes { .. }
| resource::Source::LanePhi { .. } => {
unreachable!("leaves are no phis, selects or per-lane choices")
}
};
+68 -6
View File
@@ -3183,6 +3183,9 @@ impl<'a> Lower<'a> {
{
return self.used_kind(args.first()?);
}
if let Source::LanePhi { args, .. } = src {
return args.iter().flatten().find_map(|a| self.used_kind(a));
}
if let Source::Built { address, .. } = src {
let rp = self.x.native.layout.get(address.param)?;
return self
@@ -3317,7 +3320,7 @@ impl<'a> Lower<'a> {
let index = self.s.m.select(self.cur, cond, set, clear);
Ok(self.s.heap_handle(self.cur, index, sampler, false, props))
}
Source::Fetched { .. } | Source::Lanes { .. } => {
Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
// A descriptor each lane has its own of (a waterfall loop
// reads it from the first active lane): each lane's heap
// index, non-uniform.
@@ -3328,7 +3331,8 @@ impl<'a> Lower<'a> {
}
/// The heap index of a descriptor that may differ between lanes,
/// computed in the current block.
/// computed in the current block (or, chosen by control flow, at the
/// join).
fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
match src {
Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
@@ -3355,6 +3359,36 @@ impl<'a> Lower<'a> {
let clear = self.lane_heap_index(b, sampler)?;
Ok(self.s.m.select(self.cur, cond, set, clear))
}
Source::LanePhi { block, args } => {
// Each predecessor computes its heap index at its end (what
// it reads is there: the dwords are, on that edge); the join
// picks the one of the edge the lane came by. An edge no
// lane reading it takes gives index 0.
let join =
self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
let mut incoming = Vec::new();
for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
if self.block[q].is_none() {
continue;
}
let tail =
self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
let index = match arg {
Some(arg) => {
let here = std::mem::replace(&mut self.cur, at);
let index = self.lane_heap_index(arg, sampler);
self.cur = here;
index?
}
None => self.s.m.i32(0),
};
incoming.push((index, at));
}
let phi = self.s.m.phi(join, self.s.t.i32);
self.s.m.set_phi(phi, incoming);
Ok(phi)
}
_ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
}
}
@@ -6710,9 +6744,9 @@ mod tests {
code,
};
let p = ir::build(&native.code, false, 256).unwrap();
let res = resource::track(&p, &native.layout, native.stage).unwrap();
let io = io::raise(&p, &native).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();
lower(&Parts {
native: &native,
p: &p,
@@ -6760,9 +6794,9 @@ mod tests {
code,
};
let p = ir::build(&native.code, wave64, 256).unwrap();
let res = resource::track(&p, &native.layout, native.stage)?;
let io = io::raise(&p, &native).unwrap();
let st = structure::structure(&p).unwrap();
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
let io = io::raise(&p, &native).unwrap();
lower(&Parts {
native: &native,
p: &p,
@@ -6898,6 +6932,34 @@ mod tests {
}
}
/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
let (layout, mut used) = texture_tables();
used.push(UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 16,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 0,
slot: 0,
});
(layout, used)
}
#[test]
fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
let (layout, used) = texture_and_uav_tables();
let l = lower_wave(words, layout, used, false).unwrap();
// One image handle, from the join's per-lane heap index.
assert_eq!(l.nonuniform_handles, 1);
assert!(!l.wave_ops);
}
}
#[test]
fn buffer_formats_by_number() {
// The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
+11 -6
View File
@@ -88,6 +88,8 @@ mod shader;
pub mod validator;
#[cfg(all(test, windows))]
mod valu_tests;
#[cfg(all(test, windows))]
mod waterfall_tests;
mod wave;
use crate::dxbc::{Container, FourCC};
@@ -203,9 +205,12 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
what: "a container without a vertex, pixel, compute or mesh program",
})?;
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
let res = resource::track(&p, &native.layout, native.stage)?;
// Structurisation first: tracing per-lane descriptors needs it (its
// failure is reported after the earlier stages').
let st = structure::structure(&p);
let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
let io = io::raise(&p, &native)?;
let st = structure::structure(&p)?;
let st = st?;
emit(&c, &native, &p, &st, &io, &res)
}
@@ -436,9 +441,9 @@ mod tests {
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).unwrap();
let io = io::raise(&p, &native).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 container = crate::dxbc::build(&[]);
let c = Container::parse(&container).unwrap();
if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
@@ -588,9 +593,9 @@ mod tests {
let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]);
let c = super::Container::parse(&bytes).unwrap();
let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let res = crate::resource::track(&p, &native.layout, native.stage).unwrap();
let io = crate::io::raise(&p, &native).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();
// Translated or refused with a reason; it must not panic.
let _ = super::emit(&c, &native, &p, &st, &io, &res);
}
+3 -2
View File
@@ -123,9 +123,10 @@ fn build_valu_cs(body: &[u32]) -> HostShader {
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let res = resource::track(&p, &native.layout, native.stage).expect("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let st = structure::structure(&p).expect("structure");
let res =
resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
p: &p,
@@ -0,0 +1,215 @@
//! End-to-end tests of waterfall loops over per-lane descriptors: the
//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated
//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane
//! reading the resource its own descriptor names.
use windows::Win32::Graphics::Direct3D12::*;
use super::host::{Dispatch, Host, Root, Stride, View};
use super::{HostShader, lower, validator};
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use crate::{io, ir, resource, structure};
/// Lowers a wave32 compute program of 32 threads with the table of views at
/// s0 (textures, or with `buffers` structured buffers of dwords, at entries
/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1.
fn build(words: &[u32], buffers: bool) -> HostShader {
let table = |user_data: u8| RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data,
slot: user_data,
};
let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: 0,
stride,
dwords,
user_data,
slot: user_data,
};
let views = if buffers {
range(ResourceType::Srv, 0, 4, 4, 0)
} else {
range(ResourceType::Srv, 0, 8, 0, 0)
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 32,
layout: vec![table(0), table(1)],
used: vec![
views,
range(ResourceType::Uav, 16, 4, 0, 0),
range(ResourceType::Sampler, 0, 4, 0, 1),
],
io: StageIo::Cs(ComputeIo {
rsrc2: 2 << 1,
threads: [32, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
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("track");
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,
})
.expect("lower");
// One access with each lane's own heap index, no wave operation.
assert_eq!(lowered.nonuniform_handles, 1);
assert!(!lowered.wave_ops);
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,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
v.validate(&mut shader.dxil.clone())
.expect("DXIL validation failed");
} else {
eprintln!("no dxil.dll; validation skipped");
}
shader
}
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
/// hardware GPU and on WARP (each skipped without a device) and returns,
/// per one that ran, the UAV's 32 dwords.
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
let samplers = [D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxAnisotropy: 1,
MaxLOD: f32::MAX,
..Default::default()
}];
let mut out = Vec::new();
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) = match host.compute_pipeline(shader) {
Ok(p) => p,
Err(e) => panic!("{label}: compute_pipeline failed: {e}"),
};
// Both tables start at heap index 0.
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
assert_eq!(u.root, RootType::Table, "{u:?}");
ud[u.index as usize] = 0;
}
let words = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views,
samplers: &samplers,
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
out.push((label, words[0].clone()));
}
out
}
/// The red channel each lane sampled from two 1x1 textures, red 1.0 at
/// heap index 0 and 2.0 at 1.
fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec<f32>)> {
let first = [[1.0f32, 0.0, 0.0, 1.0]];
let second = [[2.0f32, 0.0, 0.0, 1.0]];
let views = [
View::Texture(1, 1, &first),
View::Texture(1, 1, &second),
View::RawUav(32),
];
run(shader, &views)
.into_iter()
.map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect()))
.collect()
}
#[test]
fn lanes_sample_the_texture_their_if_else_arm_chose() {
use crate::resource::tests::WATERFALL_JOINED_WAVE32;
let shader = build(WATERFALL_JOINED_WAVE32, false);
for (label, red) in sampled(&shader) {
// Lanes below 16 took the first texture, the others the second.
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
assert_eq!(red, want, "{label}");
}
}
#[test]
fn lanes_sample_the_texture_their_arm_loaded_or_picked() {
use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32;
let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false);
for (label, red) in sampled(&shader) {
// Lanes below 16 loaded entry (lane & 1); of the others, lanes
// below 24 picked the first, the rest the second.
let want: Vec<f32> = (0..32)
.map(|l| match l {
0..16 => [1.0, 2.0][l & 1],
16..24 => 1.0,
_ => 2.0,
})
.collect();
assert_eq!(red, want, "{label}");
}
}
#[test]
fn lanes_load_from_the_buffer_their_nested_arms_chose() {
use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32;
let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true);
let first: Vec<u32> = (0..32).map(|i| 100 + i).collect();
let second: Vec<u32> = (0..32).map(|i| 200 + i).collect();
let views = [
View::Buffer {
data: &first,
stride: Stride::Structured(4),
},
View::Buffer {
data: &second,
stride: Stride::Structured(4),
},
View::RawUav(32),
];
for (label, got) in run(&shader, &views) {
// Dword `lane` of the first buffer below 16, of the second from 16
// to 23; lanes from 24 on load and store nothing.
let want: Vec<u32> = (0..32)
.map(|l| match l {
0..16 => 100 + l,
16..24 => 200 + l,
_ => 0,
})
.collect();
assert_eq!(got, want, "{label}");
}
}
File diff suppressed because it is too large. Load diff
+38
View File
@@ -99,6 +99,8 @@ impl Hasher for Fx {
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;
impl Bools {
fn new() -> Self {
@@ -221,6 +223,38 @@ impl Bools {
self.ite(a, nb, b)
}
/// Whether some lane can satisfy every `(b, holds)` of `all` at once:
/// `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)
}
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;
}
all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
if all.is_empty() || *budget == 0 {
return true;
}
*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)
})
}
fn implies(&mut self, a: Bool, b: Bool) -> bool {
let nb = self.not(b);
self.and(a, nb) == Bool::FALSE
@@ -306,6 +340,9 @@ pub struct Structured {
/// enough (lanes outside EXEC then never get there, so a VGPR write
/// needs no old value). Always `None` for scalar instructions.
pub guards: Vec<Vec<Option<Bool>>>,
/// Per block: what holds in every lane that enters it (over forward
/// edges; a loop header forgets what its loop redefines).
pub reach: Vec<Bool>,
/// The lane's bit of each lane-mask value, by its low dword's value.
pub masks: HashMap<Value, Bool>,
/// Wave64 masks: low dword's value by the high dword's.
@@ -587,6 +624,7 @@ impl<'a> Lanes<'a> {
bools: self.b,
exits,
guards,
reach: cond.to_vec(),
})
}
+4 -2
View File
@@ -91,7 +91,9 @@ a lane can reach them with its EXEC bit clear. `victory_shader::resource`
traces each descriptor and scalar memory address to the root parameter it
comes from (table, heap, root descriptor or constant). A descriptor a
waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced
to the per-lane load or choice that gives each lane its own, and accessed
with a non-uniform heap index in one pass. `victory translate`
to the per-lane load or choice that gives each lane its own (a mask's
`v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths
the lanes take, from structurisation), and accessed with a non-uniform heap
index in one pass. `victory translate`
runs every shader it finds (containers, SGD5 files) through these and
lists what they cannot handle yet.