naga/valid/
mod.rs

1/*!
2Shader validator.
3*/
4
5mod analyzer;
6mod compose;
7mod expression;
8mod function;
9mod handles;
10mod interface;
11mod r#type;
12
13use alloc::{boxed::Box, string::String, vec, vec::Vec};
14use core::ops;
15
16use bit_set::BitSet;
17
18use crate::{
19    arena::{Handle, HandleSet},
20    proc::{ExpressionKindTracker, LayoutError, Layouter, TypeResolution},
21    FastHashSet,
22};
23
24//TODO: analyze the model at the same time as we validate it,
25// merge the corresponding matches over expressions and statements.
26
27use crate::span::{AddSpan as _, WithSpan};
28pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements};
29pub use compose::ComposeError;
30pub use expression::{check_literal_value, LiteralError};
31pub use expression::{ConstExpressionError, ExpressionError};
32pub use function::{CallError, FunctionError, LocalVariableError, SubgroupError};
33pub use interface::{EntryPointError, GlobalVariableError, VaryingError};
34pub use r#type::{Disalignment, ImmediateError, TypeError, TypeFlags, WidthError};
35
36use self::handles::InvalidHandleError;
37
38/// Maximum size of a type, in bytes.
39pub const MAX_TYPE_SIZE: u32 = 0x4000_0000; // 1GB
40
41bitflags::bitflags! {
42    /// Validation flags.
43    ///
44    /// If you are working with trusted shaders, then you may be able
45    /// to save some time by skipping validation.
46    ///
47    /// If you do not perform full validation, invalid shaders may
48    /// cause Naga to panic. If you do perform full validation and
49    /// [`Validator::validate`] returns `Ok`, then Naga promises that
50    /// code generation will either succeed or return an error; it
51    /// should never panic.
52    ///
53    /// The default value for `ValidationFlags` is
54    /// `ValidationFlags::all()`.
55    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
56    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
57    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
58    pub struct ValidationFlags: u8 {
59        /// Expressions.
60        const EXPRESSIONS = 0x1;
61        /// Statements and blocks of them.
62        const BLOCKS = 0x2;
63        /// Uniformity of control flow for operations that require it.
64        const CONTROL_FLOW_UNIFORMITY = 0x4;
65        /// Host-shareable structure layouts.
66        const STRUCT_LAYOUTS = 0x8;
67        /// Constants.
68        const CONSTANTS = 0x10;
69        /// Group, binding, and location attributes.
70        const BINDINGS = 0x20;
71    }
72}
73
74impl Default for ValidationFlags {
75    fn default() -> Self {
76        Self::all()
77    }
78}
79
80bitflags::bitflags! {
81    /// Allowed IR capabilities.
82    #[must_use]
83    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
84    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
85    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
86    pub struct Capabilities: u64 {
87        /// Support for [`AddressSpace::Immediate`][1].
88        ///
89        /// [1]: crate::AddressSpace::Immediate
90        const IMMEDIATES = 1 << 0;
91        /// Float values with width = 8.
92        const FLOAT64 = 1 << 1;
93        /// Support for [`BuiltIn::PrimitiveIndex`][1].
94        ///
95        /// [1]: crate::BuiltIn::PrimitiveIndex
96        const PRIMITIVE_INDEX = 1 << 2;
97        /// Support for binding arrays of sampled textures and samplers.
98        const TEXTURE_AND_SAMPLER_BINDING_ARRAY = 1 << 3;
99        /// Support for binding arrays of uniform buffers.
100        const BUFFER_BINDING_ARRAY = 1 << 4;
101        /// Support for binding arrays of storage textures.
102        const STORAGE_TEXTURE_BINDING_ARRAY = 1 << 5;
103        /// Support for binding arrays of storage buffers.
104        const STORAGE_BUFFER_BINDING_ARRAY = 1 << 6;
105        /// Support for [`BuiltIn::ClipDistance`].
106        ///
107        /// [`BuiltIn::ClipDistance`]: crate::BuiltIn::ClipDistance
108        const CLIP_DISTANCE = 1 << 7;
109        /// Support for [`BuiltIn::CullDistance`].
110        ///
111        /// [`BuiltIn::CullDistance`]: crate::BuiltIn::CullDistance
112        const CULL_DISTANCE = 1 << 8;
113        /// Support for 16-bit normalized storage texture formats.
114        const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 1 << 9;
115        /// Support for [`BuiltIn::ViewIndex`].
116        ///
117        /// [`BuiltIn::ViewIndex`]: crate::BuiltIn::ViewIndex
118        const MULTIVIEW = 1 << 10;
119        /// Support for `early_depth_test`.
120        const EARLY_DEPTH_TEST = 1 << 11;
121        /// Support for [`BuiltIn::SampleIndex`] and [`Sampling::Sample`].
122        ///
123        /// [`BuiltIn::SampleIndex`]: crate::BuiltIn::SampleIndex
124        /// [`Sampling::Sample`]: crate::Sampling::Sample
125        const MULTISAMPLED_SHADING = 1 << 12;
126        /// Support for ray queries and acceleration structures.
127        const RAY_QUERY = 1 << 13;
128        /// Support for generating two sources for blending from fragment shaders.
129        const DUAL_SOURCE_BLENDING = 1 << 14;
130        /// Support for arrayed cube textures.
131        const CUBE_ARRAY_TEXTURES = 1 << 15;
132        /// Support for 64-bit signed and unsigned integers.
133        const SHADER_INT64 = 1 << 16;
134        /// Support for subgroup operations (except barriers) in fragment and compute shaders.
135        ///
136        /// Subgroup operations in the vertex stage require
137        /// [`Capabilities::SUBGROUP_VERTEX_STAGE`] in addition to `Capabilities::SUBGROUP`.
138        /// (But note that `create_validator` automatically sets
139        /// `Capabilities::SUBGROUP` whenever `Features::SUBGROUP_VERTEX` is
140        /// available.)
141        ///
142        /// Subgroup barriers require [`Capabilities::SUBGROUP_BARRIER`] in addition to
143        /// `Capabilities::SUBGROUP`.
144        const SUBGROUP = 1 << 17;
145        /// Support for subgroup barriers in compute shaders.
146        ///
147        /// Requires [`Capabilities::SUBGROUP`]. Without it, enables nothing.
148        const SUBGROUP_BARRIER = 1 << 18;
149        /// Support for subgroup operations (not including barriers) in the vertex stage.
150        ///
151        /// Without [`Capabilities::SUBGROUP`], enables nothing. (But note that
152        /// `create_validator` automatically sets `Capabilities::SUBGROUP`
153        /// whenever `Features::SUBGROUP_VERTEX` is available.)
154        const SUBGROUP_VERTEX_STAGE = 1 << 19;
155        /// Support for [`AtomicFunction::Min`] and [`AtomicFunction::Max`] on
156        /// 64-bit integers in the [`Storage`] address space, when the return
157        /// value is not used.
158        ///
159        /// This is the only 64-bit atomic functionality available on Metal 3.1.
160        ///
161        /// [`AtomicFunction::Min`]: crate::AtomicFunction::Min
162        /// [`AtomicFunction::Max`]: crate::AtomicFunction::Max
163        /// [`Storage`]: crate::AddressSpace::Storage
164        const SHADER_INT64_ATOMIC_MIN_MAX = 1 << 20;
165        /// Support for all atomic operations on 64-bit integers.
166        const SHADER_INT64_ATOMIC_ALL_OPS = 1 << 21;
167        /// Support for [`AtomicFunction::Add`], [`AtomicFunction::Sub`],
168        /// and [`AtomicFunction::Exchange { compare: None }`] on 32-bit floating-point numbers
169        /// in the [`Storage`] address space.
170        ///
171        /// [`AtomicFunction::Add`]: crate::AtomicFunction::Add
172        /// [`AtomicFunction::Sub`]: crate::AtomicFunction::Sub
173        /// [`AtomicFunction::Exchange { compare: None }`]: crate::AtomicFunction::Exchange
174        /// [`Storage`]: crate::AddressSpace::Storage
175        const SHADER_FLOAT32_ATOMIC = 1 << 22;
176        /// Support for atomic operations on images.
177        const TEXTURE_ATOMIC = 1 << 23;
178        /// Support for atomic operations on 64-bit images.
179        const TEXTURE_INT64_ATOMIC = 1 << 24;
180        /// Support for ray queries returning vertex position
181        const RAY_HIT_VERTEX_POSITION = 1 << 25;
182        /// Support for 16-bit floating-point types.
183        const SHADER_FLOAT16 = 1 << 26;
184        /// Support for [`ImageClass::External`]
185        const TEXTURE_EXTERNAL = 1 << 27;
186        /// Support for `quantizeToF16`, `pack2x16float`, and `unpack2x16float`, which store
187        /// `f16`-precision values in `f32`s.
188        const SHADER_FLOAT16_IN_FLOAT32 = 1 << 28;
189        /// Support for fragment shader barycentric coordinates.
190        const SHADER_BARYCENTRICS = 1 << 29;
191        /// Support for task shaders, mesh shaders, and per-primitive fragment inputs
192        const MESH_SHADER = 1 << 30;
193        /// Support for mesh shaders which output points.
194        const MESH_SHADER_POINT_TOPOLOGY = 1 << 31;
195        /// Support for non-uniform indexing of binding arrays of sampled textures and samplers.
196        const TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 32;
197        /// Support for non-uniform indexing of binding arrays of uniform buffers.
198        const BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 33;
199        /// Support for non-uniform indexing of binding arrays of storage textures.
200        const STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 34;
201        /// Support for non-uniform indexing of binding arrays of storage buffers.
202        const STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 35;
203        /// Support for cooperative matrix types and operations
204        const COOPERATIVE_MATRIX = 1 << 36;
205        /// Support for per-vertex fragment input.
206        const PER_VERTEX = 1 << 37;
207        /// Support for ray generation, any hit, closest hit, and miss shaders.
208        const RAY_TRACING_PIPELINE = 1 << 38;
209        /// Support for draw index builtin
210        const DRAW_INDEX = 1 << 39;
211    }
212}
213
214impl Capabilities {
215    /// Returns the extension corresponding to this capability, if there is one.
216    ///
217    /// This is used by integration tests.
218    #[cfg(feature = "wgsl-in")]
219    #[doc(hidden)]
220    pub const fn extension(&self) -> Option<crate::front::wgsl::ImplementedEnableExtension> {
221        use crate::front::wgsl::ImplementedEnableExtension as Ext;
222        match *self {
223            Self::DUAL_SOURCE_BLENDING => Some(Ext::DualSourceBlending),
224            // NOTE: `SHADER_FLOAT16_IN_FLOAT32` _does not_ require the `f16` extension
225            Self::SHADER_FLOAT16 => Some(Ext::F16),
226            Self::CLIP_DISTANCE => Some(Ext::ClipDistances),
227            Self::MESH_SHADER => Some(Ext::WgpuMeshShader),
228            Self::RAY_QUERY => Some(Ext::WgpuRayQuery),
229            Self::RAY_HIT_VERTEX_POSITION => Some(Ext::WgpuRayQueryVertexReturn),
230            Self::COOPERATIVE_MATRIX => Some(Ext::WgpuCooperativeMatrix),
231            Self::RAY_TRACING_PIPELINE => Some(Ext::WgpuRayTracingPipeline),
232            _ => None,
233        }
234    }
235}
236
237impl Default for Capabilities {
238    fn default() -> Self {
239        Self::MULTISAMPLED_SHADING | Self::CUBE_ARRAY_TEXTURES
240    }
241}
242
243bitflags::bitflags! {
244    /// Supported subgroup operations
245    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
246    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
247    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
248    pub struct SubgroupOperationSet: u8 {
249        /// Barriers
250        // Possibly elections, when that is supported.
251        // https://github.com/gfx-rs/wgpu/issues/6042#issuecomment-3272603431
252        // Contrary to what the name "basic" suggests, HLSL/DX12 support the
253        // other subgroup operations, but do not support subgroup barriers.
254        const BASIC = 1 << 0;
255        /// Any, All
256        const VOTE = 1 << 1;
257        /// reductions, scans
258        const ARITHMETIC = 1 << 2;
259        /// ballot, broadcast
260        const BALLOT = 1 << 3;
261        /// shuffle, shuffle xor
262        const SHUFFLE = 1 << 4;
263        /// shuffle up, down
264        const SHUFFLE_RELATIVE = 1 << 5;
265        // We don't support these operations yet
266        // /// Clustered
267        // const CLUSTERED = 1 << 6;
268        /// Quad supported
269        const QUAD_FRAGMENT_COMPUTE = 1 << 7;
270        // /// Quad supported in all stages
271        // const QUAD_ALL_STAGES = 1 << 8;
272    }
273}
274
275impl super::SubgroupOperation {
276    const fn required_operations(&self) -> SubgroupOperationSet {
277        use SubgroupOperationSet as S;
278        match *self {
279            Self::All | Self::Any => S::VOTE,
280            Self::Add | Self::Mul | Self::Min | Self::Max | Self::And | Self::Or | Self::Xor => {
281                S::ARITHMETIC
282            }
283        }
284    }
285}
286
287impl super::GatherMode {
288    const fn required_operations(&self) -> SubgroupOperationSet {
289        use SubgroupOperationSet as S;
290        match *self {
291            Self::BroadcastFirst | Self::Broadcast(_) => S::BALLOT,
292            Self::Shuffle(_) | Self::ShuffleXor(_) => S::SHUFFLE,
293            Self::ShuffleUp(_) | Self::ShuffleDown(_) => S::SHUFFLE_RELATIVE,
294            Self::QuadBroadcast(_) | Self::QuadSwap(_) => S::QUAD_FRAGMENT_COMPUTE,
295        }
296    }
297}
298
299bitflags::bitflags! {
300    /// Validation flags.
301    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
302    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
303    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
304    pub struct ShaderStages: u16 {
305        const VERTEX = 0x1;
306        const FRAGMENT = 0x2;
307        const COMPUTE = 0x4;
308        const MESH = 0x8;
309        const TASK = 0x10;
310        const RAY_GENERATION = 0x20;
311        const ANY_HIT = 0x40;
312        const CLOSEST_HIT = 0x80;
313        const MISS = 0x100;
314        const COMPUTE_LIKE = Self::COMPUTE.bits() | Self::TASK.bits() | Self::MESH.bits();
315    }
316}
317
318#[derive(Debug, Clone, Default)]
319#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
320#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
321pub struct ModuleInfo {
322    type_flags: Vec<TypeFlags>,
323    functions: Vec<FunctionInfo>,
324    entry_points: Vec<FunctionInfo>,
325    const_expression_types: Box<[TypeResolution]>,
326}
327
328impl ops::Index<Handle<crate::Type>> for ModuleInfo {
329    type Output = TypeFlags;
330    fn index(&self, handle: Handle<crate::Type>) -> &Self::Output {
331        &self.type_flags[handle.index()]
332    }
333}
334
335impl ops::Index<Handle<crate::Function>> for ModuleInfo {
336    type Output = FunctionInfo;
337    fn index(&self, handle: Handle<crate::Function>) -> &Self::Output {
338        &self.functions[handle.index()]
339    }
340}
341
342impl ops::Index<Handle<crate::Expression>> for ModuleInfo {
343    type Output = TypeResolution;
344    fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
345        &self.const_expression_types[handle.index()]
346    }
347}
348
349#[derive(Debug)]
350pub struct Validator {
351    flags: ValidationFlags,
352    capabilities: Capabilities,
353    subgroup_stages: ShaderStages,
354    subgroup_operations: SubgroupOperationSet,
355    types: Vec<r#type::TypeInfo>,
356    layouter: Layouter,
357    location_mask: BitSet,
358    blend_src_mask: BitSet,
359    ep_resource_bindings: FastHashSet<crate::ResourceBinding>,
360    switch_values: FastHashSet<crate::SwitchValue>,
361    valid_expression_list: Vec<Handle<crate::Expression>>,
362    valid_expression_set: HandleSet<crate::Expression>,
363    override_ids: FastHashSet<u16>,
364
365    /// Treat overrides whose initializers are not fully-evaluated
366    /// constant expressions as errors.
367    overrides_resolved: bool,
368
369    /// A checklist of expressions that must be visited by a specific kind of
370    /// statement.
371    ///
372    /// For example:
373    ///
374    /// - [`CallResult`] expressions must be visited by a [`Call`] statement.
375    /// - [`AtomicResult`] expressions must be visited by an [`Atomic`] statement.
376    ///
377    /// Be sure not to remove any [`Expression`] handle from this set unless
378    /// you've explicitly checked that it is the right kind of expression for
379    /// the visiting [`Statement`].
380    ///
381    /// [`CallResult`]: crate::Expression::CallResult
382    /// [`Call`]: crate::Statement::Call
383    /// [`AtomicResult`]: crate::Expression::AtomicResult
384    /// [`Atomic`]: crate::Statement::Atomic
385    /// [`Expression`]: crate::Expression
386    /// [`Statement`]: crate::Statement
387    needs_visit: HandleSet<crate::Expression>,
388
389    /// Whether any trace rays call is called, and whether all have vertex return.
390    /// If one call doesn't use vertex ruturn, builtins for triangle vertex positions
391    /// (not yet implemented) are not allowed.
392    trace_rays_vertex_return: TraceRayVertexReturnState,
393
394    /// The type of the ray payload, this must always be the same type in a particular
395    /// entrypoint
396    trace_rays_payload_type: Option<Handle<crate::Type>>,
397}
398
399#[derive(Debug)]
400enum TraceRayVertexReturnState {
401    /// No trace ray calls yet have been found.
402    NoTraceRays,
403    /// Trace ray calls have been found, at least
404    /// one uses an acceleration structure that
405    /// does not have the flag enabling vertex return.
406    // Don't yet have vertex return builtins to return.
407    // this error for.
408    #[expect(unused)]
409    NoVertexReturn(crate::Span),
410    /// Trace ray calls have been found, all
411    /// acceleration structures have the flag enabling
412    /// vertex return.
413    VertexReturn,
414}
415
416#[derive(Clone, Debug, thiserror::Error)]
417#[cfg_attr(test, derive(PartialEq))]
418pub enum ConstantError {
419    #[error("Initializer must be a const-expression")]
420    InitializerExprType,
421    #[error("The type doesn't match the constant")]
422    InvalidType,
423    #[error("The type is not constructible")]
424    NonConstructibleType,
425}
426
427#[derive(Clone, Debug, thiserror::Error)]
428#[cfg_attr(test, derive(PartialEq))]
429pub enum OverrideError {
430    #[error("Override name and ID are missing")]
431    MissingNameAndID,
432    #[error("Override ID must be unique")]
433    DuplicateID,
434    #[error("Initializer must be a const-expression or override-expression")]
435    InitializerExprType,
436    #[error("The type doesn't match the override")]
437    InvalidType,
438    #[error("The type is not constructible")]
439    NonConstructibleType,
440    #[error("The type is not a scalar")]
441    TypeNotScalar,
442    #[error("Override declarations are not allowed")]
443    NotAllowed,
444    #[error("Override is uninitialized")]
445    UninitializedOverride,
446    #[error("Constant expression {handle:?} is invalid")]
447    ConstExpression {
448        handle: Handle<crate::Expression>,
449        source: ConstExpressionError,
450    },
451}
452
453#[derive(Clone, Debug, thiserror::Error)]
454#[cfg_attr(test, derive(PartialEq))]
455pub enum ValidationError {
456    #[error(transparent)]
457    InvalidHandle(#[from] InvalidHandleError),
458    #[error(transparent)]
459    Layouter(#[from] LayoutError),
460    #[error("Type {handle:?} '{name}' is invalid")]
461    Type {
462        handle: Handle<crate::Type>,
463        name: String,
464        source: TypeError,
465    },
466    #[error("Constant expression {handle:?} is invalid")]
467    ConstExpression {
468        handle: Handle<crate::Expression>,
469        source: ConstExpressionError,
470    },
471    #[error("Array size expression {handle:?} is not strictly positive")]
472    ArraySizeError { handle: Handle<crate::Expression> },
473    #[error("Constant {handle:?} '{name}' is invalid")]
474    Constant {
475        handle: Handle<crate::Constant>,
476        name: String,
477        source: ConstantError,
478    },
479    #[error("Override {handle:?} '{name}' is invalid")]
480    Override {
481        handle: Handle<crate::Override>,
482        name: String,
483        source: OverrideError,
484    },
485    #[error("Global variable {handle:?} '{name}' is invalid")]
486    GlobalVariable {
487        handle: Handle<crate::GlobalVariable>,
488        name: String,
489        source: GlobalVariableError,
490    },
491    #[error("Function {handle:?} '{name}' is invalid")]
492    Function {
493        handle: Handle<crate::Function>,
494        name: String,
495        source: FunctionError,
496    },
497    #[error("Entry point {name} at {stage:?} is invalid")]
498    EntryPoint {
499        stage: crate::ShaderStage,
500        name: String,
501        source: EntryPointError,
502    },
503    #[error("Module is corrupted")]
504    Corrupted,
505}
506
507impl crate::TypeInner {
508    const fn is_sized(&self) -> bool {
509        match *self {
510            Self::Scalar { .. }
511            | Self::Vector { .. }
512            | Self::Matrix { .. }
513            | Self::CooperativeMatrix { .. }
514            | Self::Array {
515                size: crate::ArraySize::Constant(_),
516                ..
517            }
518            | Self::Atomic { .. }
519            | Self::Pointer { .. }
520            | Self::ValuePointer { .. }
521            | Self::Struct { .. } => true,
522            Self::Array { .. }
523            | Self::Image { .. }
524            | Self::Sampler { .. }
525            | Self::AccelerationStructure { .. }
526            | Self::RayQuery { .. }
527            | Self::BindingArray { .. } => false,
528        }
529    }
530
531    /// Return the `ImageDimension` for which `self` is an appropriate coordinate.
532    const fn image_storage_coordinates(&self) -> Option<crate::ImageDimension> {
533        match *self {
534            Self::Scalar(crate::Scalar {
535                kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
536                ..
537            }) => Some(crate::ImageDimension::D1),
538            Self::Vector {
539                size: crate::VectorSize::Bi,
540                scalar:
541                    crate::Scalar {
542                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
543                        ..
544                    },
545            } => Some(crate::ImageDimension::D2),
546            Self::Vector {
547                size: crate::VectorSize::Tri,
548                scalar:
549                    crate::Scalar {
550                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
551                        ..
552                    },
553            } => Some(crate::ImageDimension::D3),
554            _ => None,
555        }
556    }
557}
558
559impl Validator {
560    /// Create a validator for Naga [`Module`]s.
561    ///
562    /// The `flags` argument indicates which stages of validation the
563    /// returned `Validator` should perform. Skipping stages can make
564    /// validation somewhat faster, but the validator may not reject some
565    /// invalid modules. Regardless of `flags`, validation always returns
566    /// a usable [`ModuleInfo`] value on success.
567    ///
568    /// If `flags` contains everything in `ValidationFlags::default()`,
569    /// then the returned Naga [`Validator`] will reject any [`Module`]
570    /// that would use capabilities not included in `capabilities`.
571    ///
572    /// [`Module`]: crate::Module
573    pub fn new(flags: ValidationFlags, capabilities: Capabilities) -> Self {
574        let subgroup_operations = if capabilities.contains(Capabilities::SUBGROUP) {
575            use SubgroupOperationSet as S;
576            S::BASIC
577                | S::VOTE
578                | S::ARITHMETIC
579                | S::BALLOT
580                | S::SHUFFLE
581                | S::SHUFFLE_RELATIVE
582                | S::QUAD_FRAGMENT_COMPUTE
583        } else {
584            SubgroupOperationSet::empty()
585        };
586        let subgroup_stages = {
587            let mut stages = ShaderStages::empty();
588            if capabilities.contains(Capabilities::SUBGROUP_VERTEX_STAGE) {
589                stages |= ShaderStages::VERTEX;
590            }
591            if capabilities.contains(Capabilities::SUBGROUP) {
592                stages |= ShaderStages::FRAGMENT | ShaderStages::COMPUTE_LIKE;
593            }
594            stages
595        };
596
597        Validator {
598            flags,
599            capabilities,
600            subgroup_stages,
601            subgroup_operations,
602            types: Vec::new(),
603            layouter: Layouter::default(),
604            location_mask: BitSet::new(),
605            blend_src_mask: BitSet::new(),
606            ep_resource_bindings: FastHashSet::default(),
607            switch_values: FastHashSet::default(),
608            valid_expression_list: Vec::new(),
609            valid_expression_set: HandleSet::new(),
610            override_ids: FastHashSet::default(),
611            overrides_resolved: false,
612            needs_visit: HandleSet::new(),
613            trace_rays_vertex_return: TraceRayVertexReturnState::NoTraceRays,
614            trace_rays_payload_type: None,
615        }
616    }
617
618    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
619    pub const fn subgroup_stages(&mut self, stages: ShaderStages) -> &mut Self {
620        self.subgroup_stages = stages;
621        self
622    }
623
624    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
625    pub const fn subgroup_operations(&mut self, operations: SubgroupOperationSet) -> &mut Self {
626        self.subgroup_operations = operations;
627        self
628    }
629
630    /// Reset the validator internals
631    pub fn reset(&mut self) {
632        self.types.clear();
633        self.layouter.clear();
634        self.location_mask.clear();
635        self.blend_src_mask.clear();
636        self.ep_resource_bindings.clear();
637        self.switch_values.clear();
638        self.valid_expression_list.clear();
639        self.valid_expression_set.clear();
640        self.override_ids.clear();
641    }
642
643    fn validate_constant(
644        &self,
645        handle: Handle<crate::Constant>,
646        gctx: crate::proc::GlobalCtx,
647        mod_info: &ModuleInfo,
648        global_expr_kind: &ExpressionKindTracker,
649    ) -> Result<(), ConstantError> {
650        let con = &gctx.constants[handle];
651
652        let type_info = &self.types[con.ty.index()];
653        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
654            return Err(ConstantError::NonConstructibleType);
655        }
656
657        if !global_expr_kind.is_const(con.init) {
658            return Err(ConstantError::InitializerExprType);
659        }
660
661        if !gctx.compare_types(&TypeResolution::Handle(con.ty), &mod_info[con.init]) {
662            return Err(ConstantError::InvalidType);
663        }
664
665        Ok(())
666    }
667
668    fn validate_override(
669        &mut self,
670        handle: Handle<crate::Override>,
671        gctx: crate::proc::GlobalCtx,
672        mod_info: &ModuleInfo,
673    ) -> Result<(), OverrideError> {
674        let o = &gctx.overrides[handle];
675
676        if let Some(id) = o.id {
677            if !self.override_ids.insert(id) {
678                return Err(OverrideError::DuplicateID);
679            }
680        }
681
682        let type_info = &self.types[o.ty.index()];
683        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
684            return Err(OverrideError::NonConstructibleType);
685        }
686
687        match gctx.types[o.ty].inner {
688            crate::TypeInner::Scalar(
689                crate::Scalar::BOOL
690                | crate::Scalar::I32
691                | crate::Scalar::U32
692                | crate::Scalar::F16
693                | crate::Scalar::F32
694                | crate::Scalar::F64,
695            ) => {}
696            _ => return Err(OverrideError::TypeNotScalar),
697        }
698
699        if let Some(init) = o.init {
700            if !gctx.compare_types(&TypeResolution::Handle(o.ty), &mod_info[init]) {
701                return Err(OverrideError::InvalidType);
702            }
703        } else if self.overrides_resolved {
704            return Err(OverrideError::UninitializedOverride);
705        }
706
707        Ok(())
708    }
709
710    /// Check the given module to be valid.
711    pub fn validate(
712        &mut self,
713        module: &crate::Module,
714    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
715        self.overrides_resolved = false;
716        self.validate_impl(module)
717    }
718
719    /// Check the given module to be valid, requiring overrides to be resolved.
720    ///
721    /// This is the same as [`validate`], except that any override
722    /// whose value is not a fully-evaluated constant expression is
723    /// treated as an error.
724    ///
725    /// [`validate`]: Validator::validate
726    pub fn validate_resolved_overrides(
727        &mut self,
728        module: &crate::Module,
729    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
730        self.overrides_resolved = true;
731        self.validate_impl(module)
732    }
733
734    fn validate_impl(
735        &mut self,
736        module: &crate::Module,
737    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
738        self.reset();
739        self.reset_types(module.types.len());
740
741        Self::validate_module_handles(module).map_err(|e| e.with_span())?;
742
743        self.layouter.update(module.to_ctx()).map_err(|e| {
744            let handle = e.ty;
745            ValidationError::from(e).with_span_handle(handle, &module.types)
746        })?;
747
748        // These should all get overwritten.
749        let placeholder = TypeResolution::Value(crate::TypeInner::Scalar(crate::Scalar {
750            kind: crate::ScalarKind::Bool,
751            width: 0,
752        }));
753
754        let mut mod_info = ModuleInfo {
755            type_flags: Vec::with_capacity(module.types.len()),
756            functions: Vec::with_capacity(module.functions.len()),
757            entry_points: Vec::with_capacity(module.entry_points.len()),
758            const_expression_types: vec![placeholder; module.global_expressions.len()]
759                .into_boxed_slice(),
760        };
761
762        for (handle, ty) in module.types.iter() {
763            let ty_info = self
764                .validate_type(handle, module.to_ctx())
765                .map_err(|source| {
766                    ValidationError::Type {
767                        handle,
768                        name: ty.name.clone().unwrap_or_default(),
769                        source,
770                    }
771                    .with_span_handle(handle, &module.types)
772                })?;
773            debug_assert!(
774                ty_info.flags.contains(TypeFlags::CONSTRUCTIBLE)
775                    == module.types[handle].inner.is_constructible(&module.types)
776            );
777            mod_info.type_flags.push(ty_info.flags);
778            self.types[handle.index()] = ty_info;
779        }
780
781        {
782            let t = crate::Arena::new();
783            let resolve_context = crate::proc::ResolveContext::with_locals(module, &t, &[]);
784            for (handle, _) in module.global_expressions.iter() {
785                mod_info
786                    .process_const_expression(handle, &resolve_context, module.to_ctx())
787                    .map_err(|source| {
788                        ValidationError::ConstExpression { handle, source }
789                            .with_span_handle(handle, &module.global_expressions)
790                    })?
791            }
792        }
793
794        let global_expr_kind = ExpressionKindTracker::from_arena(&module.global_expressions);
795
796        if self.flags.contains(ValidationFlags::CONSTANTS) {
797            for (handle, _) in module.global_expressions.iter() {
798                self.validate_const_expression(
799                    handle,
800                    module.to_ctx(),
801                    &mod_info,
802                    &global_expr_kind,
803                )
804                .map_err(|source| {
805                    ValidationError::ConstExpression { handle, source }
806                        .with_span_handle(handle, &module.global_expressions)
807                })?
808            }
809
810            for (handle, constant) in module.constants.iter() {
811                self.validate_constant(handle, module.to_ctx(), &mod_info, &global_expr_kind)
812                    .map_err(|source| {
813                        ValidationError::Constant {
814                            handle,
815                            name: constant.name.clone().unwrap_or_default(),
816                            source,
817                        }
818                        .with_span_handle(handle, &module.constants)
819                    })?
820            }
821
822            for (handle, r#override) in module.overrides.iter() {
823                self.validate_override(handle, module.to_ctx(), &mod_info)
824                    .map_err(|source| {
825                        ValidationError::Override {
826                            handle,
827                            name: r#override.name.clone().unwrap_or_default(),
828                            source,
829                        }
830                        .with_span_handle(handle, &module.overrides)
831                    })?;
832            }
833        }
834
835        for (var_handle, var) in module.global_variables.iter() {
836            self.validate_global_var(var, module.to_ctx(), &mod_info, &global_expr_kind)
837                .map_err(|source| {
838                    ValidationError::GlobalVariable {
839                        handle: var_handle,
840                        name: var.name.clone().unwrap_or_default(),
841                        source,
842                    }
843                    .with_span_handle(var_handle, &module.global_variables)
844                })?;
845        }
846
847        for (handle, fun) in module.functions.iter() {
848            match self.validate_function(fun, module, &mod_info, false) {
849                Ok(info) => mod_info.functions.push(info),
850                Err(error) => {
851                    return Err(error.and_then(|source| {
852                        ValidationError::Function {
853                            handle,
854                            name: fun.name.clone().unwrap_or_default(),
855                            source,
856                        }
857                        .with_span_handle(handle, &module.functions)
858                    }))
859                }
860            }
861        }
862
863        let mut ep_map = FastHashSet::default();
864        for ep in module.entry_points.iter() {
865            if !ep_map.insert((ep.stage, &ep.name)) {
866                return Err(ValidationError::EntryPoint {
867                    stage: ep.stage,
868                    name: ep.name.clone(),
869                    source: EntryPointError::Conflict,
870                }
871                .with_span()); // TODO: keep some EP span information?
872            }
873
874            match self.validate_entry_point(ep, module, &mod_info) {
875                Ok(info) => mod_info.entry_points.push(info),
876                Err(error) => {
877                    return Err(error.and_then(|source| {
878                        ValidationError::EntryPoint {
879                            stage: ep.stage,
880                            name: ep.name.clone(),
881                            source,
882                        }
883                        .with_span()
884                    }));
885                }
886            }
887        }
888
889        Ok(mod_info)
890    }
891}
892
893fn validate_atomic_compare_exchange_struct(
894    types: &crate::UniqueArena<crate::Type>,
895    members: &[crate::StructMember],
896    scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool,
897) -> bool {
898    members.len() == 2
899        && members[0].name.as_deref() == Some("old_value")
900        && scalar_predicate(&types[members[0].ty].inner)
901        && members[1].name.as_deref() == Some("exchanged")
902        && types[members[1].ty].inner == crate::TypeInner::Scalar(crate::Scalar::BOOL)
903}