Run Grand Theft Auto VI from first boot into the world

The title now boots through every first-boot and menu screen at its own
30 fps, drawing with translated shaders, with input, sound, saves and
loading served; it reaches the world, where the host GPU path still
fails (see "Not working yet").

Loader and runtime
- Crash reports unwind properly, name C++ throws and host GPU failures,
  carry the title's last debug lines and are appended to crashes.log.
- Thread notices on our own threads, reentrant late DLL loading, exit in
  the console's order, relaunch on a launch-new-game request.
- Offline guard: the title cannot reach the network (sockets, name
  lookups, WinHTTP, the media source resolver); by-name lookups and
  loads follow the import rules.
- Every runtime area the title calls is served (networking hint,
  packages, store, saves, display, UI, speech stubs, user, async pool).
  Saves persist; an update is one rename and survives a kill at any step.
- DirectStorage reads for real: shared worker pool, priorities, zlib and
  BCPack. BCPack is our own decoder; the format's constant tables ship in
  crates/victory-formats/src/bcpack-tables.bin (the asset policy's one
  exception, see docs/asset-policy.md).
- GameInput from XInput pads and the keyboard, with a keyboard stand-in
  pad; console timers (1 ms) for the whole process.
- Audio: XMA2 decoding on the emulated contexts, Opus on the decoder
  queues, the DSP interface as a stub; title memory placed below 2^40.
- Console texture layouts (sizes, tiling, detiling) and the layout
  library's imports.

GPU
- Draws, mesh dispatches and compute dispatches run on the host with
  shaders translated at first use and cached on disk; descriptor heaps,
  views, root signatures, barriers and host texture states; rectangle
  lists; comparison samplers.
- Title memory reaches the host through persistent mirrors that copy
  only pages written since the last copy; shader-written buffers are
  copied back.
- Presentation with frame pacing per event kind; framerate in the window
  caption.

Shaders
- DXIL emission for vertex, pixel, compute and mesh programs from the
  console's native code, with a differential test suite against the PC
  compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of
  12,346, compute 1,643 of 2,539; utility set complete.

Build
- Debugging aids (debug logs, frame capture, stack dumps, scripted keys,
  the host debug layer, the software adapter) exist only with the
  `diagnostics` feature; `[profile.diag]` keeps that build apart.

Not working yet
- In the world the host device is removed within seconds (descriptor
  handling fixes are in, unproven by a surviving run) and frames present
  black.
- 64-bit image atomics, merged geometry stages and the BVH builder's own
  shaders do not translate; reverb is silent.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42526 -868

No files matched your search

