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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 129 additions & 4 deletions crates/xcl/src/gpu/dxil/bitreader_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! A test-only reader for the bitstream [`super::bitstream::BitWriter`]
//! produces (unabbreviated records only), used to check record layouts
//! that the validator and disassembler do not distinguish (e.g. atomic
//! ordering codes the LLVM reader maps leniently).
//! produces (both unabbreviated records and `DEFINE_ABBREV` abbreviated records),
//! used to check record layouts that the validator and disassembler do not
//! distinguish (e.g. atomic ordering codes the LLVM reader maps leniently).

use super::module::{BinOp, Module, RmwOp};

Expand All @@ -12,6 +12,15 @@ pub(super) struct Block {
pub blocks: Vec<Block>,
}

#[derive(Clone, Debug)]
enum AbOp {
Literal(u64),
Fixed(u32),
Vbr(u32),
ArrayFixed(u32),
ArrayVbr(u32),
}

impl Block {
/// Depth-first search for the first block with `id`.
pub fn find(&self, id: u32) -> Option<&Block> {
Expand Down Expand Up @@ -57,6 +66,7 @@ impl Reader<'_> {
}
fn block(&mut self, id: u32, width: u32, end_bit: Option<usize>) -> Block {
let mut blk = Block { id, ..Default::default() };
let mut abbrevs: Vec<Vec<AbOp>> = Vec::new();
loop {
if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 {
return blk;
Expand All @@ -77,13 +87,70 @@ impl Reader<'_> {
let end = self.pos + words * 32;
blk.blocks.push(self.block(sub, w, Some(end)));
}
2 => {
let n = self.vbr(5);
let mut ops = Vec::new();
let mut i = 0;
while i < n {
if self.fixed(1) == 1 {
ops.push(AbOp::Literal(self.vbr(8)));
i += 1;
} else {
match self.fixed(3) {
1 => {
ops.push(AbOp::Fixed(self.vbr(5) as u32));
i += 1;
}
2 => {
ops.push(AbOp::Vbr(self.vbr(5) as u32));
i += 1;
}
3 => {
assert_eq!(self.fixed(1), 0, "array element must be encoded");
match self.fixed(3) {
1 => ops.push(AbOp::ArrayFixed(self.vbr(5) as u32)),
2 => ops.push(AbOp::ArrayVbr(self.vbr(5) as u32)),
e => panic!("unsupported array elem encoding {e}"),
}
i += 2;
}
e => panic!("unsupported abbrev encoding {e}"),
}
}
}
abbrevs.push(ops);
}
3 => {
let code = self.vbr(6) as u32;
let n = self.vbr(6);
let ops = (0..n).map(|_| self.vbr(6)).collect();
blk.records.push((code, ops));
}
a => panic!("unexpected abbreviation id {a}"),
a => {
let ab = abbrevs.get((a - 4) as usize).unwrap_or_else(|| panic!("unknown abbreviation id {a}"));
let mut vals = Vec::new();
for op in ab {
match *op {
AbOp::Literal(v) => vals.push(v),
AbOp::Fixed(w) => vals.push(self.fixed(w)),
AbOp::Vbr(w) => vals.push(self.vbr(w)),
AbOp::ArrayFixed(w) => {
let len = self.vbr(6);
for _ in 0..len {
vals.push(self.fixed(w));
}
}
AbOp::ArrayVbr(w) => {
let len = self.vbr(6);
for _ in 0..len {
vals.push(self.vbr(w));
}
}
}
}
let code = vals[0] as u32;
blk.records.push((code, vals[1..].to_vec()));
}
}
}
}
Expand Down Expand Up @@ -143,6 +210,64 @@ fn a_shorter_binop_record_has_only_its_own_operands() {
assert_eq!(records, [&[1, 1, BinOp::Add as u64, 3][..], &[1, 2, BinOp::Xor as u64][..]]);
}

