naga/back/
mod.rs

1/*!
2Backend functions that export shader [`Module`](super::Module)s into binary and text formats.
3*/
4#![cfg_attr(
5    not(any(dot_out, glsl_out, hlsl_out, msl_out, spv_out, wgsl_out)),
6    allow(
7        dead_code,
8        reason = "shared helpers can be dead if none of the enabled backends need it"
9    )
10)]
11
12use alloc::string::String;
13
14#[cfg(dot_out)]
15pub mod dot;
16#[cfg(glsl_out)]
17pub mod glsl;
18#[cfg(hlsl_out)]
19pub mod hlsl;
20#[cfg(msl_out)]
21pub mod msl;
22#[cfg(spv_out)]
23pub mod spv;
24#[cfg(wgsl_out)]
25pub mod wgsl;
26
27#[cfg(any(hlsl_out, msl_out, spv_out, glsl_out))]
28pub mod pipeline_constants;
29
30#[cfg(any(hlsl_out, glsl_out))]
31mod continue_forward;
32
33/// Names of vector components.
34pub const COMPONENTS: &[char] = &['x', 'y', 'z', 'w'];
35/// Indent for backends.
36pub const INDENT: &str = "    ";
37
38/// Expressions that need baking.
39pub type NeedBakeExpressions = crate::FastHashSet<crate::Handle<crate::Expression>>;
40
41/// A type for displaying expression handles as baking identifiers.
42///
43/// Given an [`Expression`] [`Handle`] `h`, `Baked(h)` implements
44/// [`core::fmt::Display`], showing the handle's index prefixed by
45/// `_e`.
46///
47/// [`Expression`]: crate::Expression
48/// [`Handle`]: crate::Handle
49#[cfg_attr(
50    not(any(glsl_out, hlsl_out, msl_out, wgsl_out)),
51    allow(
52        dead_code,
53        reason = "shared helpers can be dead if none of the enabled backends need it"
54    )
55)]
56struct Baked(crate::Handle<crate::Expression>);
57
58impl core::fmt::Display for Baked {
59    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60        self.0.write_prefixed(f, "_e")
61    }
62}
63
64bitflags::bitflags! {
65    /// How far through a ray query are we
66    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
67    #[cfg_attr(
68        not(any(hlsl_out, spv_out)),
69        allow(
70            dead_code,
71            reason = "shared helpers can be dead if none of the enabled backends need it"
72        )
73    )]
74    pub(super) struct RayQueryPoint: u32 {
75        /// Ray query has been successfully initialized.
76        const INITIALIZED = 1 << 0;
77        /// Proceed has been called on ray query.
78        const PROCEED = 1 << 1;
79        /// Proceed has returned false (have finished traversal).
80        const FINISHED_TRAVERSAL = 1 << 2;
81    }
82}
83
84/// Specifies the values of pipeline-overridable constants in the shader module.
85///
86/// If an `@id` attribute was specified on the declaration,
87/// the key must be the pipeline constant ID as a decimal ASCII number; if not,
88/// the key must be the constant's identifier name.
89///
90/// The value may represent any of WGSL's concrete scalar types.
91pub type PipelineConstants = hashbrown::HashMap<String, f64>;
92
93/// Indentation level.
94#[derive(Clone, Copy)]
95pub struct Level(pub usize);
96
97impl Level {
98    pub const fn next(&self) -> Self {
99        Level(self.0 + 1)
100    }
101}
102
103impl core::fmt::Display for Level {
104    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
105        (0..self.0).try_for_each(|_| formatter.write_str(INDENT))
106    }
107}
108
109/// Locate the entry point(s) to write.
110///
111/// If `entry_point` is given, and the specified entry point exists, returns a
112/// length-1 `Range` containing the index of that entry point.  If no
113/// `entry_point` is given, returns the complete range of entry point indices.
114/// If `entry_point` is given but does not exist, returns an error.
115#[cfg(any(hlsl_out, msl_out))]
116fn get_entry_points(
117    module: &crate::ir::Module,
118    entry_point: Option<&(crate::ir::ShaderStage, String)>,
119) -> Result<core::ops::Range<usize>, (crate::ir::ShaderStage, String)> {
120    use alloc::borrow::ToOwned;
121
122    if let Some(&(stage, ref name)) = entry_point {
123        let Some(ep_index) = module
124            .entry_points
125            .iter()
126            .position(|ep| ep.stage == stage && ep.name == *name)
127        else {
128            return Err((stage, name.to_owned()));
129        };
130        Ok(ep_index..ep_index + 1)
131    } else {
132        Ok(0..module.entry_points.len())
133    }
134}
135
136/// Whether we're generating an entry point or a regular function.
137///
138/// Backend languages often require different code for a [`Function`]
139/// depending on whether it represents an [`EntryPoint`] or not.
140/// Backends can pass common code one of these values to select the
141/// right behavior.
142///
143/// These values also carry enough information to find the `Function`
144/// in the [`Module`]: the `Handle` for a regular function, or the
145/// index into [`Module::entry_points`] for an entry point.
146///
147/// [`Function`]: crate::Function
148/// [`EntryPoint`]: crate::EntryPoint
149/// [`Module`]: crate::Module
150/// [`Module::entry_points`]: crate::Module::entry_points
151pub enum FunctionType {
152    /// A regular function.
153    Function(crate::Handle<crate::Function>),
154    /// An [`EntryPoint`], and its index in [`Module::entry_points`].
155    ///
156    /// [`EntryPoint`]: crate::EntryPoint
157    /// [`Module::entry_points`]: crate::Module::entry_points
158    EntryPoint(crate::proc::EntryPointIndex),
159}
160
161impl FunctionType {
162    /// Returns true if the function is an entry point for a compute-like shader.
163    pub fn is_compute_like_entry_point(&self, module: &crate::Module) -> bool {
164        match *self {
165            FunctionType::EntryPoint(index) => {
166                module.entry_points[index as usize].stage.compute_like()
167            }
168            FunctionType::Function(_) => false,
169        }
170    }
171}
172
173/// Helper structure that stores data needed when writing the function
174pub struct FunctionCtx<'a> {
175    /// The current function being written
176    pub ty: FunctionType,
177    /// Analysis about the function
178    pub info: &'a crate::valid::FunctionInfo,
179    /// The expression arena of the current function being written
180    pub expressions: &'a crate::Arena<crate::Expression>,
181    /// Map of expressions that have associated variable names
182    pub named_expressions: &'a crate::NamedExpressions,
183}
184
185impl FunctionCtx<'_> {
186    /// Helper method that resolves a type of a given expression.
187    pub fn resolve_type<'a>(
188        &'a self,
189        handle: crate::Handle<crate::Expression>,
190        types: &'a crate::UniqueArena<crate::Type>,
191    ) -> &'a crate::TypeInner {
192        self.info[handle].ty.inner_with(types)
193    }
194
195    /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a local in the current function
196    pub const fn name_key(
197        &self,
198        local: crate::Handle<crate::LocalVariable>,
199    ) -> crate::proc::NameKey {
200        match self.ty {
201            FunctionType::Function(handle) => crate::proc::NameKey::FunctionLocal(handle, local),
202            FunctionType::EntryPoint(idx) => crate::proc::NameKey::EntryPointLocal(idx, local),
203        }
204    }
205
206    /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for a function argument.
207    ///
208    /// # Panics
209    /// - If the function arguments are less or equal to `arg`
210    pub const fn argument_key(&self, arg: u32) -> crate::proc::NameKey {
211        match self.ty {
212            FunctionType::Function(handle) => crate::proc::NameKey::FunctionArgument(handle, arg),
213            FunctionType::EntryPoint(ep_index) => {
214                crate::proc::NameKey::EntryPointArgument(ep_index, arg)
215            }
216        }
217    }
218
219    /// Helper method that generates a [`NameKey`](crate::proc::NameKey) for an external texture
220    /// function argument.
221    ///
222    /// # Panics
223    /// - If the function arguments are less or equal to `arg`
224    /// - If `self.ty` is not `FunctionType::Function`.
225    pub const fn external_texture_argument_key(
226        &self,
227        arg: u32,
228        external_texture_key: crate::proc::ExternalTextureNameKey,
229    ) -> crate::proc::NameKey {
230        match self.ty {
231            FunctionType::Function(handle) => {
232                crate::proc::NameKey::ExternalTextureFunctionArgument(
233                    handle,
234                    arg,
235                    external_texture_key,
236                )
237            }
238            // This is a const function, which _sometimes_ gets called,
239            // so this lint is _sometimes_ triggered, depending on feature set.
240            #[expect(clippy::allow_attributes)]
241            #[allow(clippy::panic)]
242            FunctionType::EntryPoint(_) => {
243                panic!("External textures cannot be used as arguments to entry points")
244            }
245        }
246    }
247
248    /// Returns true if the given expression points to a fixed-function pipeline input.
249    pub fn is_fixed_function_input(
250        &self,
251        mut expression: crate::Handle<crate::Expression>,
252        module: &crate::Module,
253    ) -> Option<crate::BuiltIn> {
254        let ep_function = match self.ty {
255            FunctionType::Function(_) => return None,
256            FunctionType::EntryPoint(ep_index) => &module.entry_points[ep_index as usize].function,
257        };
258        let mut built_in = None;
259        loop {
260            match self.expressions[expression] {
261                crate::Expression::FunctionArgument(arg_index) => {
262                    return match ep_function.arguments[arg_index as usize].binding {
263                        Some(crate::Binding::BuiltIn(bi)) => Some(bi),
264                        _ => built_in,
265                    };
266                }
267                crate::Expression::AccessIndex { base, index } => {
268                    match *self.resolve_type(base, &module.types) {
269                        crate::TypeInner::Struct { ref members, .. } => {
270                            if let Some(crate::Binding::BuiltIn(bi)) =
271                                members[index as usize].binding
272                            {
273                                built_in = Some(bi);
274                            }
275                        }
276                        _ => return None,
277                    }
278                    expression = base;
279                }
280                _ => return None,
281            }
282        }
283    }
284}
285
286impl crate::Expression {
287    /// Returns the ref count, upon reaching which this expression
288    /// should be considered for baking.
289    ///
290    /// Note: we have to cache any expressions that depend on the control flow,
291    /// or otherwise they may be moved into a non-uniform control flow, accidentally.
292    /// See the [module-level documentation][emit] for details.
293    ///
294    /// [emit]: index.html#expression-evaluation-time
295    pub const fn bake_ref_count(&self) -> usize {
296        match *self {
297            // accesses are never cached, only loads are
298            crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => usize::MAX,
299            // sampling may use the control flow, and image ops look better by themselves
300            crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1,
301            // derivatives use the control flow
302            crate::Expression::Derivative { .. } => 1,
303            // TODO: We need a better fix for named `Load` expressions
304            // More info - https://github.com/gfx-rs/naga/pull/914
305            // And https://github.com/gfx-rs/naga/issues/910
306            crate::Expression::Load { .. } => 1,
307            // cache expressions that are referenced multiple times
308            _ => 2,
309        }
310    }
311}
312
313/// Helper function that returns the string corresponding to the [`BinaryOperator`](crate::BinaryOperator)
314pub const fn binary_operation_str(op: crate::BinaryOperator) -> &'static str {
315    use crate::BinaryOperator as Bo;
316    match op {
317        Bo::Add => "+",
318        Bo::Subtract => "-",
319        Bo::Multiply => "*",
320        Bo::Divide => "/",
321        Bo::Modulo => "%",
322        Bo::Equal => "==",
323        Bo::NotEqual => "!=",
324        Bo::Less => "<",
325        Bo::LessEqual => "<=",
326        Bo::Greater => ">",
327        Bo::GreaterEqual => ">=",
328        Bo::And => "&",
329        Bo::ExclusiveOr => "^",
330        Bo::InclusiveOr => "|",
331        Bo::LogicalAnd => "&&",
332        Bo::LogicalOr => "||",
333        Bo::ShiftLeft => "<<",
334        Bo::ShiftRight => ">>",
335    }
336}
337
338impl crate::TypeInner {
339    /// Returns true if a variable of this type is a handle.
340    pub const fn is_handle(&self) -> bool {
341        match *self {
342            Self::Image { .. } | Self::Sampler { .. } | Self::AccelerationStructure { .. } => true,
343            _ => false,
344        }
345    }
346}
347
348impl crate::Statement {
349    /// Returns true if the statement directly terminates the current block.
350    ///
351    /// Used to decide whether case blocks require a explicit `break`.
352    pub const fn is_terminator(&self) -> bool {
353        match *self {
354            crate::Statement::Break
355            | crate::Statement::Continue
356            | crate::Statement::Return { .. }
357            | crate::Statement::Kill => true,
358            _ => false,
359        }
360    }
361}
362
363bitflags::bitflags! {
364    /// Ray flags, for a [`RayDesc`]'s `flags` field.
365    ///
366    /// Note that these exactly correspond to the SPIR-V "Ray Flags" mask, and
367    /// the SPIR-V backend passes them directly through to the
368    /// [`OpRayQueryInitializeKHR`][op] instruction. (We have to choose something, so
369    /// we might as well make one back end's life easier.)
370    ///
371    /// [`RayDesc`]: crate::Module::generate_ray_desc_type
372    /// [op]: https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpRayQueryInitializeKHR
373    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
374    pub struct RayFlag: u32 {
375        const OPAQUE = 0x01;
376        const NO_OPAQUE = 0x02;
377        const TERMINATE_ON_FIRST_HIT = 0x04;
378        const SKIP_CLOSEST_HIT_SHADER = 0x08;
379        const CULL_BACK_FACING = 0x10;
380        const CULL_FRONT_FACING = 0x20;
381        const CULL_OPAQUE = 0x40;
382        const CULL_NO_OPAQUE = 0x80;
383        const SKIP_TRIANGLES = 0x100;
384        const SKIP_AABBS = 0x200;
385    }
386}
387
388/// The intersection test to use for ray queries.
389#[repr(u32)]
390pub enum RayIntersectionType {
391    Triangle = 1,
392    BoundingBox = 4,
393}