Skip to main content

naga/back/spv/
mod.rs

1/*!
2Backend for [SPIR-V][spv] (Standard Portable Intermediate Representation).
3
4# Layout of values in `uniform` buffers
5
6WGSL's ["Internal Layout of Values"][ilov] rules specify the memory layout of
7each WGSL type. The memory layout is important for data stored in `uniform` and
8`storage` buffers, especially when exchanging data with CPU code.
9
10Both WGSL and Vulkan specify some conditions that a type's memory layout
11must satisfy in order to use that type in a `uniform` or `storage` buffer.
12For `storage` buffers, the WGSL and Vulkan restrictions are compatible, but
13for `uniform` buffers, WGSL allows some types that Vulkan does not, requiring
14adjustments when emitting SPIR-V for `uniform` buffers.
15
16## Padding in two-row matrices
17
18SPIR-V provides detailed control over the layout of matrix types, and is
19capable of describing the WGSL memory layout. However, Vulkan imposes
20additional restrictions.
21
22Vulkan's ["extended layout"][extended-layout] (also known as std140) rules
23apply to types used in `uniform` buffers. Under these rules, matrices are
24defined in terms of arrays of their vector type, and arrays are defined to have
25an alignment equal to the alignment of their element type rounded up to a
26multiple of 16. This means that each column of the matrix has a minimum
27alignment of 16. WGSL, and consequently Naga IR, on the other hand specifies
28column alignment equal to the alignment of the vector type, without being
29rounded up to 16.
30
31To compensate for this, for any `struct` used as a `uniform` buffer which
32contains a two-row matrix, we declare an additional "std140 compatible" type
33in which each column of the matrix has been decomposed into the containing
34struct. For example, the following WGSL struct type:
35
36```ignore
37struct Baz {
38    m: mat3x2<f32>,
39}
40```
41
42is rendered as the SPIR-V struct type:
43
44```ignore
45OpTypeStruct %v2float %v2float %v2float
46```
47
48This has the effect that struct indices in Naga IR for such types do not
49correspond to the struct indices used in SPIR-V. A mapping of struct indices
50for these types is maintained in [`Std140CompatTypeInfo`].
51
52Additionally, any two-row matrices that are declared directly as uniform
53buffers without being wrapped in a struct are declared as a struct containing a
54vector member for each column. Any array of a two-row matrix in a uniform
55buffer is declared as an array of a struct containing a vector member for each
56column. Any struct or array within a uniform buffer which contains a member or
57whose base type requires a std140 compatible type declaration, itself requires a
58std140 compatible type declaration.
59
60Whenever a value of such a type is [`loaded`] we insert code to convert the
61loaded value from the std140 compatible type to the regular type. This occurs
62in `BlockContext::write_checked_load`, making use of the wrapper function
63defined by `Writer::write_wrapped_convert_from_std140_compat_type`. For matrices
64that have been decomposed as separate columns in the containing struct, we load
65each column separately then composite the matrix type in
66`BlockContext::maybe_write_load_uniform_matcx2_struct_member`.
67
68Whenever a column of a matrix that has been decomposed into its containing
69struct is [`accessed`] with a constant index we adjust the emitted access chain
70to access from the containing struct instead, in `BlockContext::write_access_chain`.
71
72Whenever a column of a uniform buffer two-row matrix is [`dynamically accessed`]
73we must first load the matrix type, converting it from its std140 compatible
74type as described above, then access the column using the wrapper function
75defined by `Writer::write_wrapped_matcx2_get_column`. This is handled by
76`BlockContext::maybe_write_uniform_matcx2_dynamic_access`.
77
78Note that this approach differs somewhat from the equivalent code in the HLSL
79backend. For HLSL all structs containing two-row matrices (or arrays of such)
80have their declarations modified, not just those used as uniform buffers.
81Two-row matrices and arrays of such only use modified type declarations when
82used as uniform buffers, or additionally when used as struct member in any
83context. This avoids the need to convert struct values when loading from uniform
84buffers, but when loading arrays and matrices from uniform buffers or from any
85struct the conversion is still required. In contrast, the approach used here
86always requires converting *any* affected type when loading from a uniform
87buffer, but consistently *only* when loading from a uniform buffer. As a result
88this also means we only have to handle loads and not stores, as uniform buffers
89are read-only.
90
91[spv]: https://www.khronos.org/registry/SPIR-V/
92[ilov]: https://gpuweb.github.io/gpuweb/wgsl/#internal-value-layout
93[extended-layout]: https://docs.vulkan.org/spec/latest/chapters/interfaces.html#interfaces-resources-layout
94[`loaded`]: crate::Expression::Load
95[`accessed`]: crate::Expression::AccessIndex
96[`dynamically accessed`]: crate::Expression::Access
97*/
98
99mod block;
100mod f16_polyfill;
101mod helpers;
102mod image;
103mod index;
104mod instructions;
105mod layout;
106mod mesh_shader;
107mod ray;
108mod reclaimable;
109mod selection;
110mod subgroup;
111mod writer;
112
113pub use nt::spv::*;
114
115pub use mesh_shader::{MeshReturnInfo, MeshReturnMember};
116pub use spirv::{Capability, SourceLanguage};
117
118use alloc::{string::String, vec::Vec};
119use core::ops;
120
121use spirv::Word;
122use thiserror::Error;
123
124use crate::arena::{Handle, HandleVec};
125use crate::back::TaskDispatchLimits;
126use crate::proc::{BoundsCheckPolicies, TypeResolution};
127
128#[derive(Clone)]
129struct PhysicalLayout {
130    magic_number: Word,
131    version: Word,
132    generator: Word,
133    bound: Word,
134    instruction_schema: Word,
135}
136
137#[derive(Default)]
138struct LogicalLayout {
139    capabilities: Vec<Word>,
140    extensions: Vec<Word>,
141    ext_inst_imports: Vec<Word>,
142    memory_model: Vec<Word>,
143    entry_points: Vec<Word>,
144    execution_modes: Vec<Word>,
145    debugs: Vec<Word>,
146    annotations: Vec<Word>,
147    declarations: Vec<Word>,
148    function_declarations: Vec<Word>,
149    function_definitions: Vec<Word>,
150}
151
152#[derive(Clone)]
153struct Instruction {
154    op: spirv::Op,
155    type_id: Option<Word>,
156    result_id: Option<Word>,
157    operands: Vec<Word>,
158}
159
160const BITS_PER_BYTE: crate::Bytes = 8;
161
162#[derive(Clone, Debug, Error)]
163pub enum Error {
164    #[error("The requested entry point couldn't be found")]
165    EntryPointNotFound,
166    #[error("target SPIRV-{0}.{1} is not supported")]
167    UnsupportedVersion(u8, u8),
168    #[error("using {0} requires at least one of the capabilities {1:?}, but none are available")]
169    MissingCapabilities(&'static str, Vec<Capability>),
170    #[error("unimplemented {0}")]
171    FeatureNotImplemented(&'static str),
172    #[error("module is not validated properly: {0}")]
173    Validation(&'static str),
174    #[error("overrides should not be present at this stage")]
175    Override,
176    #[error(transparent)]
177    ResolveArraySizeError(#[from] crate::proc::ResolveArraySizeError),
178    #[error("module requires SPIRV-{0}.{1}, which isn't supported")]
179    SpirvVersionTooLow(u8, u8),
180    #[error("mapping of {0:?} is missing")]
181    MissingBinding(crate::ResourceBinding),
182}
183
184#[derive(Default)]
185struct IdGenerator(Word);
186
187impl IdGenerator {
188    const fn next(&mut self) -> Word {
189        self.0 += 1;
190        self.0
191    }
192}
193
194#[derive(Debug, Clone)]
195pub struct DebugInfo<'a> {
196    pub source_code: &'a str,
197    pub file_name: &'a str,
198    pub language: SourceLanguage,
199}
200
201/// A SPIR-V block to which we are still adding instructions.
202///
203/// A `Block` represents a SPIR-V block that does not yet have a termination
204/// instruction like `OpBranch` or `OpReturn`.
205///
206/// The `OpLabel` that starts the block is implicit. It will be emitted based on
207/// `label_id` when we write the block to a `LogicalLayout`.
208///
209/// To terminate a `Block`, pass the block and the termination instruction to
210/// `Function::consume`. This takes ownership of the `Block` and transforms it
211/// into a `TerminatedBlock`.
212struct Block {
213    label_id: Word,
214    body: Vec<Instruction>,
215}
216
217/// A SPIR-V block that ends with a termination instruction.
218struct TerminatedBlock {
219    label_id: Word,
220    body: Vec<Instruction>,
221}
222
223impl Block {
224    const fn new(label_id: Word) -> Self {
225        Block {
226            label_id,
227            body: Vec::new(),
228        }
229    }
230}
231
232struct LocalVariable {
233    id: Word,
234    instruction: Instruction,
235}
236
237struct ResultMember {
238    id: Word,
239    type_id: Word,
240    built_in: Option<crate::BuiltIn>,
241}
242
243struct EntryPointContext {
244    argument_ids: Vec<Word>,
245    results: Vec<ResultMember>,
246    task_payload_variable_id: Option<Word>,
247    mesh_state: Option<MeshReturnInfo>,
248}
249
250#[derive(Default)]
251struct Function {
252    signature: Option<Instruction>,
253    parameters: Vec<FunctionArgument>,
254    variables: crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
255    /// Map from a local variable that is a ray query to its u32 tracker.
256    ray_query_initialization_tracker_variables:
257        crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
258    /// Map from a local variable that is a ray query to its tracker for the t max.
259    ray_query_t_max_tracker_variables:
260        crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
261    /// List of local variables used as a counters to ensure that all loops are bounded.
262    force_loop_bounding_vars: Vec<LocalVariable>,
263
264    /// A map from a Naga expression to the temporary SPIR-V variable we have
265    /// spilled its value to, if any.
266    ///
267    /// Naga IR lets us apply [`Access`] expressions to expressions whose value
268    /// is an array or matrix---not a pointer to such---but SPIR-V doesn't have
269    /// instructions that can do the same. So when we encounter such code, we
270    /// spill the expression's value to a generated temporary variable. That, we
271    /// can obtain a pointer to, and then use an `OpAccessChain` instruction to
272    /// do whatever series of [`Access`] and [`AccessIndex`] operations we need
273    /// (with bounds checks). Finally, we generate an `OpLoad` to get the final
274    /// value.
275    ///
276    /// [`Access`]: crate::Expression::Access
277    /// [`AccessIndex`]: crate::Expression::AccessIndex
278    spilled_composites: crate::FastIndexMap<Handle<crate::Expression>, LocalVariable>,
279
280    /// A set of expressions that are either in [`spilled_composites`] or refer
281    /// to some component/element of such.
282    ///
283    /// [`spilled_composites`]: Function::spilled_composites
284    spilled_accesses: crate::arena::HandleSet<crate::Expression>,
285
286    /// A map taking each expression to the number of [`Access`] and
287    /// [`AccessIndex`] expressions that uses it as a base value. If an
288    /// expression has no entry, its count is zero: it is never used as a
289    /// [`Access`] or [`AccessIndex`] base.
290    ///
291    /// We use this, together with [`ExpressionInfo::ref_count`], to recognize
292    /// the tips of chains of [`Access`] and [`AccessIndex`] expressions that
293    /// access spilled values --- expressions in [`spilled_composites`]. We
294    /// defer generating code for the chain until we reach its tip, so we can
295    /// handle it with a single instruction.
296    ///
297    /// [`Access`]: crate::Expression::Access
298    /// [`AccessIndex`]: crate::Expression::AccessIndex
299    /// [`ExpressionInfo::ref_count`]: crate::valid::ExpressionInfo
300    /// [`spilled_composites`]: Function::spilled_composites
301    access_uses: crate::FastHashMap<Handle<crate::Expression>, usize>,
302
303    blocks: Vec<TerminatedBlock>,
304    entry_point_context: Option<EntryPointContext>,
305}
306
307impl Function {
308    fn consume(&mut self, mut block: Block, termination: Instruction) {
309        block.body.push(termination);
310        self.blocks.push(TerminatedBlock {
311            label_id: block.label_id,
312            body: block.body,
313        })
314    }
315
316    fn parameter_id(&self, index: u32) -> Word {
317        match self.entry_point_context {
318            Some(ref context) => context.argument_ids[index as usize],
319            None => self.parameters[index as usize]
320                .instruction
321                .result_id
322                .unwrap(),
323        }
324    }
325}
326
327/// Characteristics of a SPIR-V `OpTypeImage` type.
328///
329/// SPIR-V requires non-composite types to be unique, including images. Since we
330/// use `LocalType` for this deduplication, it's essential that `LocalImageType`
331/// be equal whenever the corresponding `OpTypeImage`s would be. To reduce the
332/// likelihood of mistakes, we use fields that correspond exactly to the
333/// operands of an `OpTypeImage` instruction, using the actual SPIR-V types
334/// where practical.
335#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
336struct LocalImageType {
337    sampled_type: crate::Scalar,
338    dim: spirv::Dim,
339    flags: ImageTypeFlags,
340    image_format: spirv::ImageFormat,
341}
342
343bitflags::bitflags! {
344    /// Flags corresponding to the boolean(-ish) parameters to OpTypeImage.
345    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
346    pub struct ImageTypeFlags: u8 {
347        const DEPTH = 0x1;
348        const ARRAYED = 0x2;
349        const MULTISAMPLED = 0x4;
350        const SAMPLED = 0x8;
351    }
352}
353
354impl LocalImageType {
355    /// Construct a `LocalImageType` from the fields of a `TypeInner::Image`.
356    fn from_inner(dim: crate::ImageDimension, arrayed: bool, class: crate::ImageClass) -> Self {
357        let make_flags = |multi: bool, other: ImageTypeFlags| -> ImageTypeFlags {
358            let mut flags = other;
359            flags.set(ImageTypeFlags::ARRAYED, arrayed);
360            flags.set(ImageTypeFlags::MULTISAMPLED, multi);
361            flags
362        };
363
364        let dim = spirv::Dim::from(dim);
365
366        match class {
367            crate::ImageClass::Sampled { kind, multi } => LocalImageType {
368                sampled_type: crate::Scalar { kind, width: 4 },
369                dim,
370                flags: make_flags(multi, ImageTypeFlags::SAMPLED),
371                image_format: spirv::ImageFormat::Unknown,
372            },
373            crate::ImageClass::Depth { multi } => LocalImageType {
374                sampled_type: crate::Scalar {
375                    kind: crate::ScalarKind::Float,
376                    width: 4,
377                },
378                dim,
379                flags: make_flags(multi, ImageTypeFlags::DEPTH | ImageTypeFlags::SAMPLED),
380                image_format: spirv::ImageFormat::Unknown,
381            },
382            crate::ImageClass::Storage { format, access: _ } => LocalImageType {
383                sampled_type: format.into(),
384                dim,
385                flags: make_flags(false, ImageTypeFlags::empty()),
386                image_format: format.into(),
387            },
388            crate::ImageClass::External => unimplemented!(),
389        }
390    }
391}
392
393/// A numeric type, for use in [`LocalType`].
394#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
395enum NumericType {
396    Scalar(crate::Scalar),
397    Vector {
398        size: crate::VectorSize,
399        scalar: crate::Scalar,
400    },
401    Matrix {
402        columns: crate::VectorSize,
403        rows: crate::VectorSize,
404        scalar: crate::Scalar,
405    },
406}
407
408impl NumericType {
409    const fn from_inner(inner: &crate::TypeInner) -> Option<Self> {
410        match *inner {
411            crate::TypeInner::Scalar(scalar) | crate::TypeInner::Atomic(scalar) => {
412                Some(NumericType::Scalar(scalar))
413            }
414            crate::TypeInner::Vector { size, scalar } => Some(NumericType::Vector { size, scalar }),
415            crate::TypeInner::Matrix {
416                columns,
417                rows,
418                scalar,
419            } => Some(NumericType::Matrix {
420                columns,
421                rows,
422                scalar,
423            }),
424            _ => None,
425        }
426    }
427
428    const fn scalar(self) -> crate::Scalar {
429        match self {
430            NumericType::Scalar(scalar)
431            | NumericType::Vector { scalar, .. }
432            | NumericType::Matrix { scalar, .. } => scalar,
433        }
434    }
435
436    const fn with_scalar(self, scalar: crate::Scalar) -> Self {
437        match self {
438            NumericType::Scalar(_) => NumericType::Scalar(scalar),
439            NumericType::Vector { size, .. } => NumericType::Vector { size, scalar },
440            NumericType::Matrix { columns, rows, .. } => NumericType::Matrix {
441                columns,
442                rows,
443                scalar,
444            },
445        }
446    }
447}
448
449/// A cooperative type, for use in [`LocalType`].
450#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
451enum CooperativeType {
452    Matrix {
453        columns: crate::CooperativeSize,
454        rows: crate::CooperativeSize,
455        scalar: crate::Scalar,
456        role: crate::CooperativeRole,
457    },
458}
459
460impl CooperativeType {
461    const fn from_inner(inner: &crate::TypeInner) -> Option<Self> {
462        match *inner {
463            crate::TypeInner::CooperativeMatrix {
464                columns,
465                rows,
466                scalar,
467                role,
468            } => Some(Self::Matrix {
469                columns,
470                rows,
471                scalar,
472                role,
473            }),
474            _ => None,
475        }
476    }
477}
478
479/// A SPIR-V type constructed during code generation.
480///
481/// This is the variant of [`LookupType`] used to represent types that might not
482/// be available in the arena. Variants are present here for one of two reasons:
483///
484/// -   They represent types synthesized during code generation, as explained
485///     in the documentation for [`LookupType`].
486///
487/// -   They represent types for which SPIR-V forbids duplicate `OpType...`
488///     instructions, requiring deduplication.
489///
490/// This is not a complete copy of [`TypeInner`]: for example, SPIR-V generation
491/// never synthesizes new struct types, so `LocalType` has nothing for that.
492///
493/// Each `LocalType` variant should be handled identically to its analogous
494/// `TypeInner` variant. You can use the [`Writer::localtype_from_inner`]
495/// function to help with this, by converting everything possible to a
496/// `LocalType` before inspecting it.
497///
498/// ## `LocalType` equality and SPIR-V `OpType` uniqueness
499///
500/// The definition of `Eq` on `LocalType` is carefully chosen to help us follow
501/// certain SPIR-V rules. SPIR-V ยง2.8 requires some classes of `OpType...`
502/// instructions to be unique; for example, you can't have two `OpTypeInt 32 1`
503/// instructions in the same module. All 32-bit signed integers must use the
504/// same type id.
505///
506/// All SPIR-V types that must be unique can be represented as a `LocalType`,
507/// and two `LocalType`s are always `Eq` if SPIR-V would require them to use the
508/// same `OpType...` instruction. This lets us avoid duplicates by recording the
509/// ids of the type instructions we've already generated in a hash table,
510/// [`Writer::lookup_type`], keyed by `LocalType`.
511///
512/// As another example, [`LocalImageType`], stored in the `LocalType::Image`
513/// variant, is designed to help us deduplicate `OpTypeImage` instructions. See
514/// its documentation for details.
515///
516/// SPIR-V does not require pointer types to be unique - but different
517/// SPIR-V ids are considered to be distinct pointer types. Since Naga
518/// uses structural type equality, we need to represent each Naga
519/// equivalence class with a single SPIR-V `OpTypePointer`.
520///
521/// As it always must, the `Hash` implementation respects the `Eq` relation.
522///
523/// [`TypeInner`]: crate::TypeInner
524#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
525enum LocalType {
526    /// A numeric type.
527    Numeric(NumericType),
528    Cooperative(CooperativeType),
529    Pointer {
530        base: Word,
531        class: spirv::StorageClass,
532    },
533    Image(LocalImageType),
534    SampledImage {
535        image_type_id: Word,
536    },
537    Sampler,
538    BindingArray {
539        base: Handle<crate::Type>,
540        size: u32,
541    },
542    AccelerationStructure,
543    RayQuery,
544    HitObject,
545}
546
547/// A type encountered during SPIR-V generation.
548///
549/// In the process of writing SPIR-V, we need to synthesize various types for
550/// intermediate results and such: pointer types, vector/matrix component types,
551/// or even booleans, which usually appear in SPIR-V code even when they're not
552/// used by the module source.
553///
554/// However, we can't use `crate::Type` or `crate::TypeInner` for these, as the
555/// type arena may not contain what we need (it only contains types used
556/// directly by other parts of the IR), and the IR module is immutable, so we
557/// can't add anything to it.
558///
559/// So for local use in the SPIR-V writer, we use this type, which holds either
560/// a handle into the arena, or a [`LocalType`] containing something synthesized
561/// locally.
562///
563/// This is very similar to the [`proc::TypeResolution`] enum, with `LocalType`
564/// playing the role of `TypeInner`. However, `LocalType` also has other
565/// properties needed for SPIR-V generation; see the description of
566/// [`LocalType`] for details.
567///
568/// [`proc::TypeResolution`]: crate::proc::TypeResolution
569#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
570enum LookupType {
571    Handle(Handle<crate::Type>),
572    Local(LocalType),
573}
574
575impl From<LocalType> for LookupType {
576    fn from(local: LocalType) -> Self {
577        Self::Local(local)
578    }
579}
580
581#[derive(Debug, PartialEq, Clone, Hash, Eq)]
582struct LookupFunctionType {
583    parameter_type_ids: Vec<Word>,
584    return_type_id: Word,
585}
586
587#[derive(Debug, PartialEq, Clone, Hash, Eq)]
588enum LookupRayQueryFunction {
589    Initialize,
590    Proceed,
591    GenerateIntersection,
592    ConfirmIntersection,
593    GetVertexPositions { committed: bool },
594    GetIntersection { committed: bool },
595    Terminate,
596}
597
598#[derive(Debug, PartialEq, Clone, Hash, Eq)]
599enum LookupRaytracingFunction {
600    TraceRay {
601        payload: Handle<crate::GlobalVariable>,
602    },
603    HitObjectTraceRay {
604        payload: Handle<crate::GlobalVariable>,
605    },
606    HitObjectRecordMiss,
607    HitObjectRecordFromQuery,
608    HitObjectExecuteShader {
609        payload: Handle<crate::GlobalVariable>,
610    },
611    HitObjectGetIntersection,
612}
613
614#[derive(Debug)]
615enum Dimension {
616    Scalar,
617    Vector,
618    Matrix,
619    CooperativeMatrix,
620}
621
622/// Key used to look up an operation which we have wrapped in a helper
623/// function, which should be called instead of directly emitting code
624/// for the expression. See [`Writer::wrapped_functions`].
625#[derive(Debug, Eq, PartialEq, Hash)]
626enum WrappedFunction {
627    BinaryOp {
628        op: crate::BinaryOperator,
629        left_type_id: Word,
630        right_type_id: Word,
631    },
632    ConvertFromStd140CompatType {
633        r#type: Handle<crate::Type>,
634    },
635    MatCx2GetColumn {
636        r#type: Handle<crate::Type>,
637    },
638}
639
640/// A map from evaluated [`Expression`](crate::Expression)s to their SPIR-V ids.
641///
642/// When we emit code to evaluate a given `Expression`, we record the
643/// SPIR-V id of its value here, under its `Handle<Expression>` index.
644///
645/// A `CachedExpressions` value can be indexed by a `Handle<Expression>` value.
646///
647/// [emit]: index.html#expression-evaluation-time-and-scope
648#[derive(Default)]
649struct CachedExpressions {
650    ids: HandleVec<crate::Expression, Word>,
651}
652impl CachedExpressions {
653    fn reset(&mut self, length: usize) {
654        self.ids.clear();
655        self.ids.resize(length, 0);
656    }
657}
658impl ops::Index<Handle<crate::Expression>> for CachedExpressions {
659    type Output = Word;
660    fn index(&self, h: Handle<crate::Expression>) -> &Word {
661        let id = &self.ids[h];
662        if *id == 0 {
663            unreachable!("Expression {:?} is not cached!", h);
664        }
665        id
666    }
667}
668impl ops::IndexMut<Handle<crate::Expression>> for CachedExpressions {
669    fn index_mut(&mut self, h: Handle<crate::Expression>) -> &mut Word {
670        let id = &mut self.ids[h];
671        if *id != 0 {
672            unreachable!("Expression {:?} is already cached!", h);
673        }
674        id
675    }
676}
677impl reclaimable::Reclaimable for CachedExpressions {
678    fn reclaim(self) -> Self {
679        CachedExpressions {
680            ids: self.ids.reclaim(),
681        }
682    }
683}
684
685#[derive(Eq, Hash, PartialEq)]
686enum CachedConstant {
687    Literal(crate::proc::HashableLiteral),
688    Composite {
689        ty: LookupType,
690        constituent_ids: Vec<Word>,
691    },
692    ZeroValue(Word),
693}
694
695/// The SPIR-V representation of a [`crate::GlobalVariable`].
696///
697/// In the Vulkan spec 1.3.296, the section [Descriptor Set Interface][dsi] says:
698///
699/// > Variables identified with the `Uniform` storage class are used to access
700/// > transparent buffer backed resources. Such variables *must* be:
701/// >
702/// > -   typed as `OpTypeStruct`, or an array of this type,
703/// >
704/// > -   identified with a `Block` or `BufferBlock` decoration, and
705/// >
706/// > -   laid out explicitly using the `Offset`, `ArrayStride`, and `MatrixStride`
707/// >     decorations as specified in "Offset and Stride Assignment".
708///
709/// This is followed by identical language for the `StorageBuffer`,
710/// except that a `BufferBlock` decoration is not allowed.
711///
712/// When we encounter a global variable in the [`Storage`] or [`Uniform`]
713/// address spaces whose type is not already [`Struct`], this backend implicitly
714/// wraps the global variable in a struct: we generate a SPIR-V global variable
715/// holding an `OpTypeStruct` with a single member, whose type is what the Naga
716/// global's type would suggest, decorated as required above.
717///
718/// The [`helpers::global_needs_wrapper`] function determines whether a given
719/// [`crate::GlobalVariable`] needs to be wrapped.
720///
721/// [dsi]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-resources-descset
722/// [`Storage`]: crate::AddressSpace::Storage
723/// [`Uniform`]: crate::AddressSpace::Uniform
724/// [`Struct`]: crate::TypeInner::Struct
725#[derive(Clone)]
726struct GlobalVariable {
727    /// The SPIR-V id of the `OpVariable` that declares the global.
728    ///
729    /// If this global has been implicitly wrapped in an `OpTypeStruct`, this id
730    /// refers to the wrapper, not the original Naga value it contains. If you
731    /// need the Naga value, use [`access_id`] instead of this field.
732    ///
733    /// If this global is not implicitly wrapped, this is the same as
734    /// [`access_id`].
735    ///
736    /// This is used to compute the `access_id` pointer in function prologues,
737    /// and used for `ArrayLength` expressions, which need to pass the wrapper
738    /// struct.
739    ///
740    /// [`access_id`]: GlobalVariable::access_id
741    var_id: Word,
742
743    /// The loaded value of a `AddressSpace::Handle` global variable.
744    ///
745    /// If the current function uses this global variable, this is the id of an
746    /// `OpLoad` instruction in the function's prologue that loads its value.
747    /// (This value is assigned as we write the prologue code of each function.)
748    /// It is then used for all operations on the global, such as `OpImageSample`.
749    handle_id: Word,
750
751    /// The SPIR-V id of a pointer to this variable's Naga IR value.
752    ///
753    /// If the current function uses this global variable, and it has been
754    /// implicitly wrapped in an `OpTypeStruct`, this is the id of an
755    /// `OpAccessChain` instruction in the function's prologue that refers to
756    /// the wrapped value inside the struct. (This value is assigned as we write
757    /// the prologue code of each function.) If you need the wrapper struct
758    /// itself, use [`var_id`] instead of this field.
759    ///
760    /// If this global is not implicitly wrapped, this is the same as
761    /// [`var_id`].
762    ///
763    /// [`var_id`]: GlobalVariable::var_id
764    access_id: Word,
765}
766
767impl GlobalVariable {
768    const fn dummy() -> Self {
769        Self {
770            var_id: 0,
771            handle_id: 0,
772            access_id: 0,
773        }
774    }
775
776    const fn new(id: Word) -> Self {
777        Self {
778            var_id: id,
779            handle_id: 0,
780            access_id: 0,
781        }
782    }
783
784    /// Prepare `self` for use within a single function.
785    const fn reset_for_function(&mut self) {
786        self.handle_id = 0;
787        self.access_id = 0;
788    }
789}
790
791struct FunctionArgument {
792    /// Actual instruction of the argument.
793    instruction: Instruction,
794    handle_id: Word,
795}
796
797/// Tracks the expressions for which the backend emits the following instructions:
798/// - OpConstantTrue
799/// - OpConstantFalse
800/// - OpConstant
801/// - OpConstantComposite
802/// - OpConstantNull
803struct ExpressionConstnessTracker {
804    inner: crate::arena::HandleSet<crate::Expression>,
805}
806
807impl ExpressionConstnessTracker {
808    fn from_arena(arena: &crate::Arena<crate::Expression>) -> Self {
809        let mut inner = crate::arena::HandleSet::for_arena(arena);
810        for (handle, expr) in arena.iter() {
811            let insert = match *expr {
812                crate::Expression::Literal(_)
813                | crate::Expression::ZeroValue(_)
814                | crate::Expression::Constant(_) => true,
815                crate::Expression::Compose { ref components, .. } => {
816                    components.iter().all(|&h| inner.contains(h))
817                }
818                crate::Expression::Splat { value, .. } => inner.contains(value),
819                _ => false,
820            };
821            if insert {
822                inner.insert(handle);
823            }
824        }
825        Self { inner }
826    }
827
828    fn is_const(&self, value: Handle<crate::Expression>) -> bool {
829        self.inner.contains(value)
830    }
831}
832
833/// General information needed to emit SPIR-V for Naga statements.
834struct BlockContext<'w> {
835    /// The writer handling the module to which this code belongs.
836    writer: &'w mut Writer,
837
838    /// The [`Module`](crate::Module) for which we're generating code.
839    ir_module: &'w crate::Module,
840
841    /// The [`Function`](crate::Function) for which we're generating code.
842    ir_function: &'w crate::Function,
843
844    /// Information module validation produced about
845    /// [`ir_function`](BlockContext::ir_function).
846    fun_info: &'w crate::valid::FunctionInfo,
847
848    /// The [`spv::Function`](Function) to which we are contributing SPIR-V instructions.
849    function: &'w mut Function,
850
851    /// SPIR-V ids for expressions we've evaluated.
852    cached: CachedExpressions,
853
854    /// The `Writer`'s temporary vector, for convenience.
855    temp_list: Vec<Word>,
856
857    /// Tracks the constness of `Expression`s residing in `self.ir_function.expressions`
858    expression_constness: ExpressionConstnessTracker,
859
860    force_loop_bounding: bool,
861
862    /// Hash from an expression whose type is a ray query / pointer to a ray query to its tracker.
863    /// Note: this is sparse, so can't be a handle vec
864    ray_query_tracker_expr: crate::FastHashMap<Handle<crate::Expression>, RayQueryTrackers>,
865}
866
867#[derive(Clone, Copy)]
868struct RayQueryTrackers {
869    // Initialization tracker
870    initialized_tracker: Word,
871    // Tracks the t max from ray query initialize.
872    // Unlike HLSL, spir-v's equivalent getter for the current committed t has UB (instead of just
873    // returning t_max) if there was no previous hit (though in some places it treats the behaviour as
874    // defined), therefore we must track the tmax inputted into ray query initialize.
875    t_max_tracker: Word,
876}
877
878impl BlockContext<'_> {
879    const fn gen_id(&mut self) -> Word {
880        self.writer.id_gen.next()
881    }
882
883    fn get_type_id(&mut self, lookup_type: LookupType) -> Word {
884        self.writer.get_type_id(lookup_type)
885    }
886
887    fn get_handle_type_id(&mut self, handle: Handle<crate::Type>) -> Word {
888        self.writer.get_handle_type_id(handle)
889    }
890
891    fn get_expression_type_id(&mut self, tr: &TypeResolution) -> Word {
892        self.writer.get_expression_type_id(tr)
893    }
894
895    fn get_index_constant(&mut self, index: Word) -> Word {
896        self.writer.get_constant_scalar(crate::Literal::U32(index))
897    }
898
899    fn get_scope_constant(&mut self, scope: Word) -> Word {
900        self.writer
901            .get_constant_scalar(crate::Literal::I32(scope as _))
902    }
903
904    fn get_pointer_type_id(&mut self, base: Word, class: spirv::StorageClass) -> Word {
905        self.writer.get_pointer_type_id(base, class)
906    }
907
908    fn get_numeric_type_id(&mut self, numeric: NumericType) -> Word {
909        self.writer.get_numeric_type_id(numeric)
910    }
911}
912
913/// Information about a type for which we have declared a std140 layout
914/// compatible variant, because the type is used in a uniform but does not
915/// adhere to std140 requirements. The uniform will be declared using the
916/// type `type_id`, and the result of any `Load` will be immediately converted
917/// to the base type. This is used for matrices with 2 rows, as well as any
918/// arrays or structs containing such matrices.
919#[derive(Debug)]
920pub struct Std140CompatTypeInfo {
921    /// ID of the std140 compatible type declaration.
922    type_id: Word,
923    /// For structs, a mapping of Naga IR struct member indices to the indices
924    /// used in the generated SPIR-V. For non-struct types this will be empty.
925    member_indices: Vec<u32>,
926}
927
928#[expect(missing_debug_implementations, reason = "would be way too verbose?")]
929pub struct Writer {
930    physical_layout: PhysicalLayout,
931    logical_layout: LogicalLayout,
932    id_gen: IdGenerator,
933
934    /// The set of capabilities modules are permitted to use.
935    ///
936    /// This is initialized from `Options::capabilities`.
937    capabilities_available: Option<crate::FastHashSet<Capability>>,
938
939    /// The set of capabilities used by this module.
940    ///
941    /// If `capabilities_available` is `Some`, then this is always a subset of
942    /// that.
943    capabilities_used: crate::FastIndexSet<Capability>,
944
945    /// The set of spirv extensions used.
946    extensions_used: crate::FastIndexSet<&'static str>,
947
948    debug_strings: Vec<Instruction>,
949    debugs: Vec<Instruction>,
950    annotations: Vec<Instruction>,
951    flags: WriterFlags,
952    bounds_check_policies: BoundsCheckPolicies,
953    zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
954    force_loop_bounding: bool,
955    use_storage_input_output_16: bool,
956    emit_int_div_checks: bool,
957    void_type: Word,
958    tuple_of_u32s_ty_id: Option<Word>,
959    //TODO: convert most of these into vectors, addressable by handle indices
960    lookup_type: crate::FastHashMap<LookupType, Word>,
961    lookup_function: crate::FastHashMap<Handle<crate::Function>, Word>,
962    lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
963    /// Operations which have been wrapped in a helper function. The value is
964    /// the ID of the function, which should be called instead of emitting code
965    /// for the operation directly.
966    wrapped_functions: crate::FastHashMap<WrappedFunction, Word>,
967    /// Indexed by const-expression handle indexes
968    constant_ids: HandleVec<crate::Expression, Word>,
969    cached_constants: crate::FastHashMap<CachedConstant, Word>,
970    global_variables: HandleVec<crate::GlobalVariable, GlobalVariable>,
971    std140_compat_uniform_types: crate::FastHashMap<Handle<crate::Type>, Std140CompatTypeInfo>,
972    fake_missing_bindings: bool,
973    binding_map: BindingMap,
974
975    // Cached expressions are only meaningful within a BlockContext, but we
976    // retain the table here between functions to save heap allocations.
977    saved_cached: CachedExpressions,
978
979    gl450_ext_inst_id: Word,
980
981    // Just a temporary list of SPIR-V ids
982    temp_list: Vec<Word>,
983
984    ray_query_functions: crate::FastHashMap<LookupRayQueryFunction, Word>,
985
986    ray_tracing_functions: crate::FastHashMap<LookupRaytracingFunction, Word>,
987
988    has_ray_tracing_pipeline: bool,
989
990    /// The module-scope `HitObjectAttributeEXT` variable used to retrieve
991    /// triangle barycentrics from a hit object, created lazily.
992    hit_object_attribute_var: Option<Word>,
993
994    /// F16 I/O polyfill manager for handling `f16` input/output variables
995    /// when `StorageInputOutput16` capability is not available.
996    io_f16_polyfills: f16_polyfill::F16IoPolyfill,
997
998    /// Non semantic debug printf extension `OpExtInstImport`
999    debug_printf: Option<Word>,
1000    pub(crate) ray_query_initialization_tracking: bool,
1001
1002    /// Whether the arguments to trace ray should be validated
1003    pub(crate) trace_ray_argument_validation: bool,
1004
1005    /// See docs in [`Options`]
1006    task_dispatch_limits: Option<TaskDispatchLimits>,
1007    /// See docs in [`Options`]
1008    mesh_shader_primitive_indices_clamp: bool,
1009}
1010
1011bitflags::bitflags! {
1012    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1013    pub struct WriterFlags: u32 {
1014        /// Include debug labels for everything.
1015        const DEBUG = 0x1;
1016
1017        /// Flip Y coordinate of [`BuiltIn::Position`] output.
1018        ///
1019        /// [`BuiltIn::Position`]: crate::BuiltIn::Position
1020        const ADJUST_COORDINATE_SPACE = 0x2;
1021
1022        /// Emit [`OpName`][op] for input/output locations.
1023        ///
1024        /// Contrary to spec, some drivers treat it as semantic, not allowing
1025        /// any conflicts.
1026        ///
1027        /// [op]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpName
1028        const LABEL_VARYINGS = 0x4;
1029
1030        /// Emit [`PointSize`] output builtin to vertex shaders, which is
1031        /// required for drawing with `PointList` topology.
1032        ///
1033        /// [`PointSize`]: crate::BuiltIn::PointSize
1034        const FORCE_POINT_SIZE = 0x8;
1035
1036        /// Clamp [`BuiltIn::FragDepth`] output between 0 and 1.
1037        ///
1038        /// [`BuiltIn::FragDepth`]: crate::BuiltIn::FragDepth
1039        const CLAMP_FRAG_DEPTH = 0x10;
1040
1041        /// Instead of silently failing if the arguments to generate a ray query are
1042        /// invalid, uses debug printf extension to print to the command line
1043        ///
1044        /// Note: VK_KHR_shader_non_semantic_info must be enabled. This will have no
1045        /// effect if `options.ray_query_initialization_tracking` is set to false.
1046        const PRINT_ON_RAY_QUERY_INITIALIZATION_FAIL = 0x20;
1047
1048        /// Instead of silently failing if the arguments to `traceRays` are
1049        /// invalid, uses debug printf extension to print to the command line
1050        ///
1051        /// Note: VK_KHR_shader_non_semantic_info must be enabled. This will have no
1052        /// effect if `options.trace_ray_argument_validation` is set to false.
1053        const PRINT_ON_TRACE_RAYS_FAIL = 0x40;
1054    }
1055}
1056
1057#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1058pub enum ZeroInitializeWorkgroupMemoryMode {
1059    /// Via `VK_KHR_zero_initialize_workgroup_memory` or Vulkan 1.3
1060    Native,
1061    /// Via assignments + barrier
1062    Polyfill,
1063    None,
1064}
1065
1066#[derive(Debug, Clone)]
1067pub struct Options<'a> {
1068    /// (Major, Minor) target version of the SPIR-V.
1069    pub lang_version: (u8, u8),
1070
1071    /// Configuration flags for the writer.
1072    pub flags: WriterFlags,
1073
1074    /// Don't panic on missing bindings. Instead use fake values for `Binding`
1075    /// and `DescriptorSet` decorations. This may result in invalid SPIR-V.
1076    pub fake_missing_bindings: bool,
1077
1078    /// Map of resources to information about the binding.
1079    pub binding_map: BindingMap,
1080
1081    /// If given, the set of capabilities modules are allowed to use. Code that
1082    /// requires capabilities beyond these is rejected with an error.
1083    ///
1084    /// If this is `None`, all capabilities are permitted.
1085    pub capabilities: Option<crate::FastHashSet<Capability>>,
1086
1087    /// How should generate code handle array, vector, matrix, or image texel
1088    /// indices that are out of range?
1089    pub bounds_check_policies: BoundsCheckPolicies,
1090
1091    /// Dictates the way workgroup variables should be zero initialized
1092    pub zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode,
1093
1094    /// If set, loops will have code injected into them, forcing the compiler
1095    /// to think the number of iterations is bounded.
1096    pub force_loop_bounding: bool,
1097
1098    /// if set, ray queries will get a variable to track their state to prevent
1099    /// misuse.
1100    pub ray_query_initialization_tracking: bool,
1101
1102    /// If set, arguments to `traceRays` calls will be validated.
1103    pub trace_ray_argument_validation: bool,
1104
1105    /// Whether to use the `StorageInputOutput16` capability for `f16` shader I/O.
1106    /// When false, `f16` I/O is polyfilled using `f32` types with conversions.
1107    pub use_storage_input_output_16: bool,
1108
1109    pub debug_info: Option<DebugInfo<'a>>,
1110
1111    /// Limits to the mesh shader dispatch group a task workgroup can dispatch.
1112    ///
1113    /// Metal for example limits to 1024 workgroups per task shader dispatch. Dispatching more is
1114    /// undefined behavior, so this would validate that to dispatch zero workgroups.
1115    pub task_dispatch_limits: Option<TaskDispatchLimits>,
1116
1117    /// If true, naga may generate checks that the primitive indices are valid in the output.
1118    ///
1119    /// Currently this validation is unimplemented.
1120    pub mesh_shader_primitive_indices_clamp: bool,
1121
1122    /// If true (the default), integer division and modulo operations emit
1123    /// wrapper functions that replace a zero divisor with one, and for signed
1124    /// integers also guard against `INT_MIN / -1` overflow. This matches the
1125    /// WGSL spec's requirement that these cases produce defined results.
1126    ///
1127    /// Set to `false` to emit raw `OpSDiv`/`OpUDiv`/`OpSRem`/`OpUMod`
1128    /// instructions without checks. This is faster but produces
1129    /// implementation-defined results when the divisor is zero. Appropriate
1130    /// for compute shaders where the developer guarantees non-zero divisors.
1131    pub emit_int_div_checks: bool,
1132}
1133
1134impl Default for Options<'_> {
1135    fn default() -> Self {
1136        let mut flags = WriterFlags::ADJUST_COORDINATE_SPACE
1137            | WriterFlags::LABEL_VARYINGS
1138            | WriterFlags::CLAMP_FRAG_DEPTH;
1139        if cfg!(debug_assertions) {
1140            flags |= WriterFlags::DEBUG;
1141        }
1142        Options {
1143            lang_version: (1, 0),
1144            flags,
1145            fake_missing_bindings: true,
1146            binding_map: BindingMap::default(),
1147            capabilities: None,
1148            bounds_check_policies: BoundsCheckPolicies::default(),
1149            zero_initialize_workgroup_memory: ZeroInitializeWorkgroupMemoryMode::Polyfill,
1150            force_loop_bounding: true,
1151            ray_query_initialization_tracking: true,
1152            trace_ray_argument_validation: true,
1153            use_storage_input_output_16: true,
1154            debug_info: None,
1155            task_dispatch_limits: None,
1156            mesh_shader_primitive_indices_clamp: true,
1157            emit_int_div_checks: true,
1158        }
1159    }
1160}
1161
1162// A subset of options meant to be changed per pipeline.
1163#[derive(Debug, Clone)]
1164#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
1165#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
1166pub struct PipelineOptions {
1167    /// The stage of the entry point.
1168    pub shader_stage: crate::ShaderStage,
1169    /// The name of the entry point.
1170    ///
1171    /// If no entry point that matches is found while creating a [`Writer`], a error will be thrown.
1172    pub entry_point: String,
1173}
1174
1175pub fn write_vec(
1176    module: &crate::Module,
1177    info: &crate::valid::ModuleInfo,
1178    options: &Options,
1179    pipeline_options: Option<&PipelineOptions>,
1180) -> Result<Vec<u32>, Error> {
1181    let mut words: Vec<u32> = Vec::new();
1182    let mut w = Writer::new(options)?;
1183
1184    w.write(
1185        module,
1186        info,
1187        pipeline_options,
1188        &options.debug_info,
1189        &mut words,
1190    )?;
1191    Ok(words)
1192}
1193
1194pub fn supported_capabilities() -> crate::valid::Capabilities {
1195    use crate::valid::Capabilities as Caps;
1196
1197    Caps::IMMEDIATES
1198        | Caps::FLOAT64
1199        | Caps::PRIMITIVE_INDEX
1200        | Caps::TEXTURE_AND_SAMPLER_BINDING_ARRAY
1201        | Caps::BUFFER_BINDING_ARRAY
1202        | Caps::STORAGE_TEXTURE_BINDING_ARRAY
1203        | Caps::STORAGE_BUFFER_BINDING_ARRAY
1204        | Caps::ACCELERATION_STRUCTURE_BINDING_ARRAY
1205        | Caps::CLIP_DISTANCES
1206        // No cull distance
1207        | Caps::STORAGE_TEXTURE_16BIT_NORM_FORMATS
1208        | Caps::MULTIVIEW
1209        | Caps::EARLY_DEPTH_TEST
1210        | Caps::MULTISAMPLED_SHADING
1211        | Caps::RAY_QUERY
1212        | Caps::DUAL_SOURCE_BLENDING
1213        | Caps::CUBE_ARRAY_TEXTURES
1214        | Caps::SHADER_INT64
1215        | Caps::SUBGROUP
1216        | Caps::SUBGROUP_BARRIER
1217        | Caps::SUBGROUP_VERTEX_STAGE
1218        | Caps::SHADER_INT64_ATOMIC_MIN_MAX
1219        | Caps::SHADER_INT64_ATOMIC_ALL_OPS
1220        | Caps::SHADER_FLOAT32_ATOMIC
1221        | Caps::TEXTURE_ATOMIC
1222        | Caps::TEXTURE_INT64_ATOMIC
1223        | Caps::RAY_HIT_VERTEX_POSITION
1224        | Caps::SHADER_FLOAT16
1225        | Caps::SHADER_INT16
1226        // No TEXTURE_EXTERNAL
1227        | Caps::SHADER_BARYCENTRICS
1228        | Caps::MESH_SHADER
1229        | Caps::MESH_SHADER_POINT_TOPOLOGY
1230        | Caps::TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING
1231        // No BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
1232        | Caps::STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING
1233        | Caps::STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
1234        | Caps::COOPERATIVE_MATRIX
1235        | Caps::PER_VERTEX
1236        | Caps::RAY_TRACING_PIPELINE
1237        | Caps::RAY_TRACING_INVOCATION_REORDER
1238        | Caps::DRAW_INDEX
1239        | Caps::MEMORY_DECORATION_COHERENT
1240        | Caps::MEMORY_DECORATION_VOLATILE
1241        | Caps::LINEAR_INTERPOLATION
1242        | Caps::DEBUG_PRINTF
1243}