/// The abbreviated records decode to the operands the unabbreviated ones had, and a table
/// of words is one `CST_CODE_DATA` record.
#[test]
fn abbreviated_records_decode_to_the_plain_layout() {
use super::module::Pred;
const BLOCK_CONSTANTS: u32 = 11;
const CST_CODE_DATA: u32 = 22;
const FUNC_CODE_INST_BR: u32 = 11;
const FUNC_CODE_INST_PHI: u32 = 16;
const FUNC_CODE_INST_LOAD: u32 = 20;
const FUNC_CODE_INST_GEP: u32 = 43;
const FUNC_CODE_INST_STORE: u32 = 44;
let words = [7, 0xDEAD_BEEF, 0, u32::MAX];
let mut m = Module::new();
m.define_entry("main");
let i32 = m.i32();
let arr = m.array(words.len() as u64, i32);
let init = m.const_data_i32(&words);
let table = m.global("table", arr, 0, Some(init), true, 4);
let lds = m.global("lds", arr, 3, None, false, 4);
let (zero, one) = (m.i32c(0), m.i32c(1));
let entry = m.entry_block();
let at = m.gep(table, &[zero, one]);
let v = m.load(at, 4);
let c = m.cmp(Pred::Eq, v, zero);
let (then, join) = (m.new_block(), m.new_block());
m.cond_br(c, then, join);
m.set_block(then);
m.br(join);
m.set_block(join);
let p = m.phi(i32);
m.add_incoming(p, v, entry);
m.add_incoming(p, one, then);
let to = m.gep(lds, &[zero, zero]);
m.store(to, p, 4);
m.ret();

let root = parse(&m.to_bitcode("dxil-ms-dx", ""));
let consts = root.find(BLOCK_CONSTANTS).unwrap();
assert_eq!(consts.records_with(CST_CODE_DATA), [&words.map(u64::from)[..]]);
let f = root.find(BLOCK_FUNCTION).unwrap();
let geps = f.records_with(FUNC_CODE_INST_GEP);
assert_eq!(geps.len(), 2);
// [inbounds, source type, pointer, indices...]
assert!(geps.iter().all(|r| r.len() == 5 && r[0] == 1), "{geps:?}");
// [pointer, type, align log2 + 1, volatile]
let loads = f.records_with(FUNC_CODE_INST_LOAD);
assert!(loads.len() == 1 && loads[0].len() == 4 && loads[0][2..] == [3, 0], "{loads:?}");
let stores = f.records_with(FUNC_CODE_INST_STORE);
assert!(stores.len() == 1 && stores[0].len() == 4 && stores[0][2..] == [3, 0], "{stores:?}");
let mut br_lens: Vec<usize> = f.records_with(FUNC_CODE_INST_BR).iter().map(|r| r.len()).collect();
br_lens.sort_unstable();
assert_eq!(br_lens, [1, 3]);
// [type, (signed relative value, block) per incoming edge]
let phis = f.records_with(FUNC_CODE_INST_PHI);
assert!(phis.len() == 1 && phis[0].len() == 5 && phis[0][2] == 0, "{phis:?}");
}

#[test]
fn atomics_use_bitcode_ordering_codes() {
let root = parse(&atomic_module());
Expand Down
141 changes: 128 additions & 13 deletions crates/xcl/src/gpu/dxil/bitstream.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
//! LLVM bitstream writer: fixed and VBR fields, nested blocks with
//! back-patched lengths, and unabbreviated records.
//!
//! DXIL accepts the plain bitstream container without any abbreviations,
//! which keeps the writer small; size is not a concern for shader modules
//! (the driver re-encodes them anyway).
//! back-patched lengths, unabbreviated records, and LLVM `DEFINE_ABBREV`
//! abbreviations for compact DXIL encoding.

/// Bit-level writer, little-endian within 32-bit words as LLVM defines.
pub struct BitWriter {
out: Vec<u8>,
acc: u64,
nbits: u32,
/// Open blocks: (byte offset of the length word, outer abbreviation width).
blocks: Vec<(usize, u32)>,
/// Open blocks: (byte offset of the length word, outer abbreviation width, next abbrev id).
blocks: Vec<(usize, u32, u32)>,
width: u32,
}

/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits).
/// Abbreviation operand encoding for LLVM `DEFINE_ABBREV` records.
#[derive(Clone, Copy, Debug)]
pub enum AbbrevOp {
Literal(u64),
Fixed(u32),
Vbr(u32),
/// Trailing array of fixed-width operands (LLVM `Array` + `Fixed(w)` pair).
ArrayFixed(u32),
/// Trailing array of VBR-encoded operands (LLVM `Array` + `VBR(w)` pair).
ArrayVbr(u32),
}

/// Abbreviation width used for every block opened via [`BitWriter::enter_block`] (IDs 0..7).
pub const ABBREV_WIDTH: u32 = 3;

