Debian Codegraph @

third_party/rust/naga/src/ir/mod.rs

raw
1 /*!
2 The Intermediate Representation shared by all frontends and backends.
3
4 The central structure of the IR, and the crate, is [`Module`]. A `Module` contains:
5
6 - [`Function`]s, which have arguments, a return type, local variables, and a body,
7
8 - [`EntryPoint`]s, which are specialized functions that can serve as the entry
9 point for pipeline stages like vertex shading or fragment shading,
10
11 - [`Constant`]s and [`GlobalVariable`]s used by `EntryPoint`s and `Function`s, and
12
13 - [`Type`]s used by the above.
14
15 The body of an `EntryPoint` or `Function` is represented using two types:
16
17 - An [`Expression`] produces a value, but has no side effects or control flow.
18 `Expressions` include variable references, unary and binary operators, and so
19 on.
20
21 - A [`Statement`] can have side effects and structured control flow.
22 `Statement`s do not produce a value, other than by storing one in some
23 designated place. `Statements` include blocks, conditionals, and loops, but also
24 operations that have side effects, like stores and function calls.
25
26 `Statement`s form a tree, with pointers into the DAG of `Expression`s.
27
28 Restricting side effects to statements simplifies analysis and code generation.
29 A Naga backend can generate code to evaluate an `Expression` however and
30 whenever it pleases, as long as it is certain to observe the side effects of all
31 previously executed `Statement`s.
32
33 Many `Statement` variants use the [`Block`] type, which is `Vec<Statement>`,
34 with optional span info, representing a series of statements executed in order. The body of an
35 `EntryPoint`s or `Function` is a `Block`, and `Statement` has a
36 [`Block`][Statement::Block] variant.
37
38 ## Function Calls
39
40 Naga's representation of function calls is unusual. Most languages treat
41 function calls as expressions, but because calls may have side effects, Naga
42 represents them as a kind of statement, [`Statement::Call`]. If the function
43 returns a value, a call statement designates a particular [`Expression::CallResult`]
44 expression to represent its return value, for use by subsequent statements and
45 expressions.
46
47 ## `Expression` evaluation time
48
49 It is essential to know when an [`Expression`] should be evaluated, because its
50 value may depend on previous [`Statement`]s' effects. But whereas the order of
51 execution for a tree of `Statement`s is apparent from its structure, it is not
52 so clear for `Expressions`, since an expression may be referred to by any number
53 of `Statement`s and other `Expression`s.
54
55 Naga's rules for when `Expression`s are evaluated are as follows:
56
57 - [`Literal`], [`Constant`], and [`ZeroValue`] expressions are
58 considered to be implicitly evaluated before execution begins.
59
60 - [`FunctionArgument`] and [`LocalVariable`] expressions are considered
61 implicitly evaluated upon entry to the function to which they belong.
62 Function arguments cannot be assigned to, and `LocalVariable` expressions
63 produce a *pointer to* the variable's value (for use with [`Load`] and
64 [`Store`]). Neither varies while the function executes, so it suffices to
65 consider these expressions evaluated once on entry.
66
67 - Similarly, [`GlobalVariable`] expressions are considered implicitly
68 evaluated before execution begins, since their value does not change while
69 code executes, for one of two reasons:
70
71 - Most `GlobalVariable` expressions produce a pointer to the variable's
72 value, for use with [`Load`] and [`Store`], as `LocalVariable`
73 expressions do. Although the variable's value may change, its address
74 does not.
75
76 - A `GlobalVariable` expression referring to a global in the
77 [`AddressSpace::Handle`] address space produces the value directly, not
78 a pointer. Such global variables hold opaque types like shaders or
79 images, and cannot be assigned to.
80
81 - A [`CallResult`] expression that is the `result` of a [`Statement::Call`],
82 representing the call's return value, is evaluated when the `Call` statement
83 is executed.
84
85 - Similarly, an [`AtomicResult`] expression that is the `result` of an
86 [`Atomic`] statement, representing the result of the atomic operation, is
87 evaluated when the `Atomic` statement is executed.
88
89 - A [`RayQueryProceedResult`] expression, which is a boolean
90 indicating if the ray query is finished, is evaluated when the
91 [`RayQuery`] statement whose [`Proceed::result`] points to it is
92 executed.
93
94 - All other expressions are evaluated when the (unique) [`Statement::Emit`]
95 statement that covers them is executed.
96
97 Now, strictly speaking, not all `Expression` variants actually care when they're
98 evaluated. For example, you can evaluate a [`BinaryOperator::Add`] expression
99 any time you like, as long as you give it the right operands. It's really only a
100 very small set of expressions that are affected by timing:
101
102 - [`Load`], [`ImageSample`], and [`ImageLoad`] expressions are influenced by
103 stores to the variables or images they access, and must execute at the
104 proper time relative to them.
105
106 - [`Derivative`] expressions are sensitive to control flow uniformity: they
107 must not be moved out of an area of uniform control flow into a non-uniform
108 area.
109
110 - More generally, any expression that's used by more than one other expression
111 or statement should probably be evaluated only once, and then stored in a
112 variable to be cited at each point of use.
113
114 Naga tries to help back ends handle all these cases correctly in a somewhat
115 circuitous way. The [`ModuleInfo`] structure returned by [`Validator::validate`]
116 provides a reference count for each expression in each function in the module.
117 Naturally, any expression with a reference count of two or more deserves to be
118 evaluated and stored in a temporary variable at the point that the `Emit`
119 statement covering it is executed. But if we selectively lower the reference
120 count threshold to _one_ for the sensitive expression types listed above, so
121 that we _always_ generate a temporary variable and save their value, then the
122 same code that manages multiply referenced expressions will take care of
123 introducing temporaries for time-sensitive expressions as well. The
124 `Expression::bake_ref_count` method (private to the back ends) is meant to help
125 with this.
126
127 ## `Expression` scope
128
129 Each `Expression` has a *scope*, which is the region of the function within
130 which it can be used by `Statement`s and other `Expression`s. It is a validation
131 error to use an `Expression` outside its scope.
132
133 An expression's scope is defined as follows:
134
135 - The scope of a [`Constant`], [`GlobalVariable`], [`FunctionArgument`] or
136 [`LocalVariable`] expression covers the entire `Function` in which it
137 occurs.
138
139 - The scope of an expression evaluated by an [`Emit`] statement covers the
140 subsequent expressions in that `Emit`, the subsequent statements in the `Block`
141 to which that `Emit` belongs (if any) and their sub-statements (if any).
142
143 - The `result` expression of a [`Call`] or [`Atomic`] statement has a scope
144 covering the subsequent statements in the `Block` in which the statement
145 occurs (if any) and their sub-statements (if any).
146
147 For example, this implies that an expression evaluated by some statement in a
148 nested `Block` is not available in the `Block`'s parents. Such a value would
149 need to be stored in a local variable to be carried upwards in the statement
150 tree.
151
152 ## Constant expressions
153
154 A Naga *constant expression* is one of the following [`Expression`]
155 variants, whose operands (if any) are also constant expressions:
156 - [`Literal`]
157 - [`Constant`], for [`Constant`]s
158 - [`ZeroValue`], for fixed-size types
159 - [`Compose`]
160 - [`Access`]
161 - [`AccessIndex`]
162 - [`Splat`]
163 - [`Swizzle`]
164 - [`Unary`]
165 - [`Binary`]
166 - [`Select`]
167 - [`Relational`]
168 - [`Math`]
169 - [`As`]
170
171 A constant expression can be evaluated at module translation time.
172
173 ## Override expressions
174
175 A Naga *override expression* is the same as a [constant expression],
176 except that it is also allowed to reference other [`Override`]s.
177
178 An override expression can be evaluated at pipeline creation time.
179
180 [`AtomicResult`]: Expression::AtomicResult
181 [`RayQueryProceedResult`]: Expression::RayQueryProceedResult
182 [`CallResult`]: Expression::CallResult
183 [`Constant`]: Expression::Constant
184 [`ZeroValue`]: Expression::ZeroValue
185 [`Literal`]: Expression::Literal
186 [`Derivative`]: Expression::Derivative
187 [`FunctionArgument`]: Expression::FunctionArgument
188 [`GlobalVariable`]: Expression::GlobalVariable
189 [`ImageLoad`]: Expression::ImageLoad
190 [`ImageSample`]: Expression::ImageSample
191 [`Load`]: Expression::Load
192 [`LocalVariable`]: Expression::LocalVariable
193
194 [`Atomic`]: Statement::Atomic
195 [`Call`]: Statement::Call
196 [`Emit`]: Statement::Emit
197 [`Store`]: Statement::Store
198 [`RayQuery`]: Statement::RayQuery
199
200 [`Proceed::result`]: RayQueryFunction::Proceed::result
201
202 [`Validator::validate`]: crate::valid::Validator::validate
203 [`ModuleInfo`]: crate::valid::ModuleInfo
204
205 [`Literal`]: Expression::Literal
206 [`ZeroValue`]: Expression::ZeroValue
207 [`Compose`]: Expression::Compose
208 [`Access`]: Expression::Access
209 [`AccessIndex`]: Expression::AccessIndex
210 [`Splat`]: Expression::Splat
211 [`Swizzle`]: Expression::Swizzle
212 [`Unary`]: Expression::Unary
213 [`Binary`]: Expression::Binary
214 [`Select`]: Expression::Select
215 [`Relational`]: Expression::Relational
216 [`Math`]: Expression::Math
217 [`As`]: Expression::As
218
219 [constant expression]: #constant-expressions
220 */
221
222 mod block;
223
224 use alloc::{string::String, vec::Vec};
225
226 #[cfg(feature = "arbitrary")]
227 use arbitrary::Arbitrary;
228 use half::f16;
229 #[cfg(feature = "deserialize")]
230 use serde::Deserialize;
231 #[cfg(feature = "serialize")]
232 use serde::Serialize;
233
234 use crate::arena::{Arena, Handle, Range, UniqueArena};
235 use crate::diagnostic_filter::DiagnosticFilterNode;
236 use crate::{FastIndexMap, NamedExpressions};
237
238 pub use block::Block;
239
240 /// Early fragment tests.
241 ///
242 /// In a standard situation, if a driver determines that it is possible to switch on early depth test, it will.
243 ///
244 /// Typical situations when early depth test is switched off:
245 /// - Calling `discard` in a shader.
246 /// - Writing to the depth buffer, unless ConservativeDepth is enabled.
247 ///
248 /// To use in a shader:
249 /// - GLSL: `layout(early_fragment_tests) in;`
250 /// - HLSL: `Attribute earlydepthstencil`
251 /// - SPIR-V: `ExecutionMode EarlyFragmentTests`
252 /// - WGSL: `@early_depth_test`
253 ///
254 /// For more, see:
255 /// - <https://www.khronos.org/opengl/wiki/Early_Fragment_Test#Explicit_specification>
256 /// - <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-earlydepthstencil>
257 /// - <https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#Execution_Mode>
258 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
259 #[cfg_attr(feature = "serialize", derive(Serialize))]
260 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
261 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
262 pub struct EarlyDepthTest {
263 pub conservative: Option<ConservativeDepth>,
264 }
265
266 /// Enables adjusting depth without disabling early Z.
267 ///
268 /// To use in a shader:
269 /// - GLSL: `layout (depth_<greater/less/unchanged/any>) out float gl_FragDepth;`
270 /// - `depth_any` option behaves as if the layout qualifier was not present.
271 /// - HLSL: `SV_DepthGreaterEqual`/`SV_DepthLessEqual`/`SV_Depth`
272 /// - SPIR-V: `ExecutionMode Depth<Greater/Less/Unchanged>`
273 /// - WGSL: `@early_depth_test(greater_equal/less_equal/unchanged)`
274 ///
275 /// For more, see:
276 /// - <https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt>
277 /// - <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#system-value-semantics>
278 /// - <https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#Execution_Mode>
279 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
280 #[cfg_attr(feature = "serialize", derive(Serialize))]
281 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
282 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
283 pub enum ConservativeDepth {
284 /// Shader may rewrite depth only with a value greater than calculated.
285 GreaterEqual,
286
287 /// Shader may rewrite depth smaller than one that would have been written without the modification.
288 LessEqual,
289
290 /// Shader may not rewrite depth value.
291 Unchanged,
292 }
293
294 /// Stage of the programmable pipeline.
295 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
296 #[cfg_attr(feature = "serialize", derive(Serialize))]
297 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
298 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
299 #[allow(missing_docs)] // The names are self evident
300 pub enum ShaderStage {
301 Vertex,
302 Fragment,
303 Compute,
304 Task,
305 Mesh,
306 }
307
308 /// Addressing space of variables.
309 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
310 #[cfg_attr(feature = "serialize", derive(Serialize))]
311 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
312 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
313 pub enum AddressSpace {
314 /// Function locals.
315 Function,
316 /// Private data, per invocation, mutable.
317 Private,
318 /// Workgroup shared data, mutable.
319 WorkGroup,
320 /// Uniform buffer data.
321 Uniform,
322 /// Storage buffer data, potentially mutable.
323 Storage { access: StorageAccess },
324 /// Opaque handles, such as samplers and images.
325 Handle,
326 /// Push constants.
327 PushConstant,
328 }
329
330 /// Built-in inputs and outputs.
331 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
332 #[cfg_attr(feature = "serialize", derive(Serialize))]
333 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
334 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
335 pub enum BuiltIn {
336 Position { invariant: bool },
337 ViewIndex,
338 // vertex
339 BaseInstance,
340 BaseVertex,
341 ClipDistance,
342 CullDistance,
343 InstanceIndex,
344 PointSize,
345 VertexIndex,
346 DrawID,
347 // fragment
348 FragDepth,
349 PointCoord,
350 FrontFacing,
351 PrimitiveIndex,
352 SampleIndex,
353 SampleMask,
354 // compute
355 GlobalInvocationId,
356 LocalInvocationId,
357 LocalInvocationIndex,
358 WorkGroupId,
359 WorkGroupSize,
360 NumWorkGroups,
361 // subgroup
362 NumSubgroups,
363 SubgroupId,
364 SubgroupSize,
365 SubgroupInvocationId,
366 }
367
368 /// Number of bytes per scalar.
369 pub type Bytes = u8;
370
371 /// Number of components in a vector.
372 #[repr(u8)]
373 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
374 #[cfg_attr(feature = "serialize", derive(Serialize))]
375 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
376 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
377 pub enum VectorSize {
378 /// 2D vector
379 Bi = 2,
380 /// 3D vector
381 Tri = 3,
382 /// 4D vector
383 Quad = 4,
384 }
385
386 impl VectorSize {
387 pub const MAX: usize = Self::Quad as usize;
388 }
389
390 /// Primitive type for a scalar.
391 #[repr(u8)]
392 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
393 #[cfg_attr(feature = "serialize", derive(Serialize))]
394 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
395 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
396 pub enum ScalarKind {
397 /// Signed integer type.
398 Sint,
399 /// Unsigned integer type.
400 Uint,
401 /// Floating point type.
402 Float,
403 /// Boolean type.
404 Bool,
405
406 /// WGSL abstract integer type.
407 ///
408 /// These are forbidden by validation, and should never reach backends.
409 AbstractInt,
410
411 /// Abstract floating-point type.
412 ///
413 /// These are forbidden by validation, and should never reach backends.
414 AbstractFloat,
415 }
416
417 /// Characteristics of a scalar type.
418 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
419 #[cfg_attr(feature = "serialize", derive(Serialize))]
420 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
421 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
422 pub struct Scalar {
423 /// How the value's bits are to be interpreted.
424 pub kind: ScalarKind,
425
426 /// This size of the value in bytes.
427 pub width: Bytes,
428 }
429
430 /// Size of an array.
431 #[repr(u8)]
432 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
433 #[cfg_attr(feature = "serialize", derive(Serialize))]
434 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
435 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
436 pub enum ArraySize {
437 /// The array size is constant.
438 Constant(core::num::NonZeroU32),
439 /// The array size is an override-expression.
440 Pending(Handle<Override>),
441 /// The array size can change at runtime.
442 Dynamic,
443 }
444
445 /// The interpolation qualifier of a binding or struct field.
446 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
447 #[cfg_attr(feature = "serialize", derive(Serialize))]
448 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
449 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
450 pub enum Interpolation {
451 /// The value will be interpolated in a perspective-correct fashion.
452 /// Also known as "smooth" in glsl.
453 Perspective,
454 /// Indicates that linear, non-perspective, correct
455 /// interpolation must be used.
456 /// Also known as "no_perspective" in glsl.
457 Linear,
458 /// Indicates that no interpolation will be performed.
459 Flat,
460 }
461
462 /// The sampling qualifiers of a binding or struct field.
463 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
464 #[cfg_attr(feature = "serialize", derive(Serialize))]
465 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
466 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
467 pub enum Sampling {
468 /// Interpolate the value at the center of the pixel.
469 Center,
470
471 /// Interpolate the value at a point that lies within all samples covered by
472 /// the fragment within the current primitive. In multisampling, use a
473 /// single value for all samples in the primitive.
474 Centroid,
475
476 /// Interpolate the value at each sample location. In multisampling, invoke
477 /// the fragment shader once per sample.
478 Sample,
479
480 /// Use the value provided by the first vertex of the current primitive.
481 First,
482
483 /// Use the value provided by the first or last vertex of the current primitive. The exact
484 /// choice is implementation-dependent.
485 Either,
486 }
487
488 /// Member of a user-defined structure.
489 // Clone is used only for error reporting and is not intended for end users
490 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
491 #[cfg_attr(feature = "serialize", derive(Serialize))]
492 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
493 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
494 pub struct StructMember {
495 pub name: Option<String>,
496 /// Type of the field.
497 pub ty: Handle<Type>,
498 /// For I/O structs, defines the binding.
499 pub binding: Option<Binding>,
500 /// Offset from the beginning from the struct.
501 pub offset: u32,
502 }
503
504 /// The number of dimensions an image has.
505 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
506 #[cfg_attr(feature = "serialize", derive(Serialize))]
507 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
508 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
509 pub enum ImageDimension {
510 /// 1D image
511 D1,
512 /// 2D image
513 D2,
514 /// 3D image
515 D3,
516 /// Cube map
517 Cube,
518 }
519
520 bitflags::bitflags! {
521 /// Flags describing an image.
522 #[cfg_attr(feature = "serialize", derive(Serialize))]
523 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
524 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
525 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
526 pub struct StorageAccess: u32 {
527 /// Storage can be used as a source for load ops.
528 const LOAD = 0x1;
529 /// Storage can be used as a target for store ops.
530 const STORE = 0x2;
531 /// Storage can be used as a target for atomic ops.
532 const ATOMIC = 0x4;
533 }
534 }
535
536 /// Image storage format.
537 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
538 #[cfg_attr(feature = "serialize", derive(Serialize))]
539 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
540 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
541 pub enum StorageFormat {
542 // 8-bit formats
543 R8Unorm,
544 R8Snorm,
545 R8Uint,
546 R8Sint,
547
548 // 16-bit formats
549 R16Uint,
550 R16Sint,
551 R16Float,
552 Rg8Unorm,
553 Rg8Snorm,
554 Rg8Uint,
555 Rg8Sint,
556
557 // 32-bit formats
558 R32Uint,
559 R32Sint,
560 R32Float,
561 Rg16Uint,
562 Rg16Sint,
563 Rg16Float,
564 Rgba8Unorm,
565 Rgba8Snorm,
566 Rgba8Uint,
567 Rgba8Sint,
568 Bgra8Unorm,
569
570 // Packed 32-bit formats
571 Rgb10a2Uint,
572 Rgb10a2Unorm,
573 Rg11b10Ufloat,
574
575 // 64-bit formats
576 R64Uint,
577 Rg32Uint,
578 Rg32Sint,
579 Rg32Float,
580 Rgba16Uint,
581 Rgba16Sint,
582 Rgba16Float,
583
584 // 128-bit formats
585 Rgba32Uint,
586 Rgba32Sint,
587 Rgba32Float,
588
589 // Normalized 16-bit per channel formats
590 R16Unorm,
591 R16Snorm,
592 Rg16Unorm,
593 Rg16Snorm,
594 Rgba16Unorm,
595 Rgba16Snorm,
596 }
597
598 /// Sub-class of the image type.
599 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
600 #[cfg_attr(feature = "serialize", derive(Serialize))]
601 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
602 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
603 pub enum ImageClass {
604 /// Regular sampled image.
605 Sampled {
606 /// Kind of values to sample.
607 kind: ScalarKind,
608 /// Multi-sampled image.
609 ///
610 /// A multi-sampled image holds several samples per texel. Multi-sampled
611 /// images cannot have mipmaps.
612 multi: bool,
613 },
614 /// Depth comparison image.
615 Depth {
616 /// Multi-sampled depth image.
617 multi: bool,
618 },
619 /// Storage image.
620 Storage {
621 format: StorageFormat,
622 access: StorageAccess,
623 },
624 }
625
626 /// A data type declared in the module.
627 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
628 #[cfg_attr(feature = "serialize", derive(Serialize))]
629 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
630 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
631 pub struct Type {
632 /// The name of the type, if any.
633 pub name: Option<String>,
634 /// Inner structure that depends on the kind of the type.
635 pub inner: TypeInner,
636 }
637
638 /// Enum with additional information, depending on the kind of type.
639 ///
640 /// Comparison using `==` is not reliable in the case of [`Pointer`],
641 /// [`ValuePointer`], or [`Struct`] variants. For these variants,
642 /// use [`TypeInner::non_struct_equivalent`] or [`compare_types`].
643 ///
644 /// [`compare_types`]: crate::proc::compare_types
645 /// [`ValuePointer`]: TypeInner::ValuePointer
646 /// [`Pointer`]: TypeInner::Pointer
647 /// [`Struct`]: TypeInner::Struct
648 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
649 #[cfg_attr(feature = "serialize", derive(Serialize))]
650 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
651 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
652 pub enum TypeInner {
653 /// Number of integral or floating-point kind.
654 Scalar(Scalar),
655 /// Vector of numbers.
656 Vector { size: VectorSize, scalar: Scalar },
657 /// Matrix of numbers.
658 Matrix {
659 columns: VectorSize,
660 rows: VectorSize,
661 scalar: Scalar,
662 },
663 /// Atomic scalar.
664 Atomic(Scalar),
665 /// Pointer to another type.
666 ///
667 /// Pointers to scalars and vectors should be treated as equivalent to
668 /// [`ValuePointer`] types. Use either [`TypeInner::non_struct_equivalent`]
669 /// or [`compare_types`] to compare types in a way that treats pointers
670 /// correctly.
671 ///
672 /// ## Pointers to non-`SIZED` types
673 ///
674 /// The `base` type of a pointer may be a non-[`SIZED`] type like a
675 /// dynamically-sized [`Array`], or a [`Struct`] whose last member is a
676 /// dynamically sized array. Such pointers occur as the types of
677 /// [`GlobalVariable`] or [`AccessIndex`] expressions referring to
678 /// dynamically-sized arrays.
679 ///
680 /// However, among pointers to non-`SIZED` types, only pointers to `Struct`s
681 /// are [`DATA`]. Pointers to dynamically sized `Array`s cannot be passed as
682 /// arguments, stored in variables, or held in arrays or structures. Their
683 /// only use is as the types of `AccessIndex` expressions.
684 ///
685 /// [`SIZED`]: crate::valid::TypeFlags::SIZED
686 /// [`DATA`]: crate::valid::TypeFlags::DATA
687 /// [`Array`]: TypeInner::Array
688 /// [`Struct`]: TypeInner::Struct
689 /// [`ValuePointer`]: TypeInner::ValuePointer
690 /// [`GlobalVariable`]: Expression::GlobalVariable
691 /// [`AccessIndex`]: Expression::AccessIndex
692 /// [`compare_types`]: crate::proc::compare_types
693 Pointer {
694 base: Handle<Type>,
695 space: AddressSpace,
696 },
697
698 /// Pointer to a scalar or vector.
699 ///
700 /// A `ValuePointer` type is equivalent to a `Pointer` whose `base` is a
701 /// `Scalar` or `Vector` type. This is for use in [`TypeResolution::Value`]
702 /// variants; see the documentation for [`TypeResolution`] for details.
703 ///
704 /// Use [`TypeInner::non_struct_equivalent`] or [`compare_types`] to compare
705 /// types that could be pointers, to ensure that `Pointer` and
706 /// `ValuePointer` types are recognized as equivalent.
707 ///
708 /// [`TypeResolution`]: crate::proc::TypeResolution
709 /// [`TypeResolution::Value`]: crate::proc::TypeResolution::Value
710 /// [`compare_types`]: crate::proc::compare_types
711 ValuePointer {
712 size: Option<VectorSize>,
713 scalar: Scalar,
714 space: AddressSpace,
715 },
716
717 /// Homogeneous list of elements.
718 ///
719 /// The `base` type must be a [`SIZED`], [`DATA`] type.
720 ///
721 /// ## Dynamically sized arrays
722 ///
723 /// An `Array` is [`SIZED`] unless its `size` is [`Dynamic`].
724 /// Dynamically-sized arrays may only appear in a few situations:
725 ///
726 /// - They may appear as the type of a [`GlobalVariable`], or as the last
727 /// member of a [`Struct`].
728 ///
729 /// - They may appear as the base type of a [`Pointer`]. An
730 /// [`AccessIndex`] expression referring to a struct's final
731 /// unsized array member would have such a pointer type. However, such
732 /// pointer types may only appear as the types of such intermediate
733 /// expressions. They are not [`DATA`], and cannot be stored in
734 /// variables, held in arrays or structs, or passed as parameters.
735 ///
736 /// [`SIZED`]: crate::valid::TypeFlags::SIZED
737 /// [`DATA`]: crate::valid::TypeFlags::DATA
738 /// [`Dynamic`]: ArraySize::Dynamic
739 /// [`Struct`]: TypeInner::Struct
740 /// [`Pointer`]: TypeInner::Pointer
741 /// [`AccessIndex`]: Expression::AccessIndex
742 Array {
743 base: Handle<Type>,
744 size: ArraySize,
745 stride: u32,
746 },
747
748 /// User-defined structure.
749 ///
750 /// There must always be at least one member.
751 ///
752 /// A `Struct` type is [`DATA`], and the types of its members must be
753 /// `DATA` as well.
754 ///
755 /// Member types must be [`SIZED`], except for the final member of a
756 /// struct, which may be a dynamically sized [`Array`]. The
757 /// `Struct` type itself is `SIZED` when all its members are `SIZED`.
758 ///
759 /// Two structure types with different names are not equivalent. Because
760 /// this variant does not contain the name, it is not possible to use it
761 /// to compare struct types. Use [`compare_types`] to compare two types
762 /// that may be structs.
763 ///
764 /// [`DATA`]: crate::valid::TypeFlags::DATA
765 /// [`SIZED`]: crate::∅TypeFlags::SIZED
766 /// [`Array`]: TypeInner::Array
767 /// [`compare_types`]: crate::proc::compare_types
768 Struct {
769 members: Vec<StructMember>,
770 //TODO: should this be unaligned?
771 span: u32,
772 },
773 /// Possibly multidimensional array of texels.
774 Image {
775 dim: ImageDimension,
776 arrayed: bool,
777 //TODO: consider moving `multisampled: bool` out
778 class: ImageClass,
779 },
780 /// Can be used to sample values from images.
781 Sampler { comparison: bool },
782
783 /// Opaque object representing an acceleration structure of geometry.
784 AccelerationStructure { vertex_return: bool },
785
786 /// Locally used handle for ray queries.
787 RayQuery { vertex_return: bool },
788
789 /// Array of bindings.
790 ///
791 /// A `BindingArray` represents an array where each element draws its value
792 /// from a separate bound resource. The array's element type `base` may be
793 /// [`Image`], [`Sampler`], or any type that would be permitted for a global
794 /// in the [`Uniform`] or [`Storage`] address spaces. Only global variables
795 /// may be binding arrays; on the host side, their values are provided by
796 /// [`TextureViewArray`], [`SamplerArray`], or [`BufferArray`]
797 /// bindings.
798 ///
799 /// Since each element comes from a distinct resource, a binding array of
800 /// images could have images of varying sizes (but not varying dimensions;
801 /// they must all have the same `Image` type). Or, a binding array of
802 /// buffers could have elements that are dynamically sized arrays, each with
803 /// a different length.
804 ///
805 /// Binding arrays are in the same address spaces as their underlying type.
806 /// As such, referring to an array of images produces an [`Image`] value
807 /// directly (as opposed to a pointer). The only operation permitted on
808 /// `BindingArray` values is indexing, which works transparently: indexing
809 /// a binding array of samplers yields a [`Sampler`], indexing a pointer to the
810 /// binding array of storage buffers produces a pointer to the storage struct.
811 ///
812 /// Unlike textures and samplers, binding arrays are not [`ARGUMENT`], so
813 /// they cannot be passed as arguments to functions.
814 ///
815 /// Naga's WGSL front end supports binding arrays with the type syntax
816 /// `binding_array<T, N>`.
817 ///
818 /// [`Image`]: TypeInner::Image
819 /// [`Sampler`]: TypeInner::Sampler
820 /// [`Uniform`]: AddressSpace::Uniform
821 /// [`Storage`]: AddressSpace::Storage
822 /// [`TextureViewArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.TextureViewArray
823 /// [`SamplerArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.SamplerArray
824 /// [`BufferArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.BufferArray
825 /// [`DATA`]: crate::valid::TypeFlags::DATA
826 /// [`ARGUMENT`]: crate::valid::TypeFlags::ARGUMENT
827 /// [naga#1864]: https://github.com/gfx-rs/naga/issues/1864
828 BindingArray { base: Handle<Type>, size: ArraySize },
829 }
830
831 #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
832 #[cfg_attr(feature = "serialize", derive(Serialize))]
833 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
834 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
835 pub enum Literal {
836 /// May not be NaN or infinity.
837 F64(f64),
838 /// May not be NaN or infinity.
839 F32(f32),
840 /// May not be NaN or infinity.
841 F16(f16),
842 U32(u32),
843 I32(i32),
844 U64(u64),
845 I64(i64),
846 Bool(bool),
847 AbstractInt(i64),
848 AbstractFloat(f64),
849 }
850
851 /// Pipeline-overridable constant.
852 #[derive(Clone, Debug, PartialEq)]
853 #[cfg_attr(feature = "serialize", derive(Serialize))]
854 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
855 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
856 pub struct Override {
857 pub name: Option<String>,
858 /// Pipeline Constant ID.
859 pub id: Option<u16>,
860 pub ty: Handle<Type>,
861
862 /// The default value of the pipeline-overridable constant.
863 ///
864 /// This [`Handle`] refers to [`Module::global_expressions`], not
865 /// any [`Function::expressions`] arena.
866 pub init: Option<Handle<Expression>>,
867 }
868
869 /// Constant value.
870 #[derive(Clone, Debug, PartialEq)]
871 #[cfg_attr(feature = "serialize", derive(Serialize))]
872 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
873 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
874 pub struct Constant {
875 pub name: Option<String>,
876 pub ty: Handle<Type>,
877
878 /// The value of the constant.
879 ///
880 /// This [`Handle`] refers to [`Module::global_expressions`], not
881 /// any [`Function::expressions`] arena.
882 pub init: Handle<Expression>,
883 }
884
885 /// Describes how an input/output variable is to be bound.
886 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
887 #[cfg_attr(feature = "serialize", derive(Serialize))]
888 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
889 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
890 pub enum Binding {
891 /// Built-in shader variable.
892 BuiltIn(BuiltIn),
893
894 /// Indexed location.
895 ///
896 /// Values passed from the [`Vertex`] stage to the [`Fragment`] stage must
897 /// have their `interpolation` defaulted (i.e. not `None`) by the front end
898 /// as appropriate for that language.
899 ///
900 /// For other stages, we permit interpolations even though they're ignored.
901 /// When a front end is parsing a struct type, it usually doesn't know what
902 /// stages will be using it for IO, so it's easiest if it can apply the
903 /// defaults to anything with a `Location` binding, just in case.
904 ///
905 /// For anything other than floating-point scalars and vectors, the
906 /// interpolation must be `Flat`.
907 ///
908 /// [`Vertex`]: crate::ShaderStage::Vertex
909 /// [`Fragment`]: crate::ShaderStage::Fragment
910 Location {
911 location: u32,
912 interpolation: Option<Interpolation>,
913 sampling: Option<Sampling>,
914 /// Optional `blend_src` index used for dual source blending.
915 /// See <https://www.w3.org/TR/WGSL/#attribute-blend_src>
916 blend_src: Option<u32>,
917 },
918 }
919
920 /// Pipeline binding information for global resources.
921 #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
922 #[cfg_attr(feature = "serialize", derive(Serialize))]
923 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
924 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
925 pub struct ResourceBinding {
926 /// The bind group index.
927 pub group: u32,
928 /// Binding number within the group.
929 pub binding: u32,
930 }
931
932 /// Variable defined at module level.
933 #[derive(Clone, Debug, PartialEq)]
934 #[cfg_attr(feature = "serialize", derive(Serialize))]
935 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
936 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
937 pub struct GlobalVariable {
938 /// Name of the variable, if any.
939 pub name: Option<String>,
940 /// How this variable is to be stored.
941 pub space: AddressSpace,
942 /// For resources, defines the binding point.
943 pub binding: Option<ResourceBinding>,
944 /// The type of this variable.
945 pub ty: Handle<Type>,
946 /// Initial value for this variable.
947 ///
948 /// This refers to an [`Expression`] in [`Module::global_expressions`].
949 pub init: Option<Handle<Expression>>,
950 }
951
952 /// Variable defined at function level.
953 #[derive(Clone, Debug)]
954 #[cfg_attr(feature = "serialize", derive(Serialize))]
955 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
956 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
957 pub struct LocalVariable {
958 /// Name of the variable, if any.
959 pub name: Option<String>,
960 /// The type of this variable.
961 pub ty: Handle<Type>,
962 /// Initial value for this variable.
963 ///
964 /// This handle refers to an expression in this `LocalVariable`'s function's
965 /// [`expressions`] arena, but it is required to be an evaluated override
966 /// expression.
967 ///
968 /// [`expressions`]: Function::expressions
969 pub init: Option<Handle<Expression>>,
970 }
971
972 /// Operation that can be applied on a single value.
973 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
974 #[cfg_attr(feature = "serialize", derive(Serialize))]
975 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
976 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
977 pub enum UnaryOperator {
978 Negate,
979 LogicalNot,
980 BitwiseNot,
981 }
982
983 /// Operation that can be applied on two values.
984 ///
985 /// ## Arithmetic type rules
986 ///
987 /// The arithmetic operations `Add`, `Subtract`, `Multiply`, `Divide`, and
988 /// `Modulo` can all be applied to [`Scalar`] types other than [`Bool`], or
989 /// [`Vector`]s thereof. Both operands must have the same type.
990 ///
991 /// `Add` and `Subtract` can also be applied to [`Matrix`] values. Both operands
992 /// must have the same type.
993 ///
994 /// `Multiply` supports additional cases:
995 ///
996 /// - A [`Matrix`] or [`Vector`] can be multiplied by a scalar [`Float`],
997 /// either on the left or the right.
998 ///
999 /// - A [`Matrix`] on the left can be multiplied by a [`Vector`] on the right
1000 /// if the matrix has as many columns as the vector has components
1001 /// (`matCxR * VecC`).
1002 ///
1003 /// - A [`Vector`] on the left can be multiplied by a [`Matrix`] on the right
1004 /// if the matrix has as many rows as the vector has components
1005 /// (`VecR * matCxR`).
1006 ///
1007 /// - Two matrices can be multiplied if the left operand has as many columns
1008 /// as the right operand has rows (`matNxR * matCxN`).
1009 ///
1010 /// In all the above `Multiply` cases, the byte widths of the underlying scalar
1011 /// types of both operands must be the same.
1012 ///
1013 /// Note that `Multiply` supports mixed vector and scalar operations directly,
1014 /// whereas the other arithmetic operations require an explicit [`Splat`] for
1015 /// mixed-type use.
1016 ///
1017 /// [`Scalar`]: TypeInner::Scalar
1018 /// [`Vector`]: TypeInner::Vector
1019 /// [`Matrix`]: TypeInner::Matrix
1020 /// [`Float`]: ScalarKind::Float
1021 /// [`Bool`]: ScalarKind::Bool
1022 /// [`Splat`]: Expression::Splat
1023 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1024 #[cfg_attr(feature = "serialize", derive(Serialize))]
1025 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1026 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1027 pub enum BinaryOperator {
1028 Add,
1029 Subtract,
1030 Multiply,
1031 Divide,
1032 /// Equivalent of the WGSL's `%` operator or SPIR-V's `OpFRem`
1033 Modulo,
1034 Equal,
1035 NotEqual,
1036 Less,
1037 LessEqual,
1038 Greater,
1039 GreaterEqual,
1040 And,
1041 ExclusiveOr,
1042 InclusiveOr,
1043 LogicalAnd,
1044 LogicalOr,
1045 ShiftLeft,
1046 /// Right shift carries the sign of signed integers only.
1047 ShiftRight,
1048 }
1049
1050 /// Function on an atomic value.
1051 ///
1052 /// Note: these do not include load/store, which use the existing
1053 /// [`Expression::Load`] and [`Statement::Store`].
1054 ///
1055 /// All `Handle<Expression>` values here refer to an expression in
1056 /// [`Function::expressions`].
1057 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1058 #[cfg_attr(feature = "serialize", derive(Serialize))]
1059 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1060 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1061 pub enum AtomicFunction {
1062 Add,
1063 Subtract,
1064 And,
1065 ExclusiveOr,
1066 InclusiveOr,
1067 Min,
1068 Max,
1069 Exchange { compare: Option<Handle<Expression>> },
1070 }
1071
1072 /// Hint at which precision to compute a derivative.
1073 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1074 #[cfg_attr(feature = "serialize", derive(Serialize))]
1075 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1076 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1077 pub enum DerivativeControl {
1078 Coarse,
1079 Fine,
1080 None,
1081 }
1082
1083 /// Axis on which to compute a derivative.
1084 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1085 #[cfg_attr(feature = "serialize", derive(Serialize))]
1086 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1087 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1088 pub enum DerivativeAxis {
1089 X,
1090 Y,
1091 Width,
1092 }
1093
1094 /// Built-in shader function for testing relation between values.
1095 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1096 #[cfg_attr(feature = "serialize", derive(Serialize))]
1097 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1098 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1099 pub enum RelationalFunction {
1100 All,
1101 Any,
1102 IsNan,
1103 IsInf,
1104 }
1105
1106 /// Built-in shader function for math.
1107 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1108 #[cfg_attr(feature = "serialize", derive(Serialize))]
1109 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1110 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1111 pub enum MathFunction {
1112 // comparison
1113 Abs,
1114 Min,
1115 Max,
1116 Clamp,
1117 Saturate,
1118 // trigonometry
1119 Cos,
1120 Cosh,
1121 Sin,
1122 Sinh,
1123 Tan,
1124 Tanh,
1125 Acos,
1126 Asin,
1127 Atan,
1128 Atan2,
1129 Asinh,
1130 Acosh,
1131 Atanh,
1132 Radians,
1133 Degrees,
1134 // decomposition
1135 Ceil,
1136 Floor,
1137 Round,
1138 Fract,
1139 Trunc,
1140 Modf,
1141 Frexp,
1142 Ldexp,
1143 // exponent
1144 Exp,
1145 Exp2,
1146 Log,
1147 Log2,
1148 Pow,
1149 // geometry
1150 Dot,
1151 Dot4I8Packed,
1152 Dot4U8Packed,
1153 Outer,
1154 Cross,
1155 Distance,
1156 Length,
1157 Normalize,
1158 FaceForward,
1159 Reflect,
1160 Refract,
1161 // computational
1162 Sign,
1163 Fma,
1164 Mix,
1165 Step,
1166 SmoothStep,
1167 Sqrt,
1168 InverseSqrt,
1169 Inverse,
1170 Transpose,
1171 Determinant,
1172 QuantizeToF16,
1173 // bits
1174 CountTrailingZeros,
1175 CountLeadingZeros,
1176 CountOneBits,
1177 ReverseBits,
1178 ExtractBits,
1179 InsertBits,
1180 FirstTrailingBit,
1181 FirstLeadingBit,
1182 // data packing
1183 Pack4x8snorm,
1184 Pack4x8unorm,
1185 Pack2x16snorm,
1186 Pack2x16unorm,
1187 Pack2x16float,
1188 Pack4xI8,
1189 Pack4xU8,
1190 Pack4xI8Clamp,
1191 Pack4xU8Clamp,
1192 // data unpacking
1193 Unpack4x8snorm,
1194 Unpack4x8unorm,
1195 Unpack2x16snorm,
1196 Unpack2x16unorm,
1197 Unpack2x16float,
1198 Unpack4xI8,
1199 Unpack4xU8,
1200 }
1201
1202 /// Sampling modifier to control the level of detail.
1203 ///
1204 /// All `Handle<Expression>` values here refer to an expression in
1205 /// [`Function::expressions`].
1206 #[derive(Clone, Copy, Debug, PartialEq)]
1207 #[cfg_attr(feature = "serialize", derive(Serialize))]
1208 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1209 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1210 pub enum SampleLevel {
1211 Auto,
1212 Zero,
1213 Exact(Handle<Expression>),
1214 Bias(Handle<Expression>),
1215 Gradient {
1216 x: Handle<Expression>,
1217 y: Handle<Expression>,
1218 },
1219 }
1220
1221 /// Type of an image query.
1222 ///
1223 /// All `Handle<Expression>` values here refer to an expression in
1224 /// [`Function::expressions`].
1225 #[derive(Clone, Copy, Debug, PartialEq)]
1226 #[cfg_attr(feature = "serialize", derive(Serialize))]
1227 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1228 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1229 pub enum ImageQuery {
1230 /// Get the size at the specified level.
1231 ///
1232 /// The return value is a `u32` for 1D images, and a `vecN<u32>`
1233 /// for an image with dimensions N > 2.
1234 Size {
1235 /// If `None`, the base level is considered.
1236 level: Option<Handle<Expression>>,
1237 },
1238 /// Get the number of mipmap levels, a `u32`.
1239 NumLevels,
1240 /// Get the number of array layers, a `u32`.
1241 NumLayers,
1242 /// Get the number of samples, a `u32`.
1243 NumSamples,
1244 }
1245
1246 /// Component selection for a vector swizzle.
1247 #[repr(u8)]
1248 #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
1249 #[cfg_attr(feature = "serialize", derive(Serialize))]
1250 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1251 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1252 pub enum SwizzleComponent {
1253 X = 0,
1254 Y = 1,
1255 Z = 2,
1256 W = 3,
1257 }
1258
1259 /// The specific behavior of a [`SubgroupGather`] statement.
1260 ///
1261 /// All `Handle<Expression>` values here refer to an expression in
1262 /// [`Function::expressions`].
1263 ///
1264 /// [`SubgroupGather`]: Statement::SubgroupGather
1265 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1266 #[cfg_attr(feature = "serialize", derive(Serialize))]
1267 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1268 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1269 pub enum GatherMode {
1270 /// All gather from the active lane with the smallest index
1271 BroadcastFirst,
1272 /// All gather from the same lane at the index given by the expression
1273 Broadcast(Handle<Expression>),
1274 /// Each gathers from a different lane at the index given by the expression
1275 Shuffle(Handle<Expression>),
1276 /// Each gathers from their lane plus the shift given by the expression
1277 ShuffleDown(Handle<Expression>),
1278 /// Each gathers from their lane minus the shift given by the expression
1279 ShuffleUp(Handle<Expression>),
1280 /// Each gathers from their lane xored with the given by the expression
1281 ShuffleXor(Handle<Expression>),
1282 }
1283
1284 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1285 #[cfg_attr(feature = "serialize", derive(Serialize))]
1286 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1287 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1288 pub enum SubgroupOperation {
1289 All = 0,
1290 Any = 1,
1291 Add = 2,
1292 Mul = 3,
1293 Min = 4,
1294 Max = 5,
1295 And = 6,
1296 Or = 7,
1297 Xor = 8,
1298 }
1299
1300 #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1301 #[cfg_attr(feature = "serialize", derive(Serialize))]
1302 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1303 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1304 pub enum CollectiveOperation {
1305 Reduce = 0,
1306 InclusiveScan = 1,
1307 ExclusiveScan = 2,
1308 }
1309
1310 bitflags::bitflags! {
1311 /// Memory barrier flags.
1312 #[cfg_attr(feature = "serialize", derive(Serialize))]
1313 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1314 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1315 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1316 pub struct Barrier: u32 {
1317 /// Barrier affects all [`AddressSpace::Storage`] accesses.
1318 const STORAGE = 1 << 0;
1319 /// Barrier affects all [`AddressSpace::WorkGroup`] accesses.
1320 const WORK_GROUP = 1 << 1;
1321 /// Barrier synchronizes execution across all invocations within a subgroup that execute this instruction.
1322 const SUB_GROUP = 1 << 2;
1323 /// Barrier synchronizes texture memory accesses in a workgroup.
1324 const TEXTURE = 1 << 3;
1325 }
1326 }
1327
1328 /// An expression that can be evaluated to obtain a value.
1329 ///
1330 /// This is a Single Static Assignment (SSA) scheme similar to SPIR-V.
1331 ///
1332 /// When an `Expression` variant holds `Handle<Expression>` fields, they refer
1333 /// to another expression in the same arena, unless explicitly noted otherwise.
1334 /// One `Arena<Expression>` may only refer to a different arena indirectly, via
1335 /// [`Constant`] or [`Override`] expressions, which hold handles for their
1336 /// respective types.
1337 ///
1338 /// [`Constant`]: Expression::Constant
1339 /// [`Override`]: Expression::Override
1340 #[derive(Clone, Debug, PartialEq)]
1341 #[cfg_attr(feature = "serialize", derive(Serialize))]
1342 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1343 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1344 pub enum Expression {
1345 /// Literal.
1346 Literal(Literal),
1347 /// Constant value.
1348 Constant(Handle<Constant>),
1349 /// Pipeline-overridable constant.
1350 Override(Handle<Override>),
1351 /// Zero value of a type.
1352 ZeroValue(Handle<Type>),
1353 /// Composite expression.
1354 Compose {
1355 ty: Handle<Type>,
1356 components: Vec<Handle<Expression>>,
1357 },
1358
1359 /// Array access with a computed index.
1360 ///
1361 /// ## Typing rules
1362 ///
1363 /// The `base` operand must be some composite type: [`Vector`], [`Matrix`],
1364 /// [`Array`], a [`Pointer`] to one of those, or a [`ValuePointer`] with a
1365 /// `size`.
1366 ///
1367 /// The `index` operand must be an integer, signed or unsigned.
1368 ///
1369 /// Indexing a [`Vector`] or [`Array`] produces a value of its element type.
1370 /// Indexing a [`Matrix`] produces a [`Vector`].
1371 ///
1372 /// Indexing a [`Pointer`] to any of the above produces a pointer to the
1373 /// element/component type, in the same [`space`]. In the case of [`Array`],
1374 /// the result is an actual [`Pointer`], but for vectors and matrices, there
1375 /// may not be any type in the arena representing the component's type, so
1376 /// those produce [`ValuePointer`] types equivalent to the appropriate
1377 /// [`Pointer`].
1378 ///
1379 /// ## Dynamic indexing restrictions
1380 ///
1381 /// To accommodate restrictions in some of the shader languages that Naga
1382 /// targets, it is not permitted to subscript a matrix with a dynamically
1383 /// computed index unless that matrix appears behind a pointer. In other
1384 /// words, if the inner type of `base` is [`Matrix`], then `index` must be a
1385 /// constant. But if the type of `base` is a [`Pointer`] to an matrix, then
1386 /// the index may be any expression of integer type.
1387 ///
1388 /// You can use the [`Expression::is_dynamic_index`] method to determine
1389 /// whether a given index expression requires matrix base operands to be
1390 /// behind a pointer.
1391 ///
1392 /// (It would be simpler to always require the use of `AccessIndex` when
1393 /// subscripting matrices that are not behind pointers, but to accommodate
1394 /// existing front ends, Naga also permits `Access`, with a restricted
1395 /// `index`.)
1396 ///
1397 /// [`Vector`]: TypeInner::Vector
1398 /// [`Matrix`]: TypeInner::Matrix
1399 /// [`Array`]: TypeInner::Array
1400 /// [`Pointer`]: TypeInner::Pointer
1401 /// [`space`]: TypeInner::Pointer::space
1402 /// [`ValuePointer`]: TypeInner::ValuePointer
1403 /// [`Float`]: ScalarKind::Float
1404 Access {
1405 base: Handle<Expression>,
1406 index: Handle<Expression>,
1407 },
1408 /// Access the same types as [`Access`], plus [`Struct`] with a known index.
1409 ///
1410 /// [`Access`]: Expression::Access
1411 /// [`Struct`]: TypeInner::Struct
1412 AccessIndex {
1413 base: Handle<Expression>,
1414 index: u32,
1415 },
1416 /// Splat scalar into a vector.
1417 Splat {
1418 size: VectorSize,
1419 value: Handle<Expression>,
1420 },
1421 /// Vector swizzle.
1422 Swizzle {
1423 size: VectorSize,
1424 vector: Handle<Expression>,
1425 pattern: [SwizzleComponent; 4],
1426 },
1427
1428 /// Reference a function parameter, by its index.
1429 ///
1430 /// A `FunctionArgument` expression evaluates to the argument's value.
1431 FunctionArgument(u32),
1432
1433 /// Reference a global variable.
1434 ///
1435 /// If the given `GlobalVariable`'s [`space`] is [`AddressSpace::Handle`],
1436 /// then the variable stores some opaque type like a sampler or an image,
1437 /// and a `GlobalVariable` expression referring to it produces the
1438 /// variable's value directly.
1439 ///
1440 /// For any other address space, a `GlobalVariable` expression produces a
1441 /// pointer to the variable's value. You must use a [`Load`] expression to
1442 /// retrieve its value, or a [`Store`] statement to assign it a new value.
1443 ///
1444 /// [`space`]: GlobalVariable::space
1445 /// [`Load`]: Expression::Load
1446 /// [`Store`]: Statement::Store
1447 GlobalVariable(Handle<GlobalVariable>),
1448
1449 /// Reference a local variable.
1450 ///
1451 /// A `LocalVariable` expression evaluates to a pointer to the variable's value.
1452 /// You must use a [`Load`](Expression::Load) expression to retrieve its value,
1453 /// or a [`Store`](Statement::Store) statement to assign it a new value.
1454 LocalVariable(Handle<LocalVariable>),
1455
1456 /// Load a value indirectly.
1457 ///
1458 /// For [`TypeInner::Atomic`] the result is a corresponding scalar.
1459 /// For other types behind the `pointer<T>`, the result is `T`.
1460 Load { pointer: Handle<Expression> },
1461 /// Sample a point from a sampled or a depth image.
1462 ImageSample {
1463 image: Handle<Expression>,
1464 sampler: Handle<Expression>,
1465 /// If Some(), this operation is a gather operation
1466 /// on the selected component.
1467 gather: Option<SwizzleComponent>,
1468 coordinate: Handle<Expression>,
1469 array_index: Option<Handle<Expression>>,
1470 /// This must be a const-expression.
1471 offset: Option<Handle<Expression>>,
1472 level: SampleLevel,
1473 depth_ref: Option<Handle<Expression>>,
1474 },
1475
1476 /// Load a texel from an image.
1477 ///
1478 /// For most images, this returns a four-element vector of the same
1479 /// [`ScalarKind`] as the image. If the format of the image does not have
1480 /// four components, default values are provided: the first three components
1481 /// (typically R, G, and B) default to zero, and the final component
1482 /// (typically alpha) defaults to one.
1483 ///
1484 /// However, if the image's [`class`] is [`Depth`], then this returns a
1485 /// [`Float`] scalar value.
1486 ///
1487 /// [`ScalarKind`]: ScalarKind
1488 /// [`class`]: TypeInner::Image::class
1489 /// [`Depth`]: ImageClass::Depth
1490 /// [`Float`]: ScalarKind::Float
1491 ImageLoad {
1492 /// The image to load a texel from. This must have type [`Image`]. (This
1493 /// will necessarily be a [`GlobalVariable`] or [`FunctionArgument`]
1494 /// expression, since no other expressions are allowed to have that
1495 /// type.)
1496 ///
1497 /// [`Image`]: TypeInner::Image
1498 /// [`GlobalVariable`]: Expression::GlobalVariable
1499 /// [`FunctionArgument`]: Expression::FunctionArgument
1500 image: Handle<Expression>,
1501
1502 /// The coordinate of the texel we wish to load. This must be a scalar
1503 /// for [`D1`] images, a [`Bi`] vector for [`D2`] images, and a [`Tri`]
1504 /// vector for [`D3`] images. (Array indices, sample indices, and
1505 /// explicit level-of-detail values are supplied separately.) Its
1506 /// component type must be [`Sint`].
1507 ///
1508 /// [`D1`]: ImageDimension::D1
1509 /// [`D2`]: ImageDimension::D2
1510 /// [`D3`]: ImageDimension::D3
1511 /// [`Bi`]: VectorSize::Bi
1512 /// [`Tri`]: VectorSize::Tri
1513 /// [`Sint`]: ScalarKind::Sint
1514 coordinate: Handle<Expression>,
1515
1516 /// The index into an arrayed image. If the [`arrayed`] flag in
1517 /// `image`'s type is `true`, then this must be `Some(expr)`, where
1518 /// `expr` is a [`Sint`] scalar. Otherwise, it must be `None`.
1519 ///
1520 /// [`arrayed`]: TypeInner::Image::arrayed
1521 /// [`Sint`]: ScalarKind::Sint
1522 array_index: Option<Handle<Expression>>,
1523
1524 /// A sample index, for multisampled [`Sampled`] and [`Depth`] images.
1525 ///
1526 /// [`Sampled`]: ImageClass::Sampled
1527 /// [`Depth`]: ImageClass::Depth
1528 sample: Option<Handle<Expression>>,
1529
1530 /// A level of detail, for mipmapped images.
1531 ///
1532 /// This must be present when accessing non-multisampled
1533 /// [`Sampled`] and [`Depth`] images, even if only the
1534 /// full-resolution level is present (in which case the only
1535 /// valid level is zero).
1536 ///
1537 /// [`Sampled`]: ImageClass::Sampled
1538 /// [`Depth`]: ImageClass::Depth
1539 level: Option<Handle<Expression>>,
1540 },
1541
1542 /// Query information from an image.
1543 ImageQuery {
1544 image: Handle<Expression>,
1545 query: ImageQuery,
1546 },
1547 /// Apply an unary operator.
1548 Unary {
1549 op: UnaryOperator,
1550 expr: Handle<Expression>,
1551 },
1552 /// Apply a binary operator.
1553 Binary {
1554 op: BinaryOperator,
1555 left: Handle<Expression>,
1556 right: Handle<Expression>,
1557 },
1558 /// Select between two values based on a condition.
1559 ///
1560 /// Note that, because expressions have no side effects, it is unobservable
1561 /// whether the non-selected branch is evaluated.
1562 Select {
1563 /// Boolean expression
1564 condition: Handle<Expression>,
1565 accept: Handle<Expression>,
1566 reject: Handle<Expression>,
1567 },
1568 /// Compute the derivative on an axis.
1569 Derivative {
1570 axis: DerivativeAxis,
1571 ctrl: DerivativeControl,
1572 expr: Handle<Expression>,
1573 },
1574 /// Call a relational function.
1575 Relational {
1576 fun: RelationalFunction,
1577 argument: Handle<Expression>,
1578 },
1579 /// Call a math function
1580 Math {
1581 fun: MathFunction,
1582 arg: Handle<Expression>,
1583 arg1: Option<Handle<Expression>>,
1584 arg2: Option<Handle<Expression>>,
1585 arg3: Option<Handle<Expression>>,
1586 },
1587 /// Cast a simple type to another kind.
1588 As {
1589 /// Source expression, which can only be a scalar or a vector.
1590 expr: Handle<Expression>,
1591 /// Target scalar kind.
1592 kind: ScalarKind,
1593 /// If provided, converts to the specified byte width.
1594 /// Otherwise, bitcast.
1595 convert: Option<Bytes>,
1596 },
1597 /// Result of calling another function.
1598 CallResult(Handle<Function>),
1599
1600 /// Result of an atomic operation.
1601 ///
1602 /// This expression must be referred to by the [`result`] field of exactly one
1603 /// [`Atomic`][stmt] statement somewhere in the same function. Let `T` be the
1604 /// scalar type contained by the [`Atomic`][type] value that the statement
1605 /// operates on.
1606 ///
1607 /// If `comparison` is `false`, then `ty` must be the scalar type `T`.
1608 ///
1609 /// If `comparison` is `true`, then `ty` must be a [`Struct`] with two members:
1610 ///
1611 /// - A member named `old_value`, whose type is `T`, and
1612 ///
1613 /// - A member named `exchanged`, of type [`BOOL`].
1614 ///
1615 /// [`result`]: Statement::Atomic::result
1616 /// [stmt]: Statement::Atomic
1617 /// [type]: TypeInner::Atomic
1618 /// [`Struct`]: TypeInner::Struct
1619 /// [`BOOL`]: Scalar::BOOL
1620 AtomicResult { ty: Handle<Type>, comparison: bool },
1621
1622 /// Result of a [`WorkGroupUniformLoad`] statement.
1623 ///
1624 /// [`WorkGroupUniformLoad`]: Statement::WorkGroupUniformLoad
1625 WorkGroupUniformLoadResult {
1626 /// The type of the result
1627 ty: Handle<Type>,
1628 },
1629 /// Get the length of an array.
1630 /// The expression must resolve to a pointer to an array with a dynamic size.
1631 ///
1632 /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed
1633 /// a pointer to a structure containing a runtime array in its' last field.
1634 ArrayLength(Handle<Expression>),
1635
1636 /// Get the Positions of the triangle hit by the [`RayQuery`]
1637 ///
1638 /// [`RayQuery`]: Statement::RayQuery
1639 RayQueryVertexPositions {
1640 query: Handle<Expression>,
1641 committed: bool,
1642 },
1643
1644 /// Result of a [`Proceed`] [`RayQuery`] statement.
1645 ///
1646 /// [`Proceed`]: RayQueryFunction::Proceed
1647 /// [`RayQuery`]: Statement::RayQuery
1648 RayQueryProceedResult,
1649
1650 /// Return an intersection found by `query`.
1651 ///
1652 /// If `committed` is true, return the committed result available when
1653 RayQueryGetIntersection {
1654 query: Handle<Expression>,
1655 committed: bool,
1656 },
1657 /// Result of a [`SubgroupBallot`] statement.
1658 ///
1659 /// [`SubgroupBallot`]: Statement::SubgroupBallot
1660 SubgroupBallotResult,
1661 /// Result of a [`SubgroupCollectiveOperation`] or [`SubgroupGather`] statement.
1662 ///
1663 /// [`SubgroupCollectiveOperation`]: Statement::SubgroupCollectiveOperation
1664 /// [`SubgroupGather`]: Statement::SubgroupGather
1665 SubgroupOperationResult { ty: Handle<Type> },
1666 }
1667
1668 /// The value of the switch case.
1669 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1670 #[cfg_attr(feature = "serialize", derive(Serialize))]
1671 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1672 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1673 pub enum SwitchValue {
1674 I32(i32),
1675 U32(u32),
1676 Default,
1677 }
1678
1679 /// A case for a switch statement.
1680 // Clone is used only for error reporting and is not intended for end users
1681 #[derive(Clone, Debug)]
1682 #[cfg_attr(feature = "serialize", derive(Serialize))]
1683 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1684 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1685 pub struct SwitchCase {
1686 /// Value, upon which the case is considered true.
1687 pub value: SwitchValue,
1688 /// Body of the case.
1689 pub body: Block,
1690 /// If true, the control flow continues to the next case in the list,
1691 /// or default.
1692 pub fall_through: bool,
1693 }
1694
1695 /// An operation that a [`RayQuery` statement] applies to its [`query`] operand.
1696 ///
1697 /// [`RayQuery` statement]: Statement::RayQuery
1698 /// [`query`]: Statement::RayQuery::query
1699 #[derive(Clone, Debug)]
1700 #[cfg_attr(feature = "serialize", derive(Serialize))]
1701 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1702 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1703 pub enum RayQueryFunction {
1704 /// Initialize the `RayQuery` object.
1705 Initialize {
1706 /// The acceleration structure within which this query should search for hits.
1707 ///
1708 /// The expression must be an [`AccelerationStructure`].
1709 ///
1710 /// [`AccelerationStructure`]: TypeInner::AccelerationStructure
1711 acceleration_structure: Handle<Expression>,
1712
1713 #[allow(rustdoc::private_intra_doc_links)]
1714 /// A struct of detailed parameters for the ray query.
1715 ///
1716 /// This expression should have the struct type given in
1717 /// [`SpecialTypes::ray_desc`]. This is available in the WGSL
1718 /// front end as the `RayDesc` type.
1719 descriptor: Handle<Expression>,
1720 },
1721
1722 /// Start or continue the query given by the statement's [`query`] operand.
1723 ///
1724 /// After executing this statement, the `result` expression is a
1725 /// [`Bool`] scalar indicating whether there are more intersection
1726 /// candidates to consider.
1727 ///
1728 /// [`query`]: Statement::RayQuery::query
1729 /// [`Bool`]: ScalarKind::Bool
1730 Proceed {
1731 result: Handle<Expression>,
1732 },
1733
1734 /// Add a candidate generated intersection to be included
1735 /// in the determination of the closest hit for a ray query.
1736 GenerateIntersection {
1737 hit_t: Handle<Expression>,
1738 },
1739
1740 /// Confirm a triangle intersection to be included in the determination of
1741 /// the closest hit for a ray query.
1742 ConfirmIntersection,
1743
1744 Terminate,
1745 }
1746
1747 //TODO: consider removing `Clone`. It's not valid to clone `Statement::Emit` anyway.
1748 /// Instructions which make up an executable block.
1749 ///
1750 /// `Handle<Expression>` and `Range<Expression>` values in `Statement` variants
1751 /// refer to expressions in [`Function::expressions`], unless otherwise noted.
1752 // Clone is used only for error reporting and is not intended for end users
1753 #[derive(Clone, Debug)]
1754 #[cfg_attr(feature = "serialize", derive(Serialize))]
1755 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1756 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1757 pub enum Statement {
1758 /// Emit a range of expressions, visible to all statements that follow in this block.
1759 ///
1760 /// See the [module-level documentation][emit] for details.
1761 ///
1762 /// [emit]: index.html#expression-evaluation-time
1763 Emit(Range<Expression>),
1764 /// A block containing more statements, to be executed sequentially.
1765 Block(Block),
1766 /// Conditionally executes one of two blocks, based on the value of the condition.
1767 ///
1768 /// Naga IR does not have "phi" instructions. If you need to use
1769 /// values computed in an `accept` or `reject` block after the `If`,
1770 /// store them in a [`LocalVariable`].
1771 If {
1772 condition: Handle<Expression>, //bool
1773 accept: Block,
1774 reject: Block,
1775 },
1776 /// Conditionally executes one of multiple blocks, based on the value of the selector.
1777 ///
1778 /// Each case must have a distinct [`value`], exactly one of which must be
1779 /// [`Default`]. The `Default` may appear at any position, and covers all
1780 /// values not explicitly appearing in other cases. A `Default` appearing in
1781 /// the midst of the list of cases does not shadow the cases that follow.
1782 ///
1783 /// Some backend languages don't support fallthrough (HLSL due to FXC,
1784 /// WGSL), and may translate fallthrough cases in the IR by duplicating
1785 /// code. However, all backend languages do support cases selected by
1786 /// multiple values, like `case 1: case 2: case 3: { ... }`. This is
1787 /// represented in the IR as a series of fallthrough cases with empty
1788 /// bodies, except for the last.
1789 ///
1790 /// Naga IR does not have "phi" instructions. If you need to use
1791 /// values computed in a [`SwitchCase::body`] block after the `Switch`,
1792 /// store them in a [`LocalVariable`].
1793 ///
1794 /// [`value`]: SwitchCase::value
1795 /// [`body`]: SwitchCase::body
1796 /// [`Default`]: SwitchValue::Default
1797 Switch {
1798 selector: Handle<Expression>,
1799 cases: Vec<SwitchCase>,
1800 },
1801
1802 /// Executes a block repeatedly.
1803 ///
1804 /// Each iteration of the loop executes the `body` block, followed by the
1805 /// `continuing` block.
1806 ///
1807 /// Executing a [`Break`], [`Return`] or [`Kill`] statement exits the loop.
1808 ///
1809 /// A [`Continue`] statement in `body` jumps to the `continuing` block. The
1810 /// `continuing` block is meant to be used to represent structures like the
1811 /// third expression of a C-style `for` loop head, to which `continue`
1812 /// statements in the loop's body jump.
1813 ///
1814 /// The `continuing` block and its substatements must not contain `Return`
1815 /// or `Kill` statements, or any `Break` or `Continue` statements targeting
1816 /// this loop. (It may have `Break` and `Continue` statements targeting
1817 /// loops or switches nested within the `continuing` block.) Expressions
1818 /// emitted in `body` are in scope in `continuing`.
1819 ///
1820 /// If present, `break_if` is an expression which is evaluated after the
1821 /// continuing block. Expressions emitted in `body` or `continuing` are
1822 /// considered to be in scope. If the expression's value is true, control
1823 /// continues after the `Loop` statement, rather than branching back to the
1824 /// top of body as usual. The `break_if` expression corresponds to a "break
1825 /// if" statement in WGSL, or a loop whose back edge is an
1826 /// `OpBranchConditional` instruction in SPIR-V.
1827 ///
1828 /// Naga IR does not have "phi" instructions. If you need to use
1829 /// values computed in a `body` or `continuing` block after the
1830 /// `Loop`, store them in a [`LocalVariable`].
1831 ///
1832 /// [`Break`]: Statement::Break
1833 /// [`Continue`]: Statement::Continue
1834 /// [`Kill`]: Statement::Kill
1835 /// [`Return`]: Statement::Return
1836 /// [`break if`]: Self::Loop::break_if
1837 Loop {
1838 body: Block,
1839 continuing: Block,
1840 break_if: Option<Handle<Expression>>,
1841 },
1842
1843 /// Exits the innermost enclosing [`Loop`] or [`Switch`].
1844 ///
1845 /// A `Break` statement may only appear within a [`Loop`] or [`Switch`]
1846 /// statement. It may not break out of a [`Loop`] from within the loop's
1847 /// `continuing` block.
1848 ///
1849 /// [`Loop`]: Statement::Loop
1850 /// [`Switch`]: Statement::Switch
1851 Break,
1852
1853 /// Skips to the `continuing` block of the innermost enclosing [`Loop`].
1854 ///
1855 /// A `Continue` statement may only appear within the `body` block of the
1856 /// innermost enclosing [`Loop`] statement. It must not appear within that
1857 /// loop's `continuing` block.
1858 ///
1859 /// [`Loop`]: Statement::Loop
1860 Continue,
1861
1862 /// Returns from the function (possibly with a value).
1863 ///
1864 /// `Return` statements are forbidden within the `continuing` block of a
1865 /// [`Loop`] statement.
1866 ///
1867 /// [`Loop`]: Statement::Loop
1868 Return { value: Option<Handle<Expression>> },
1869
1870 /// Aborts the current shader execution.
1871 ///
1872 /// `Kill` statements are forbidden within the `continuing` block of a
1873 /// [`Loop`] statement.
1874 ///
1875 /// [`Loop`]: Statement::Loop
1876 Kill,
1877
1878 /// Synchronize invocations within the work group.
1879 /// The `Barrier` flags control which memory accesses should be synchronized.
1880 /// If empty, this becomes purely an execution barrier.
1881 Barrier(Barrier),
1882 /// Stores a value at an address.
1883 ///
1884 /// For [`TypeInner::Atomic`] type behind the pointer, the value
1885 /// has to be a corresponding scalar.
1886 /// For other types behind the `pointer<T>`, the value is `T`.
1887 ///
1888 /// This statement is a barrier for any operations on the
1889 /// `Expression::LocalVariable` or `Expression::GlobalVariable`
1890 /// that is the destination of an access chain, started
1891 /// from the `pointer`.
1892 Store {
1893 pointer: Handle<Expression>,
1894 value: Handle<Expression>,
1895 },
1896 /// Stores a texel value to an image.
1897 ///
1898 /// The `image`, `coordinate`, and `array_index` fields have the same
1899 /// meanings as the corresponding operands of an [`ImageLoad`] expression;
1900 /// see that documentation for details. Storing into multisampled images or
1901 /// images with mipmaps is not supported, so there are no `level` or
1902 /// `sample` operands.
1903 ///
1904 /// This statement is a barrier for any operations on the corresponding
1905 /// [`Expression::GlobalVariable`] for this image.
1906 ///
1907 /// [`ImageLoad`]: Expression::ImageLoad
1908 ImageStore {
1909 image: Handle<Expression>,
1910 coordinate: Handle<Expression>,
1911 array_index: Option<Handle<Expression>>,
1912 value: Handle<Expression>,
1913 },
1914 /// Atomic function.
1915 Atomic {
1916 /// Pointer to an atomic value.
1917 ///
1918 /// This must be a [`Pointer`] to an [`Atomic`] value. The atomic's
1919 /// scalar type may be [`I32`] or [`U32`].
1920 ///
1921 /// If [`SHADER_INT64_ATOMIC_MIN_MAX`] or [`SHADER_INT64_ATOMIC_ALL_OPS`] are
1922 /// enabled, this may also be [`I64`] or [`U64`].
1923 ///
1924 /// If [`SHADER_FLOAT32_ATOMIC`] is enabled, this may be [`F32`].
1925 ///
1926 /// [`Pointer`]: TypeInner::Pointer
1927 /// [`Atomic`]: TypeInner::Atomic
1928 /// [`I32`]: Scalar::I32
1929 /// [`U32`]: Scalar::U32
1930 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
1931 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
1932 /// [`SHADER_FLOAT32_ATOMIC`]: crate::valid::Capabilities::SHADER_FLOAT32_ATOMIC
1933 /// [`I64`]: Scalar::I64
1934 /// [`U64`]: Scalar::U64
1935 /// [`F32`]: Scalar::F32
1936 pointer: Handle<Expression>,
1937
1938 /// Function to run on the atomic value.
1939 ///
1940 /// If [`pointer`] refers to a 64-bit atomic value, then:
1941 ///
1942 /// - The [`SHADER_INT64_ATOMIC_ALL_OPS`] capability allows any [`AtomicFunction`]
1943 /// value here.
1944 ///
1945 /// - The [`SHADER_INT64_ATOMIC_MIN_MAX`] capability allows
1946 /// [`AtomicFunction::Min`] and [`AtomicFunction::Max`]
1947 /// in the [`Storage`] address space here.
1948 ///
1949 /// - If neither of those capabilities are present, then 64-bit scalar
1950 /// atomics are not allowed.
1951 ///
1952 /// If [`pointer`] refers to a 32-bit floating-point atomic value, then:
1953 ///
1954 /// - The [`SHADER_FLOAT32_ATOMIC`] capability allows [`AtomicFunction::Add`],
1955 /// [`AtomicFunction::Subtract`], and [`AtomicFunction::Exchange { compare: None }`]
1956 /// in the [`Storage`] address space here.
1957 ///
1958 /// [`AtomicFunction::Exchange { compare: None }`]: AtomicFunction::Exchange
1959 /// [`pointer`]: Statement::Atomic::pointer
1960 /// [`Storage`]: AddressSpace::Storage
1961 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
1962 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
1963 /// [`SHADER_FLOAT32_ATOMIC`]: crate::valid::Capabilities::SHADER_FLOAT32_ATOMIC
1964 fun: AtomicFunction,
1965
1966 /// Value to use in the function.
1967 ///
1968 /// This must be a scalar of the same type as [`pointer`]'s atomic's scalar type.
1969 ///
1970 /// [`pointer`]: Statement::Atomic::pointer
1971 value: Handle<Expression>,
1972
1973 /// [`AtomicResult`] expression representing this function's result.
1974 ///
1975 /// If [`fun`] is [`Exchange { compare: None }`], this must be `Some`,
1976 /// as otherwise that operation would be equivalent to a simple [`Store`]
1977 /// to the atomic.
1978 ///
1979 /// Otherwise, this may be `None` if the return value of the operation is not needed.
1980 ///
1981 /// If `pointer` refers to a 64-bit atomic value, [`SHADER_INT64_ATOMIC_MIN_MAX`]
1982 /// is enabled, and [`SHADER_INT64_ATOMIC_ALL_OPS`] is not, this must be `None`.
1983 ///
1984 /// [`AtomicResult`]: crate::Expression::AtomicResult
1985 /// [`fun`]: Statement::Atomic::fun
1986 /// [`Store`]: Statement::Store
1987 /// [`Exchange { compare: None }`]: AtomicFunction::Exchange
1988 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
1989 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
1990 result: Option<Handle<Expression>>,
1991 },
1992 /// Performs an atomic operation on a texel value of an image.
1993 ///
1994 /// Doing atomics on images with mipmaps is not supported, so there is no
1995 /// `level` operand.
1996 ImageAtomic {
1997 /// The image to perform an atomic operation on. This must have type
1998 /// [`Image`]. (This will necessarily be a [`GlobalVariable`] or
1999 /// [`FunctionArgument`] expression, since no other expressions are
2000 /// allowed to have that type.)
2001 ///
2002 /// [`Image`]: TypeInner::Image
2003 /// [`GlobalVariable`]: Expression::GlobalVariable
2004 /// [`FunctionArgument`]: Expression::FunctionArgument
2005 image: Handle<Expression>,
2006
2007 /// The coordinate of the texel we wish to load. This must be a scalar
2008 /// for [`D1`] images, a [`Bi`] vector for [`D2`] images, and a [`Tri`]
2009 /// vector for [`D3`] images. (Array indices, sample indices, and
2010 /// explicit level-of-detail values are supplied separately.) Its
2011 /// component type must be [`Sint`].
2012 ///
2013 /// [`D1`]: ImageDimension::D1
2014 /// [`D2`]: ImageDimension::D2
2015 /// [`D3`]: ImageDimension::D3
2016 /// [`Bi`]: VectorSize::Bi
2017 /// [`Tri`]: VectorSize::Tri
2018 /// [`Sint`]: ScalarKind::Sint
2019 coordinate: Handle<Expression>,
2020
2021 /// The index into an arrayed image. If the [`arrayed`] flag in
2022 /// `image`'s type is `true`, then this must be `Some(expr)`, where
2023 /// `expr` is a [`Sint`] scalar. Otherwise, it must be `None`.
2024 ///
2025 /// [`arrayed`]: TypeInner::Image::arrayed
2026 /// [`Sint`]: ScalarKind::Sint
2027 array_index: Option<Handle<Expression>>,
2028
2029 /// The kind of atomic operation to perform on the texel.
2030 fun: AtomicFunction,
2031
2032 /// The value with which to perform the atomic operation.
2033 value: Handle<Expression>,
2034 },
2035 /// Load uniformly from a uniform pointer in the workgroup address space.
2036 ///
2037 /// Corresponds to the [`workgroupUniformLoad`](https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin)
2038 /// built-in function of wgsl, and has the same barrier semantics
2039 WorkGroupUniformLoad {
2040 /// This must be of type [`Pointer`] in the [`WorkGroup`] address space
2041 ///
2042 /// [`Pointer`]: TypeInner::Pointer
2043 /// [`WorkGroup`]: AddressSpace::WorkGroup
2044 pointer: Handle<Expression>,
2045 /// The [`WorkGroupUniformLoadResult`] expression representing this load's result.
2046 ///
2047 /// [`WorkGroupUniformLoadResult`]: Expression::WorkGroupUniformLoadResult
2048 result: Handle<Expression>,
2049 },
2050 /// Calls a function.
2051 ///
2052 /// If the `result` is `Some`, the corresponding expression has to be
2053 /// `Expression::CallResult`, and this statement serves as a barrier for any
2054 /// operations on that expression.
2055 Call {
2056 function: Handle<Function>,
2057 arguments: Vec<Handle<Expression>>,
2058 result: Option<Handle<Expression>>,
2059 },
2060 RayQuery {
2061 /// The [`RayQuery`] object this statement operates on.
2062 ///
2063 /// [`RayQuery`]: TypeInner::RayQuery
2064 query: Handle<Expression>,
2065
2066 /// The specific operation we're performing on `query`.
2067 fun: RayQueryFunction,
2068 },
2069 /// Calculate a bitmask using a boolean from each active thread in the subgroup
2070 SubgroupBallot {
2071 /// The [`SubgroupBallotResult`] expression representing this load's result.
2072 ///
2073 /// [`SubgroupBallotResult`]: Expression::SubgroupBallotResult
2074 result: Handle<Expression>,
2075 /// The value from this thread to store in the ballot
2076 predicate: Option<Handle<Expression>>,
2077 },
2078 /// Gather a value from another active thread in the subgroup
2079 SubgroupGather {
2080 /// Specifies which thread to gather from
2081 mode: GatherMode,
2082 /// The value to broadcast over
2083 argument: Handle<Expression>,
2084 /// The [`SubgroupOperationResult`] expression representing this load's result.
2085 ///
2086 /// [`SubgroupOperationResult`]: Expression::SubgroupOperationResult
2087 result: Handle<Expression>,
2088 },
2089 /// Compute a collective operation across all active threads in the subgroup
2090 SubgroupCollectiveOperation {
2091 /// What operation to compute
2092 op: SubgroupOperation,
2093 /// How to combine the results
2094 collective_op: CollectiveOperation,
2095 /// The value to compute over
2096 argument: Handle<Expression>,
2097 /// The [`SubgroupOperationResult`] expression representing this load's result.
2098 ///
2099 /// [`SubgroupOperationResult`]: Expression::SubgroupOperationResult
2100 result: Handle<Expression>,
2101 },
2102 }
2103
2104 /// A function argument.
2105 #[derive(Clone, Debug)]
2106 #[cfg_attr(feature = "serialize", derive(Serialize))]
2107 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2108 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2109 pub struct FunctionArgument {
2110 /// Name of the argument, if any.
2111 pub name: Option<String>,
2112 /// Type of the argument.
2113 pub ty: Handle<Type>,
2114 /// For entry points, an argument has to have a binding
2115 /// unless it's a structure.
2116 pub binding: Option<Binding>,
2117 }
2118
2119 /// A function result.
2120 #[derive(Clone, Debug)]
2121 #[cfg_attr(feature = "serialize", derive(Serialize))]
2122 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2123 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2124 pub struct FunctionResult {
2125 /// Type of the result.
2126 pub ty: Handle<Type>,
2127 /// For entry points, the result has to have a binding
2128 /// unless it's a structure.
2129 pub binding: Option<Binding>,
2130 }
2131
2132 /// A function defined in the module.
2133 #[derive(Debug, Default, Clone)]
2134 #[cfg_attr(feature = "serialize", derive(Serialize))]
2135 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2136 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2137 pub struct Function {
2138 /// Name of the function, if any.
2139 pub name: Option<String>,
2140 /// Information about function argument.
2141 pub arguments: Vec<FunctionArgument>,
2142 /// The result of this function, if any.
2143 pub result: Option<FunctionResult>,
2144 /// Local variables defined and used in the function.
2145 pub local_variables: Arena<LocalVariable>,
2146 /// Expressions used inside this function.
2147 ///
2148 /// Unless explicitly stated otherwise, if an [`Expression`] is in this
2149 /// arena, then its subexpressions are in this arena too. In other words,
2150 /// every `Handle<Expression>` in this arena refers to an [`Expression`] in
2151 /// this arena too.
2152 ///
2153 /// The main ways this arena refers to [`Module::global_expressions`] are:
2154 ///
2155 /// - [`Constant`], [`Override`], and [`GlobalVariable`] expressions hold
2156 /// handles for their respective types, whose initializer expressions are
2157 /// in [`Module::global_expressions`].
2158 ///
2159 /// - Various expressions hold [`Type`] handles, and [`Type`]s may refer to
2160 /// global expressions, for things like array lengths.
2161 ///
2162 /// An [`Expression`] must occur before all other [`Expression`]s that use
2163 /// its value.
2164 ///
2165 /// [`Constant`]: Expression::Constant
2166 /// [`Override`]: Expression::Override
2167 /// [`GlobalVariable`]: Expression::GlobalVariable
2168 pub expressions: Arena<Expression>,
2169 /// Map of expressions that have associated variable names
2170 pub named_expressions: NamedExpressions,
2171 /// Block of instructions comprising the body of the function.
2172 pub body: Block,
2173 /// The leaf of all diagnostic filter rules tree (stored in [`Module::diagnostic_filters`])
2174 /// parsed on this function.
2175 ///
2176 /// In WGSL, this corresponds to `@diagnostic(…)` attributes.
2177 ///
2178 /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
2179 /// validation.
2180 pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
2181 }
2182
2183 /// The main function for a pipeline stage.
2184 ///
2185 /// An [`EntryPoint`] is a [`Function`] that serves as the main function for a
2186 /// graphics or compute pipeline stage. For example, an `EntryPoint` whose
2187 /// [`stage`] is [`ShaderStage::Vertex`] can serve as a graphics pipeline's
2188 /// vertex shader.
2189 ///
2190 /// Since an entry point is called directly by the graphics or compute pipeline,
2191 /// not by other WGSL functions, you must specify what the pipeline should pass
2192 /// as the entry point's arguments, and what values it will return. For example,
2193 /// a vertex shader needs a vertex's attributes as its arguments, but if it's
2194 /// used for instanced draw calls, it will also want to know the instance id.
2195 /// The vertex shader's return value will usually include an output vertex
2196 /// position, and possibly other attributes to be interpolated and passed along
2197 /// to a fragment shader.
2198 ///
2199 /// To specify this, the arguments and result of an `EntryPoint`'s [`function`]
2200 /// must each have a [`Binding`], or be structs whose members all have
2201 /// `Binding`s. This associates every value passed to or returned from the entry
2202 /// point with either a [`BuiltIn`] or a [`Location`]:
2203 ///
2204 /// - A [`BuiltIn`] has special semantics, usually specific to its pipeline
2205 /// stage. For example, the result of a vertex shader can include a
2206 /// [`BuiltIn::Position`] value, which determines the position of a vertex
2207 /// of a rendered primitive. Or, a compute shader might take an argument
2208 /// whose binding is [`BuiltIn::WorkGroupSize`], through which the compute
2209 /// pipeline would pass the number of invocations in your workgroup.
2210 ///
2211 /// - A [`Location`] indicates user-defined IO to be passed from one pipeline
2212 /// stage to the next. For example, a vertex shader might also produce a
2213 /// `uv` texture location as a user-defined IO value.
2214 ///
2215 /// In other words, the pipeline stage's input and output interface are
2216 /// determined by the bindings of the arguments and result of the `EntryPoint`'s
2217 /// [`function`].
2218 ///
2219 /// [`Function`]: crate::Function
2220 /// [`Location`]: Binding::Location
2221 /// [`function`]: EntryPoint::function
2222 /// [`stage`]: EntryPoint::stage
2223 #[derive(Debug, Clone)]
2224 #[cfg_attr(feature = "serialize", derive(Serialize))]
2225 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2226 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2227 pub struct EntryPoint {
2228 /// Name of this entry point, visible externally.
2229 ///
2230 /// Entry point names for a given `stage` must be distinct within a module.
2231 pub name: String,
2232 /// Shader stage.
2233 pub stage: ShaderStage,
2234 /// Early depth test for fragment stages.
2235 pub early_depth_test: Option<EarlyDepthTest>,
2236 /// Workgroup size for compute stages
2237 pub workgroup_size: [u32; 3],
2238 /// Override expressions for workgroup size in the global_expressions arena
2239 pub workgroup_size_overrides: Option<[Option<Handle<Expression>>; 3]>,
2240 /// The entrance function.
2241 pub function: Function,
2242 }
2243
2244 /// Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions.
2245 ///
2246 /// These cannot be spelled in WGSL source.
2247 ///
2248 /// Stored in [`SpecialTypes::predeclared_types`] and created by [`Module::generate_predeclared_type`].
2249 #[derive(Debug, PartialEq, Eq, Hash, Clone)]
2250 #[cfg_attr(feature = "serialize", derive(Serialize))]
2251 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2252 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2253 pub enum PredeclaredType {
2254 AtomicCompareExchangeWeakResult(Scalar),
2255 ModfResult {
2256 size: Option<VectorSize>,
2257 scalar: Scalar,
2258 },
2259 FrexpResult {
2260 size: Option<VectorSize>,
2261 scalar: Scalar,
2262 },
2263 }
2264
2265 /// Set of special types that can be optionally generated by the frontends.
2266 #[derive(Debug, Default, Clone)]
2267 #[cfg_attr(feature = "serialize", derive(Serialize))]
2268 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2269 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2270 pub struct SpecialTypes {
2271 /// Type for `RayDesc`.
2272 ///
2273 /// Call [`Module::generate_ray_desc_type`] to populate this if
2274 /// needed and return the handle.
2275 pub ray_desc: Option<Handle<Type>>,
2276
2277 /// Type for `RayIntersection`.
2278 ///
2279 /// Call [`Module::generate_ray_intersection_type`] to populate
2280 /// this if needed and return the handle.
2281 pub ray_intersection: Option<Handle<Type>>,
2282
2283 /// Type for `RayVertexReturn`.
2284 ///
2285 /// Call [`Module::generate_vertex_return_type`]
2286 pub ray_vertex_return: Option<Handle<Type>>,
2287
2288 /// Types for predeclared wgsl types instantiated on demand.
2289 ///
2290 /// Call [`Module::generate_predeclared_type`] to populate this if
2291 /// needed and return the handle.
2292 pub predeclared_types: FastIndexMap<PredeclaredType, Handle<Type>>,
2293 }
2294
2295 bitflags::bitflags! {
2296 /// Ray flags used when casting rays.
2297 /// Matching vulkan constants can be found in
2298 /// https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/ray_common/ray_flags_section.txt
2299 #[cfg_attr(feature = "serialize", derive(Serialize))]
2300 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2301 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2302 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
2303 pub struct RayFlag: u32 {
2304 /// Force all intersections to be treated as opaque.
2305 const FORCE_OPAQUE = 0x1;
2306 /// Force all intersections to be treated as non-opaque.
2307 const FORCE_NO_OPAQUE = 0x2;
2308 /// Stop traversal after the first hit.
2309 const TERMINATE_ON_FIRST_HIT = 0x4;
2310 /// Don't execute the closest hit shader.
2311 const SKIP_CLOSEST_HIT_SHADER = 0x8;
2312 /// Cull back facing geometry.
2313 const CULL_BACK_FACING = 0x10;
2314 /// Cull front facing geometry.
2315 const CULL_FRONT_FACING = 0x20;
2316 /// Cull opaque geometry.
2317 const CULL_OPAQUE = 0x40;
2318 /// Cull non-opaque geometry.
2319 const CULL_NO_OPAQUE = 0x80;
2320 /// Skip triangular geometry.
2321 const SKIP_TRIANGLES = 0x100;
2322 /// Skip axis-aligned bounding boxes.
2323 const SKIP_AABBS = 0x200;
2324 }
2325 }
2326
2327 /// Type of a ray query intersection.
2328 /// Matching vulkan constants can be found in
2329 /// <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_ray_query.asciidoc>
2330 /// but the actual values are different for candidate intersections.
2331 #[cfg_attr(feature = "serialize", derive(Serialize))]
2332 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2333 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2334 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
2335 pub enum RayQueryIntersection {
2336 /// No intersection found.
2337 /// Matches `RayQueryCommittedIntersectionNoneKHR`.
2338 #[default]
2339 None = 0,
2340 /// Intersecting with triangles.
2341 /// Matches `RayQueryCommittedIntersectionTriangleKHR` and `RayQueryCandidateIntersectionTriangleKHR`.
2342 Triangle = 1,
2343 /// Intersecting with generated primitives.
2344 /// Matches `RayQueryCommittedIntersectionGeneratedKHR`.
2345 Generated = 2,
2346 /// Intersecting with Axis Aligned Bounding Boxes.
2347 /// Matches `RayQueryCandidateIntersectionAABBKHR`.
2348 Aabb = 3,
2349 }
2350
2351 /// Shader module.
2352 ///
2353 /// A module is a set of constants, global variables and functions, as well as
2354 /// the types required to define them.
2355 ///
2356 /// Some functions are marked as entry points, to be used in a certain shader stage.
2357 ///
2358 /// To create a new module, use the `Default` implementation.
2359 /// Alternatively, you can load an existing shader using one of the [available front ends].
2360 ///
2361 /// When finished, you can export modules using one of the [available backends].
2362 ///
2363 /// ## Module arenas
2364 ///
2365 /// Most module contents are stored in [`Arena`]s. In a valid module, arena
2366 /// elements only refer to prior arena elements. That is, whenever an element in
2367 /// some `Arena<T>` contains a `Handle<T>` referring to another element the same
2368 /// arena, the handle's referent always precedes the element containing the
2369 /// handle.
2370 ///
2371 /// The elements of [`Module::types`] may refer to [`Expression`]s in
2372 /// [`Module::global_expressions`], and those expressions may in turn refer back
2373 /// to [`Type`]s in [`Module::types`]. In a valid module, there exists an order
2374 /// in which all types and global expressions can be visited such that:
2375 ///
2376 /// - types and expressions are visited in the order in which they appear in
2377 /// their arenas, and
2378 ///
2379 /// - every element refers only to previously visited elements.
2380 ///
2381 /// This implies that the graph of types and global expressions is acyclic.
2382 /// (However, it is a stronger condition: there are cycle-free arrangements of
2383 /// types and expressions for which an order like the one described above does
2384 /// not exist. Modules arranged in such a way are not valid.)
2385 ///
2386 /// [available front ends]: crate::front
2387 /// [available backends]: crate::back
2388 #[derive(Debug, Default, Clone)]
2389 #[cfg_attr(feature = "serialize", derive(Serialize))]
2390 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2391 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2392 pub struct Module {
2393 /// Arena for the types defined in this module.
2394 ///
2395 /// See the [`Module`] docs for more details about this field.
2396 pub types: UniqueArena<Type>,
2397 /// Dictionary of special type handles.
2398 pub special_types: SpecialTypes,
2399 /// Arena for the constants defined in this module.
2400 pub constants: Arena<Constant>,
2401 /// Arena for the pipeline-overridable constants defined in this module.
2402 pub overrides: Arena<Override>,
2403 /// Arena for the global variables defined in this module.
2404 pub global_variables: Arena<GlobalVariable>,
2405 /// [Constant expressions] and [override expressions] used by this module.
2406 ///
2407 /// If an expression is in this arena, then its subexpressions are in this
2408 /// arena too. In other words, every `Handle<Expression>` in this arena
2409 /// refers to an [`Expression`] in this arena too.
2410 ///
2411 /// See the [`Module`] docs for more details about this field.
2412 ///
2413 /// [Constant expressions]: index.html#constant-expressions
2414 /// [override expressions]: index.html#override-expressions
2415 pub global_expressions: Arena<Expression>,
2416 /// Arena for the functions defined in this module.
2417 ///
2418 /// Each function must appear in this arena strictly before all its callers.
2419 /// Recursion is not supported.
2420 pub functions: Arena<Function>,
2421 /// Entry points.
2422 pub entry_points: Vec<EntryPoint>,
2423 /// Arena for all diagnostic filter rules parsed in this module, including those in functions
2424 /// and statements.
2425 ///
2426 /// This arena contains elements of a _tree_ of diagnostic filter rules. When nodes are built
2427 /// by a front-end, they refer to a parent scope
2428 pub diagnostic_filters: Arena<DiagnosticFilterNode>,
2429 /// The leaf of all diagnostic filter rules tree parsed from directives in this module.
2430 ///
2431 /// In WGSL, this corresponds to `diagnostic(…);` directives.
2432 ///
2433 /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
2434 /// validation.
2435 pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
2436 }