vulkane_kernel_text/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The shared text walker for Vulkane's kernel emitters (ROADMAP rows 8a, 8b and 8g for GLSL and WGSL).
3//!
4//! [`lower_kernel`] takes an Unpopped kernel-layer [`KernelFn`] and a
5//! [`Dialect`] and writes shader source. The walk (scope checks, statements, control flow, the
6//! structure of a `For`) is written once; a dialect supplies only the spellings that differ between
7//! GLSL and WGSL: declarations, the entry point, literals, operators, barriers.
8//!
9//! ## What it lowers (v1)
10//!
11//! Integer kernels (`I32`/`U32`): buffer parameters, static `Shared` arrays, locals, `Let`, `Load`,
12//! `Assign`, `Store`, `Barrier` and `Fence`, `If`, `For`, `While`, `Break`, `Continue`, `Return`, and
13//! the expressions `Local`, `ConstInt`, `Exec` (thread, block, `BlockDim`, `GridDim`), `Add`, `Sub`,
14//! `Mul`, the comparisons, `BitAnd`/`BitOr`/`BitXor`, `Shl`/`Shr` (the count masked to the width, as
15//! the SPIR-V emitter does) and `Select`. Anything else is a typed
16//! [`UnsupportedKernel`](unpopped::backend::LowerError::UnsupportedKernel) naming it.
17//!
18//! ## Semantics shared with the SPIR-V emitter
19//!
20//! A comparison gives `1` or `0` in the compute dtype. A `For` evaluates its bounds once; a zero step
21//! leaves the loop at once (a shader cannot trap). A barrier under thread-divergent control is refused
22//! by `check_kernel` (`BarrierDivergent`) before any text is written.
23//!
24//! ## Refused by name
25//!
26//! The twelve NVIDIA-only statements of board 434 C and its extension (`CopyAsync`, `Collective`,
27//! `MbarInit`, `WgmmaWait`, ...) are refused by name, at any nesting depth, before the walk starts.
28
29mod decline;
30mod dialect;
31mod expr;
32mod scope;
33mod stmt;
34
35pub use decline::{DECLINED_434C, DECLINED_434C_EXT, declined_by_name};
36pub use dialect::{BIT_OPS, COMPARISONS, Decl, Dialect, Layout, operator};
37
38use unpopped::backend::{GeneratedKernel, LowerError};
39use unpopped::kernel::KernelFn;
40
41/// Lower `kernel` to source in `dialect`, or say why it cannot.
42///
43/// # Errors
44///
45/// [`LowerError::UnsupportedKernel`] naming what is not lowered, with the by-name patent refusal
46/// first.
47pub fn lower_kernel(
48 dialect: &dyn Dialect,
49 kernel: &KernelFn,
50) -> Result<GeneratedKernel, LowerError> {
51 if let Some(e) = declined_by_name(dialect.name(), kernel) {
52 return Err(e);
53 }
54 let sc = scope::check(dialect, kernel)?;
55 // The body first: a rounding conversion in it adds a declaration to the prologue.
56 let mut body = String::new();
57 stmt::emit_body(dialect, kernel, &sc, &mut body)?;
58 let mut out = dialect.prologue(&sc.layout(kernel));
59 out.push_str(&body);
60 out.push_str(dialect.epilogue());
61 Ok(GeneratedKernel::new(kernel.name.clone(), out))
62}