impl Default for BitWriter {
Expand All @@ -31,7 +40,7 @@ impl BitWriter {

pub fn emit(&mut self, value: u64, width: u32) {
debug_assert!(width <= 32);
debug_assert!(width == 64 || value >> width == 0, "value {value:#x} does not fit {width} bits");
debug_assert!(width == 64 || width == 32 || value >> width == 0, "value {value:#x} does not fit {width} bits");
self.acc |= value << self.nbits;
self.nbits += width;
while self.nbits >= 8 {
Expand Down Expand Up @@ -60,25 +69,114 @@ impl BitWriter {
}

pub fn enter_block(&mut self, id: u32) {
self.enter_block_with_width(id, ABBREV_WIDTH);
}

pub fn enter_block_with_width(&mut self, id: u32, abbrev_width: u32) {
self.emit(1, self.width); // ENTER_SUBBLOCK
self.vbr(id as u64, 8);
self.vbr(ABBREV_WIDTH as u64, 4);
self.vbr(abbrev_width as u64, 4);
self.align32();
let at = self.out.len();
self.out.extend_from_slice(&[0; 4]);
self.blocks.push((at, self.width));
self.width = ABBREV_WIDTH;
self.blocks.push((at, self.width, 4));
self.width = abbrev_width;
}

pub fn end_block(&mut self) {
self.emit(0, self.width); // END_BLOCK
self.align32();
let (at, outer) = self.blocks.pop().expect("end_block without enter_block");
let (at, outer, _) = self.blocks.pop().expect("end_block without enter_block");
let words = ((self.out.len() - at - 4) / 4) as u32;
self.out[at..at + 4].copy_from_slice(&words.to_le_bytes());
self.width = outer;
}

/// Define a block-local abbreviation (`DEFINE_ABBREV = 2`) and return its ID (`>= 4`).
pub fn define_abbrev(&mut self, ops: &[AbbrevOp]) -> u32 {
let id = {
let top = self.blocks.last_mut().expect("define_abbrev outside block");
let id = top.2;
top.2 += 1;
id
};
debug_assert!((id as u64) < (1u64 << self.width), "abbrev id {id} exceeds width {}", self.width);
let num_ops: u64 = ops.iter().map(|o| if matches!(o, AbbrevOp::ArrayFixed(_) | AbbrevOp::ArrayVbr(_)) { 2 } else { 1 }).sum();
self.emit(2, self.width); // DEFINE_ABBREV
self.vbr(num_ops, 5);
for &op in ops {
match op {
AbbrevOp::Literal(v) => {
self.emit(1, 1);
self.vbr(v, 8);
}
AbbrevOp::Fixed(w) => {
self.emit(0, 1);
self.emit(1, 3);
self.vbr(w as u64, 5);
}
AbbrevOp::Vbr(w) => {
self.emit(0, 1);
self.emit(2, 3);
self.vbr(w as u64, 5);
}
AbbrevOp::ArrayFixed(w) => {
self.emit(0, 1);
self.emit(3, 3); // Array
self.emit(0, 1);
self.emit(1, 3); // Fixed element
self.vbr(w as u64, 5);
}
AbbrevOp::ArrayVbr(w) => {
self.emit(0, 1);
self.emit(3, 3); // Array
self.emit(0, 1);
self.emit(2, 3); // VBR element
self.vbr(w as u64, 5);
}
}
}
id
}

/// Emit an abbreviated record defined by [`Self::define_abbrev`]. `values` supplies only the
/// non-literal operands in order; if `ops` ends with `ArrayFixed`/`ArrayVbr`, remaining items
/// in `values` form the array payload.
pub fn emit_abbrev(&mut self, id: u32, ops: &[AbbrevOp], values: &[u64]) {
self.emit(id as u64, self.width);
let mut idx = 0usize;
for &op in ops {
match op {
AbbrevOp::Literal(_) => {}
AbbrevOp::Fixed(w) => {
self.emit(values[idx], w);
idx += 1;
}
AbbrevOp::Vbr(w) => {
self.vbr(values[idx], w);
idx += 1;
}
AbbrevOp::ArrayFixed(w) => {
let rest = &values[idx..];
self.vbr(rest.len() as u64, 6);
for &v in rest {
self.emit(v, w);
}
idx = values.len();
}
AbbrevOp::ArrayVbr(w) => {
let rest = &values[idx..];
self.vbr(rest.len() as u64, 6);
for &v in rest {
self.vbr(v, w);
}
idx = values.len();
}
}
}
debug_assert_eq!(idx, values.len());
}

/// An unabbreviated record.
pub fn record(&mut self, code: u32, ops: &[u64]) {
self.emit(3, self.width); // UNABBREV_RECORD
Expand Down Expand Up @@ -152,4 +250,21 @@ mod tests {
assert_eq!(signed(-3), 7);
assert_eq!(signed(i64::MIN), 1);
}

#[test]
fn define_abbrev_round_trips_fixed_vbr_and_arrays() {
const AB: &[AbbrevOp] = &[AbbrevOp::Literal(22), AbbrevOp::ArrayFixed(32)];
let mut w = BitWriter::new();
for b in [b'B', b'C', 0xC0, 0xDE] {
w.emit(b as u64, 8);
}
w.enter_block_with_width(11, 3);
let id = w.define_abbrev(AB);
assert_eq!(id, 4);
w.emit_abbrev(id, AB, &[0x1234_5678, 0xDEAD_BEEF]);
w.end_block();
let bc = w.finish();
assert_eq!(&bc[..4], b"BC\xC0\xDE");
assert_eq!(bc.len() % 4, 0);
}
}
Loading
Loading