From e13ccd7fff4d29f7382e56d0df44a65154710a5f Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:14:24 +0100 Subject: [PATCH] Recompiler: encode direct DXIL with bitcode abbreviations The direct DXIL writer emitted every record unabbreviated, so each operand took a full 6-bit VBR chunk plus the record header. Define LLVM DEFINE_ABBREV records for the hot function-block opcodes (binop without flags, cast, cmp2, vselect, extractval, 4-byte-aligned load / store, br, call, phi, gep) and for integer / f32 constants, and write the compact form's lookup tables as one CST_CODE_DATA record instead of an aggregate of interned integer constants. The records decode to the same operands, so the module means the same; only its encoding is smaller. Measured on the retail title with an RTX 5070 Ti (numbers in the PR). Ported from the bitcode-encoding part of amd-dev's f089a9df (cherry picked there from 46aecbf7, raylitebull, Assisted-by: Antigravity (Gemini 4 Neon High)). Left out here: its dead-constant pruning (main already prunes, 09a65d63) and its IR / compact-form changes, which follow separately. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/bitreader_tests.rs | 133 ++++++++++++++- crates/xcl/src/gpu/dxil/bitstream.rs | 141 ++++++++++++++-- crates/xcl/src/gpu/dxil/compact.rs | 3 +- crates/xcl/src/gpu/dxil/module.rs | 184 ++++++++++++++++----- 4 files changed, 400 insertions(+), 61 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/bitreader_tests.rs b/crates/xcl/src/gpu/dxil/bitreader_tests.rs index b3a7b3dd41..81823c4386 100644 --- a/crates/xcl/src/gpu/dxil/bitreader_tests.rs +++ b/crates/xcl/src/gpu/dxil/bitreader_tests.rs @@ -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}; @@ -12,6 +12,15 @@ pub(super) struct Block { pub blocks: Vec, } +#[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> { @@ -57,6 +66,7 @@ impl Reader<'_> { } fn block(&mut self, id: u32, width: u32, end_bit: Option) -> Block { let mut blk = Block { id, ..Default::default() }; + let mut abbrevs: Vec> = Vec::new(); loop { if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 { return blk; @@ -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())); + } } } } @@ -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 = 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()); diff --git a/crates/xcl/src/gpu/dxil/bitstream.rs b/crates/xcl/src/gpu/dxil/bitstream.rs index 70757093f1..6b23eedd51 100644 --- a/crates/xcl/src/gpu/dxil/bitstream.rs +++ b/crates/xcl/src/gpu/dxil/bitstream.rs @@ -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, 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 { @@ -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 { @@ -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 @@ -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); + } } diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index c8bfab774b..7f8a6f8566 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -133,10 +133,9 @@ fn bits(n: usize) -> u32 { /// A constant table of 32-bit words. fn table(lw: &mut Lw, name: &str, words: &[u32]) -> Value { - let vals: Vec = words.iter().map(|&w| lw.c(w)).collect(); let i32 = lw.s.m.i32(); let at = lw.s.m.array(words.len() as u64, i32); - let init = lw.s.m.aggregate(at, &vals); + let init = lw.s.m.const_data_i32(words); lw.s.m.global(name, at, 0, Some(init), true, 4) } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index a9601ad981..394c976eb6 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; -use super::bitstream::{signed, BitWriter}; +use super::bitstream::{signed, AbbrevOp, BitWriter}; mod opt; #[cfg(test)] @@ -60,6 +60,9 @@ enum ConstDef { Undef(Ty), Null(Ty), Aggregate(Ty, Vec), + /// Packed `i32` constant array (`CST_CODE_DATA = 22`), avoiding per-element `CST_CODE_INTEGER` + /// interning for large lookup tables (e.g. `compact.rs`). + DataI32(Ty, Vec), } #[derive(Clone)] @@ -462,6 +465,16 @@ impl Module { self.constant(ConstDef::Aggregate(ty, elems.to_vec())) } + /// Packed `[N x i32]` constant data array (`CST_CODE_DATA`), avoiding interning each element. + pub fn const_data_i32(&mut self, words: &[u32]) -> Value { + let i32 = self.i32(); + let at = self.array(words.len() as u64, i32); + if words.is_empty() { + return self.null(at); + } + self.constant(ConstDef::DataI32(at, words.to_vec())) + } + // ---- functions and globals /// Declares (or finds) a function by name. @@ -511,7 +524,12 @@ impl Module { self.ptr(t, 0) } Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -964,18 +982,30 @@ impl Module { // Module-level constants. if n_consts > 0 { + const ABBREV_CST_INT: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_INTEGER as u64), AbbrevOp::Vbr(6)]; + const ABBREV_CST_F32: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_FLOAT as u64), AbbrevOp::Fixed(32)]; + const ABBREV_CST_DATA: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_DATA as u64), AbbrevOp::ArrayFixed(32)]; w.enter_block(BLOCK_CONSTANTS); + let ab_int = w.define_abbrev(ABBREV_CST_INT); + let ab_f32 = w.define_abbrev(ABBREV_CST_F32); + let ab_data = w.define_abbrev(ABBREV_CST_DATA); let mut cur_ty = None; for c in self.consts.iter().enumerate().filter(|(i, _)| cused[*i]).map(|x| x.1) { let t = match c { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }; if cur_ty != Some(t) { w.record(CST_CODE_SETTYPE, &[t.0 as u64]); cur_ty = Some(t); } match c { - ConstDef::Int(_, v) => w.record(CST_CODE_INTEGER, &[signed(*v)]), + ConstDef::Int(_, v) => w.emit_abbrev(ab_int, ABBREV_CST_INT, &[signed(*v)]), + ConstDef::Float(_, bits) if *bits <= u32::MAX as u64 => w.emit_abbrev(ab_f32, ABBREV_CST_F32, &[*bits]), ConstDef::Float(_, bits) => w.record(CST_CODE_FLOAT, &[*bits]), ConstDef::Undef(_) => w.record(CST_CODE_UNDEF, &[]), ConstDef::Null(_) => w.record(CST_CODE_NULL, &[]), @@ -983,6 +1013,10 @@ impl Module { let ops: Vec = e.iter().map(|&v| abs(v)).collect(); w.record(CST_CODE_AGGREGATE, &ops) } + ConstDef::DataI32(_, words) => { + let ops: Vec = words.iter().map(|&x| x as u64).collect(); + w.emit_abbrev(ab_data, ABBREV_CST_DATA, &ops); + } } } w.end_block(); @@ -1023,15 +1057,16 @@ impl Module { } w.end_block(); - // The entry's body. - w.enter_block(BLOCK_FUNCTION); + // The entry's body (abbrev width 4 -> 12 user abbreviations for hot DXIL opcodes). + w.enter_block_with_width(BLOCK_FUNCTION, 4); + let ab = FuncAbbrevs::define(&mut w); w.record(FUNC_CODE_DECLAREBLOCKS, &[order.len() as u64]); let mut inst_id = inst_base; let mut operands = Vec::new(); for &b in &order { for k in 0..self.blocks[b].len() { let i = self.blocks[b][k] as usize; - self.write_inst(&mut w, i, inst_id, &abs, &pos, &mut operands); + self.write_inst(&mut w, &ab, i, inst_id, &abs, &pos, &mut operands); if !self.is_void(self.insts[i].ty) { inst_id += 1; } @@ -1230,6 +1265,7 @@ impl Module { fn write_inst( &self, w: &mut BitWriter, + ab: &FuncAbbrevs, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, @@ -1255,21 +1291,22 @@ impl Module { ops.clear(); match &self.insts[i].op { Op::Bin(op, a, b, flags) => { - ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64]); - if *flags != 0 { - ops.push(*flags); + if *flags == 0 { + w.emit_abbrev(ab.binop, ABBREV_BINOP, &[rel(*a), rel(*b), *op as u64]); + } else { + ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64, *flags]); + w.record(FUNC_CODE_INST_BINOP, ops); } - w.record(FUNC_CODE_INST_BINOP, ops) } - Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), - Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), - Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), - Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), + Op::Cast(op, v, t) => w.emit_abbrev(ab.cast, ABBREV_CAST, &[rel(*v), t.0 as u64, *op as u64]), + Op::Cmp(p, a, b) => w.emit_abbrev(ab.cmp2, ABBREV_CMP2, &[rel(*a), rel(*b), *p as u64]), + Op::Select(c, t, f) => w.emit_abbrev(ab.vselect, ABBREV_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.emit_abbrev(ab.extract, ABBREV_EXTRACT, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; - ops.extend_from_slice(&[0, 1 << 15, fd.ty.0 as u64, rel(Value::Func(*f))]); + ops.extend_from_slice(&[fd.ty.0 as u64, rel(Value::Func(*f))]); ops.extend(args.iter().map(|&a| rel(a))); - w.record(FUNC_CODE_INST_CALL, ops) + w.emit_abbrev(ab.call, ABBREV_CALL, ops); } Op::Phi(inc) => { ops.push(self.insts[i].ty.0 as u64); @@ -1278,22 +1315,30 @@ impl Module { ops.push(signed(inst_id as i64 - abs(v) as i64)); ops.push(bb(b)); } - w.record(FUNC_CODE_INST_PHI, ops) + w.emit_abbrev(ab.phi, ABBREV_PHI, ops); } Op::Load(p, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]) + if a == 3 { + w.emit_abbrev(ab.load, ABBREV_LOAD, &[rel(*p), self.insts[i].ty.0 as u64]); + } else { + w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]); + } } Op::Store(p, v, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]) + if a == 3 { + w.emit_abbrev(ab.store, ABBREV_STORE, &[rel(*p), rel(*v)]); + } else { + w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]); + } } Op::Gep(p, idx) => { let pt = self.value_ty(*p); let (src, _) = self.pointee_of(pt).unwrap_or((pt, 0)); - ops.extend_from_slice(&[1, src.0 as u64, rel(*p)]); + ops.extend_from_slice(&[src.0 as u64, rel(*p)]); ops.extend(idx.iter().map(|&v| rel(v))); - w.record(FUNC_CODE_INST_GEP, ops) + w.emit_abbrev(ab.gep, ABBREV_GEP, ops); } Op::AtomicRmw(op, p, v) => { // [ptr, val, op, vol, ordering, synchscope (crossthread = 1)] @@ -1309,8 +1354,8 @@ impl Module { let a = align.trailing_zeros() as u64 + 1; w.record(FUNC_CODE_INST_ALLOCA, &[t.0 as u64, i32t.0 as u64, abs(*n), a | 1 << 6]) } - Op::Br(b) => w.record(FUNC_CODE_INST_BR, &[bb(*b)]), - Op::CondBr(c, t, f) => w.record(FUNC_CODE_INST_BR, &[bb(*t), bb(*f), rel(*c)]), + Op::Br(b) => w.emit_abbrev(ab.br, ABBREV_BR, &[bb(*b)]), + Op::CondBr(c, t, f) => w.emit_abbrev(ab.condbr, ABBREV_CONDBR, &[bb(*t), bb(*f), rel(*c)]), Op::Switch(v, d, cases) => { ops.extend_from_slice(&[self.value_ty(*v).0 as u64, rel(*v), bb(*d)]); for &(c, b) in cases { @@ -1330,7 +1375,12 @@ impl Module { Value::Global(g) => self.globals[g as usize].ptr, Value::Func(f) => self.type_ids[&TypeDef::Ptr(self.funcs[f as usize].ty, 0)], Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -1389,6 +1439,7 @@ const CST_CODE_UNDEF: u32 = 3; const CST_CODE_INTEGER: u32 = 4; const CST_CODE_FLOAT: u32 = 6; const CST_CODE_AGGREGATE: u32 = 7; +const CST_CODE_DATA: u32 = 22; const METADATA_STRING: u32 = 1; const METADATA_VALUE: u32 = 2; @@ -1417,6 +1468,66 @@ const FUNC_CODE_INST_GEP: u32 = 43; const FUNC_CODE_INST_STORE: u32 = 44; const FUNC_CODE_INST_CMPXCHG: u32 = 46; +const ABBREV_BINOP: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BINOP as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CAST: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CAST as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CMP2: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CMP2 as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(6)]; +const ABBREV_VSELECT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_VSELECT as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5)]; +const ABBREV_EXTRACT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_EXTRACTVAL as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(4)]; +const ABBREV_LOAD: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_LOAD as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_STORE: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_STORE as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_BR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6)]; +const ABBREV_CONDBR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5)]; +const ABBREV_CALL: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_CALL as u64), + AbbrevOp::Literal(0), + AbbrevOp::Literal(1 << 15), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(6), + AbbrevOp::ArrayVbr(5), +]; +const ABBREV_PHI: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_PHI as u64), AbbrevOp::Vbr(5), AbbrevOp::ArrayVbr(6)]; +const ABBREV_GEP: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_GEP as u64), + AbbrevOp::Literal(1), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(5), + AbbrevOp::ArrayVbr(5), +]; + +struct FuncAbbrevs { + binop: u32, + cast: u32, + cmp2: u32, + vselect: u32, + extract: u32, + load: u32, + store: u32, + br: u32, + condbr: u32, + call: u32, + phi: u32, + gep: u32, +} + +impl FuncAbbrevs { + fn define(w: &mut BitWriter) -> Self { + Self { + binop: w.define_abbrev(ABBREV_BINOP), + cast: w.define_abbrev(ABBREV_CAST), + cmp2: w.define_abbrev(ABBREV_CMP2), + vselect: w.define_abbrev(ABBREV_VSELECT), + extract: w.define_abbrev(ABBREV_EXTRACT), + load: w.define_abbrev(ABBREV_LOAD), + store: w.define_abbrev(ABBREV_STORE), + br: w.define_abbrev(ABBREV_BR), + condbr: w.define_abbrev(ABBREV_CONDBR), + call: w.define_abbrev(ABBREV_CALL), + phi: w.define_abbrev(ABBREV_PHI), + gep: w.define_abbrev(ABBREV_GEP), + } + } +} + // ------------------------------------------------------- introspection /// What an instruction is, for analyses over the built function (e.g. the @@ -1628,25 +1739,14 @@ mod tests { } fn symtab_names(bc: &[u8]) -> Vec { - assert!(bc.starts_with(&[b'B', b'C', 0xC0, 0xDE])); - let (mut bit, mut w, mut blk, mut stack, mut out) = (32usize, 2u32, 0u32, Vec::new(), Vec::new()); - let bits = |bit: &mut usize, n: u32| (0..n).fold(0u64, |v, k| { let b = (bc[*bit / 8] >> (*bit % 8)) & 1; *bit += 1; v | ((b as u64) << k) }); - let vbr = |bit: &mut usize, n: u32| { - let (mut o, mut s, hi) = (0u64, 0u32, 1u64 << (n - 1)); - loop { let c = bits(bit, n); o |= (c & (hi - 1)) << s; if c & hi == 0 { return o; } s += n - 1; } - }; - while bit + w as usize <= bc.len() * 8 { - match bits(&mut bit, w) { - 0 => { bit = (bit + 31) & !31; if let Some((pw, pb)) = stack.pop() { w = pw; blk = pb; } else { break; } } - 1 => { let (id, nw) = (vbr(&mut bit, 8) as u32, vbr(&mut bit, 4) as u32); bit = ((bit + 31) & !31) + 32; stack.push((w, blk)); w = nw; blk = id; } - 3 => { - let (code, n) = (vbr(&mut bit, 6) as u32, vbr(&mut bit, 6) as usize); - let ops: Vec = (0..n).map(|_| vbr(&mut bit, 6)).collect(); - if blk == BLOCK_VALUE_SYMTAB && code == VST_CODE_ENTRY { out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } - } - other => panic!("unexpected abbrev {other}"), + fn walk(b: &super::super::bitreader_tests::Block, out: &mut Vec) { + if b.id == BLOCK_VALUE_SYMTAB { + out.extend(b.records_with(VST_CODE_ENTRY).iter().map(|ops| String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap())); } + b.blocks.iter().for_each(|c| walk(c, out)); } + let mut out = Vec::new(); + walk(&super::super::bitreader_tests::parse(bc), &mut out); out }