Skip to main content

vulkane_spirv_parse/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! SPIR-V module model and reflection for Vulkane.
3//!
4//! [`Module::parse`] decodes a binary SPIR-V module (a `&[u32]`) into a typed model built on
5//! [`rspirv`]; [`Module::to_words`] encodes it back. Reflection ([`Module::entry_points`],
6//! [`Module::bindings`], [`Module::capabilities`]) reads the module without validating it:
7//! a parsed module can still be invalid SPIR-V, so run `spirv-val` before trusting one.
8
9use std::collections::HashMap;
10
11use rspirv::binary::Assemble;
12use rspirv::dr;
13use rspirv::spirv::{self, Decoration, ExecutionMode, ExecutionModel, Op, StorageClass};
14
15/// Why a module could not be decoded.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum ParseError {
19    /// The words are not a well-formed SPIR-V binary.
20    #[error("malformed SPIR-V: {0}")]
21    Malformed(String),
22}
23
24/// A decoded SPIR-V module.
25#[derive(Debug, Clone)]
26pub struct Module {
27    inner: dr::Module,
28    /// Header word 2 (the tool that produced the module); `rspirv` re-encodes its own value.
29    generator: u32,
30}
31
32/// One `OpEntryPoint` with the facts that belong to it.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct EntryPoint {
35    /// The execution model (`GLCompute`, `Vertex`, ...).
36    pub model: ExecutionModel,
37    /// The entry point's name.
38    pub name: String,
39    /// The id of the function it enters.
40    pub function: u32,
41    /// `LocalSize` execution mode (`x, y, z`), when the module declares one literally.
42    pub local_size: Option<[u32; 3]>,
43}
44
45/// A resource variable decorated with a binding.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Binding {
48    /// The variable's result id.
49    pub variable: u32,
50    /// `DescriptorSet` decoration; `None` when the module does not decorate one.
51    pub set: Option<u32>,
52    /// `Binding` decoration.
53    pub binding: u32,
54    /// The variable's storage class (`StorageBuffer`, `Uniform`, `UniformConstant`, ...).
55    pub storage_class: StorageClass,
56    /// The variable's `OpName`, when the module carries debug names.
57    pub name: Option<String>,
58}
59
60impl Module {
61    /// Decode a binary module.
62    pub fn parse(words: &[u32]) -> Result<Self, ParseError> {
63        let generator = words.get(2).copied().unwrap_or(0);
64        dr::load_words(words)
65            .map(|inner| Self { inner, generator })
66            .map_err(|e| ParseError::Malformed(e.to_string()))
67    }
68
69    /// Encode back to words. For a module produced by a standard compiler this reproduces the
70    /// input exactly; the corpus test checks that over every module it is given.
71    pub fn to_words(&self) -> Vec<u32> {
72        let mut w = self.inner.assemble();
73        w[2] = self.generator;
74        w
75    }
76
77    /// The underlying `rspirv` model, for callers that need the full instruction stream.
78    pub fn as_rspirv(&self) -> &dr::Module {
79        &self.inner
80    }
81
82    /// The declared capabilities, in declaration order.
83    pub fn capabilities(&self) -> Vec<spirv::Capability> {
84        self.inner
85            .capabilities
86            .iter()
87            .filter_map(|i| match i.operands.first() {
88                Some(dr::Operand::Capability(c)) => Some(*c),
89                _ => None,
90            })
91            .collect()
92    }
93
94    /// Every entry point, with its `LocalSize` when declared as a literal.
95    pub fn entry_points(&self) -> Vec<EntryPoint> {
96        self.inner
97            .entry_points
98            .iter()
99            .filter_map(|ep| {
100                let (model, function, name) = match ep.operands.as_slice() {
101                    [
102                        dr::Operand::ExecutionModel(m),
103                        dr::Operand::IdRef(f),
104                        dr::Operand::LiteralString(n),
105                        ..,
106                    ] => (*m, *f, n.clone()),
107                    _ => return None,
108                };
109                let local_size =
110                    self.inner
111                        .execution_modes
112                        .iter()
113                        .find_map(|em| match em.operands.as_slice() {
114                            [
115                                dr::Operand::IdRef(f),
116                                dr::Operand::ExecutionMode(ExecutionMode::LocalSize),
117                                dr::Operand::LiteralBit32(x),
118                                dr::Operand::LiteralBit32(y),
119                                dr::Operand::LiteralBit32(z),
120                            ] if *f == function => Some([*x, *y, *z]),
121                            _ => None,
122                        });
123                Some(EntryPoint {
124                    model,
125                    name,
126                    function,
127                    local_size,
128                })
129            })
130            .collect()
131    }
132
133    /// Variables carrying a `Binding` decoration, ordered by (set, binding, id).
134    pub fn bindings(&self) -> Vec<Binding> {
135        let (set, bind) = self.descriptor_decorations();
136        let names = self.names();
137        let mut out: Vec<Binding> = self
138            .inner
139            .types_global_values
140            .iter()
141            .filter(|i| i.class.opcode == Op::Variable)
142            .filter_map(|i| {
143                let id = i.result_id?;
144                let binding = *bind.get(&id)?;
145                Some(Binding {
146                    variable: id,
147                    set: set.get(&id).copied(),
148                    binding,
149                    storage_class: storage_class_of(i)?,
150                    name: names.get(&id).cloned(),
151                })
152            })
153            .collect();
154        out.sort_by_key(|b| (b.set, b.binding, b.variable));
155        out
156    }
157
158    /// `DescriptorSet` and `Binding` literals by target id.
159    fn descriptor_decorations(&self) -> (HashMap<u32, u32>, HashMap<u32, u32>) {
160        let mut set = HashMap::new();
161        let mut bind = HashMap::new();
162        for d in self
163            .inner
164            .annotations
165            .iter()
166            .filter(|d| d.class.opcode == Op::Decorate)
167        {
168            if let [
169                dr::Operand::IdRef(id),
170                dr::Operand::Decoration(dec),
171                dr::Operand::LiteralBit32(v),
172            ] = d.operands.as_slice()
173            {
174                match dec {
175                    Decoration::DescriptorSet => set.insert(*id, *v),
176                    Decoration::Binding => bind.insert(*id, *v),
177                    _ => None,
178                };
179            }
180        }
181        (set, bind)
182    }
183
184    fn names(&self) -> HashMap<u32, String> {
185        self.inner
186            .debug_names
187            .iter()
188            .filter_map(|i| match i.operands.as_slice() {
189                [dr::Operand::IdRef(id), dr::Operand::LiteralString(n)] => Some((*id, n.clone())),
190                _ => None,
191            })
192            .collect()
193    }
194}
195
196fn storage_class_of(var: &dr::Instruction) -> Option<StorageClass> {
197    match var.operands.first() {
198        Some(dr::Operand::StorageClass(s)) => Some(*s),
199        _ => None,
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn rejects_garbage() {
209        assert!(Module::parse(&[1, 2, 3]).is_err());
210        assert!(Module::parse(&[]).is_err());
211    }
212}