+25
View File
@@ -11,5 +11,30 @@ publish.workspace = true
thiserror.workspace = true
miniz_oxide.workspace = true
[features]
# Host D3D12 pipeline checks (`emit::host`).
host = ["dep:windows"]
# Debugging switches (emitted-module dumps and the like).
diagnostics = []
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] }
windows = { workspace = true, optional = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[target.'cfg(windows)'.dev-dependencies]
windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[lints]
workspace = true
+2
View File
@@ -22,6 +22,8 @@ impl FourCC {
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
/// Per-primitive outputs of a mesh shader.
pub const PSG1: FourCC = FourCC(*b"PSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
+986
View File
@@ -0,0 +1,986 @@
//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated
//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`).
//!
//! Values are symbolic while the module is built ([`V`]) and numbered when
//! it is written: functions, then constants (all at module level), then the
//! instructions of `main` in block order.
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct Ty(u32);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum TypeDef {
Void,
Int(u32),
Float,
/// Pointee and address space.
Ptr(Ty, u32),
Struct(Option<String>, Vec<Ty>),
Array(u32, Ty),
Func(Ty, Vec<Ty>),
}
/// A value: a global variable, a function, a module constant, or an
/// instruction result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum V {
Global(u32),
Func(u32),
Const(u32),
Inst(u32),
}
/// A global variable declaration (thread-group shared memory).
struct Global {
name: String,
ty: Ty,
/// Its pointer type.
ptr: Ty,
space: u32,
/// An internal constant with this initialiser (a constant table).
init: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Const {
Int(i64),
Float(u32),
Undef,
Aggregate(Vec<u32>),
}
/// LLVM binary opcodes (the same codes serve the float forms).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Bin {
Add = 0,
Sub = 1,
Mul = 2,
UDiv = 3,
SDiv = 4,
URem = 5,
Shl = 7,
LShr = 8,
AShr = 9,
And = 10,
Or = 11,
Xor = 12,
}
/// `atomicrmw` operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Rmw {
Xchg = 0,
Add = 1,
Sub = 2,
And = 3,
Or = 5,
Xor = 6,
Max = 7,
Min = 8,
UMax = 9,
UMin = 10,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cast {
Trunc = 0,
ZExt = 1,
SExt = 2,
FpToUi = 3,
FpToSi = 4,
UiToFp = 5,
SiToFp = 6,
Bitcast = 11,
}
/// Compare predicates: floats 0-15, integers 32-41.
pub(crate) mod pred {
pub const FALSE: u8 = 0;
pub const OEQ: u8 = 1;
pub const OGT: u8 = 2;
pub const OGE: u8 = 3;
pub const OLT: u8 = 4;
pub const OLE: u8 = 5;
pub const ONE: u8 = 6;
pub const ORD: u8 = 7;
pub const UNO: u8 = 8;
pub const UEQ: u8 = 9;
pub const UGT: u8 = 10;
pub const UGE: u8 = 11;
pub const ULT: u8 = 12;
pub const ULE: u8 = 13;
pub const UNE: u8 = 14;
pub const TRUE: u8 = 15;
pub const EQ: u8 = 32;
pub const NE: u8 = 33;
pub const IUGT: u8 = 34;
pub const IUGE: u8 = 35;
pub const IULT: u8 = 36;
pub const IULE: u8 = 37;
pub const SGT: u8 = 38;
pub const SGE: u8 = 39;
pub const SLT: u8 = 40;
pub const SLE: u8 = 41;
}
#[derive(Debug, Clone)]
enum Op {
Bin(Bin, V, V),
Cast(Cast, V),
Cmp(u8, V, V),
Select(V, V, V),
Extract(V, u32),
Call(u32, Vec<V>),
/// Filled in later: (value, block).
Phi(Vec<(V, usize)>),
/// `getelementptr` over the pointee type, from a pointer.
Gep(Ty, V, Vec<V>),
Load(V),
/// Pointer, value.
Store(V, V),
AtomicRmw(Rmw, V, V),
/// Pointer, expected, new; returns `{i32, i1}`.
CmpXchg(V, V, V),
}
#[derive(Debug, Clone)]
struct Inst {
ty: Ty,
op: Op,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Term {
Br(usize),
CondBr(V, usize, usize),
Ret,
}
#[derive(Debug, Clone, Default)]
struct Block {
phis: Vec<u32>,
body: Vec<u32>,
term: Option<Term>,
}
/// Function attributes of a `dx.op` declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Attr {
ReadNone = 1,
NoUnwind = 2,
ReadOnly = 3,
/// Barriers.
NoDuplicate = 4,
}
struct Func {
name: String,
ty: Ty,
attr: Option<Attr>,
body: bool,
}
/// A metadata node operand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Md(u32);
enum MdDef {
Str(String),
Value(Ty, V),
Node(Vec<Option<Md>>),
}
#[derive(Default)]
pub(crate) struct Module {
types: Vec<TypeDef>,
type_ids: HashMap<TypeDef, u32>,
consts: Vec<(Ty, Const)>,
const_ids: HashMap<(Ty, Const), u32>,
globals: Vec<Global>,
funcs: Vec<Func>,
func_ids: HashMap<String, u32>,
insts: Vec<Inst>,
blocks: Vec<Block>,
mds: Vec<MdDef>,
named: Vec<(String, Vec<Md>)>,
}
impl Module {
fn ty(&mut self, def: TypeDef) -> Ty {
if let Some(&t) = self.type_ids.get(&def) {
return Ty(t);
}
let t = self.types.len() as u32;
self.types.push(def.clone());
self.type_ids.insert(def, t);
Ty(t)
}
pub fn void(&mut self) -> Ty {
self.ty(TypeDef::Void)
}
pub fn int(&mut self, bits: u32) -> Ty {
self.ty(TypeDef::Int(bits))
}
pub fn float(&mut self) -> Ty {
self.ty(TypeDef::Float)
}
pub fn ptr(&mut self, to: Ty) -> Ty {
self.ty(TypeDef::Ptr(to, 0))
}
pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty {
self.ty(TypeDef::Ptr(to, space))
}
pub fn array(&mut self, n: u32, of: Ty) -> Ty {
self.ty(TypeDef::Array(n, of))
}
pub fn named_struct(&mut self, name: &str, fields: Vec<Ty>) -> Ty {
self.ty(TypeDef::Struct(Some(name.into()), fields))
}
pub fn func_ty(&mut self, ret: Ty, params: Vec<Ty>) -> Ty {
self.ty(TypeDef::Func(ret, params))
}
fn is_void(&self, t: Ty) -> bool {
self.types[t.0 as usize] == TypeDef::Void
}
fn constant(&mut self, ty: Ty, c: Const) -> V {
if let Some(&i) = self.const_ids.get(&(ty, c.clone())) {
return V::Const(i);
}
let i = self.consts.len() as u32;
self.consts.push((ty, c.clone()));
self.const_ids.insert((ty, c), i);
V::Const(i)
}
pub fn int_const(&mut self, ty: Ty, v: i64) -> V {
self.constant(ty, Const::Int(v))
}
pub fn i32(&mut self, v: u32) -> V {
let t = self.int(32);
self.int_const(t, i64::from(v as i32))
}
pub fn i8(&mut self, v: u8) -> V {
let t = self.int(8);
self.int_const(t, i64::from(v as i8))
}
pub fn bool(&mut self, v: bool) -> V {
let t = self.int(1);
self.int_const(t, -i64::from(v))
}
pub fn f32(&mut self, bits: u32) -> V {
let t = self.float();
self.constant(t, Const::Float(bits))
}
pub fn undef(&mut self, ty: Ty) -> V {
self.constant(ty, Const::Undef)
}
/// A constant struct or array of constants.
pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V {
let ids = fields
.iter()
.map(|f| match f {
V::Const(i) => *i,
_ => panic!("aggregate of a non-constant"),
})
.collect();
self.constant(ty, Const::Aggregate(ids))
}
/// 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) {
self.consts[o as usize] = self.consts[n as usize].clone();
}
}
/// A function declaration (or `main` with `body`), found by name.
pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V {
if let Some(&i) = self.func_ids.get(name) {
return V::Func(i);
}
let i = self.funcs.len() as u32;
self.funcs.push(Func {
name: name.into(),
ty,
attr,
body,
});
self.func_ids.insert(name.into(), i);
V::Func(i)
}
/// An external global of type `ty` in address space `space` (DXIL
/// declares thread-group shared memory this way).
pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V {
let ptr = self.ptr_in(ty, space);
self.globals.push(Global {
name: name.into(),
ty,
ptr,
space,
init: None,
});
V::Global(self.globals.len() as u32 - 1)
}
/// An internal constant global initialised with the constant `init`.
pub fn constant_global(&mut self, name: &str, init: V) -> V {
let V::Const(i) = init else {
panic!("a global initialised with a non-constant")
};
let ty = self.consts[i as usize].0;
let g = self.global(name, ty, 0);
if let V::Global(n) = g {
self.globals[n as usize].init = Some(i);
}
g
}
pub fn new_block(&mut self) -> usize {
self.blocks.push(Block::default());
self.blocks.len() - 1
}
pub fn type_of(&self, v: V) -> Ty {
match v {
V::Global(i) => self.globals[i as usize].ptr,
V::Const(i) => self.consts[i as usize].0,
V::Inst(i) => self.insts[i as usize].ty,
V::Func(i) => {
let t = self.funcs[i as usize].ty;
*self
.type_ids
.get(&TypeDef::Ptr(t, 0))
.map(|t| Ty(*t))
.as_ref()
.expect("function pointer type")
}
}
}
fn push(&mut self, block: usize, ty: Ty, op: Op) -> V {
let i = self.insts.len() as u32;
self.insts.push(Inst { ty, op });
// Terminators are kept apart, so a block can still grow at its end.
self.blocks[block].body.push(i);
V::Inst(i)
}
pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V {
let ty = self.type_of(a);
self.push(block, ty, Op::Bin(op, a, b))
}
pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V {
self.push(block, to, Op::Cast(op, v))
}
pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V {
let t = self.int(1);
self.push(block, t, Op::Cmp(pred, a, b))
}
pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V {
let ty = self.type_of(t);
self.push(block, ty, Op::Select(c, t, f))
}
pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V {
let ty = match &self.types[self.type_of(agg).0 as usize] {
TypeDef::Struct(_, f) => f[index as usize],
TypeDef::Array(_, t) => *t,
t => panic!("extractvalue from {t:?}"),
};
self.push(block, ty, Op::Extract(agg, index))
}
pub fn call(&mut self, block: usize, f: V, args: Vec<V>) -> V {
let V::Func(i) = f else {
panic!("call of a non-function")
};
let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else {
unreachable!()
};
self.push(block, ret, Op::Call(i, args))
}
/// A phi at the top of `block`; incoming values come with [`Module::set_phi`].
pub fn phi(&mut self, block: usize, ty: Ty) -> V {
let i = self.insts.len() as u32;
self.insts.push(Inst {
ty,
op: Op::Phi(Vec::new()),
});
self.blocks[block].phis.push(i);
V::Inst(i)
}
/// The address of element `index` of the array `ptr` points to.
pub fn element(&mut self, block: usize, ptr: V, index: V) -> V {
let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else {
panic!("element of a non-pointer")
};
let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else {
panic!("element of a non-array")
};
let ty = self.ptr_in(elem, space);
let zero = self.i32(0);
self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index]))
}
pub fn load(&mut self, block: usize, ptr: V) -> V {
let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else {
panic!("load from a non-pointer")
};
self.push(block, ty, Op::Load(ptr))
}
pub fn store(&mut self, block: usize, ptr: V, value: V) {
let void = self.void();
self.push(block, void, Op::Store(ptr, value));
}
pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V {
let ty = self.type_of(value);
self.push(block, ty, Op::AtomicRmw(op, ptr, value))
}
/// The old value of a compare-exchange.
pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V {
let (i32t, i1) = (self.type_of(new), self.int(1));
let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1]));
let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new));
self.extract(block, r, 0)
}
pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) {
let V::Inst(i) = phi else { panic!() };
self.insts[i as usize].op = Op::Phi(incoming);
}
pub fn terminate(&mut self, block: usize, t: Term) {
self.blocks[block].term = Some(t);
}
pub fn md_str(&mut self, s: &str) -> Md {
self.mds.push(MdDef::Str(s.into()));
Md(self.mds.len() as u32 - 1)
}
pub fn md_value(&mut self, v: V) -> Md {
let ty = self.type_of(v);
self.mds.push(MdDef::Value(ty, v));
Md(self.mds.len() as u32 - 1)
}
pub fn md_node(&mut self, ops: Vec<Option<Md>>) -> Md {
self.mds.push(MdDef::Node(ops));
Md(self.mds.len() as u32 - 1)
}
pub fn named_md(&mut self, name: &str, nodes: Vec<Md>) {
self.named.push((name.into(), nodes));
}
/// The module as bitcode.
pub fn write(&self) -> Vec<u8> {
let mut w = Writer::default();
w.bytes(b"BC\xC0\xDE");
w.enter(MODULE_BLOCK, 3);
w.record(1, &[1]); // VERSION: relative value ids
// Attribute groups 1-4 and one list per group.
w.enter(PARAMATTR_GROUP_BLOCK, 3);
for (id, kinds) in [
(1, &[18u64, 20][..]),
(2, &[18]),
(3, &[18, 21]),
(4, &[12, 18]),
] {
let mut r = vec![id, 0xFFFF_FFFF];
for &k in kinds {
r.extend([0, k]);
}
w.record(3, &r);
}
w.exit();
w.enter(PARAMATTR_BLOCK, 3);
for id in 1..=4 {
w.record(2, &[id]);
}
w.exit();
w.enter(TYPE_BLOCK, 4);
w.record(1, &[self.types.len() as u64]);
for t in &self.types {
match t {
TypeDef::Void => w.record(2, &[]),
TypeDef::Float => w.record(3, &[]),
TypeDef::Int(b) => w.record(7, &[u64::from(*b)]),
TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]),
TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]),
TypeDef::Struct(name, fields) => {
let mut r = vec![0];
r.extend(fields.iter().map(|f| u64::from(f.0)));
match name {
Some(n) => {
w.record(19, &chars(n));
w.record(20, &r);
}
None => w.record(18, &r),
}
}
TypeDef::Func(ret, params) => {
let mut r = vec![0, u64::from(ret.0)];
r.extend(params.iter().map(|p| u64::from(p.0)));
w.record(21, &r);
}
}
}
w.exit();
w.record(2, &chars("dxil-ms-dx"));
w.record(
3,
&chars(
"e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
),
);
let first_const = (self.globals.len() + self.funcs.len()) as u64;
for g in &self.globals {
// [type, address space << 2 | explicit type | constant, init id
// + 1, linkage (external 0, internal 3), log2 alignment + 1,
// section]
let (constant, init, linkage) = match g.init {
Some(i) => (1, first_const + u64::from(i) + 1, 3),
None => (0, 0, 0),
};
w.record(
7,
&[
u64::from(g.ty.0),
u64::from(g.space) << 2 | 2 | constant,
init,
linkage,
3,
0,
],
);
}
for f in &self.funcs {
// [type, cc, isproto, linkage, paramattr, align, section,
// visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix]
let attr = f.attr.map_or(0, |a| a as u64);
w.record(
8,
&[
u64::from(f.ty.0),
0,
u64::from(!f.body),
0,
attr,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
);
}
// Value ids: globals, functions, constants, instructions.
let globals = self.globals.len() as u32;
let funcs = globals + self.funcs.len() as u32;
let const_id = |i: u32| u64::from(funcs + i);
w.enter(CONSTANTS_BLOCK, 4);
let mut current = None;
for (ty, c) in &self.consts {
if current != Some(*ty) {
w.record(1, &[u64::from(ty.0)]);
current = Some(*ty);
}
match c {
Const::Undef => w.record(3, &[]),
Const::Int(v) => w.record(4, &[signed(*v)]),
Const::Float(bits) => w.record(6, &[u64::from(*bits)]),
Const::Aggregate(ids) => {
let r: Vec<u64> = ids.iter().map(|&i| const_id(i)).collect();
w.record(7, &r);
}
}
}
w.exit();
// Phis nothing reads are left out (one register per phi makes many).
let mut live = vec![false; self.insts.len()];
let mark = |live: &mut Vec<bool>, v: V| {
if let V::Inst(i) = v
&& !live[i as usize]
{
live[i as usize] = true;
return true;
}
false
};
let operands = |op: &Op| -> Vec<V> {
match op {
Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
vec![*a, *b]
}
Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v],
Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c],
Op::Call(_, args) => args.clone(),
Op::Phi(inc) => inc.iter().map(|x| x.0).collect(),
Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(),
}
};
for b in &self.blocks {
for &i in &b.body {
live[i as usize] = true;
}
if let Some(Term::CondBr(c, ..)) = b.term {
mark(&mut live, c);
}
}
let mut changed = true;
while changed {
changed = false;
for (i, inst) in self.insts.iter().enumerate() {
if live[i] {
for v in operands(&inst.op) {
changed |= mark(&mut live, v);
}
}
}
}
// Blocks are laid out in reverse postorder, so every block follows
// its forward predecessors (drivers take a branch to an earlier
// block for a loop's back edge).
let succs = |b: usize| match self.blocks[b].term {
Some(Term::Br(t)) => vec![t],
Some(Term::CondBr(_, t, f)) => vec![t, f],
_ => vec![],
};
let mut seen = vec![false; self.blocks.len()];
let mut post = Vec::new();
let mut stack = vec![(0usize, 0usize)];
seen[0] = true;
while let Some(top) = stack.last_mut() {
let (b, k) = *top;
top.1 += 1;
match succs(b).get(k) {
Some(&s) if !seen[s] => {
seen[s] = true;
stack.push((s, 0));
}
Some(_) => {}
None => {
post.push(b);
stack.pop();
}
}
}
post.reverse();
let mut pos = vec![u64::MAX; self.blocks.len()];
for (n, &b) in post.iter().enumerate() {
pos[b] = n as u64;
}
// An empty latch (only a branch back to its loop header) is folded
// into its one predecessor, so the exiting block is the latch as in
// DXC's loops; the AMD driver hangs on divergent loops otherwise.
let mut preds = vec![Vec::new(); self.blocks.len()];
for &b in &post {
for s in succs(b) {
preds[s].push(b);
}
}
let mut fold = vec![None; self.blocks.len()];
for &b in &post {
let blk = &self.blocks[b];
if let (Some(Term::Br(h)), true, [p]) = (
blk.term,
blk.phis.is_empty() && blk.body.is_empty(),
&preds[b][..],
) && pos[h] < pos[b]
&& !succs(*p).contains(&h)
{
fold[b] = Some((*p, h));
}
}
let layout: Vec<usize> = post.into_iter().filter(|&b| fold[b].is_none()).collect();
let mut pos = vec![u64::MAX; self.blocks.len()];
for (n, &b) in layout.iter().enumerate() {
pos[b] = n as u64;
}
// Branch targets and phi blocks through folded latches.
let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]);
let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]);
// Instruction value ids, in layout order.
let base = funcs + self.consts.len() as u32;
let mut ids = vec![u32::MAX; self.insts.len()];
let mut next = base;
for b in layout.iter().map(|&b| &self.blocks[b]) {
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
if !self.is_void(self.insts[i as usize].ty) {
ids[i as usize] = next;
next += 1;
}
}
}
let abs = |v: V| -> u32 {
match v {
V::Global(i) => i,
V::Func(i) => globals + i,
V::Const(i) => funcs + i,
V::Inst(i) => {
let id = ids[i as usize];
assert_ne!(id, u32::MAX, "use of a void value");
id
}
}
};
w.enter(METADATA_BLOCK, 3);
for m in &self.mds {
match m {
MdDef::Str(s) => w.record(1, &chars(s)),
MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]),
MdDef::Node(ops) => {
let r: Vec<u64> = ops
.iter()
.map(|o| o.map_or(0, |m| u64::from(m.0) + 1))
.collect();
w.record(3, &r);
}
}
}
for (name, nodes) in &self.named {
w.record(4, &chars(name));
let r: Vec<u64> = nodes.iter().map(|m| u64::from(m.0)).collect();
w.record(10, &r);
}
w.exit();
// The metadata kinds an LLVM 3.7 module declares, as DXC writes them.
w.enter(METADATA_BLOCK, 3);
for (id, kind) in [
"dbg",
"tbaa",
"prof",
"fpmath",
"range",
"tbaa.struct",
"invariant.load",
"alias.scope",
"noalias",
"nontemporal",
"llvm.mem.parallel_loop_access",
"nonnull",
"dereferenceable",
"dereferenceable_or_null",
]
.into_iter()
.enumerate()
{
let mut r = vec![id as u64];
r.extend(chars(kind));
w.record(6, &r);
}
w.exit();
w.enter(VALUE_SYMTAB_BLOCK, 4);
let names = self.globals.iter().map(|g| &g.name);
for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() {
let mut r = vec![i as u64];
r.extend(chars(name));
w.record(1, &r);
}
w.exit();
w.enter(FUNCTION_BLOCK, 4);
w.record(1, &[layout.len() as u64]);
let mut inst_id = base;
for b in layout.iter().map(|&b| &self.blocks[b]) {
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
let inst = &self.insts[i as usize];
let rel = |v: V| {
let a = abs(v);
assert!(a < inst_id, "forward reference outside a phi");
u64::from(inst_id - a)
};
match &inst.op {
Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]),
Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]),
Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]),
Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]),
Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]),
Op::Call(f, args) => {
let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)];
r.push(rel(V::Func(*f)));
r.extend(args.iter().map(|&a| rel(a)));
w.record(34, &r);
}
Op::Phi(incoming) => {
let mut r = vec![u64::from(inst.ty.0)];
for &(v, b) in incoming {
r.push(signed(i64::from(inst_id) - i64::from(abs(v))));
r.push(from(b));
}
w.record(16, &r);
}
Op::Gep(ty, p, idx) => {
let mut r = vec![0, u64::from(ty.0), rel(*p)];
r.extend(idx.iter().map(|&i| rel(i)));
w.record(43, &r);
}
// Alignment 4 (log2 + 1), not volatile.
Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]),
Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]),
// Sequentially consistent, across threads.
Op::AtomicRmw(op, p, v) => {
w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1])
}
Op::CmpXchg(p, c, n) => {
w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]);
}
}
if !self.is_void(inst.ty) {
inst_id += 1;
}
}
match b.term.expect("unterminated block") {
Term::Ret => w.record(10, &[]),
Term::Br(t) => w.record(11, &[target(t)]),
Term::CondBr(c, t, f) => {
let a = abs(c);
assert!(a < inst_id);
w.record(11, &[target(t), target(f), u64::from(inst_id - a)]);
}
}
}
w.exit();
w.exit();
w.finish()
}
}
const MODULE_BLOCK: u64 = 8;
const PARAMATTR_BLOCK: u64 = 9;
const PARAMATTR_GROUP_BLOCK: u64 = 10;
const CONSTANTS_BLOCK: u64 = 11;
const FUNCTION_BLOCK: u64 = 12;
const VALUE_SYMTAB_BLOCK: u64 = 14;
const METADATA_BLOCK: u64 = 15;
const TYPE_BLOCK: u64 = 17;
fn chars(s: &str) -> Vec<u64> {
s.bytes().map(u64::from).collect()
}
/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0.
fn signed(v: i64) -> u64 {
if v >= 0 {
(v as u64) << 1
} else {
(v.unsigned_abs() << 1) | 1
}
}
/// The bitstream: little-endian 32-bit words filled from bit 0.
#[derive(Default)]
struct Writer {
words: Vec<u32>,
cur: u64,
bits: u32,
/// Per open block: abbreviation width, index of its length word.
stack: Vec<(u32, usize)>,
}
impl Writer {
fn width(&self) -> u32 {
self.stack.last().map_or(2, |b| b.0)
}
fn emit(&mut self, v: u64, width: u32) {
debug_assert!(width == 64 || v >> width == 0);
self.cur |= v << self.bits;
self.bits += width;
while self.bits >= 32 {
self.words.push(self.cur as u32);
self.cur >>= 32;
self.bits -= 32;
}
}
fn vbr(&mut self, mut v: u64, width: u32) {
let hi = 1u64 << (width - 1);
while v >= hi {
self.emit(v & (hi - 1) | hi, width);
v >>= width - 1;
}
self.emit(v, width);
}
fn align(&mut self) {
if self.bits > 0 {
self.words.push(self.cur as u32);
self.cur = 0;
self.bits = 0;
}
}
fn bytes(&mut self, b: &[u8]) {
for &x in b {
self.emit(u64::from(x), 8);
}
}
fn enter(&mut self, id: u64, width: u32) {
self.emit(1, self.width()); // ENTER_SUBBLOCK
self.vbr(id, 8);
self.vbr(u64::from(width), 4);
self.align();
self.words.push(0);
self.stack.push((width, self.words.len()));
}
fn exit(&mut self) {
self.emit(0, self.width()); // END_BLOCK
self.align();
let (_, start) = self.stack.pop().expect("open block");
self.words[start - 1] = (self.words.len() - start) as u32;
}
/// An unabbreviated record.
fn record(&mut self, code: u64, ops: &[u64]) {
self.emit(3, self.width());
self.vbr(code, 6);
self.vbr(ops.len() as u64, 6);
for &o in ops {
self.vbr(o, 6);
}
}
fn finish(mut self) -> Vec<u8> {
self.align();
self.words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vbr_and_blocks() {
let mut w = Writer::default();
w.vbr(5, 6);
w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3
assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12));
let mut w = Writer::default();
w.enter(8, 3);
w.record(1, &[1]);
w.exit();
let bytes = w.finish();
// header word, length word, one record word, end word.
assert_eq!(bytes.len() % 4, 0);
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1);
assert_eq!(signed(-3), 7);
assert_eq!(signed(2), 4);
}
}
+380
View File
@@ -0,0 +1,380 @@
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
//! the container hash that D3D12 checks.
/// One signature element: one row (D3D12 links stages by semantic).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SigElement {
pub name: String,
pub index: u32,
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
pub kind: u8,
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
pub comp: u8,
/// DXIL interpolation mode (0 for none).
pub interp: u8,
/// Start row, if the element has a register.
pub row: Option<u32>,
pub col: u8,
pub cols: u8,
/// Components read (inputs) or written (outputs), relative to `col`.
pub usage: u8,
/// 16-bit on the console (declared 32-bit here).
pub half: bool,
}
impl SigElement {
fn system_value(&self) -> u32 {
match self.kind {
1 => 6, // vertex id
2 => 8, // instance id
3 => 1, // position
4 => 4, // render target array index
5 => 5, // viewport array index
6 => 2, // clip distance
7 => 3, // cull distance
10 => 7, // primitive id
12 => 10,
13 => 9, // front face
14 => 66,
15 => 70,
16 => 64, // target
17 => 65, // depth
18 => 68,
19 => 67,
20 => 69,
30 => 25, // cull primitive
_ => 0,
}
}
fn sig_comp(&self) -> u32 {
match self.comp {
1 | 5 => 1, // bool and u32
4 => 2,
9 => 3,
_ => 0,
}
}
fn mask(&self) -> u8 {
((1u8 << self.cols) - 1) << self.col
}
}
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
let mut out = Vec::new();
out.extend((elements.len() as u32).to_le_bytes());
out.extend(8u32.to_le_bytes());
// Validator 1.6 writes one name per element in element order, repeats
// included, except that system values share theirs (it keys names by
// the semantic's string, which is one static string per system value);
// the rows sorted by register (unallocated last).
let mut offsets: Vec<u32> = Vec::new();
let mut next = 8 + 32 * elements.len() as u32;
let mut names = Vec::new();
for (i, e) in elements.iter().enumerate() {
let shared = (e.kind != 0)
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
.flatten();
match shared {
Some(j) => offsets.push(offsets[j]),
None => {
offsets.push(next);
next += e.name.len() as u32 + 1;
names.push(&e.name);
}
}
}
let mut order: Vec<usize> = (0..elements.len()).collect();
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
for i in order {
let (e, offset) = (&elements[i], offsets[i]);
let used = e.usage << e.col;
let rw = if input { used } else { !used & 0xf };
for v in [
0,
offset,
e.index,
e.system_value(),
e.sig_comp(),
e.row.unwrap_or(u32::MAX),
] {
out.extend(v.to_le_bytes());
}
out.extend([e.mask(), rw, 0, 0]);
out.extend(0u32.to_le_bytes());
}
for name in names {
out.extend(name.as_bytes());
out.push(0);
}
out
}
/// A resource bound by register, as `PSV0` lists it.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Binding {
/// PSV resource type: 1 sampler, 2 CBV.
pub kind: u32,
pub space: u32,
pub register: u32,
/// DXIL resource kind (13 cbuffer, 14 sampler).
pub dxil_kind: u32,
}
pub(crate) struct Psv<'a> {
/// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
pub stage: u8,
/// Vertex: writes `SV_Position`. Pixel: writes depth.
pub flag: bool,
pub inputs: &'a [SigElement],
pub outputs: &'a [SigElement],
/// Mesh: per-primitive outputs.
pub prims: &'a [SigElement],
/// Mesh: its state and the group-shared bytes it declares.
pub mesh: Option<(super::shader::Mesh, u32)>,
pub bindings: &'a [Binding],
/// Compute: thread-group size and required wave size.
pub threads: [u32; 3],
pub wave_size: Option<u32>,
}
/// `PSV0` with runtime info version 2 (validator 1.6).
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
let vectors = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row)
.map(|r| r + 1)
.max()
.unwrap_or(0)
};
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
let mut out = Vec::new();
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
for v in vs {
out.extend(v.to_le_bytes());
}
};
u32s(&mut out, &[48]);
let mut info = [0u8; 48];
info[0] = u8::from(p.flag);
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());
info[24] = p.stage;
for (k, n) in p.threads.into_iter().enumerate() {
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
}
info[28] = p.inputs.len() as u8;
info[29] = p.outputs.len() as u8;
info[31] = in_vectors as u8;
info[32] = out_vectors as u8;
if let Some((mesh, shared)) = p.mesh {
info[0..4].copy_from_slice(&shared.to_le_bytes());
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
info[26] = vectors(p.prims) as u8;
info[27] = mesh.topology;
info[30] = p.prims.len() as u8;
}
out.extend(info);
u32s(&mut out, &[p.bindings.len() as u32]);
if !p.bindings.is_empty() {
u32s(&mut out, &[24]);
for b in p.bindings {
u32s(
&mut out,
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
);
}
}
// Names of arbitrary semantics (system values use ""), then indices.
let mut strings = vec![0u8];
let mut indices: Vec<u32> = Vec::new();
let mut elements = Vec::new();
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
let name = if e.kind == 0 {
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
match find(&strings, &needle) {
Some(at) => at,
None => {
strings.extend(&needle);
strings.len() - needle.len()
}
}
} else {
0
};
let index = match indices.iter().position(|&i| i == e.index) {
Some(at) => at,
None => {
indices.push(e.index);
indices.len() - 1
}
};
let (start, alloc) = match e.row {
Some(r) => (r as u8, 0x40 | (e.col << 4)),
None => (0, 0),
};
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
}
strings.resize(strings.len().next_multiple_of(4), 0);
u32s(&mut out, &[strings.len() as u32]);
out.extend(&strings);
u32s(&mut out, &[indices.len() as u32]);
u32s(&mut out, &indices);
if !elements.is_empty() {
u32s(&mut out, &[16]);
for (name, index, start, cols, e) in elements {
u32s(&mut out, &[name, index]);
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
}
}
// Input-to-output dependencies, as the view-id state declares them:
// every output scalar on every input scalar.
if in_vectors > 0 && out_vectors > 0 {
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
let per = (out_vectors * 4).div_ceil(32);
for i in 0..in_vectors * 4 {
for k in 0..per {
let bits = if i < ni {
no.saturating_sub(32 * k).min(32)
} else {
0
};
let mask = if bits == 32 {
u32::MAX
} else {
(1u32 << bits) - 1
};
u32s(&mut out, &[mask]);
}
}
}
out
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
/// The container: parts in order, hashed.
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
let table = 0x20 + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend(b"DXBC");
out.extend([0; 16]);
out.extend(1u16.to_le_bytes());
out.extend(0u16.to_le_bytes());
out.extend((total as u32).to_le_bytes());
out.extend((parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend((offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend(*fourcc);
out.extend((d.len() as u32).to_le_bytes());
out.extend(*d);
}
let digest = hash(&out[20..]);
out[4..20].copy_from_slice(&digest);
out
}
/// The container hash D3D12 checks: MD5 whose last block carries the bit
/// count first and `2 × bytes + 1` last instead of standard padding.
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
let len = data.len();
let left = len % 64;
let mut tail = Vec::with_capacity(128);
if left < 56 {
tail.extend(((len as u32) << 3).to_le_bytes());
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(60, 0);
} else {
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(64, 0);
tail.extend(((len as u32) << 3).to_le_bytes());
tail.resize(124, 0);
}
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
for block in data[..len - left]
.as_chunks::<64>()
.0
.iter()
.chain(tail.as_chunks::<64>().0)
{
md5_block(&mut state, block);
}
let mut out = [0; 16];
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
o.copy_from_slice(&s.to_le_bytes());
}
out
}
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
let x: Vec<u32> = block
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect();
let [mut a, mut b, mut c, mut d] = *state;
for i in 0..64 {
let (f, g) = match i / 16 {
0 => ((b & c) | (!b & d), i),
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | !d), (7 * i) % 16),
};
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
let rotated = a
.wrapping_add(f)
.wrapping_add(k)
.wrapping_add(x[g])
.rotate_left(S[(i / 16) * 4 + i % 4]);
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
}
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
*s = s.wrapping_add(v);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn md5_core_matches_the_standard() {
// Standard MD5 of "abc" with standard padding, through md5_block.
let mut block = b"abc".to_vec();
block.push(0x80);
block.resize(56, 0);
block.extend(24u64.to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
md5_block(&mut state, block.as_slice().try_into().unwrap());
let hex: String = state
.iter()
.flat_map(|s| s.to_le_bytes())
.map(|b| format!("{b:02x}"))
.collect();
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+452
View File
@@ -0,0 +1,452 @@
//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
//! Compute shaders keep the console's thread-group size; one that depends
//! on the lane layout (cross-lane operations) declares the console's wave
//! size (`WaveSize`), so the host device must support it.
//!
//! What the host binds for a translated shader ([`HostShader`]):
//!
//! * **User data** at `b0, space 0` (32-bit root constants or a constant
//! buffer, per stage): dword `index` holds a root parameter's value, as
//! [`UserData`] lists. A root-constant dword is the constant. A
//! descriptor table is the byte offset of its first descriptor in its
//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
//! for sampler tables (the console's descriptor sizes; the code adds
//! offsets in those units). The heap bases of dynamic resources are 0
//! and not listed.
//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
//! `SamplerDescriptorHeap[]`, at the index the console address gives, so
//! the host heaps keep the title's descriptor order. The root signature
//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
//! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
//! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
//! position in [`HostShader::samplers`] (the console sampler words) and
//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
//! sampler description). Comparison sampling (added 2026-11-23): an
//! immediate sampler it uses has a comparison filter there (bit 0x80);
//! a heap sampler it uses must be a comparison sampler on the host.
//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
//! address the title sets is the buffer's.
//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and
//! vertex programs fetch vertices themselves with typed-format loads
//! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
//! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
//! instruction, so the translation reads raw bytes and converts them
//! itself. Their descriptors are built around a root SRV (stride 1, no
//! record limit): the host binds the root SRV `t<slot>` above with the
//! address the title sets, nothing more. The vertex index, the stride
//! and the attribute offset are the shader's own arithmetic on data in
//! that buffer (per-stream headers), not descriptor fields.
//! * **Buffer views in the heap** are declared by how the shader reads
//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
//! typed-format loads without an index; structured with the used-resource
//! entry's stride when indexed; typed with four 32-bit float channels for
//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
//! that index must be of that kind and start at the console descriptor's
//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
//! title's view description says. Typed-format loads from heap
//! descriptors (1,024 world compute programs, ray-tracing material
//! resolves) read raw views this way.
//!
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
//! atomically is declared a 32-bit unsigned single-channel view; the
//! host's view at that index must be an R32 integer view (64-bit atomics
//! stop the translation). Global loads from a root SRV read it raw.
//!
//! Entry points: [`translate`] (container bytes as the title passes them
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
//! earlier stages already run). The root constants of each stage must
//! cover [`HostShader::user_data_dwords`]. Stability: these types and the
//! binding scheme are what pipeline creation builds on; changes are
//! announced.
//! * **Signatures** as the console container has them (same semantics,
//! registers and masks), so the input layout and stage linking are the
//! title's; pixel outputs are plain 32-bit values.
//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
//! descriptors as above (the root constants visible to the mesh stage);
//! the pipeline is a mesh pipeline (pipeline-state stream, no input
//! layout) with the title's pixel shader. The thread group is the
//! console's in lanes (`[numthreads]` in the DXIL), the vertex and
//! primitive maxima its own, triangles only, no wave size required. The
//! console numbers groups in x only: the draw path passes the title's
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
//! console never exports them).
mod bitcode;
mod container;
#[cfg(all(test, windows))]
mod diff_tests;
#[cfg(all(windows, any(test, feature = "host")))]
pub mod host;
mod lower;
mod sampler;
mod shader;
#[cfg(windows)]
pub mod validator;
mod wave;
use crate::dxbc::{Container, FourCC};
use crate::native::{HwStage, NativeProgram, RootType};
use crate::{ShaderError, io, ir, resource, structure};
pub use sampler::StaticSampler;
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
/// A translated shader and what the host binds for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostShader {
pub stage: HwStage,
/// The DXIL container, hashed as D3D12 expects.
pub dxil: Vec<u8>,
/// The user-data dwords the shader reads.
pub user_data: Vec<UserData>,
/// Immediate samplers: the four sampler words of `s<n>`.
pub samplers: Vec<[u32; 4]>,
/// The same samplers decoded, `s<n>` at position n: the static sampler
/// descriptions the host's root signature declares.
pub static_samplers: Vec<StaticSampler>,
/// Root CBVs the shader reads: root parameter indices, each bound as
/// `b<index>` in [`ROOT_CBV_SPACE`].
pub root_cbvs: Vec<u8>,
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
/// [`ROOT_CBV_SPACE`].
pub root_srvs: Vec<u8>,
}
impl HostShader {
/// Size of the user-data buffer the shader declares, in dwords (a
/// multiple of 4; 0 when it reads none). Root constants must cover it.
pub fn user_data_dwords(&self) -> u32 {
let n = self
.user_data
.iter()
.map(|u| u.index + 1)
.max()
.unwrap_or(0);
n.next_multiple_of(4)
}
}
/// One dword of user data and the root parameter that fills it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UserData {
/// Dword in the user-data buffer (the console's user-data index).
pub index: u32,
/// Root parameter index in the title's root signature.
pub slot: u8,
/// `Constants` or `Table` (see the module notes for the value).
pub root: RootType,
/// Dword within the parameter.
pub dword: u32,
}
/// Translates the vertex, pixel, compute or mesh program of a console
/// shader container.
pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
let c = Container::parse(container)?;
let dxil = c
.part(FourCC::DXIL)
.ok_or(ShaderError::Malformed("no DXIL part"))?;
let native = crate::native_programs(dxil.data)?
.into_iter()
.find(|p| {
matches!(
p.stage,
HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
)
})
.ok_or(ShaderError::Unsupported {
offset: 0,
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)?;
let io = io::raise(&p, &native)?;
let st = structure::structure(&p)?;
emit(&c, &native, &p, &st, &io, &res)
}
/// Emits a program whose earlier stages already ran.
pub fn emit(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<HostShader, ShaderError> {
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
match c.part(fourcc) {
Some(part) => signature(part.data),
None => Ok(Vec::new()),
}
};
let pixel = native.stage == HwStage::Ps;
let mut inputs = sig(FourCC::ISG1)?;
let mut outputs = sig(FourCC::OSG1)?;
// Interpolation as DXC declares it by default; pixel inputs that are
// read get the mode their barycentrics say.
let interpolated = if pixel { &mut inputs } else { &mut outputs };
for e in interpolated {
e.interp = match (e.kind, e.comp) {
(3, _) => 4,
// Constant, as DXC declares it (the AMD compiler crashed on a
// front face without a mode).
(13, _) => 1,
(0 | 6 | 7, 9) => 2,
(0, _) => 1,
_ => 0,
};
}
// 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.
let mut prims = sig(FourCC::PSG1)?;
prims.retain(|e| !matches!(e.kind, 10 | 30));
for e in &mut prims {
e.interp = 1;
}
// A mesh group's id arrives multiplied by max(threads, vertices,
// primitives) (the code divides by that); the thread count is in PSV0
// from runtime info version 2 on.
// shortcut: older containers fall back to the group's lane count, right
// when the HLSL group fills its waves (Grand Theft Auto VI's do).
let mesh_stride = match &native.io {
crate::native::StageIo::Ms(ms) => {
let psv = c.part(FourCC::PSV0).map(|p| p.data);
let threads = psv
.filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
.and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
threads.map_or(ms.threads, |t| {
t.max(ms.max_vertices).max(ms.max_primitives)
})
}
_ => 0,
};
let l = lower::lower(&lower::Parts {
native,
p,
st,
io,
res,
inputs,
outputs,
prims,
mesh_stride,
})?;
Ok(HostShader {
stage: native.stage,
dxil: l.dxil,
user_data: l.user_data,
static_samplers: l
.samplers
.iter()
.enumerate()
.map(|(n, &w)| {
let mut s = StaticSampler::from_words(w);
if l.cmp_samplers >> n & 1 != 0 {
s.filter |= 0x80;
}
s
})
.collect(),
samplers: l.samplers,
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
})
}
/// The rows of an `ISG1`/`OSG1` part.
fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
use crate::dxbc::u32_at;
let count = u32_at(part, 0)? as usize;
let base = u32_at(part, 4)? as usize;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let at = base + 32 * i;
let name_at = u32_at(part, at + 4)? as usize;
let name = part
.get(name_at..)
.and_then(|s| s.split(|&b| b == 0).next())
.ok_or(ShaderError::Malformed("signature name out of bounds"))?;
let mask = *part
.get(at + 24)
.ok_or(ShaderError::Malformed("truncated"))?;
if u32_at(part, at + 28)? != 0 {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a minimum-precision signature element",
});
}
if u32_at(part, at)? != 0 {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a signature element of another stream",
});
}
let kind = match u32_at(part, at + 12)? {
0 => 0,
1 => 3,
2 => 6,
3 => 7,
4 => 4,
5 => 5,
6 => 1,
7 => 10,
8 => 2,
9 => 13,
10 => 12,
64 => 16,
65 => 17,
66 => 14,
67 => 19,
68 => 18,
69 => 20,
70 => 15,
25 => 30, // cull primitive
_ => {
return Err(ShaderError::Unsupported {
offset: 0,
what: "a system value in the signature",
});
}
};
// 16-bit elements are declared 32-bit; reading or writing one
// converts (16-bit values travel packed on the console).
let raw = u32_at(part, at + 16)?;
let comp = match (kind, raw) {
// DXIL declares the front face a uint (the validator insists).
(13, _) => 5,
(_, 1 | 4) => 5,
(_, 2 | 5) => 4,
(_, 3 | 6) => 9,
(_, c) => {
return Err(ShaderError::Unsupported {
offset: 0,
what: match c {
0 => "a signature element of unknown type",
_ => "a 64-bit signature element",
},
});
}
};
let register = u32_at(part, at + 20)?;
out.push(container::SigElement {
name: String::from_utf8_lossy(name).into_owned(),
index: u32_at(part, at + 8)?,
kind,
comp,
interp: 0,
row: (register != u32::MAX).then_some(register),
col: mask.trailing_zeros().min(3) as u8,
cols: mask.count_ones().max(1) as u8,
usage: 0,
half: (4..=6).contains(&raw),
});
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::bitcode::Attr;
use super::container::SigElement;
use super::shader::Shader;
/// A pixel shader writing a constant colour.
fn constant_color() -> Vec<u8> {
let mut s = Shader::new(true);
s.outputs.push(SigElement {
name: "SV_Target".into(),
index: 0,
kind: 16,
comp: 9,
interp: 0,
row: Some(0),
col: 0,
cols: 4,
usage: 15,
half: false,
});
let b = s.entry;
for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
let args = [
s.m.i32(0),
s.m.i32(0),
s.m.i8(c as u8),
s.m.f32(v.to_bits()),
];
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
}
s.m.terminate(b, super::bitcode::Term::Ret);
s.finish()
}
#[test]
#[cfg(windows)]
fn stub_pipeline_is_created() {
let Ok(host) = super::host::Host::new(false) else {
eprintln!("no SM 6.6 device; skipped");
return;
};
let ps = super::HostShader {
stage: crate::HwStage::Ps,
dxil: constant_color(),
user_data: Vec::new(),
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
};
let file = |var: &str, stage| {
std::env::var(var).ok().map(|p| super::HostShader {
stage,
dxil: std::fs::read(p).unwrap(),
user_data: Vec::new(),
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
})
};
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
.unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut vs.dxil.clone()).unwrap();
}
host.pipeline(&vs, &ps).unwrap();
// The runtime checks the container hash: no hash or a wrong one is
// refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
// value; ours works with older ones too.)
let mut wrong = ps.dxil[4..20].to_vec();
wrong[0] ^= 1;
for digest in [&[0u8; 16][..], &wrong] {
let mut other = ps.clone();
other.dxil[4..20].copy_from_slice(digest);
assert!(
host.pipeline(&vs, &other).is_err(),
"digest {digest:02x?} accepted"
);
}
}
#[test]
#[cfg(windows)]
fn constant_color_validates() {
let mut c = constant_color();
let path = super::validator::Validator::default_path();
let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
eprintln!("no dxil.dll; skipped");
return;
};
let ours = c[4..20].to_vec();
v.validate(&mut c).unwrap();
assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Immediate samplers: the console's four sampler words (the GPU's public
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
//!
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
//! magnification and minification filters (20-21, 22-23: point, linear,
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
//! opaque white, custom).
//!
//! Comparison is the sampling instruction's, not the sampler's: the console
//! encodes a comparison function in every sampler (D3D's default, less or
//! equal, when unused).
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
/// `D3D12_STATIC_BORDER_COLOR` values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StaticSampler {
pub filter: u32,
/// U, V, W.
pub address: [u32; 3],
pub mip_lod_bias: f32,
pub max_anisotropy: u32,
pub comparison: u32,
pub border: u32,
pub min_lod: f32,
pub max_lod: f32,
}
// The floats come from fixed-point fields: never NaN.
impl Eq for StaticSampler {}
impl StaticSampler {
/// Decodes the four sampler words.
pub fn from_words(w: [u32; 4]) -> Self {
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
// wrap, mirror, clamp, mirror once; the half-border modes have no
// D3D form and become their nearest.
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
let reduction = match bits(w[0], 29, 2) {
1 => 2,
2 => 3,
_ => 0,
};
let filter = if mag >= 2 || min >= 2 {
0x55 | reduction << 7
} else {
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
};
let lod = |v: u32| v as f32 / 256.0;
// Without a mip filter the base level is sampled.
let (min_lod, max_lod) = if mip == 0 {
(0.0, 0.0)
} else {
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
};
StaticSampler {
filter,
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
comparison: bits(w[0], 12, 3) + 1,
// shortcut: a custom border colour (type 3, a table entry) becomes
// transparent black; upgrade when a title uses one.
border: bits(w[3], 30, 2) % 3,
min_lod,
max_lod,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn console_compiled_samplers_decode() {
// Words the console compiler wrote for static samplers of known
// descriptions.
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
assert_eq!(
point,
StaticSampler {
filter: 0,
address: [1, 2, 3],
mip_lod_bias: 0.5,
max_anisotropy: 1,
comparison: 4,
border: 2,
min_lod: 1.0,
max_lod: 5.25,
}
);
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
assert_eq!(
(aniso.filter, aniso.address, aniso.max_anisotropy),
(0x55, [4, 5, 3], 8)
);
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
assert_eq!(
(compare.filter, compare.address, compare.border),
(0x14, [4, 1, 1], 1)
);
let minimum =
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
let max_aniso =
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
assert_eq!(
(
max_aniso.filter,
max_aniso.max_anisotropy,
max_aniso.mip_lod_bias
),
(0x1D5, 16, 15.0)
);
}
}
+645
View File
@@ -0,0 +1,645 @@
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
//! the `dx.op` declarations it calls, its signatures and bound resources,
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
use super::bitcode::{Attr, Md, Module, Ty, V};
use super::container::{self, Binding, Psv, SigElement};
/// Where the shader reads its user data: `b0` in this space.
pub const USER_DATA_SPACE: u32 = 0;
/// Where immediate samplers are bound: `s<n>` in this space.
pub const SAMPLER_SPACE: u32 = 0;
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
/// `t<root parameter index>` in this space.
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 TYPED_UAV_LOADS: u64 = 1 << 13;
pub const WAVE_OPS: u64 = 1 << 19;
pub const INT64: u64 = 1 << 20;
pub const RESOURCE_HEAP: u64 = 1 << 30;
pub const SAMPLER_HEAP: u64 = 1 << 31;
}
pub(crate) struct Types {
pub void: Ty,
pub i1: Ty,
pub i32: Ty,
pub f32: Ty,
pub handle: Ty,
pub props: Ty,
pub bind: Ty,
pub cbuf_ret: Ty,
pub res_ret: Ty,
}
/// What a mesh shader declares beyond its thread-group size.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Mesh {
pub max_vertices: u32,
pub max_primitives: u32,
/// 1 lines, 2 triangles.
pub topology: u8,
}
pub(crate) struct Shader {
pub m: Module,
pub t: Types,
pub pixel: bool,
pub inputs: Vec<SigElement>,
pub outputs: Vec<SigElement>,
/// A mesh shader's per-primitive outputs.
pub prims: Vec<SigElement>,
/// A mesh shader (`threads` is its thread-group size).
pub mesh: Option<Mesh>,
/// Dwords of user data the shader reads (0: no user-data buffer).
pub user_data: u32,
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
pub samplers: u32,
/// Bit n: immediate sampler n is a comparison sampler.
pub cmp_samplers: u64,
/// Root CBVs read, by root parameter index, with their handles.
pub root_cbvs: Vec<(u8, V)>,
/// Root SRVs (raw buffers) read, likewise.
pub root_srvs: Vec<(u8, V)>,
pub flags: u64,
/// A compute shader with this thread-group size.
pub threads: Option<[u32; 3]>,
/// The wave size a compute shader requires (`WaveSize`).
pub wave_size: Option<u32>,
/// Thread-group shared memory, in dwords.
pub lds_dwords: u32,
lds: Option<V>,
main: V,
pub entry: usize,
}
impl Shader {
pub fn new(pixel: bool) -> Self {
let mut m = Module::default();
let void = m.void();
let i1 = m.int(1);
let i8 = m.int(8);
let i32 = m.int(32);
let f32 = m.float();
let i8p = m.ptr(i8);
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
let main_ty = m.func_ty(void, vec![]);
m.ptr(main_ty);
let main = m.function("main", main_ty, None, true);
let entry = m.new_block();
Shader {
m,
t: Types {
void,
i1,
i32,
f32,
handle,
props,
bind,
cbuf_ret,
res_ret,
},
pixel,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh: None,
user_data: 0,
samplers: 0,
cmp_samplers: 0,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
flags: 0,
threads: None,
wave_size: None,
lds_dwords: 0,
lds: None,
main,
entry,
}
}
/// The thread-group shared memory: `[lds_dwords x i32]` in address
/// space 3.
pub fn lds(&mut self) -> V {
if let Some(g) = self.lds {
return g;
}
let arr = self.m.array(self.lds_dwords, self.t.i32);
let g = self.m.global("lds", arr, 3);
self.lds = Some(g);
g
}
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
pub fn op(
&mut self,
block: usize,
name: &str,
attr: Attr,
ret: Ty,
opcode: u32,
args: &[V],
) -> V {
let mut params = vec![self.t.i32];
params.extend(args.iter().map(|&a| self.m.type_of(a)));
let fty = self.m.func_ty(ret, params);
self.m.ptr(fty);
let f = self
.m
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
let mut all = vec![self.m.i32(opcode)];
all.extend(args);
self.m.call(block, f, all)
}
/// The handle of the user-data constant buffer, made in the entry block.
pub fn user_data_handle(&mut self) -> V {
let bind = [
self.m.i32(0),
self.m.i32(0),
self.m.i32(USER_DATA_SPACE),
self.m.i8(2), // CBV
];
let bind = self.m.aggregate(self.t.bind, &bind);
let block = self.entry;
let (i, f) = (self.m.i32(0), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
// The size is known in `finish`, which fixes this placeholder.
self.annotate(block, h, 13, u32::MAX)
}
/// The handle of the root CBV of root parameter `slot`, made in the
/// entry block.
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 13, 65536);
self.root_cbvs.push((slot, h));
h
}
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
pub fn root_srv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 11, 0);
self.flags |= flags::RAW_BUFFERS;
self.root_srvs.push((slot, h));
h
}
/// The handle of immediate sampler `n` (a comparison sampler when its
/// bit in `cmp_samplers` is set).
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
let bind = [
self.m.i32(n),
self.m.i32(n),
self.m.i32(SAMPLER_SPACE),
self.m.i8(3), // sampler
];
let bind = self.m.aggregate(self.t.bind, &bind);
let (i, f) = (self.m.i32(n), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
let cmp = if self.cmp_samplers >> n & 1 != 0 {
0x8000
} else {
0
};
self.annotate(block, h, 14 | cmp, 0)
}
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
let p = [self.m.i32(props0), self.m.i32(props1)];
let p = self.m.aggregate(self.t.props, &p);
self.op(
block,
"annotateHandle",
Attr::ReadNone,
self.t.handle,
216,
&[h, p],
)
}
/// A descriptor heap handle, annotated with `props`.
pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V {
self.flags |= if sampler {
flags::SAMPLER_HEAP
} else {
flags::RESOURCE_HEAP
};
let (s, n) = (self.m.bool(sampler), self.m.bool(false));
let h = self.op(
block,
"createHandleFromHeap",
Attr::ReadNone,
self.t.handle,
218,
&[index, s, n],
);
self.annotate(block, h, props.0, props.1)
}
/// The finished container.
pub fn finish(mut self) -> Vec<u8> {
let ud_size = (self.user_data * 4).next_multiple_of(16);
self.fix_user_data_size(ud_size);
let mut resources = None;
let mut bindings = Vec::new();
let i32c = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
s.m.md_value(c)
};
if self.user_data > 0
|| self.samplers > 0
|| !self.root_cbvs.is_empty()
|| !self.root_srvs.is_empty()
{
let empty = self.m.md_str("");
let mut cbvs = None;
let mut cbv_list = Vec::new();
if self.user_data > 0 {
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
let ty = self.m.named_struct("UserData", vec![arr]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let ops = vec![
Some(i32c(&mut self, 0)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, USER_DATA_SPACE)),
Some(i32c(&mut self, 0)),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, ud_size)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: USER_DATA_SPACE,
register: 0,
dxil_kind: 13,
});
}
let blob = self.m.array(16384, self.t.i32);
let ty = self.m.named_struct("RootCbv", vec![blob]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
for (slot, _) in self.root_cbvs.clone() {
let ops = vec![
Some(i32c(&mut self, cbv_list.len() as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 65536)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 13,
});
}
if !cbv_list.is_empty() {
cbvs = Some(self.m.md_node(cbv_list));
}
let mut srvs = None;
if !self.root_srvs.is_empty() {
let ty = self
.m
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
let ops = vec![
Some(i32c(&mut self, n as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 11)),
Some(i32c(&mut self, 0)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 4,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 11,
});
}
srvs = Some(self.m.md_node(list));
}
let mut samplers = None;
if self.samplers > 0 {
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for n in 0..self.samplers {
let kind = (self.cmp_samplers >> n & 1) as u32;
let ops = vec![
Some(i32c(&mut self, n)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, SAMPLER_SPACE)),
Some(i32c(&mut self, n)),
Some(i32c(&mut self, 1)),
// Sampler kind: 1 comparison.
Some(i32c(&mut self, kind)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 1,
space: SAMPLER_SPACE,
register: n,
dxil_kind: 14,
});
}
samplers = Some(self.m.md_node(list));
}
resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers]));
// PSV0 lists them as the module does: CBVs, samplers, SRVs.
bindings.sort_by_key(|b| match b.kind {
2 => 0,
1 => 1,
_ => 2,
});
}
if let Some(r) = resources {
self.m.named_md("dx.resources", vec![r]);
}
let graphics = self.threads.is_none() || self.mesh.is_some();
if graphics {
// shortcut: every output is declared to depend on every input; the
// exact sets need a dependence pass. Drivers read this state.
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
let mut view = vec![ni, no];
// Mesh shaders have no inputs: then the primitive outputs' count.
if self.mesh.is_some() {
view.push(scalars(&self.prims));
}
for _ in 0..ni {
for k in 0..no.div_ceil(32) {
let bits = (no - 32 * k).min(32);
view.push(if bits == 32 {
u32::MAX
} else {
(1 << bits) - 1
});
}
}
let arr = self.m.array(view.len() as u32, self.t.i32);
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
let arr = self.m.aggregate(arr, &elems);
let arr = self.m.md_value(arr);
let view_node = self.m.md_node(vec![Some(arr)]);
self.m.named_md("dx.viewIdState", vec![view_node]);
}
let sigs = if graphics {
let ins = self.signature_md(self.inputs.clone());
let outs = self.signature_md(self.outputs.clone());
let prims = self.signature_md(self.prims.clone());
Some(self.m.md_node(vec![ins, outs, prims]))
} else {
None
};
// Entry properties: shader flags (tag 0), thread-group size (4),
// wave size (11).
let mut props = Vec::new();
if self.flags != 0 {
props.push(i32c(&mut self, 0));
let i64t = self.m.int(64);
let f = self.m.int_const(i64t, self.flags as i64);
props.push(self.m.md_value(f));
}
if let Some(threads) = self.threads {
let t = threads.map(|n| Some(i32c(&mut self, n)));
let t = self.m.md_node(t.to_vec());
match self.mesh {
// Mesh state (tag 9): threads, maximum vertices and
// primitives, topology, payload bytes.
Some(mesh) => {
props.push(i32c(&mut self, 9));
let state = [
mesh.max_vertices,
mesh.max_primitives,
mesh.topology.into(),
0,
]
.map(|n| Some(i32c(&mut self, n)));
let mut node = vec![Some(t)];
node.extend(state);
props.push(self.m.md_node(node));
}
None => {
props.push(i32c(&mut self, 4));
props.push(t);
}
}
}
if let Some(n) = self.wave_size {
props.push(i32c(&mut self, 11));
let n = Some(i32c(&mut self, n));
props.push(self.m.md_node(vec![n]));
}
let props =
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
let main = self.m.md_value(self.main);
let name = self.m.md_str("main");
let entry = self
.m
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
let ident = self.m.md_str("victory");
let ident = self.m.md_node(vec![Some(ident)]);
self.m.named_md("llvm.ident", vec![ident]);
let one = i32c(&mut self, 1);
let six = i32c(&mut self, 6);
let version = self.m.md_node(vec![Some(one), Some(six)]);
self.m.named_md("dx.version", vec![version]);
self.m.named_md("dx.valver", vec![version]);
// Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh.
let (name, kind) = match (self.threads, self.pixel) {
_ if self.mesh.is_some() => ("ms", 13u32),
(Some(_), _) => ("cs", 5u32),
(None, true) => ("ps", 0),
(None, false) => ("vs", 1),
};
let name = self.m.md_str(name);
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
self.m.named_md("dx.shaderModel", vec![sm]);
self.m.named_md("dx.entryPoints", vec![entry]);
let bitcode = self.m.write();
let mut dxil = Vec::with_capacity(24 + bitcode.len());
dxil.extend((kind << 16 | 0x66).to_le_bytes());
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
dxil.extend(b"DXIL");
dxil.extend(0x106u32.to_le_bytes());
dxil.extend(16u32.to_le_bytes());
dxil.extend((bitcode.len() as u32).to_le_bytes());
dxil.extend(&bitcode);
let mut features = 0u64;
if self.flags & flags::TYPED_UAV_LOADS != 0 {
features |= 0x800;
}
if self.flags & flags::WAVE_OPS != 0 {
features |= 0x4000;
}
if self.flags & flags::INT64 != 0 {
features |= 0x8000;
}
if self.flags & flags::RESOURCE_HEAP != 0 {
features |= 0x200_0000;
}
if self.flags & flags::SAMPLER_HEAP != 0 {
features |= 0x400_0000;
}
let sfi0 = features.to_le_bytes();
let isg1 = container::signature(&self.inputs, true);
let osg1 = container::signature(&self.outputs, false);
let flag = if self.pixel {
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
} else {
self.outputs.iter().any(|o| o.kind == 3)
};
let psv0 = container::psv(&Psv {
stage: kind as u8,
flag: flag && self.threads.is_none(),
inputs: &self.inputs,
outputs: &self.outputs,
prims: &self.prims,
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
bindings: &bindings,
threads: self.threads.unwrap_or_default(),
wave_size: self.wave_size,
});
let hash = [0u8; 20];
let psg1 = container::signature(&self.prims, false);
let mut parts: Vec<(&[u8; 4], &[u8])> =
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
if self.mesh.is_some() {
parts.push((b"PSG1", &psg1));
}
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
container::build(&parts)
}
/// The user-data buffer's annotation carries its size, known only now.
fn fix_user_data_size(&mut self, size: u32) {
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
let old = self.m.aggregate(self.t.props, &old);
let new = [self.m.i32(13), self.m.i32(size)];
let new = self.m.aggregate(self.t.props, &new);
self.m.replace_const(old, new);
}
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
if elements.is_empty() {
return None;
}
let mut list = Vec::new();
for (id, e) in elements.iter().enumerate() {
let c32 = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
Some(s.m.md_value(c))
};
let c8 = |s: &mut Self, v: u8| {
let c = s.m.i8(v);
Some(s.m.md_value(c))
};
let idx = c32(self, e.index);
let indices = Some(self.m.md_node(vec![idx]));
let usage = if e.usage != 0 {
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
Some(self.m.md_node(vec![tag, mask]))
} else {
None
};
let ops = vec![
c32(self, id as u32),
Some(self.m.md_str(&e.name)),
c8(self, e.comp),
c8(self, e.kind),
indices,
c8(self, e.interp),
c32(self, 1),
c8(self, e.cols),
c32(self, e.row.unwrap_or(u32::MAX)),
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
usage,
];
list.push(Some(self.m.md_node(ops)));
}
Some(self.m.md_node(list))
}
}
+221
View File
@@ -0,0 +1,221 @@
//! 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`]).
//!
//! 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.
use std::ffi::c_void;
use std::path::PathBuf;
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
type Hresult = i32;
#[repr(C)]
struct Guid(u32, u16, u16, [u8; 8]);
const CLSID_DXC_VALIDATOR: Guid = Guid(
0x8ca3_e215,
0xf728,
0x4cf3,
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
);
const IID_IDXC_VALIDATOR: Guid = Guid(
0xa6e8_2bd2,
0x1fd7,
0x4826,
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
);
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
const IN_PLACE_EDIT: u32 = 1;
type CreateInstance =
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
/// COM object: a pointer to a table of method pointers.
type Object = *mut *const usize;
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
// SAFETY: the caller names a slot of the object's interface.
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
}
unsafe fn release(obj: Object) {
if !obj.is_null() {
// SAFETY: slot 2 of every COM interface is Release.
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
}
}
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
#[repr(C)]
struct Blob {
vtable: *const BlobVtable,
data: *mut u8,
len: usize,
}
/// IUnknown and IDxcBlob, as raw GUID bytes.
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
const IDXC_BLOB: [u8; 16] = [
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
];
unsafe extern "system" fn blob_qi(
this: *mut Blob,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> Hresult {
// SAFETY: the validator passes valid pointers.
unsafe {
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
*out = this.cast();
0
} else {
*out = std::ptr::null_mut();
0x8000_4002_u32 as i32 // E_NOINTERFACE
}
}
}
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
1
}
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
// SAFETY: `this` is our blob.
unsafe { (*this).data }
}
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
// SAFETY: `this` is our blob.
unsafe { (*this).len }
}
#[repr(C)]
struct BlobVtable {
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
release: unsafe extern "system" fn(*mut Blob) -> u32,
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
len: unsafe extern "system" fn(*mut Blob) -> usize,
}
static BLOB_VTABLE: BlobVtable = BlobVtable {
qi: blob_qi,
add_ref: blob_ref,
release: blob_ref,
ptr: blob_ptr,
len: blob_len,
};
pub struct Validator {
object: Object,
}
// SAFETY: the validator object is free-threaded (DXC's validator has no
// thread affinity); calls are serialised by `&mut self`.
unsafe impl Send for Validator {}
impl Validator {
/// Where `dxil.dll` is looked for.
pub fn default_path() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
return Some(p.into());
}
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
.ok()?
.filter_map(Result::ok)
.map(|e| e.path().join(r"x64\dxil.dll"))
.filter(|p| p.exists())
.collect();
versions.sort();
versions.pop()
}
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
let name: Vec<u16> = path
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
.to_string_lossy()
.encode_utf16()
.chain([0])
.collect();
// SAFETY: plain Win32 calls with a NUL-terminated name.
unsafe {
let module = LoadLibraryW(name.as_ptr());
if module.is_null() {
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
}
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
.ok_or("dxil.dll lacks DxcCreateInstance")?;
let create: CreateInstance = std::mem::transmute(create);
let mut object = std::ptr::null_mut();
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
if hr < 0 || object.is_null() {
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
}
Ok(Validator {
object: object.cast(),
})
}
}
/// Validates `container` and signs it in place; the error text if it
/// is rejected.
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
let mut blob = Blob {
vtable: &BLOB_VTABLE,
data: container.as_mut_ptr(),
len: container.len(),
};
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
unsafe {
let mut result: Object = std::ptr::null_mut();
let validate: unsafe extern "system" fn(
Object,
*mut Blob,
u32,
*mut Object,
) -> Hresult = method(self.object, 3);
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
if hr < 0 || result.is_null() {
return Err(format!("Validate failed: {hr:#x}"));
}
let mut status = 0;
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
method(result, 3);
get_status(result, &mut status);
let mut text = String::new();
if status < 0 {
let mut errors: Object = std::ptr::null_mut();
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
method(result, 5);
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
text = String::from_utf8_lossy(bytes)
.trim_end_matches('\0')
.trim()
.into();
release(errors);
}
if text.is_empty() {
text = format!("rejected ({status:#x})");
}
}
release(result);
if status < 0 { Err(text) } else { Ok(()) }
}
}
}
impl Drop for Validator {
fn drop(&mut self) {
// SAFETY: we own one reference.
unsafe { release(self.object) };
}
}
+679
View File
@@ -0,0 +1,679 @@
//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1`
//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's
//! wave, the inactive ones included, which is how the compiler expands
//! HLSL wave reductions and prefix sums (an identity put into the inactive
//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane`
//! steps). A host lane that is elsewhere cannot run that code, so each
//! section is simulated on the console's lanes with symbolic values, and a
//! value it leaves is lowered by what it turned out to be: the reduction or
//! prefix of one operation over the lanes' (masked) inputs, which DXIL's
//! wave operations compute over the host's active lanes. No instruction
//! sequence is matched; any step the simulation does not model leaves the
//! values it writes unknown.
use std::collections::HashMap;
use crate::gfx10::{Dpp, Fields, NULL, Operand};
use crate::ir::{EXEC, Inst, Program, Reg, Value};
/// An associative operation and its identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Op {
AddU,
AddF,
MinU,
MaxU,
MinI,
MaxI,
MinF,
MaxF,
Or,
And,
Xor,
}
impl Op {
fn of(name: &str) -> Option<Op> {
Some(match name {
"v_add_nc_u32" => Op::AddU,
"v_add_f32" => Op::AddF,
"v_min_u32" => Op::MinU,
"v_max_u32" => Op::MaxU,
"v_min_i32" => Op::MinI,
"v_max_i32" => Op::MaxI,
"v_min_f32" => Op::MinF,
"v_max_f32" => Op::MaxF,
"v_or_b32" => Op::Or,
"v_and_b32" => Op::And,
"v_xor_b32" => Op::Xor,
_ => return None,
})
}
/// Whether `k` leaves the other operand unchanged.
fn identity(self, k: u32) -> bool {
match self {
Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0,
Op::AddF => k == 0 || k == 0x8000_0000,
Op::MinU | Op::And => k == u32::MAX,
Op::MinI => k == 0x7FFF_FFFF,
Op::MaxI => k == 0x8000_0000,
Op::MinF => k == 0x7F80_0000,
Op::MaxF => k == 0xFF80_0000,
}
}
/// Counting a lane twice changes the result.
fn counts(self) -> bool {
matches!(self, Op::AddU | Op::AddF | Op::Xor)
}
}
/// A lane's value inside a section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sym {
Unknown,
K(u32),
/// The lane's own value of a VGPR value from before the section.
Own(Value),
/// A uniform value from before the section.
Uni(Value),
/// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane).
Red {
op: Option<Op>,
src: Value,
mask: Value,
ident: u32,
lanes: u64,
},
}
/// What a value a section leaves holds in every lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Shape {
K(u32),
Value(Value),
/// The lane's own `mask ? src : ident`.
Masked(Value, Value, u32),
/// `op` over every lane.
Active(Op, Value, Value, u32),
/// `op` over the lanes below (`inclusive`: and including) each lane.
Prefix(Op, Value, Value, u32, bool),
}
/// The section starting at instruction `start` of a block: its restore
/// index and the shapes of the values it writes.
pub(crate) struct Section {
pub end: usize,
pub shapes: HashMap<Value, Shape>,
}
/// Every whole-wave section of `block`, by start index.
pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> {
let insts = &p.blocks[block].insts;
let wave: u32 = if p.wave64 { 64 } else { 32 };
let mut out = HashMap::new();
let mut i = 0;
while i < insts.len() {
let inst = &insts[i];
// EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`.
let all = match inst.name() {
"s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)),
"s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)),
_ => None,
};
let start = all.is_some_and(
|k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)),
);
let saved = match &inst.fields {
Fields::Sop {
dst: Some(Operand::Scalar { code, .. }),
..
} if start => inst.write(Reg::S(*code)),
_ => None,
};
let Some(saved) = saved else {
i += 1;
continue;
};
let end = (i + 1..insts.len()).find(|&j| {
insts[j].write(Reg::S(EXEC)).is_some()
&& insts[j].read(Reg::S(saved_code(inst))) == Some(saved)
});
let Some(end) = end else {
break;
};
let shapes = simulate(&insts[i + 1..end], wave, saved);
out.insert(i, Section { end, shapes });
i = end + 1;
}
out
}
fn saved_code(inst: &Inst) -> u8 {
match &inst.fields {
Fields::Sop {
dst: Some(Operand::Scalar { code, .. }),
..
} => *code,
_ => NULL,
}
}
/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it
/// writes; `None` for patterns not modelled.
fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> {
match d {
Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)),
Dpp::Row {
ctrl,
row_mask,
bank_mask,
bound_ctrl,
..
} => {
let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15));
let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0;
let (src, inside) = match ctrl {
0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true),
0x101..=0x10F => (l + n, pos + n < 16),
0x111..=0x11F => (l.wrapping_sub(n), pos >= n),
0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true),
0x140 => (l ^ 15, true),
0x141 => (l ^ 7, true),
0x150..=0x15F => (row | n, true),
0x160..=0x16F => (l ^ n, true),
_ => return None,
};
match (inside, bound_ctrl) {
(true, _) => Some((src, false, enabled)),
(false, true) => Some((l, true, enabled)),
(false, false) => Some((l, false, false)),
}
}
}
}
fn combine(op: Op, a: Sym, b: Sym) -> Sym {
match (a, b) {
(Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x,
(
Sym::Red {
op: oa,
src,
mask,
ident,
lanes: la,
},
Sym::Red {
op: ob,
src: sb,
mask: mb,
ident: ib,
lanes: lb,
},
) if (src, mask, ident) == (sb, mb, ib)
&& op.identity(ident)
&& oa.is_none_or(|o| o == op)
&& ob.is_none_or(|o| o == op)
&& (!op.counts() || la & lb == 0) =>
{
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes: la | lb,
}
}
_ => Sym::Unknown,
}
}
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
let all = if wave == 64 {
u64::MAX
} else {
u64::from(u32::MAX)
};
let mut exec = all;
let mut vec: HashMap<Value, Vec<Sym>> = HashMap::new();
let mut uni: HashMap<Value, Sym> = HashMap::new();
// Masks the section derives from the saved EXEC (`s_and` with it).
let mut masked = vec![saved];
for inst in insts {
let name = inst.name();
if inst.write(Reg::S(EXEC)).is_some() {
// Constant lane sets (prefix sums); anything else ends what
// the simulation can follow.
let lo = name
.starts_with("s_mov_b")
.then(|| constant(inst))
.flatten();
let Some(k) = lo else {
return shapes(vec, uni, wave);
};
exec = if name == "s_mov_b64" {
k
} else {
exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF
};
continue;
}
if inst.write(Reg::S(EXEC + 1)).is_some() {
let Some(k) = name
.starts_with("s_mov_b")
.then(|| constant(inst))
.flatten()
else {
return shapes(vec, uni, wave);
};
exec = exec & 0xFFFF_FFFF | k << 32;
continue;
}
if let Fields::Sop { src, .. } = &inst.fields {
if name.starts_with("s_and_b")
&& src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v))))
&& let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_)))
{
masked.push(w);
}
for &(_, w) in &inst.writes {
uni.entry(w).or_insert(Sym::Unknown);
}
continue;
}
let Fields::Valu(v) = &inst.fields else {
for &(_, w) in &inst.writes {
vec.insert(w, vec![Sym::Unknown; wave as usize]);
}
continue;
};
let lanes = |op: &Operand,
vec: &HashMap<Value, Vec<Sym>>,
uni: &HashMap<Value, Sym>|
-> Vec<Sym> {
let one = |s: Sym| vec![s; wave as usize];
match *op {
Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) {
Some(x) => vec
.get(&x)
.cloned()
.unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()),
None => one(Sym::Unknown),
},
Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) {
Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))),
None => one(Sym::Unknown),
},
Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)),
Operand::Literal(x) => one(Sym::K(x)),
_ => one(Sym::Unknown),
}
};
let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some();
if name == "v_readlane_b32" {
let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) =
(v.dst, v.src.first(), v.src.get(1))
else {
continue;
};
let l = match *lane {
Operand::Const(c) => crate::resource::inline(c),
Operand::Literal(x) => Some(x),
_ => None,
};
let x = lanes(src, &vec, &uni);
if let Some(w) = inst.write(Reg::S(code)) {
let s = l
.and_then(|l| x.get(l as usize).copied())
.unwrap_or(Sym::Unknown);
uni.insert(w, s);
}
continue;
}
let Some(Operand::Vector { reg: dreg, .. }) = v.dst else {
for &(_, w) in &inst.writes {
uni.insert(w, Sym::Unknown);
}
continue;
};
let Some(dst) = inst.write(Reg::V(dreg)) else {
continue;
};
let old = lanes(
&Operand::Vector {
reg: dreg,
dwords: 1,
},
&vec,
&uni,
);
// src0 as each lane fetches it (DPP), with the lanes that write.
let src0 = v.src.first().map(|o| lanes(o, &vec, &uni));
let mut writes = exec;
let fetched: Option<Vec<Sym>> = match (v.dpp, &src0) {
(Some(d), Some(s)) => {
if exec != all {
vec.insert(dst, vec![Sym::Unknown; wave as usize]);
continue;
}
let mut f = Vec::with_capacity(wave as usize);
let mut ok = true;
for l in 0..wave {
match dpp_lane(d, l) {
Some((src, zero, on)) if src < wave => {
f.push(if zero { Sym::K(0) } else { s[src as usize] });
if !on {
writes &= !(1u64 << l);
}
}
_ => ok = false,
}
}
ok.then_some(f)
}
(None, Some(s)) => Some(s.clone()),
_ => None,
};
let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni));
let result: Vec<Sym> = match (name, fetched) {
_ if modifiers => vec![Sym::Unknown; wave as usize],
("v_mov_b32", Some(a)) => a,
("v_bfrev_b32", Some(a)) => a
.into_iter()
.map(|s| match s {
Sym::K(k) => Sym::K(k.reverse_bits()),
_ => Sym::Unknown,
})
.collect(),
("v_cndmask_b32", Some(a)) => {
let mask = match v.src.get(2) {
Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
_ => None,
};
let b = src(1).unwrap_or_default();
(0..wave as usize)
.map(|l| match (a[l], b.get(l).copied(), mask) {
(Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => {
Sym::Red {
op: None,
src: x,
mask: m,
ident,
lanes: 1 << l,
}
}
_ => Sym::Unknown,
})
.collect()
}
("v_permlanex16_b32", Some(a)) => {
// Lanes of each row read the other row of their half; lane
// i's pick is nibble i of {src2, src1}.
let sel = |k: usize| match v.src.get(k) {
Some(&Operand::Const(c)) => crate::resource::inline(c),
Some(&Operand::Literal(x)) => Some(x),
_ => None,
};
match (sel(1), sel(2)) {
(Some(s1), Some(s2)) => {
let s = u64::from(s1) | u64::from(s2) << 32;
(0..wave)
.map(|l| {
let other = (l & !31) | ((l & 16) ^ 16);
let pick = (s >> (4 * (l & 15)) & 15) as u32;
a[(other | pick) as usize]
})
.collect()
}
_ => vec![Sym::Unknown; wave as usize],
}
}
("v_sub_nc_u32", Some(a)) => {
// A prefix sum less the lane's own term: the exclusive one.
let b = src(1).unwrap_or_default();
(0..wave as usize)
.map(|l| match (a[l], b.get(l).copied()) {
(
Sym::Red {
op: None | Some(Op::AddU),
src,
mask,
ident: 0,
lanes,
},
Some(Sym::Red {
op: None | Some(Op::AddU),
src: s2,
mask: m2,
ident: 0,
lanes: l2,
}),
) if (src, mask) == (s2, m2) && lanes & l2 == l2 => {
let rest = lanes & !l2;
if rest == 0 {
Sym::K(0)
} else {
Sym::Red {
op: Some(Op::AddU),
src,
mask,
ident: 0,
lanes: rest,
}
}
}
_ => Sym::Unknown,
})
.collect()
}
(n, Some(a)) => match (Op::of(n), src(1)) {
(Some(op), Some(b)) => (0..wave as usize)
.map(|l| combine(op, a[l], b[l]))
.collect(),
_ => vec![Sym::Unknown; wave as usize],
},
_ => vec![Sym::Unknown; wave as usize],
};
let merged = (0..wave as usize)
.map(|l| {
if writes >> l & 1 != 0 {
result[l]
} else {
old[l]
}
})
.collect();
vec.insert(dst, merged);
}
shapes(vec, uni, wave)
}
fn constant(inst: &Inst) -> Option<u64> {
let Fields::Sop { src, .. } = &inst.fields else {
return None;
};
match *src.first()? {
Operand::Const(c) => {
let x = crate::resource::inline(c)?;
Some(if (x as i32) < 0 {
u64::MAX
} else {
u64::from(x)
})
}
Operand::Literal(x) => Some(u64::from(x)),
_ => None,
}
}
/// The shape of each value, where every lane agrees on one.
fn shapes(
vec: HashMap<Value, Vec<Sym>>,
uni: HashMap<Value, Sym>,
wave: u32,
) -> HashMap<Value, Shape> {
let all = if wave == 64 {
u64::MAX
} else {
u64::from(u32::MAX)
};
let mut out = HashMap::new();
let single = |s: Sym| match s {
Sym::K(k) => Some(Shape::K(k)),
Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)),
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes,
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
_ => None,
};
for (v, s) in uni {
if let Some(sh) = single(s) {
out.insert(v, sh);
}
}
for (v, lanes) in vec {
if let Some(sh) = per_lane(&lanes, all) {
out.insert(v, sh);
}
}
out
}
fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
let first = lanes[0];
let own = |l: usize, s: Sym| match s {
Sym::Red {
op: None,
src,
mask,
ident,
lanes,
} if lanes == 1 << l => Some((src, mask, ident)),
_ => None,
};
if let Some(m) = own(0, first)
&& lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m))
{
return Some(Shape::Masked(m.0, m.1, m.2));
}
if lanes.iter().all(|&s| s == first) {
return match first {
Sym::K(k) => Some(Shape::K(k)),
Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)),
Sym::Red {
op: Some(op),
src,
mask,
ident,
lanes,
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
_ => None,
};
}
// Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive).
let mut found: Option<(Op, Value, Value, u32, bool)> = None;
for (l, &s) in lanes.iter().enumerate() {
let below = (1u64 << l) - 1;
let (op, src, mask, ident, set) = match s {
Sym::Red {
op,
src,
mask,
ident,
lanes,
} => (op, src, mask, ident, lanes),
// Lane 0 of an exclusive prefix holds the identity.
Sym::K(_) if l == 0 => continue,
_ => return None,
};
let inclusive = set == below | 1 << l;
if !inclusive && set != below {
return None;
}
let op = match (op, found) {
(Some(o), _) => o,
(None, Some(f)) => f.0,
(None, None) => continue,
};
let me = (op, src, mask, ident, inclusive);
match found {
None => found = Some(me),
Some(f) if f == me => {}
_ => return None,
}
}
let (op, src, mask, ident, inclusive) = found?;
if let Sym::K(k) = lanes[0]
&& (inclusive || k != ident)
{
return None;
}
Some(Shape::Prefix(op, src, mask, ident, inclusive))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dpp_lanes_follow_the_isa() {
// row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16.
let shr = Dpp::Row {
ctrl: 0x111,
row_mask: 0xF,
bank_mask: 0xF,
bound_ctrl: true,
fi: false,
};
assert_eq!(dpp_lane(shr, 16), Some((16, true, true)));
assert_eq!(dpp_lane(shr, 17), Some((16, false, true)));
// row_mirror: lane 3 reads lane 12.
let mirror = Dpp::Row {
ctrl: 0x140,
row_mask: 0xF,
bank_mask: 0xF,
bound_ctrl: true,
fi: false,
};
assert_eq!(dpp_lane(mirror, 3), Some((12, false, true)));
// dpp8 [1,0,3,2,5,4,7,6] swaps neighbours.
let swap = Dpp::Lanes {
sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21,
fi: false,
};
assert_eq!(dpp_lane(swap, 8), Some((9, false, true)));
}
#[test]
fn prefixes_are_recognised() {
let (x, m) = (Value(1), Value(2));
let red = |lanes: u64| Sym::Red {
op: Some(Op::AddU),
src: x,
mask: m,
ident: 0,
lanes,
};
let inclusive: Vec<Sym> = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect();
assert_eq!(
per_lane(&inclusive, u64::MAX),
Some(Shape::Prefix(Op::AddU, x, m, 0, true))
);
let mut exclusive: Vec<Sym> = (0..64).map(|l| red((1u64 << l) - 1)).collect();
exclusive[0] = Sym::K(0);
assert_eq!(
per_lane(&exclusive, u64::MAX),
Some(Shape::Prefix(Op::AddU, x, m, 0, false))
);
assert_eq!(
per_lane(&vec![red(u64::MAX); 64], u64::MAX),
Some(Shape::Active(Op::AddU, x, m, 0))
);
}
}
+693
View File
@@ -0,0 +1,693 @@
//! I/O raising (decision 0003): what a program's input registers, its
//! interpolation and its exports mean.
//!
//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
//! order (barycentrics, then position, front face...). `v_interp_p1` and
//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
//! export patch ([`NativeProgram::patched_code`]) exports carry plain
//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
//! export that ends the program (`done`) is discarded: that export's guard
//! after structurisation.
//!
//! Vertex shaders that run as the hardware VS get the vertex id in v0, the
//! primitive id in v2 and the instance id in v3; the fetch shader loads
//! channel k of each attribute into its VGPR + k. `exp pos0` is the
//! position, `exp param<n>` the output with parameter n.
//!
//! Attributes and outputs are named by their row: a register of the
//! container's signature part.
//!
//! Compute programs get the thread id in the group in v0-v2 and the group
//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
//!
//! Mesh programs run as one NGG stage. The program computes its thread
//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
//! its group id from v5 of the first lane (`v_readfirstlane`: the group
//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
//! primitives << 12).
use crate::ShaderError;
use crate::gfx10::{Fields, Operand};
use crate::ir::{Inst, Program, Reg, Value};
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
use crate::resource::Site;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Input {
VertexId,
PrimitiveId,
InstanceId,
/// A vertex attribute the fetch shader loads.
Attribute {
row: u8,
channel: u8,
},
/// `index` 0 is i, 1 is j (2 the pull model's w).
Barycentric {
kind: Barycentric,
index: u8,
},
/// Pixel position channel (0-3: x, y, z, w).
Position(u8),
FrontFace,
/// Sample id and other bits.
Ancillary,
SampleCoverage,
FixedPosition,
LineStipple,
/// Compute: thread-group id component (an SGPR).
GroupId(u8),
/// Compute: thread id within the group, component (a VGPR).
ThreadIdInGroup(u8),
/// Compute: the thread-group info SGPR (wave index and count).
GroupInfo,
/// Mesh: v5, the group id times the group size (read as uniform).
MeshGroup,
/// Mesh: s3, the wave's index in the group in bits 24-27.
MergedWaveInfo,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Barycentric {
PerspectiveSample,
PerspectiveCenter,
PerspectiveCentroid,
PerspectivePullModel,
LinearSample,
LinearCenter,
LinearCentroid,
}
/// The pixel input VGPRs in hardware order: one entry per
/// `SPI_PS_INPUT_ADDR` bit.
const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
(2, Some(Barycentric::PerspectiveSample)),
(2, Some(Barycentric::PerspectiveCenter)),
(2, Some(Barycentric::PerspectiveCentroid)),
(3, Some(Barycentric::PerspectivePullModel)),
(2, Some(Barycentric::LinearSample)),
(2, Some(Barycentric::LinearCenter)),
(2, Some(Barycentric::LinearCentroid)),
(1, None), // line stipple
(1, None), // position x
(1, None), // y
(1, None), // z
(1, None), // w
(1, None), // front face
(1, None), // ancillary
(1, None), // sample coverage
(1, None), // fixed-point position
];
fn ps_system(bit: usize) -> Input {
match bit {
7 => Input::LineStipple,
8..=11 => Input::Position(bit as u8 - 8),
12 => Input::FrontFace,
13 => Input::Ancillary,
14 => Input::SampleCoverage,
_ => Input::FixedPosition,
}
}
/// An attribute channel of the input signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Attribute {
pub usage: Usage,
pub row: u8,
pub channel: u8,
/// The upper f16 half of the channel (packed fp16 inputs).
pub high: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Interp {
/// This site's result (`v_interp_p2*`) is the attribute interpolated
/// with `barycentric`; `first` are the `v_interp_p1*` halves it
/// completes (one per path where the compiler shares a first half).
Interpolated {
attribute: Attribute,
barycentric: Barycentric,
first: Vec<Site>,
},
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
/// 1 for P20, 2 for P0 (the provoking vertex).
Vertex { attribute: Attribute, vertex: u8 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
Color(u8),
/// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
Depth,
Null,
Position(u8),
Param {
usage: Usage,
row: u8,
},
/// `param0` of a vertex shader without outputs: the hardware wants one
/// parameter export regardless.
Unread,
/// The primitive export of a merged or mesh stage.
Primitive,
/// A mesh program's per-primitive output (a row of `PSG1`).
PrimitiveParam {
usage: Usage,
row: u8,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Export {
pub site: Site,
pub target: Target,
/// Per channel, as the instruction enables them.
pub values: [Option<Value>; 4],
/// Two f16 values per dword.
pub compressed: bool,
/// The program's last export (for pixels: kills the lanes not in EXEC).
pub done: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Io {
/// Input values the hardware loads, with their meaning; other VGPRs
/// read before written hold undefined values.
pub inputs: Vec<(Value, Input)>,
pub interps: Vec<(Site, Interp)>,
pub exports: Vec<Export>,
}
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
/// stages whose stage data is not read and on constructs not covered yet.
pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
(
StageIo::Ps {
inputs, input_addr, ..
},
HwStage::Ps,
) => {
// A pixel shader exports no parameters; `[]` never reaches `Unread`.
let loaded = ps_vgprs(*input_addr)
.into_iter()
.map(|(r, i)| (Reg::V(r), i))
.collect();
(loaded, &inputs[..], &[][..])
}
(StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
let mut loaded = vec![
(Reg::V(0), Input::VertexId),
(Reg::V(2), Input::PrimitiveId),
(Reg::V(3), Input::InstanceId),
];
for i in inputs {
for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
let input = Input::Attribute {
row: i.row,
channel,
};
loaded.push((Reg::V(i.vgpr + channel), input));
}
}
(loaded, &[][..], &outputs[..])
}
// Compute: thread ids in v0-v2, group ids and the group info in the
// SGPRs after the user data.
(StageIo::Cs(cs), HwStage::Cs) => {
let (ids, info) = cs.system_sgprs();
let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
.map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
.collect();
for (c, s) in ids.into_iter().enumerate() {
if let Some(s) = s {
loaded.push((Reg::S(s), Input::GroupId(c as u8)));
}
}
loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
(loaded, &[][..], &[][..])
}
(StageIo::Ms(ms), HwStage::Ms) => {
let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1);
// The group input holds the same value in every lane only as the
// first lane reads it; a VGPR write reads its old value too.
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g)))
&& i.name() != "v_readfirstlane_b32"
&& i.write(Reg::V(5)).is_none()
});
if let Some(i) = per_lane {
return Err(unsupported(
i.machine.offset,
"the mesh group input read per lane",
));
}
let loaded = vec![
(Reg::V(5), Input::MeshGroup),
(Reg::S(3), Input::MergedWaveInfo),
];
(loaded, &[][..], &ms.outputs[..])
}
_ => return Err(unsupported(0, "I/O of this stage")),
};
let inputs: Vec<(Value, Input)> = p
.inputs
.iter()
.filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
.collect();
let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
let attribute = |inst: &Inst, attr: &Operand| match *attr {
Operand::Attr { index, chan, high } => ps_inputs
.iter()
.find(|i: &&PsInput| i.attr == index)
.map(|i| Attribute {
usage: i.usage,
row: i.row,
channel: chan,
high,
})
.ok_or(unsupported(
inst.machine.offset,
"an interpolated attribute the stage data does not list",
)),
_ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
};
// A VGPR value's barycentric kind and index, if it is one as loaded.
let barycentric = |v: Option<Value>| match v.and_then(input_of) {
Some(Input::Barycentric { kind, index }) => Some((kind, index)),
_ => None,
};
let mut io = Io {
inputs: inputs.clone(),
..Io::default()
};
let defs: std::collections::HashMap<Value, Site> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.insts
.iter()
.enumerate()
.flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
})
.collect();
let phis: std::collections::HashMap<Value, (usize, usize)> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.phis
.iter()
.enumerate()
.map(move |(i, phi)| (phi.value, (b, i)))
})
.collect();
let halves = Halves {
p,
defs: &defs,
phis: &phis,
};
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i);
let at = inst.machine.offset;
let name = inst.name();
match &inst.fields {
Fields::Vintrp { dst, src, attr } => {
let attribute = attribute(inst, attr)?;
match (name, *src) {
("v_interp_mov_f32", Operand::Const(vertex)) => {
io.interps
.push((site, Interp::Vertex { attribute, vertex }));
}
("v_interp_p1_f32", _) => {}
("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
let Operand::Vector { reg: d, .. } = *dst else {
return Err(unsupported(at, "an interpolation operand"));
};
// The first half's result is this one's old dst.
let interp = halves
.pair(
attr,
inst.read(Reg::V(d)),
inst.read(Reg::V(reg)),
&barycentric,
)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
}
_ => return Err(unsupported(at, "an interpolation form")),
}
}
Fields::Valu(v) if name.starts_with("v_interp_") => match name {
"v_interp_p1ll_f16" => {}
"v_interp_p2_f16" => {
let attribute = attribute(inst, &v.src[0])?;
let read = |k: usize| match v.src.get(k) {
Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
};
let interp = halves
.pair(&v.src[0], read(2), read(1), &barycentric)
.map_err(|what| unsupported(at, what))?;
io.interps.push((site, interp.with(attribute)));
}
_ => return Err(unsupported(at, "an interpolation form")),
},
Fields::Exp {
target,
src,
compr,
done,
..
} => {
let target = match *target {
t @ 0..=7 => Target::Color(t),
8 => Target::Depth,
9 => Target::Null,
t @ 12..=16 => Target::Position(t - 12),
20 => Target::Primitive,
32 if params.is_empty() => Target::Unread,
t @ 32..=63 => {
// Bit 7: a mesh program's per-primitive output.
let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
unsupported(at, "a parameter export the stage data does not list"),
)?;
let (usage, row) = (o.usage, o.row);
if o.param & 0x80 != 0 {
Target::PrimitiveParam { usage, row }
} else {
Target::Param { usage, row }
}
}
_ => return Err(unsupported(at, "an export target")),
};
let values = src.map(|s| match s {
Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
});
io.exports.push(Export {
site,
target,
values,
compressed: *compr,
done: *done,
});
}
_ => {}
}
}
}
Ok(io)
}
/// The pixel input VGPRs that `addr` enables, with their meaning.
fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
let mut out = Vec::new();
let mut next = 0u8;
for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
if addr >> bit & 1 == 0 {
continue;
}
for index in 0..count {
let input = match kind {
Some(kind) => Input::Barycentric { kind, index },
None => ps_system(bit),
};
out.push((next + index, input));
}
next += count;
}
out
}
/// An interpolation before its attribute is known.
struct Pair {
barycentric: Barycentric,
first: Vec<Site>,
}
impl Pair {
fn with(self, attribute: Attribute) -> Interp {
Interp::Interpolated {
attribute,
barycentric: self.barycentric,
first: self.first,
}
}
}
/// Finds the first halves of interpolations.
struct Halves<'a> {
p: &'a Program,
defs: &'a std::collections::HashMap<Value, Site>,
phis: &'a std::collections::HashMap<Value, (usize, usize)>,
}
impl Halves<'_> {
/// The interpolation whose second half reads the first half's result
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
/// must read the same attribute channel and the same kind's i.
fn pair(
&self,
attr: &Operand,
acc: Option<Value>,
j: Option<Value>,
barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
) -> Result<Pair, &'static str> {
let mut first = Vec::new();
self.sites(
acc.ok_or("an interpolation without its first half")?,
&mut Vec::new(),
&mut first,
)?;
let Some((kind, 1)) = barycentric(j) else {
return Err("an interpolation with computed barycentrics");
};
for &(b, i) in &first {
let inst = &self.p.blocks[b].insts[i];
let (a, i) = match &inst.fields {
Fields::Vintrp {
src: Operand::Vector { reg, .. },
attr,
..
} if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
_ => return Err("an interpolation without its first half"),
},
_ => return Err("an interpolation without its first half"),
};
if a != *attr {
return Err("interpolation halves of different attributes");
}
if barycentric(i) != Some((kind, 0)) {
return Err("an interpolation with computed barycentrics");
}
}
Ok(Pair {
barycentric: kind,
first,
})
}
/// The instructions `v` comes from, through phis (`seen`: phis on the
/// way; a loop back to one adds nothing).
fn sites(
&self,
v: Value,
seen: &mut Vec<Value>,
out: &mut Vec<Site>,
) -> Result<(), &'static str> {
if let Some(&site) = self.defs.get(&v) {
if !out.contains(&site) {
out.push(site);
}
return Ok(());
}
let &(b, i) = self
.phis
.get(&v)
.ok_or("an interpolation without its first half")?;
if !seen.contains(&v) {
seen.push(v);
for &a in &self.p.blocks[b].phis[i].args {
self.sites(a, seen, out)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::native::ExportPatch;
const S_ENDPGM: u32 = 0xBF81_0000;
fn program(words: &[u32]) -> Program {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
crate::ir::build(&code, false, 256).unwrap()
}
fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs,
input_addr,
db_shader_control: 0,
patches: Vec::<ExportPatch>::new(),
},
code: vec![],
}
}
const TEXCOORD: PsInput = PsInput {
usage: Usage::Generic,
row: 1,
mask: 3,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 1,
};
#[test]
fn interpolation_pairs_and_color_exports() {
// Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
// in v0/v1, then exported unconverted to MRT0.
let p = program(&[
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xF800_180F,
0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
S_ENDPGM,
]);
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
let center = |index| Input::Barycentric {
kind: Barycentric::PerspectiveCenter,
index,
};
assert!(io.inputs.contains(&(input(0), center(0))));
assert!(io.inputs.contains(&(input(1), center(1))));
// v2 and v3 are read before written but hold nothing.
assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
assert_eq!(
io.interps,
[(
(0, 1),
Interp::Interpolated {
attribute: Attribute {
usage: Usage::Generic,
row: 1,
channel: 0,
high: false
},
barycentric: Barycentric::PerspectiveCenter,
first: vec![(0, 0)],
}
)]
);
let [e] = &io.exports[..] else {
panic!("{:?}", io.exports)
};
assert_eq!(
(e.target, e.done, e.compressed),
(Target::Color(0), true, false)
);
assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
}
#[test]
fn unpaired_or_unknown_interpolation_fails() {
// p2 alone: its old dst is no p1's result.
let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
// attr1 is not in the stage data.
let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
}
#[test]
fn mesh_inputs_and_primitive_export() {
let mesh = |words: &[u32]| {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let p = crate::ir::build(&code, true, 256).unwrap();
let native = NativeProgram {
stage: HwStage::Ms,
wave64: true,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ms(crate::native::MeshIo {
outputs: vec![],
clip_cntl: 0,
threads: 128,
max_vertices: 128,
max_primitives: 128,
topology: 2,
lds_bytes: 0,
}),
code,
};
raise(&p, &native)
};
let io = mesh(&[
0x7E04_0505, // v_readfirstlane_b32 s2, v5
0xF800_0941,
0x0000_0009, // exp prim, v9, off, off, off done
S_ENDPGM,
])
.unwrap();
assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
assert_eq!(io.exports[0].target, Target::Primitive);
// The group input is uniform only as the first lane reads it.
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
}
#[test]
fn pixel_vgprs_follow_the_input_address() {
// Linear center (bit 5), then position x and y (bits 8, 9).
let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
assert_eq!(
v,
[
(
0,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 0
}
),
(
1,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 1
}
),
(2, Input::Position(0)),
(3, Input::Position(1)),
]
);
}
}
+52 -15
View File
@@ -360,7 +360,32 @@ pub(crate) fn irreducible_edge(
index: &[usize],
) -> Option<(usize, usize)> {
let &entry = order.first()?;
let idom = idoms(blocks, order, index);
for &b in order {
for s in blocks[b].exit.successors() {
if index[s] > index[b] {
continue;
}
let mut d = b;
while d != s && d != entry {
d = idom[d];
}
if d != s {
return Some((b, s));
}
}
}
None
}
/// Each block's immediate dominator (the entry's is itself, unreachable
/// blocks' `usize::MAX`); `order` is reverse postorder, `index` each
/// block's position in it.
pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> {
let mut idom = vec![usize::MAX; blocks.len()];
let Some(&entry) = order.first() else {
return idom;
};
idom[entry] = entry;
let intersect = |idom: &[usize], mut a: usize, mut b: usize| {
while a != b {
@@ -391,21 +416,7 @@ pub(crate) fn irreducible_edge(
}
}
}
for &b in order {
for s in blocks[b].exit.successors() {
if index[s] > index[b] {
continue;
}
let mut d = b;
while d != s && d != entry {
d = idom[d];
}
if d != s {
return Some((b, s));
}
}
}
None
idom
}
/// Node splitting, before SSA. While a loop is entered at several blocks
@@ -692,6 +703,13 @@ fn effects(
}
if let Some(d) = dst {
regs(d, &mut w)?;
// These change (or may keep) the destination's old value.
if name.starts_with("s_bitset")
|| name.starts_with("s_cmov")
|| matches!(name, "s_addk_i32" | "s_mulk_i32")
{
regs(d, &mut r)?;
}
}
if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32")
|| name.starts_with("s_cselect_")
@@ -1063,6 +1081,25 @@ mod tests {
}
}
#[test]
fn in_place_scalar_ops_read_their_destination() {
let p = build_words(
&[
0xBE8D_1D94, // s_bitset1_b32 s13, 20
0xB78E_0010, // s_addk_i32 s14, 0x10
0xBE8F_0380, // s_mov_b32 s15, 0
S_ENDPGM,
],
false,
);
let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else {
panic!("{:?}", p.blocks[0].insts)
};
assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13))));
assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14))));
assert_eq!(mov.read(Reg::S(15)), None);
}
#[test]
fn loops_carry_values_through_phis() {
let p = build_words(
+6 -1
View File
@@ -8,14 +8,19 @@
pub mod dxbc;
pub mod dxil;
pub mod emit;
pub mod gfx10;
pub mod io;
pub mod ir;
pub mod native;
pub mod resource;
pub mod structure;
pub use dxbc::{Container, FourCC, Part};
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
pub use native::{HwStage, NativeProgram, native_programs};
pub use native::{
HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs,
};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ShaderError {
+682 -5
View File
@@ -17,9 +17,52 @@
//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative),
//! +0x14 u32 flags: bit 5 wave32 (else wave64)
//! +0x28 u64 root layout table, +0x30 u64 used-resource table
//! (payload-relative), +0x38 u32 and +0x3c u32 their counts
//! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used
//! layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs,
//! u32 base register, u8 first user-data dword, u8 root slot,
//! u16 0
//! used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset
//! (dwords), u32 lower bound, u32 stride, u8 descriptor
//! dwords, u8 first user-data dword, u8 root slot, u8 0
//! ```
//!
//! Stage data follows the record; offsets from its end (E = record + 0x54):
//!
//! ```text
//! PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel
//! mask, u8 attribute (v_interp `attr`), u8 default, u8 second
//! row (of a packed pair), u8 parameter slot, u8 flags (bit 0
//! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count
//! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL
//! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per
//! MRT: u32 code offset (dwords, -1 none), then the export code
//! for each color format in 10 slots of 10 dwords (ZERO, 32_R,
//! 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR)
//! VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR
//! of channel 0 (channel k in VGPR + k), u8 highest channel;
//! E+0xc4 u32 count
//! E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp
//! param<n>`), u8 row again, u8 slot, u8 flags (bit 0 fp16,
//! bit 1 two fp16 values per dword); E+0x188 u32 count
//! CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size
//! MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a
//! per-primitive output (`PSG1` row); the 3 bytes more are the
//! second row of a packed pair, a slot, flags (bit 0 fp16, bit 1
//! two fp16 elements packed)
//! E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT,
//! PA_CL_VS_OUT_CNTL, VGT_STRMOUT_CONFIG, SPI_SHADER_PGM_RSRC2_GS,
//! VGT_GS_OUT_PRIM_TYPE, VGT_GS_INSTANCE_CNT, SPI_SHADER_IDX_FORMAT
//! E+0x448 u16 thread-group size in lanes, u16 maximum vertices,
//! u16 maximum primitives, u8 user SGPRs, u8 output topology
//! (2 triangles); code follows at E+0x45c
//! record +0x4c u32 LDS bytes (`lds_byte_size`; mesh programs read it here)
//! ```
//!
//! Rows are registers of the container's signature parts (`ISG1`, `OSG1`).
//! Merged stages keep their stage data in another layout (not read).
//!
//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and
//! 0x12 16-byte blobs (0x10 is the shader hash).
@@ -52,6 +95,31 @@ const RECORD_SIZE: u64 = 0x54;
const RECORD_FLAGS: usize = 0x14;
const FLAG_WAVE32: u32 = 1 << 5;
const RECORD_REGS: usize = 0x50;
const RECORD_LAYOUT: usize = 0x28;
const RECORD_USED: usize = 0x30;
const RECORD_COUNTS: usize = 0x38;
const ENTRY_SIZE: u64 = 20;
const MAX_SEMANTICS: u32 = 32;
const PS_INPUTS: usize = 0x24;
const PS_INPUT_COUNT: usize = 0x124;
const PS_INPUT_ADDR: usize = 0x134;
const PS_DB_SHADER_CONTROL: usize = 0x138;
const PS_PATCH_SIZE: usize = 0x148;
const PS_PATCHES: usize = 0x14c;
const PATCH_SLOT_DWORDS: usize = 10;
/// The variant that exports every channel as a raw 32-bit value.
const PATCH_FULL: usize = 9;
const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4;
const MRTS: usize = 8;
const VS_INPUTS: usize = 0x24;
const VS_INPUT_COUNT: usize = 0xc4;
const VS_OUTPUTS: usize = 0xc8;
const VS_OUTPUT_COUNT: usize = 0x188;
const CS_RSRC2: usize = 0x24;
const CS_THREADS: usize = 0x28;
const RECORD_LDS: usize = 0x4c;
const MS_CLIP_CNTL: usize = 0x194;
const MS_INFO: usize = 0x448;
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
const MAX_UNPACKED: u64 = 16 << 20;
@@ -69,6 +137,17 @@ pub enum HwStage {
Cs,
}
impl HwStage {
/// The SGPR holding user-data dword `index`: merged stages (and mesh
/// shaders, which run as one) have 8 system SGPRs first.
pub fn user_sgpr(self, index: u8) -> u8 {
match self {
HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8,
HwStage::Vs | HwStage::Ps | HwStage::Cs => index,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeProgram {
pub stage: HwStage,
@@ -76,10 +155,251 @@ pub struct NativeProgram {
pub wave64: bool,
/// VGPRs the program uses (v0 up to this), the bound of indexed access.
pub vgprs: u16,
/// GFX10 machine code.
/// Where the root signature's parameters arrive (user SGPRs).
pub layout: Vec<RootParam>,
/// The descriptors the program reads, by root parameter.
pub used: Vec<UsedResource>,
pub io: StageIo,
/// GFX10 machine code, as stored.
pub code: Vec<u8>,
}
impl NativeProgram {
/// The code with each render target's export patched for its full
/// 32-bit format, so exports carry the shader's values unconverted (as
/// the console does at pipeline creation for that format).
pub fn patched_code(&self) -> Vec<u8> {
let mut code = self.code.clone();
if let StageIo::Ps { patches, .. } = &self.io {
for p in patches {
let at = p.offset as usize * 4;
for (i, word) in p.code.iter().enumerate() {
code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes());
}
}
}
code
}
}
/// What a semantic is, as the stage data names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Usage {
Generic,
ClipDistance,
Other(u8),
}
impl Usage {
fn from_raw(raw: u8) -> Self {
match raw {
6 => Usage::Generic,
7 => Usage::ClipDistance,
n => Usage::Other(n),
}
}
}
/// A pixel shader input: what `v_interp` of attribute `attr` reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PsInput {
pub usage: Usage,
/// Register in the input signature.
pub row: u8,
pub mask: u8,
pub attr: u8,
pub flat: bool,
pub fp16: bool,
/// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the
/// second element's register.
pub pack2: bool,
pub row2: u8,
}
/// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VsInput {
pub usage: Usage,
pub row: u8,
pub mask: u8,
pub vgpr: u8,
}
/// What `exp param<param>` of a vertex shader writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VsOutput {
pub usage: Usage,
/// Register in the output signature.
pub row: u8,
pub param: u8,
/// 16-bit values, one per dword (low half) unless `pack2`: then two per
/// dword, channel c of this row in dword c / 2 (odd channels in the
/// high half), then a second 16-bit row from the next whole dword (the
/// next 16-bit row of the signature no entry names).
pub fp16: bool,
pub pack2: bool,
}
/// The export code of one render target for its full 32-bit format.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExportPatch {
pub mrt: u8,
/// Where it goes in the code, in dwords.
pub offset: u32,
pub code: Vec<u32>,
}
/// Inputs and outputs, for the stages whose stage data is read.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum StageIo {
#[default]
None,
Vs {
inputs: Vec<VsInput>,
outputs: Vec<VsOutput>,
},
Ps {
inputs: Vec<PsInput>,
/// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs.
input_addr: u32,
/// `DB_SHADER_CONTROL`: depth export, kill.
db_shader_control: u32,
patches: Vec<ExportPatch>,
},
Cs(ComputeIo),
Ms(MeshIo),
}
/// A mesh program's outputs and limits. It runs as one hardware NGG stage:
/// lane n of the group (`threads` lanes) exports vertex n (`exp pos`,
/// `exp param`) and primitive n (`exp prim`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeshIo {
/// `exp param<n>` targets; `param` bit 7 set: a per-primitive output,
/// `row` then a row of the primitive signature (`PSG1`).
pub outputs: Vec<VsOutput>,
/// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry.
pub clip_cntl: u32,
/// Thread-group size in lanes (the HLSL group rounded up to waves).
pub threads: u32,
pub max_vertices: u32,
pub max_primitives: u32,
/// 1 lines, 2 triangles.
pub topology: u8,
pub lds_bytes: u32,
}
/// A compute program's dispatch settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ComputeIo {
/// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs
/// follow them, LDS size.
pub rsrc2: u32,
/// Thread-group size (`numthreads`).
pub threads: [u32; 3],
}
impl ComputeIo {
/// User SGPRs before the system ones.
pub fn user_sgprs(&self) -> u8 {
(self.rsrc2 >> 1 & 0x1F) as u8
}
/// The SGPR of each enabled thread-group id component, in order after
/// the user SGPRs, then the thread-group info SGPR if enabled.
pub fn system_sgprs(&self) -> ([Option<u8>; 3], Option<u8>) {
let mut next = self.user_sgprs();
let mut take = |bit: u32| {
(self.rsrc2 >> bit & 1 != 0).then(|| {
next += 1;
next - 1
})
};
let ids = [take(7), take(8), take(9)];
(ids, take(10))
}
/// Thread id components in v0, v1, v2 (1 to 3).
pub fn thread_id_vgprs(&self) -> u8 {
(self.rsrc2 >> 11 & 3) as u8 + 1
}
/// LDS bytes per thread group (512-byte granules).
pub fn lds_bytes(&self) -> u32 {
(self.rsrc2 >> 15 & 0x1FF) * 512
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RootType {
Constants,
/// A 64-bit buffer address.
Descriptor,
/// The 32-bit heap address of a descriptor table range.
Table,
/// A sampler the root signature fixes.
ImmediateSampler,
/// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources).
ResourceHeap,
/// The 32-bit address of the sampler heap.
SamplerHeap,
Other(u32),
}
impl RootType {
fn from_raw(raw: u32) -> Self {
match raw {
0 => RootType::Constants,
1 => RootType::Descriptor,
3 => RootType::Table,
4 => RootType::ImmediateSampler,
5 => RootType::ResourceHeap,
6 => RootType::SamplerHeap,
n => RootType::Other(n),
}
}
}
/// One root parameter (or table range) and the user SGPRs holding it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RootParam {
pub root: RootType,
/// Of the range within its table.
pub table_offset_dwords: u32,
/// User SGPRs from `user_data` on.
pub sgprs: u32,
/// Shader register of the first descriptor (`b`/`t`/`u`/`s` number).
pub base_register: u32,
/// First user-data dword ([`HwStage::user_sgpr`]).
pub user_data: u8,
/// Index of the parameter in the root signature.
pub slot: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ResourceType {
Srv,
Sampler,
Cbv,
Uav,
Other(u8),
}
/// A descriptor range the program reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UsedResource {
pub kind: ResourceType,
pub root: RootType,
pub table_offset_dwords: u32,
/// Shader register of the first descriptor read.
pub lower_bound: u32,
pub stride: u32,
/// Size of the descriptor (4 or 8).
pub dwords: u8,
pub user_data: u8,
pub slot: u8,
}
/// The native programs in a `DXIL` part's data; empty for the PC layout.
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
@@ -141,28 +461,198 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
}
let mut out = Vec::new();
for (stage, at) in SLOTS {
let record = u64_at(payload, at)?;
if record == ABSENT {
let start = u64_at(payload, at)?;
if start == ABSENT {
continue;
}
let record =
bytes(payload, record, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
.ok_or(Malformed("native code out of bounds"))?;
let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16;
if vgprs > 256 {
return Err(Malformed("implausible VGPR count"));
}
let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> {
let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?);
if len == 0 {
return Ok(&[]);
}
bytes(payload, u64_at(record, at)?, len)
.ok_or(Malformed("FSSM root table out of bounds"))
};
let layout = table(RECORD_LAYOUT, RECORD_COUNTS)?
.as_chunks::<{ ENTRY_SIZE as usize }>()
.0
.iter()
.map(|e| RootParam {
root: RootType::from_raw(le32(e, 0)),
table_offset_dwords: le32(e, 4),
sgprs: le32(e, 8),
base_register: le32(e, 12),
user_data: e[16],
slot: e[17],
})
.collect();
let used = table(RECORD_USED, RECORD_COUNTS + 4)?
.as_chunks::<{ ENTRY_SIZE as usize }>()
.0
.iter()
.map(|e| UsedResource {
kind: match e[0] {
0 => ResourceType::Srv,
1 => ResourceType::Sampler,
2 => ResourceType::Cbv,
3 => ResourceType::Uav,
n => ResourceType::Other(n),
},
root: RootType::from_raw(e[1].into()),
table_offset_dwords: le32(e, 4),
lower_bound: le32(e, 8),
stride: le32(e, 12),
dwords: e[16],
user_data: e[17],
slot: e[18],
})
.collect();
// The record is in bounds, so its end is too.
let stage_data = &payload[(start + RECORD_SIZE) as usize..];
let io = match stage {
HwStage::Ps => ps_io(stage_data, code.len())?,
HwStage::Vs => vs_io(stage_data)?,
HwStage::Cs => StageIo::Cs(ComputeIo {
rsrc2: u32_at(stage_data, CS_RSRC2)?,
threads: [
u32_at(stage_data, CS_THREADS)?,
u32_at(stage_data, CS_THREADS + 4)?,
u32_at(stage_data, CS_THREADS + 8)?,
],
}),
HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?,
_ => StageIo::None,
};
out.push(NativeProgram {
stage,
wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0,
vgprs,
layout,
used,
io,
code: code.to_vec(),
});
}
Ok(out)
}
/// The entries of `size` bytes from `at`, with their count at `count_at`.
fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> {
let count = u32_at(data, count_at)?;
if count > MAX_SEMANTICS {
return Err(Malformed("implausible semantic count"));
}
data.get(at..at + size * count as usize)
.ok_or(Malformed("stage data out of bounds"))
}
fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> {
let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)?
.as_chunks::<8>()
.0
.iter()
.map(|e| PsInput {
usage: Usage::from_raw(e[0]),
row: e[1],
mask: e[2] & 0xf,
attr: e[3],
flat: e[7] & 1 != 0,
fp16: e[7] & 8 != 0,
pack2: e[7] & 0x10 != 0,
row2: e[5],
})
.collect();
let size = u32_at(data, PS_PATCH_SIZE)? as usize;
if size > PATCH_SLOT_DWORDS {
return Err(Malformed("implausible export patch size"));
}
let mut patches = Vec::new();
for mrt in 0..MRTS {
let at = PS_PATCHES + mrt * PATCH_BYTES;
let offset = u32_at(data, at)?;
if offset == u32::MAX {
continue;
}
if (offset as usize + size) * 4 > code_len {
return Err(Malformed("export patch outside the code"));
}
let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
let code = (0..size)
.map(|i| u32_at(data, full + 4 * i))
.collect::<Result<_, _>>()?;
patches.push(ExportPatch {
mrt: mrt as u8,
offset,
code,
});
}
Ok(StageIo::Ps {
inputs,
input_addr: u32_at(data, PS_INPUT_ADDR)?,
db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?,
patches,
})
}
fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> {
let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)?
.as_chunks::<5>()
.0
.iter()
.map(|e| VsInput {
usage: Usage::from_raw(e[0]),
row: e[1],
mask: e[2] & 0xf,
vgpr: e[3],
})
.collect();
let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)?
.as_chunks::<6>()
.0
.iter()
.map(|e| VsOutput {
usage: Usage::from_raw(e[0]),
row: e[1],
param: e[2],
fp16: e[5] & 1 != 0,
pack2: e[5] & 2 != 0,
})
.collect();
Ok(StageIo::Vs { inputs, outputs })
}
fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> {
let StageIo::Vs { outputs, .. } = vs_io(data)? else {
unreachable!()
};
let info = data
.get(MS_INFO..MS_INFO + 8)
.ok_or(Malformed("stage data out of bounds"))?;
let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]]));
Ok(StageIo::Ms(MeshIo {
outputs,
clip_cntl: u32_at(data, MS_CLIP_CNTL)?,
threads: half(0),
max_vertices: half(2),
max_primitives: half(4),
topology: info[7],
lds_bytes,
}))
}
/// For entries already sized by `as_chunks`.
fn le32(entry: &[u8], at: usize) -> u32 {
u32::from_le_bytes(entry[at..at + 4].try_into().unwrap())
}
/// `data[offset..offset + len]` with untrusted 64-bit bounds.
fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
@@ -181,6 +671,25 @@ mod tests {
SLOTS.iter().find(|s| s.0 == stage).unwrap().1
}
/// Stage data: no semantics, and every export patch absent.
const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES;
fn empty_stage_data() -> Vec<u8> {
let mut data = vec![0; STAGE_DATA];
for mrt in 0..MRTS {
let at = PS_PATCHES + mrt * PATCH_BYTES;
data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
}
data
}
/// Where a one-program blob's stage data starts.
fn stage_data_at(blob: &[u8], stage: HwStage) -> usize {
FSSM_HEADER
+ u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize
+ RECORD_SIZE as usize
}
/// FSSM blob with `programs` as (stage, code) pairs.
fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> {
let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec();
@@ -192,13 +701,15 @@ mod tests {
let slot = slot(stage);
let record = payload.len() as u64;
payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
payload.extend_from_slice(&(record + RECORD_SIZE).to_le_bytes());
let code_at = record + RECORD_SIZE + STAGE_DATA as u64;
payload.extend_from_slice(&code_at.to_le_bytes());
payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 };
payload.extend_from_slice(&[0; 4]);
payload.extend_from_slice(&flags.to_le_bytes());
payload.resize(record as usize + RECORD_REGS, 0);
payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes());
payload.extend_from_slice(&empty_stage_data());
payload.extend_from_slice(code);
}
let mut out = b"FSSM".to_vec();
@@ -249,18 +760,131 @@ mod tests {
stage: HwStage::Vs,
wave64: true,
vgprs: 28,
layout: vec![],
used: vec![],
io: StageIo::Vs {
inputs: vec![],
outputs: vec![],
},
code: VS_CODE.to_vec()
},
NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 28,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs: vec![],
input_addr: 0,
db_shader_control: 0,
patches: vec![],
},
code: PS_CODE.to_vec()
},
]
);
}
#[test]
fn reads_root_tables() {
let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]);
let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize;
let tables = (blob.len() - FSSM_HEADER) as u64;
// A table range in s9 (root slot 1), and an SRV read from it.
for v in [3u32, 2, 1, 5] {
blob.extend_from_slice(&v.to_le_bytes());
}
blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]);
for v in [2u32, 5, 4] {
blob.extend_from_slice(&v.to_le_bytes());
}
blob.extend_from_slice(&[8, 9, 1, 0]);
let payload = (blob.len() - FSSM_HEADER) as u64;
blob[8..16].copy_from_slice(&payload.to_le_bytes());
blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes());
blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes());
blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]);
let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
assert_eq!(
p.layout,
[RootParam {
root: RootType::Table,
table_offset_dwords: 2,
sgprs: 1,
base_register: 5,
user_data: 9,
slot: 1
}]
);
assert_eq!(
p.used,
[UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 2,
lower_bound: 5,
stride: 4,
dwords: 8,
user_data: 9,
slot: 1
}]
);
blob[record + RECORD_COUNTS] = 9;
assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
}
#[test]
fn reads_pixel_io_and_applies_the_full_export_patch() {
let code = [0xBF80_0000u32; 4]; // s_nop
let bytes: Vec<u8> = code.iter().flat_map(|w| w.to_le_bytes()).collect();
let mut blob = fssm(&[(HwStage::Ps, &bytes)]);
let e = stage_data_at(&blob, HwStage::Ps);
// TEXCOORD in row 1 (xy), read as attr0, flat.
blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]);
blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes());
blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes());
blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes());
// MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`.
let patch = e + PS_PATCHES + PATCH_BYTES;
blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes());
let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
let StageIo::Ps {
inputs,
input_addr,
patches,
..
} = &p.io
else {
panic!("{:?}", p.io)
};
let input = PsInput {
usage: Usage::Generic,
row: 1,
mask: 3,
attr: 0,
flat: true,
fp16: false,
pack2: false,
row2: 0,
};
assert_eq!((&inputs[..], *input_addr), (&[input][..], 2));
assert_eq!(patches.len(), 1);
assert_eq!((patches[0].mrt, patches[0].offset), (1, 1));
let patched = p.patched_code();
assert_eq!(patched[..4], p.code[..4]);
assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
assert_eq!(patched[12..], p.code[12..]);
blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes());
assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
}
#[test]
fn finds_mesh_and_compute_programs() {
for stage in [HwStage::Ms, HwStage::Cs] {
@@ -271,6 +895,59 @@ mod tests {
}
}
#[test]
fn reads_mesh_outputs_and_limits() {
let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]);
let e = stage_data_at(&blob, HwStage::Ms);
// param0 is row 1 per vertex, param2 row 0 of the primitive signature.
blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]);
blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes());
blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes());
// 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles.
blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]);
let record = e - RECORD_SIZE as usize;
blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes());
let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
let out = |row, param| VsOutput {
usage: Usage::Generic,
row,
param,
fp16: false,
pack2: false,
};
assert_eq!(
p.io,
StageIo::Ms(MeshIo {
outputs: vec![out(1, 0), out(0, 0x82)],
clip_cntl: 0x0040_000F,
threads: 128,
max_vertices: 128,
max_primitives: 64,
topology: 2,
lds_bytes: 16,
})
);
}
#[test]
fn compute_dispatch_settings() {
// 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS.
let cs = ComputeIo {
rsrc2: 0x1098A,
threads: [16, 16, 1],
};
assert_eq!(cs.user_sgprs(), 5);
assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None));
assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024));
// 6 user SGPRs, all three group ids, v0-v2, no LDS.
let cs = ComputeIo {
rsrc2: 0x138C,
threads: [8, 8, 1],
};
assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None));
assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0));
}
#[test]
fn reads_every_native_blob() {
let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));
File diff suppressed because it is too large. Load diff
+51 -4
View File
@@ -308,6 +308,12 @@ pub struct Structured {
pub guards: Vec<Vec<Option<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.
pub highs: HashMap<Value, Value>,
/// Masks (low dwords) set only in lanes whose EXEC bit is set where
/// they are written: every such lane reaches the writing block, so a
/// ballot there gives the mask as data.
pub active: HashSet<Value>,
}
/// Builds the per-lane form of `program`.
@@ -356,6 +362,8 @@ struct Lanes<'a> {
first: Vec<Bool>,
/// Per block ending in a branch: when a lane takes it.
when: Vec<Option<Bool>>,
/// See [`Structured::active`].
active: HashSet<Value>,
}
/// A mask join taken as `value` in every lane that reaches `block`: each
@@ -418,6 +426,7 @@ impl<'a> Lanes<'a> {
joins: Vec::new(),
first: vec![Bool::FALSE; blocks.len()],
when: vec![None; blocks.len()],
active: HashSet::new(),
})
}
@@ -429,6 +438,7 @@ impl<'a> Lanes<'a> {
self.joins.clear();
self.first.fill(Bool::FALSE);
self.when.fill(None);
self.active.clear();
}
/// Lane masks, branch conditions and forward-edge knowledge, block by
@@ -443,6 +453,7 @@ impl<'a> Lanes<'a> {
lo
};
self.masks.insert((lo, hi), Bool::TRUE);
self.active.insert(lo);
}
let mut execs: Vec<Vec<Option<Bool>>> =
p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect();
@@ -457,11 +468,24 @@ impl<'a> Lanes<'a> {
}
}
self.first[b] = c;
// EXEC joined at the block's entry holds the lanes that arrive.
for phi in &p.blocks[b].phis {
if phi.reg == Reg::S(EXEC) {
self.active.insert(phi.value);
}
}
// EXEC where known in this block (read or written so far).
let mut now = None;
for (i, inst) in p.blocks[b].insts.iter().enumerate() {
if inst.read(Reg::S(EXEC)).is_some() {
execs[b][i] = Some(self.exec(inst));
let e = self.exec(inst);
execs[b][i] = Some(e);
now = Some(e);
}
self.step(inst, now);
if let Some(k) = self.key(|r| inst.write(r), EXEC) {
now = self.masks.get(&k).or(self.other.get(&k)).copied();
}
self.step(inst);
}
if let Exit::Branch { .. } = p.blocks[b].exit
&& let Some(last) = p.blocks[b].insts.last()
@@ -553,6 +577,13 @@ impl<'a> Lanes<'a> {
}
Ok(Structured {
masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(),
highs: self
.masks
.keys()
.filter(|(lo, hi)| lo != hi)
.map(|&(lo, hi)| (hi, lo))
.collect(),
active: self.active,
bools: self.b,
exits,
guards,
@@ -828,8 +859,8 @@ impl<'a> Lanes<'a> {
})
}
/// Records the masks `inst` defines.
fn step(&mut self, inst: &Inst) {
/// Records the masks `inst` defines; `exec` is EXEC there, if known.
fn step(&mut self, inst: &Inst, exec: Option<Bool>) {
let name = inst.name();
match &inst.fields {
Fields::Sop { src, .. } => {
@@ -850,6 +881,12 @@ impl<'a> Lanes<'a> {
{
for (k, m) in r.dst.into_iter().chain(r.exec) {
self.masks.insert(k, m);
// EXEC itself holds the lanes that run here.
if r.exec.is_some_and(|e| e.0 == k)
|| exec.is_some_and(|e| self.b.implies(m, e))
{
self.active.insert(k.0);
}
}
if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) {
self.scc_lane.insert(scc, m);
@@ -883,7 +920,17 @@ impl<'a> Lanes<'a> {
let a = l.b.atom(Atom::Lane(k.0), born);
let m = l.b.and(exec, a);
l.masks.insert(k, m);
l.active.insert(k.0);
};
// A select reads a mask nothing else may: a join of compare
// results is resolved here, as for EXEC.
if name == "v_cndmask_b32"
&& let Some(&Operand::Scalar { code, .. }) = v.src.get(2)
&& code != NULL
&& let Some(k) = self.key(|r| inst.read(r), code)
{
self.mask(k);
}
if name.starts_with("v_cmpx") {
if let Some(k) = self.key(|r| inst.write(r), EXEC) {
lane(self, k);