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    }
204}
205
206impl Capabilities {
207    /// Returns the extension corresponding to this capability, if there is one.
208    ///
209    /// This is used by integration tests.
210    #[cfg(feature = "wgsl-in")]
211    #[doc(hidden)]
212    pub const fn extension(&self) -> Option<crate::front::wgsl::ImplementedEnableExtension> {
213        use crate::front::wgsl::ImplementedEnableExtension as Ext;
214        match *self {
215            Self::DUAL_SOURCE_BLENDING => Some(Ext::DualSourceBlending),
216            // NOTE: `SHADER_FLOAT16_IN_FLOAT32` _does not_ require the `f16` extension
217            Self::SHADER_FLOAT16 => Some(Ext::F16),
218            Self::CLIP_DISTANCE => Some(Ext::ClipDistances),
219            Self::MESH_SHADER => Some(Ext::WgpuMeshShader),
220            Self::RAY_QUERY => Some(Ext::WgpuRayQuery),
221            Self::RAY_HIT_VERTEX_POSITION => Some(Ext::WgpuRayQueryVertexReturn),
222            _ => None,
223        }
224    }
225}
226
227impl Default for Capabilities {
228    fn default() -> Self {
229        Self::MULTISAMPLED_SHADING | Self::CUBE_ARRAY_TEXTURES
230    }
231}
232
233bitflags::bitflags! {
234    /// Supported subgroup operations
235    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
236    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
237    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
238    pub struct SubgroupOperationSet: u8 {
239        /// Barriers
240        // Possibly elections, when that is supported.
241        // https://github.com/gfx-rs/wgpu/issues/6042#issuecomment-3272603431
242        // Contrary to what the name "basic" suggests, HLSL/DX12 support the
243        // other subgroup operations, but do not support subgroup barriers.
244        const BASIC = 1 << 0;
245        /// Any, All
246        const VOTE = 1 << 1;
247        /// reductions, scans
248        const ARITHMETIC = 1 << 2;
249        /// ballot, broadcast
250        const BALLOT = 1 << 3;
251        /// shuffle, shuffle xor
252        const SHUFFLE = 1 << 4;
253        /// shuffle up, down
254        const SHUFFLE_RELATIVE = 1 << 5;
255        // We don't support these operations yet
256        // /// Clustered
257        // const CLUSTERED = 1 << 6;
258        /// Quad supported
259        const QUAD_FRAGMENT_COMPUTE = 1 << 7;
260        // /// Quad supported in all stages
261        // const QUAD_ALL_STAGES = 1 << 8;
262    }
263}
264
265impl super::SubgroupOperation {
266    const fn required_operations(&self) -> SubgroupOperationSet {
267        use SubgroupOperationSet as S;
268        match *self {
269            Self::All | Self::Any => S::VOTE,
270            Self::Add | Self::Mul | Self::Min | Self::Max | Self::And | Self::Or | Self::Xor => {
271                S::ARITHMETIC
272            }
273        }
274    }
275}
276
277impl super::GatherMode {
278    const fn required_operations(&self) -> SubgroupOperationSet {
279        use SubgroupOperationSet as S;
280        match *self {
281            Self::BroadcastFirst | Self::Broadcast(_) => S::BALLOT,
282            Self::Shuffle(_) | Self::ShuffleXor(_) => S::SHUFFLE,
283            Self::ShuffleUp(_) | Self::ShuffleDown(_) => S::SHUFFLE_RELATIVE,
284            Self::QuadBroadcast(_) | Self::QuadSwap(_) => S::QUAD_FRAGMENT_COMPUTE,
285        }
286    }
287}
288
289bitflags::bitflags! {
290    /// Validation flags.
291    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
292    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
293    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
294    pub struct ShaderStages: u8 {
295        const VERTEX = 0x1;
296        const FRAGMENT = 0x2;
297        const COMPUTE = 0x4;
298        const MESH = 0x8;
299        const TASK = 0x10;
300        const COMPUTE_LIKE = Self::COMPUTE.bits() | Self::TASK.bits() | Self::MESH.bits();
301    }
302}
303
304#[derive(Debug, Clone, Default)]
305#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
306#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
307pub struct ModuleInfo {
308    type_flags: Vec<TypeFlags>,
309    functions: Vec<FunctionInfo>,
310    entry_points: Vec<FunctionInfo>,
311    const_expression_types: Box<[TypeResolution]>,
312}
313
314impl ops::Index<Handle<crate::Type>> for ModuleInfo {
315    type Output = TypeFlags;
316    fn index(&self, handle: Handle<crate::Type>) -> &Self::Output {
317        &self.type_flags[handle.index()]
318    }
319}
320
321impl ops::Index<Handle<crate::Function>> for ModuleInfo {
322    type Output = FunctionInfo;
323    fn index(&self, handle: Handle<crate::Function>) -> &Self::Output {
324        &self.functions[handle.index()]
325    }
326}
327
328impl ops::Index<Handle<crate::Expression>> for ModuleInfo {
329    type Output = TypeResolution;
330    fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
331        &self.const_expression_types[handle.index()]
332    }
333}
334
335#[derive(Debug)]
336pub struct Validator {
337    flags: ValidationFlags,
338    capabilities: Capabilities,
339    subgroup_stages: ShaderStages,
340    subgroup_operations: SubgroupOperationSet,
341    types: Vec<r#type::TypeInfo>,
342    layouter: Layouter,
343    location_mask: BitSet,
344    blend_src_mask: BitSet,
345    ep_resource_bindings: FastHashSet<crate::ResourceBinding>,
346    #[allow(dead_code)]
347    switch_values: FastHashSet<crate::SwitchValue>,
348    valid_expression_list: Vec<Handle<crate::Expression>>,
349    valid_expression_set: HandleSet<crate::Expression>,
350    override_ids: FastHashSet<u16>,
351
352    /// Treat overrides whose initializers are not fully-evaluated
353    /// constant expressions as errors.
354    overrides_resolved: bool,
355
356    /// A checklist of expressions that must be visited by a specific kind of
357    /// statement.
358    ///
359    /// For example:
360    ///
361    /// - [`CallResult`] expressions must be visited by a [`Call`] statement.
362    /// - [`AtomicResult`] expressions must be visited by an [`Atomic`] statement.
363    ///
364    /// Be sure not to remove any [`Expression`] handle from this set unless
365    /// you've explicitly checked that it is the right kind of expression for
366    /// the visiting [`Statement`].
367    ///
368    /// [`CallResult`]: crate::Expression::CallResult
369    /// [`Call`]: crate::Statement::Call
370    /// [`AtomicResult`]: crate::Expression::AtomicResult
371    /// [`Atomic`]: crate::Statement::Atomic
372    /// [`Expression`]: crate::Expression
373    /// [`Statement`]: crate::Statement
374    needs_visit: HandleSet<crate::Expression>,
375}
376
377#[derive(Clone, Debug, thiserror::Error)]
378#[cfg_attr(test, derive(PartialEq))]
379pub enum ConstantError {
380    #[error("Initializer must be a const-expression")]
381    InitializerExprType,
382    #[error("The type doesn't match the constant")]
383    InvalidType,
384    #[error("The type is not constructible")]
385    NonConstructibleType,
386}
387
388#[derive(Clone, Debug, thiserror::Error)]
389#[cfg_attr(test, derive(PartialEq))]
390pub enum OverrideError {
391    #[error("Override name and ID are missing")]
392    MissingNameAndID,
393    #[error("Override ID must be unique")]
394    DuplicateID,
395    #[error("Initializer must be a const-expression or override-expression")]
396    InitializerExprType,
397    #[error("The type doesn't match the override")]
398    InvalidType,
399    #[error("The type is not constructible")]
400    NonConstructibleType,
401    #[error("The type is not a scalar")]
402    TypeNotScalar,
403    #[error("Override declarations are not allowed")]
404    NotAllowed,
405    #[error("Override is uninitialized")]
406    UninitializedOverride,
407    #[error("Constant expression {handle:?} is invalid")]
408    ConstExpression {
409        handle: Handle<crate::Expression>,
410        source: ConstExpressionError,
411    },
412}
413
414#[derive(Clone, Debug, thiserror::Error)]
415#[cfg_attr(test, derive(PartialEq))]
416pub enum ValidationError {
417    #[error(transparent)]
418    InvalidHandle(#[from] InvalidHandleError),
419    #[error(transparent)]
420    Layouter(#[from] LayoutError),
421    #[error("Type {handle:?} '{name}' is invalid")]
422    Type {
423        handle: Handle<crate::Type>,
424        name: String,
425        source: TypeError,
426    },
427    #[error("Constant expression {handle:?} is invalid")]
428    ConstExpression {
429        handle: Handle<crate::Expression>,
430        source: ConstExpressionError,
431    },
432    #[error("Array size expression {handle:?} is not strictly positive")]
433    ArraySizeError { handle: Handle<crate::Expression> },
434    #[error("Constant {handle:?} '{name}' is invalid")]
435    Constant {
436        handle: Handle<crate::Constant>,
437        name: String,
438        source: ConstantError,
439    },
440    #[error("Override {handle:?} '{name}' is invalid")]
441    Override {
442        handle: Handle<crate::Override>,
443        name: String,
444        source: OverrideError,
445    },
446    #[error("Global variable {handle:?} '{name}' is invalid")]
447    GlobalVariable {
448        handle: Handle<crate::GlobalVariable>,
449        name: String,
450        source: GlobalVariableError,
451    },
452    #[error("Function {handle:?} '{name}' is invalid")]
453    Function {
454        handle: Handle<crate::Function>,
455        name: String,
456        source: FunctionError,
457    },
458    #[error("Entry point {name} at {stage:?} is invalid")]
459    EntryPoint {
460        stage: crate::ShaderStage,
461        name: String,
462        source: EntryPointError,
463    },
464    #[error("Module is corrupted")]
465    Corrupted,
466}
467
468impl crate::TypeInner {
469    const fn is_sized(&self) -> bool {
470        match *self {
471            Self::Scalar { .. }
472            | Self::Vector { .. }
473            | Self::Matrix { .. }
474            | Self::Array {
475                size: crate::ArraySize::Constant(_),
476                ..
477            }
478            | Self::Atomic { .. }
479            | Self::Pointer { .. }
480            | Self::ValuePointer { .. }
481            | Self::Struct { .. } => true,
482            Self::Array { .. }
483            | Self::Image { .. }
484            | Self::Sampler { .. }
485            | Self::AccelerationStructure { .. }
486            | Self::RayQuery { .. }
487            | Self::BindingArray { .. } => false,
488        }
489    }
490
491    /// Return the `ImageDimension` for which `self` is an appropriate coordinate.
492    const fn image_storage_coordinates(&self) -> Option<crate::ImageDimension> {
493        match *self {
494            Self::Scalar(crate::Scalar {
495                kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
496                ..
497            }) => Some(crate::ImageDimension::D1),
498            Self::Vector {
499                size: crate::VectorSize::Bi,
500                scalar:
501                    crate::Scalar {
502                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
503                        ..
504                    },
505            } => Some(crate::ImageDimension::D2),
506            Self::Vector {
507                size: crate::VectorSize::Tri,
508                scalar:
509                    crate::Scalar {
510                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
511                        ..
512                    },
513            } => Some(crate::ImageDimension::D3),
514            _ => None,
515        }
516    }
517}
518
519impl Validator {
520    /// Create a validator for Naga [`Module`]s.
521    ///
522    /// The `flags` argument indicates which stages of validation the
523    /// returned `Validator` should perform. Skipping stages can make
524    /// validation somewhat faster, but the validator may not reject some
525    /// invalid modules. Regardless of `flags`, validation always returns
526    /// a usable [`ModuleInfo`] value on success.
527    ///
528    /// If `flags` contains everything in `ValidationFlags::default()`,
529    /// then the returned Naga [`Validator`] will reject any [`Module`]
530    /// that would use capabilities not included in `capabilities`.
531    ///
532    /// [`Module`]: crate::Module
533    pub fn new(flags: ValidationFlags, capabilities: Capabilities) -> Self {
534        let subgroup_operations = if capabilities.contains(Capabilities::SUBGROUP) {
535            use SubgroupOperationSet as S;
536            S::BASIC
537                | S::VOTE
538                | S::ARITHMETIC
539                | S::BALLOT
540                | S::SHUFFLE
541                | S::SHUFFLE_RELATIVE
542                | S::QUAD_FRAGMENT_COMPUTE
543        } else {
544            SubgroupOperationSet::empty()
545        };
546        let subgroup_stages = {
547            let mut stages = ShaderStages::empty();
548            if capabilities.contains(Capabilities::SUBGROUP_VERTEX_STAGE) {
549                stages |= ShaderStages::VERTEX;
550            }
551            if capabilities.contains(Capabilities::SUBGROUP) {
552                stages |= ShaderStages::FRAGMENT | ShaderStages::COMPUTE_LIKE;
553            }
554            stages
555        };
556
557        Validator {
558            flags,
559            capabilities,
560            subgroup_stages,
561            subgroup_operations,
562            types: Vec::new(),
563            layouter: Layouter::default(),
564            location_mask: BitSet::new(),
565            blend_src_mask: BitSet::new(),
566            ep_resource_bindings: FastHashSet::default(),
567            switch_values: FastHashSet::default(),
568            valid_expression_list: Vec::new(),
569            valid_expression_set: HandleSet::new(),
570            override_ids: FastHashSet::default(),
571            overrides_resolved: false,
572            needs_visit: HandleSet::new(),
573        }
574    }
575
576    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
577    pub fn subgroup_stages(&mut self, stages: ShaderStages) -> &mut Self {
578        self.subgroup_stages = stages;
579        self
580    }
581
582    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
583    pub fn subgroup_operations(&mut self, operations: SubgroupOperationSet) -> &mut Self {
584        self.subgroup_operations = operations;
585        self
586    }
587
588    /// Reset the validator internals
589    pub fn reset(&mut self) {
590        self.types.clear();
591        self.layouter.clear();
592        self.location_mask.clear();
593        self.blend_src_mask.clear();
594        self.ep_resource_bindings.clear();
595        self.switch_values.clear();
596        self.valid_expression_list.clear();
597        self.valid_expression_set.clear();
598        self.override_ids.clear();
599    }
600
601    fn validate_constant(
602        &self,
603        handle: Handle<crate::Constant>,
604        gctx: crate::proc::GlobalCtx,
605        mod_info: &ModuleInfo,
606        global_expr_kind: &ExpressionKindTracker,
607    ) -> Result<(), ConstantError> {
608        let con = &gctx.constants[handle];
609
610        let type_info = &self.types[con.ty.index()];
611        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
612            return Err(ConstantError::NonConstructibleType);
613        }
614
615        if !global_expr_kind.is_const(con.init) {
616            return Err(ConstantError::InitializerExprType);
617        }
618
619        if !gctx.compare_types(&TypeResolution::Handle(con.ty), &mod_info[con.init]) {
620            return Err(ConstantError::InvalidType);
621        }
622
623        Ok(())
624    }
625
626    fn validate_override(
627        &mut self,
628        handle: Handle<crate::Override>,
629        gctx: crate::proc::GlobalCtx,
630        mod_info: &ModuleInfo,
631    ) -> Result<(), OverrideError> {
632        let o = &gctx.overrides[handle];
633
634        if let Some(id) = o.id {
635            if !self.override_ids.insert(id) {
636                return Err(OverrideError::DuplicateID);
637            }
638        }
639
640        let type_info = &self.types[o.ty.index()];
641        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
642            return Err(OverrideError::NonConstructibleType);
643        }
644
645        match gctx.types[o.ty].inner {
646            crate::TypeInner::Scalar(
647                crate::Scalar::BOOL
648                | crate::Scalar::I32
649                | crate::Scalar::U32
650                | crate::Scalar::F16
651                | crate::Scalar::F32
652                | crate::Scalar::F64,
653            ) => {}
654            _ => return Err(OverrideError::TypeNotScalar),
655        }
656
657        if let Some(init) = o.init {
658            if !gctx.compare_types(&TypeResolution::Handle(o.ty), &mod_info[init]) {
659                return Err(OverrideError::InvalidType);
660            }
661        } else if self.overrides_resolved {
662            return Err(OverrideError::UninitializedOverride);
663        }
664
665        Ok(())
666    }
667
668    /// Check the given module to be valid.
669    pub fn validate(
670        &mut self,
671        module: &crate::Module,
672    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
673        self.overrides_resolved = false;
674        self.validate_impl(module)
675    }
676
677    /// Check the given module to be valid, requiring overrides to be resolved.
678    ///
679    /// This is the same as [`validate`], except that any override
680    /// whose value is not a fully-evaluated constant expression is
681    /// treated as an error.
682    ///
683    /// [`validate`]: Validator::validate
684    pub fn validate_resolved_overrides(
685        &mut self,
686        module: &crate::Module,
687    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
688        self.overrides_resolved = true;
689        self.validate_impl(module)
690    }
691
692    fn validate_impl(
693        &mut self,
694        module: &crate::Module,
695    ) -> Result<ModuleInfo, WithSpan<ValidationError>> {
696        self.reset();
697        self.reset_types(module.types.len());
698
699        Self::validate_module_handles(module).map_err(|e| e.with_span())?;
700
701        self.layouter.update(module.to_ctx()).map_err(|e| {
702            let handle = e.ty;
703            ValidationError::from(e).with_span_handle(handle, &module.types)
704        })?;
705
706        // These should all get overwritten.
707        let placeholder = TypeResolution::Value(crate::TypeInner::Scalar(crate::Scalar {
708            kind: crate::ScalarKind::Bool,
709            width: 0,
710        }));
711
712        let mut mod_info = ModuleInfo {
713            type_flags: Vec::with_capacity(module.types.len()),
714            functions: Vec::with_capacity(module.functions.len()),
715            entry_points: Vec::with_capacity(module.entry_points.len()),
716            const_expression_types: vec![placeholder; module.global_expressions.len()]
717                .into_boxed_slice(),
718        };
719
720        for (handle, ty) in module.types.iter() {
721            let ty_info = self
722                .validate_type(handle, module.to_ctx())
723                .map_err(|source| {
724                    ValidationError::Type {
725                        handle,
726                        name: ty.name.clone().unwrap_or_default(),
727                        source,
728                    }
729                    .with_span_handle(handle, &module.types)
730                })?;
731            mod_info.type_flags.push(ty_info.flags);
732            self.types[handle.index()] = ty_info;
733        }
734
735        {
736            let t = crate::Arena::new();
737            let resolve_context = crate::proc::ResolveContext::with_locals(module, &t, &[]);
738            for (handle, _) in module.global_expressions.iter() {
739                mod_info
740                    .process_const_expression(handle, &resolve_context, module.to_ctx())
741                    .map_err(|source| {
742                        ValidationError::ConstExpression { handle, source }
743                            .with_span_handle(handle, &module.global_expressions)
744                    })?
745            }
746        }
747
748        let global_expr_kind = ExpressionKindTracker::from_arena(&module.global_expressions);
749
750        if self.flags.contains(ValidationFlags::CONSTANTS) {
751            for (handle, _) in module.global_expressions.iter() {
752                self.validate_const_expression(
753                    handle,
754                    module.to_ctx(),
755                    &mod_info,
756                    &global_expr_kind,
757                )
758                .map_err(|source| {
759                    ValidationError::ConstExpression { handle, source }
760                        .with_span_handle(handle, &module.global_expressions)
761                })?
762            }
763
764            for (handle, constant) in module.constants.iter() {
765                self.validate_constant(handle, module.to_ctx(), &mod_info, &global_expr_kind)
766                    .map_err(|source| {
767                        ValidationError::Constant {
768                            handle,
769                            name: constant.name.clone().unwrap_or_default(),
770                            source,
771                        }
772                        .with_span_handle(handle, &module.constants)
773                    })?
774            }
775
776            for (handle, r#override) in module.overrides.iter() {
777                self.validate_override(handle, module.to_ctx(), &mod_info)
778                    .map_err(|source| {
779                        ValidationError::Override {
780                            handle,
781                            name: r#override.name.clone().unwrap_or_default(),
782                            source,
783                        }
784                        .with_span_handle(handle, &module.overrides)
785                    })?;
786            }
787        }
788
789        for (var_handle, var) in module.global_variables.iter() {
790            self.validate_global_var(var, module.to_ctx(), &mod_info, &global_expr_kind)
791                .map_err(|source| {
792                    ValidationError::GlobalVariable {
793                        handle: var_handle,
794                        name: var.name.clone().unwrap_or_default(),
795                        source,
796                    }
797                    .with_span_handle(var_handle, &module.global_variables)
798                })?;
799        }
800
801        for (handle, fun) in module.functions.iter() {
802            match self.validate_function(fun, module, &mod_info, false) {
803                Ok(info) => mod_info.functions.push(info),
804                Err(error) => {
805                    return Err(error.and_then(|source| {
806                        ValidationError::Function {
807                            handle,
808                            name: fun.name.clone().unwrap_or_default(),
809                            source,
810                        }
811                        .with_span_handle(handle, &module.functions)
812                    }))
813                }
814            }
815        }
816
817        let mut ep_map = FastHashSet::default();
818        for ep in module.entry_points.iter() {
819            if !ep_map.insert((ep.stage, &ep.name)) {
820                return Err(ValidationError::EntryPoint {
821                    stage: ep.stage,
822                    name: ep.name.clone(),
823                    source: EntryPointError::Conflict,
824                }
825                .with_span()); // TODO: keep some EP span information?
826            }
827
828            match self.validate_entry_point(ep, module, &mod_info) {
829                Ok(info) => mod_info.entry_points.push(info),
830                Err(error) => {
831                    return Err(error.and_then(|source| {
832                        ValidationError::EntryPoint {
833                            stage: ep.stage,
834                            name: ep.name.clone(),
835                            source,
836                        }
837                        .with_span()
838                    }));
839                }
840            }
841        }
842
843        Ok(mod_info)
844    }
845}
846
847fn validate_atomic_compare_exchange_struct(
848    types: &crate::UniqueArena<crate::Type>,
849    members: &[crate::StructMember],
850    scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool,
851) -> bool {
852    members.len() == 2
853        && members[0].name.as_deref() == Some("old_value")
854        && scalar_predicate(&types[members[0].ty].inner)
855        && members[1].name.as_deref() == Some("exchanged")
856        && types[members[1].ty].inner == crate::TypeInner::Scalar(crate::Scalar::BOOL)
857}