Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

build foundation

eugeneb314322de7b4
diff --git a/Cargo.lock b/Cargo.lock
index 124f48c68..41db1266c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10031,6 +10031,7 @@ dependencies = [
"shader-slang",
"shader-slang-sys",
"shoji",
+ "spirv",
"syn 3.0.9",
"tempfile",
"test-tag",
diff --git a/Cargo.toml b/Cargo.toml
index 44b69ff56..d07723f82 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -113,6 +113,7 @@ clang-ast = "0.1.35"
shader-slang = { git = "https://github.com/trymirai/slang-rs.git", branch = "unsigned_char_fix" }
shader-slang-sys = { git = "https://github.com/trymirai/slang-rs.git", branch = "unsigned_char_fix" }
naga = { git = "https://github.com/gfx-rs/wgpu", branch = "v30" }
+spirv = "0.4.0"
rangemap = "1.8.0"
parking_lot = "0.12.5"
futures = "0.3.34"
diff --git a/crates/uzu-engine/Cargo.toml b/crates/uzu-engine/Cargo.toml
index 54a229daf..ed3ae27eb 100644
--- a/crates/uzu-engine/Cargo.toml
+++ b/crates/uzu-engine/Cargo.toml
@@ -39,6 +39,16 @@ webgpu = [
"dep:wgpu",
]
+vulkan = [
+ "cpu",
+ "dep:shader-slang",
+ "dep:blake3",
+ "dep:serde_json",
+ "dep:regex",
+ "dep:rayon",
+ "dep:spirv",
+]
+
cpu = [] # TODO: move libm here
[build-dependencies]
@@ -56,6 +66,7 @@ shader-slang = { workspace = true, optional = true }
shader-slang-sys = { workspace = true, optional = true }
regex = { workspace = true, optional = true }
naga = { workspace = true, optional = true, features = ["wgsl-in"] }
+spirv = { workspace = true, optional = true }
blake3 = { workspace = true, optional = true }
serde_json = { workspace = true, features = ["unbounded_depth"], optional = true }
rayon = { workspace = true, optional = true }
diff --git a/crates/uzu-engine/build/common/caching.rs b/crates/uzu-engine/build/common/caching.rs
index 46f70e5bc..8702a41b3 100644
--- a/crates/uzu-engine/build/common/caching.rs
+++ b/crates/uzu-engine/build/common/caching.rs
@@ -1,4 +1,4 @@
-#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu"))]
+#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu", feature = "vulkan"))]
use std::{
fs,
diff --git a/crates/uzu-engine/build/common/expr_rewrite.rs b/crates/uzu-engine/build/common/expr_rewrite.rs
index 1d16a69f4..8ca024c0f 100644
--- a/crates/uzu-engine/build/common/expr_rewrite.rs
+++ b/crates/uzu-engine/build/common/expr_rewrite.rs
@@ -1,8 +1,10 @@
use syn::{
- Expr, ExprPath, LitInt, Path,
+ Expr, ExprPath, LitInt, Path, parse_quote,
visit_mut::{self, VisitMut},
};
+use crate::common::gpu_type_paths::GpuTypePaths;
+
pub fn rewrite_paths_with<F>(
expr: &mut Expr,
rewriter: F,
@@ -15,6 +17,20 @@ pub fn rewrite_paths_with<F>(
.visit_expr_mut(expr);
}
+pub fn qualify_enum_path(
+ path: &Path,
+ gpu_type_paths: &GpuTypePaths,
+) -> Option<Expr> {
+ if path.segments.len() < 2 {
+ return None;
+ }
+ let head = path.segments.first()?;
+ let full_path_text = gpu_type_paths.full_path_for(&head.ident.to_string())?;
+ let prefix: Path = syn::parse_str(full_path_text).ok()?;
+ let suffix: Vec<_> = path.segments.iter().skip(1).cloned().collect();
+ Some(parse_quote! { #prefix #( :: #suffix )* })
+}
+
struct Walker<F: FnMut(&Path) -> Option<Expr>> {
rewriter: F,
}
diff --git a/crates/uzu-engine/build/common/gpu_type_paths.rs b/crates/uzu-engine/build/common/gpu_type_paths.rs
index 0bd5123bc..0f10c4cfb 100644
--- a/crates/uzu-engine/build/common/gpu_type_paths.rs
+++ b/crates/uzu-engine/build/common/gpu_type_paths.rs
@@ -62,6 +62,11 @@ impl GpuTypePaths {
Ok(())
}
+ #[cfg_attr(not(any(feature = "webgpu", feature = "vulkan")), allow(dead_code))]
+ pub fn entries(&self) -> impl Iterator<Item = (&str, &str)> {
+ self.short_name_to_entry.iter().map(|(name, entry)| (&**name, &*entry.path))
+ }
+
pub fn full_path_for(
&self,
short_name: &str,
diff --git a/crates/uzu-engine/build/common/gpu_types/mod.rs b/crates/uzu-engine/build/common/gpu_types/mod.rs
index 22c1a5a5e..7d2e7cff4 100644
--- a/crates/uzu-engine/build/common/gpu_types/mod.rs
+++ b/crates/uzu-engine/build/common/gpu_types/mod.rs
@@ -8,7 +8,8 @@ use std::{
use anyhow::Context;
use derive_more::{AsRef, Deref, Display, From};
use syn::{Attribute, Ident, Item};
-use walkdir::WalkDir;
+
+use crate::common::sources::source_files;
mod item_constant;
mod item_enum;
@@ -101,14 +102,8 @@ impl GpuTypes {
.join(format!("src/backends/{backend}/gpu_types"));
println!("cargo::rerun-if-changed={}", src_dir.display());
- let mut sources: Vec<PathBuf> = WalkDir::new(&src_dir)
- .into_iter()
- .filter_map(|e| e.ok())
- .filter_map(|e| e.file_type().is_file().then(|| e.into_path()))
- .filter(|e| e.extension().and_then(|s| s.to_str()) == Some("rs") && e.file_stem() != Some("mod".as_ref()))
- .collect();
-
- sources.sort();
+ let sources: Vec<PathBuf> =
+ source_files(&src_dir, "rs")?.into_iter().filter(|e| e.file_stem() != Some("mod".as_ref())).collect();
Ok(Self {
module_path: format!("crate::backends::{backend}::gpu_types").into(),
diff --git a/crates/uzu-engine/build/common/mangling.rs b/crates/uzu-engine/build/common/mangling.rs
index 4c4303650..5afb4577e 100644
--- a/crates/uzu-engine/build/common/mangling.rs
+++ b/crates/uzu-engine/build/common/mangling.rs
@@ -1,4 +1,4 @@
-#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu"))]
+#![cfg(any(all(feature = "metal", target_os = "macos"), feature = "webgpu", feature = "vulkan"))]
#[cfg(all(feature = "metal", target_os = "macos"))]
use std::iter::repeat_n;
diff --git a/crates/uzu-engine/build/common/mod.rs b/crates/uzu-engine/build/common/mod.rs
index 9ad50233d..1d49fdba2 100644
--- a/crates/uzu-engine/build/common/mod.rs
+++ b/crates/uzu-engine/build/common/mod.rs
@@ -3,7 +3,7 @@ pub mod codegen;
pub mod compiler;
pub mod constraints;
pub mod envs;
-#[cfg(all(feature = "metal", target_os = "macos"))]
+#[cfg(any(all(feature = "metal", target_os = "macos"), feature = "vulkan"))]
pub mod expr_rewrite;
pub mod gpu_type_paths;
pub mod gpu_types;
@@ -11,4 +11,5 @@ pub mod identifiers;
pub mod kernel;
pub mod logging;
pub mod mangling;
+pub mod sources;
pub mod traitgen;
diff --git a/crates/uzu-engine/build/common/sources.rs b/crates/uzu-engine/build/common/sources.rs
new file mode 100644
index 000000000..af35b0581
--- /dev/null
+++ b/crates/uzu-engine/build/common/sources.rs
@@ -0,0 +1,20 @@
+use std::path::{Path, PathBuf};
+
+use anyhow::Context;
+use walkdir::WalkDir;
+
+pub fn source_files(
+ directory: &Path,
+ extension: &str,
+) -> anyhow::Result<Vec<PathBuf>> {
+ anyhow::ensure!(directory.is_dir(), "source directory {} does not exist", directory.display());
+ let mut files = Vec::new();
+ for entry in WalkDir::new(directory) {
+ let entry = entry.with_context(|| format!("cannot walk {}", directory.display()))?;
+ if entry.file_type().is_file() && entry.path().extension().is_some_and(|found| found == extension) {
+ files.push(entry.into_path());
+ }
+ }
+ files.sort();
+ Ok(files)
+}
diff --git a/crates/uzu-engine/build/cpu/compiler.rs b/crates/uzu-engine/build/cpu/compiler.rs
index 23fbdc879..17591442e 100644
--- a/crates/uzu-engine/build/cpu/compiler.rs
+++ b/crates/uzu-engine/build/cpu/compiler.rs
@@ -8,7 +8,6 @@ use syn::{
Expr, FnArg, GenericArgument, GenericParam, Ident, Item, ItemFn, PathArguments, Type, punctuated::Punctuated,
token::Comma, visit_mut::VisitMut,
};
-use walkdir::WalkDir;
use crate::common::{
codegen::write_tokens,
@@ -18,6 +17,7 @@ use crate::common::{
gpu_types::GpuTypes,
identifiers::{ArgumentName, KernelName, KernelPath},
kernel::{Kernel, KernelArgument, KernelArgumentType, KernelBufferAccess, KernelParameter, KernelParameterType},
+ sources::source_files,
};
#[derive(PartialEq, Debug)]
@@ -668,13 +668,9 @@ impl Compiler for CpuCompiler {
_gpu_types: &GpuTypes,
gpu_type_paths: &GpuTypePaths,
) -> anyhow::Result<HashMap<KernelPath, Box<[Kernel]>>> {
- let objects = WalkDir::new(&self.src_dir)
+ let objects = source_files(&self.src_dir, "rs")?
.into_iter()
- .filter_map(|entry| entry.ok())
- .filter(|entry| {
- entry.file_type().is_file() && entry.path().extension().and_then(|s| s.to_str()) == Some("rs")
- })
- .map(|entry| self.compile(entry.into_path(), gpu_type_paths))
+ .map(|path| self.compile(path, gpu_type_paths))
.collect::<anyhow::Result<Vec<(KernelPath, Box<[Kernel]>)>>>()
.context("cannot compile cpu sources")?;
diff --git a/crates/uzu-engine/build/main.rs b/crates/uzu-engine/build/main.rs
index b6ed7f2da..68f5649bc 100644
--- a/crates/uzu-engine/build/main.rs
+++ b/crates/uzu-engine/build/main.rs
@@ -8,12 +8,15 @@ use common::{compiler::Compiler, envs, gpu_type_paths::GpuTypePaths, gpu_types::
#[cfg(all(feature = "metal", target_os = "macos"))]
mod metal;
-#[cfg(feature = "webgpu")]
+#[cfg(any(feature = "webgpu", feature = "vulkan"))]
mod slang;
#[cfg(feature = "webgpu")]
mod webgpu;
+#[cfg(feature = "vulkan")]
+mod vulkan;
+
mod cpu;
fn main() -> anyhow::Result<ExitCode> {
@@ -25,7 +28,7 @@ fn main() -> anyhow::Result<ExitCode> {
let target_os = env::var("CARGO_CFG_TARGET_OS")?;
- println!("cargo::rustc-check-cfg=cfg(backend, values(\"metal\", \"webgpu\", \"cpu\"))");
+ println!("cargo::rustc-check-cfg=cfg(backend, values(\"metal\", \"webgpu\", \"vulkan\", \"cpu\"))");
let backend_metal = cfg!(feature = "metal") && matches!(target_os.as_ref(), "macos" | "ios" | "tvos" | "visionos");
if backend_metal {
@@ -37,6 +40,11 @@ fn main() -> anyhow::Result<ExitCode> {
println!("cargo::rustc-cfg=backend=\"webgpu\"");
}
+ let backend_vulkan = cfg!(feature = "vulkan");
+ if backend_vulkan {
+ println!("cargo::rustc-cfg=backend=\"vulkan\"");
+ }
+
let backend_cpu = cfg!(feature = "cpu");
if backend_cpu {
println!("cargo::rustc-cfg=backend=\"cpu\"");
@@ -70,6 +78,11 @@ fn main() -> anyhow::Result<ExitCode> {
compilers.push(Box::new(slang::SlangCompiler::<webgpu::WebGPU>::new()?));
}
+ #[cfg(feature = "vulkan")]
+ if backend_vulkan {
+ compilers.push(Box::new(slang::SlangCompiler::<vulkan::VulkanTarget>::new()?));
+ }
+
if backend_cpu {
compilers.push(Box::new(cpu::CpuCompiler::new()?));
}
diff --git a/crates/uzu-engine/build/metal/bindgen/host_expression_rewriter.rs b/crates/uzu-engine/build/metal/bindgen/host_expression_rewriter.rs
index 15fca0a52..33acadb54 100644
--- a/crates/uzu-engine/build/metal/bindgen/host_expression_rewriter.rs
+++ b/crates/uzu-engine/build/metal/bindgen/host_expression_rewriter.rs
@@ -6,8 +6,11 @@ use quote::{format_ident, quote};
use syn::Expr;
use crate::{
- common::{expr_rewrite::rewrite_paths_with, gpu_type_paths::GpuTypePaths},
- metal::{bindgen::variants::VariantBind, enum_path_rewrite::qualify_enum_path},
+ common::{
+ expr_rewrite::{qualify_enum_path, rewrite_paths_with},
+ gpu_type_paths::GpuTypePaths,
+ },
+ metal::bindgen::variants::VariantBind,
};
pub struct HostExpressionRewriter<'context> {
diff --git a/crates/uzu-engine/build/metal/compiler.rs b/crates/uzu-engine/build/metal/compiler.rs
index 2abca4dea..9ab012a5c 100644
--- a/crates/uzu-engine/build/metal/compiler.rs
+++ b/crates/uzu-engine/build/metal/compiler.rs
@@ -9,7 +9,6 @@ use itertools::{Itertools, izip};
use quote::{format_ident, quote};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
-use walkdir::WalkDir;
use xxhash_rust::xxh3::xxh3_64;
use super::{
@@ -20,7 +19,7 @@ use super::{
use crate::{
common::{
caching, codegen::write_tokens, compiler::Compiler, gpu_type_paths::GpuTypePaths, gpu_types::GpuTypes,
- identifiers::KernelPath, kernel::Kernel,
+ identifiers::KernelPath, kernel::Kernel, sources::source_files,
},
debug_log,
metal::{compression, gpu_types::gpu_type_gen},
@@ -322,12 +321,7 @@ impl Compiler for MetalCompiler {
hasher.finalize().into()
};
- let metal_sources: Vec<PathBuf> = WalkDir::new(&self.source_directory)
- .into_iter()
- .filter_map(|e| e.ok())
- .filter(|e| e.file_type().is_file() && e.path().extension().and_then(|s| s.to_str()) == Some("metal"))
- .map(|e| e.into_path())
- .collect();
+ let metal_sources: Vec<PathBuf> = source_files(&self.source_directory, "metal")?;
let compiled: Vec<(KernelPath, Box<[Kernel]>, bool)> = metal_sources
.into_par_iter()
diff --git a/crates/uzu-engine/build/metal/enum_path_rewrite.rs b/crates/uzu-engine/build/metal/enum_path_rewrite.rs
index 2a708378a..368950292 100644
--- a/crates/uzu-engine/build/metal/enum_path_rewrite.rs
+++ b/crates/uzu-engine/build/metal/enum_path_rewrite.rs
@@ -1,10 +1,10 @@
use anyhow::Context;
use proc_macro2::TokenStream;
use quote::ToTokens;
-use syn::{Expr, Path, parse_quote};
+use syn::Expr;
use crate::common::{
- expr_rewrite::rewrite_paths_with,
+ expr_rewrite::{qualify_enum_path, rewrite_paths_with},
gpu_type_paths::{GpuTypeKind, GpuTypePaths},
};
@@ -34,17 +34,3 @@ pub fn rewrite_for_rust(
rewrite_paths_with(&mut parsed, |path| qualify_enum_path(path, gpu_type_paths));
Ok(parsed.into_token_stream())
}
-
-pub(super) fn qualify_enum_path(
- path: &Path,
- gpu_type_paths: &GpuTypePaths,
-) -> Option<Expr> {
- if path.segments.len() < 2 {
- return None;
- }
- let head = path.segments.first()?;
- let full_path_text = gpu_type_paths.full_path_for(&head.ident.to_string())?;
- let prefix: Path = syn::parse_str(full_path_text).ok()?;
- let suffix: Vec<_> = path.segments.iter().skip(1).cloned().collect();
- Some(parse_quote! { #prefix #( :: #suffix )* })
-}
diff --git a/crates/uzu-engine/build/slang/axis_expression.rs b/crates/uzu-engine/build/slang/axis_expression.rs
new file mode 100644
index 000000000..e26b65c38
--- /dev/null
+++ b/crates/uzu-engine/build/slang/axis_expression.rs
@@ -0,0 +1,68 @@
+use crate::slang::{SlangArgumentType, SlangKernel};
+
+pub fn slang_axis_expr(
+ expr: &str,
+ kernel: &SlangKernel,
+) -> String {
+ let expr = rewrite_slang_method(expr, "unwrap_or", |receiver, fallback| {
+ let condition = kernel
+ .arguments
+ .iter()
+ .find_map(|argument| {
+ if argument.name != receiver {
+ return None;
+ }
+ match &argument.argument_type {
+ SlangArgumentType::Uniform {
+ condition,
+ } => condition.as_deref(),
+ _ => None,
+ }
+ })
+ .expect("unwrap_or receiver must be an optional constant");
+ format!("(({condition}) ? ({receiver}) : ({fallback}))")
+ });
+ let expr = rewrite_slang_method(&expr, "div_ceil", |receiver, argument| {
+ format!("(({receiver}) / ({argument}) + uint(({receiver}) % ({argument}) != 0))")
+ });
+ let expr =
+ rewrite_slang_method(&expr, "saturating_mul", |receiver, argument| format!("(({receiver}) * ({argument}))"));
+
+ rewrite_slang_method(&expr, "saturating_sub", |receiver, argument| {
+ format!("(({receiver}) > ({argument}) ? ({receiver}) - ({argument}) : 0)")
+ })
+}
+
+fn rewrite_slang_method(
+ expr: &str,
+ method: &str,
+ rewrite: impl Fn(&str, &str) -> String,
+) -> String {
+ let pattern = format!(".{method}(");
+ let Some(dot) = expr.find(&pattern) else {
+ return expr.to_string();
+ };
+
+ let receiver_start = expr[..dot].rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).map_or(0, |idx| idx + 1);
+ let argument_start = dot + pattern.len();
+ let mut depth = 1;
+ let mut argument_end = argument_start;
+ for (offset, ch) in expr[argument_start..].char_indices() {
+ match ch {
+ '(' => depth += 1,
+ ')' => {
+ depth -= 1;
+ if depth == 0 {
+ argument_end = argument_start + offset;
+ break;
+ }
+ },
+ _ => (),
+ }
+ }
+
+ let receiver = &expr[receiver_start..dot];
+ let argument = &expr[argument_start..argument_end];
+ let rewritten = rewrite(receiver, argument);
+ format!("{}{}{}", &expr[..receiver_start], rewritten, &expr[argument_end + 1..])
+}
diff --git a/crates/uzu-engine/build/slang/compiler.rs b/crates/uzu-engine/build/slang/compiler.rs
index 3840cf773..02b9d63c4 100644
--- a/crates/uzu-engine/build/slang/compiler.rs
+++ b/crates/uzu-engine/build/slang/compiler.rs
@@ -1,22 +1,22 @@
-use std::{
- collections::HashMap,
- fs,
- path::PathBuf,
- sync::{Arc, Mutex},
-};
+use std::{collections::HashMap, fs, iter::once, path::PathBuf, sync::Mutex};
use anyhow::Context;
use rayon::prelude::*;
-use walkdir::WalkDir;
use crate::{
common::{
- codegen::write_tokens, compiler::Compiler, gpu_type_paths::GpuTypePaths, gpu_types::GpuTypes,
- identifiers::KernelPath, kernel::Kernel,
+ codegen::write_tokens,
+ compiler::Compiler,
+ gpu_type_paths::GpuTypePaths,
+ gpu_types::GpuTypes,
+ identifiers::{KernelName, KernelPath},
+ kernel::Kernel,
+ sources::source_files,
},
slang::{
+ SlangGpuTypes,
compiler_internal::{BlockingSlangCompiler, SlangCompilerFields, SlangTarget},
- gpu_types::gpu_type_gen,
+ gpu_type_gen,
},
};
@@ -64,50 +64,54 @@ impl<T: SlangTarget> Compiler for SlangCompiler<T> {
gpu_types: &GpuTypes,
gpu_type_paths: &GpuTypePaths,
) -> anyhow::Result<HashMap<KernelPath, Box<[Kernel]>>> {
- let gpu_type_map = Arc::new(
- gpu_type_gen(&self.fields.source_directory.join("generated"), gpu_types)
- .context("cannot generate shared gpu types")?,
- );
+ let private_gpu_types =
+ T::PRIVATE_GPU_TYPES.map(GpuTypes::scan).transpose().context("cannot scan private gpu types")?;
+ let mut paths = gpu_type_paths.clone();
+ if let Some(private_gpu_types) = &private_gpu_types {
+ paths.extend(private_gpu_types).context("cannot extend gpu type paths")?;
+ }
+ let definitions = once(gpu_types).chain(&private_gpu_types).collect::<Vec<_>>();
+ gpu_type_gen(&self.fields.source_directory.join("generated"), &definitions)
+ .context("cannot generate shared gpu types")?;
+ let gpu_types = SlangGpuTypes {
+ paths,
+ definitions,
+ };
- let slang_sources: Vec<PathBuf> = WalkDir::new(&self.fields.source_directory)
- .into_iter()
- .filter_map(|res| res.ok())
- .filter(|entry| {
- entry.path().is_file()
- && entry.path().extension().and_then(|s| s.to_str()) == Some("slang")
- && fs::read(entry.path()).map(|p| !p.starts_with(b"implementing")).unwrap_or(true)
- })
- .map(|e| e.into_path())
- .collect();
+ let mut slang_sources: Vec<PathBuf> = Vec::new();
+ for path in source_files(&self.fields.source_directory, "slang")? {
+ let contents = fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?;
+ if !contents.starts_with(b"implementing") {
+ slang_sources.push(path);
+ }
+ }
let kernels = slang_sources
.into_par_iter()
.map(|path| {
- self.with_blocking_compiler(|compiler| {
- compiler.compile(path.clone(), gpu_type_map.clone(), gpu_type_paths)
- })
- .with_context(|| format!("cannot compile {}", path.display()))
+ self.with_blocking_compiler(|compiler| compiler.compile(path.clone(), &gpu_types))
+ .with_context(|| format!("cannot compile {}", path.display()))
})
- .collect::<anyhow::Result<HashMap<Box<[Box<str>]>, Box<[Kernel]>>>>()?;
+ .collect::<anyhow::Result<Vec<(Box<[Box<str>]>, Box<[Kernel]>, Box<[KernelName]>)>>>()?;
let mut kernels_bindgen = kernels
.iter()
- .filter(|(_segments, kernels)| !kernels.is_empty())
- .map(|(segments, kernels)| {
- (self.fields.output_directory.join(segments.join("/")).with_extension("rs"), kernels.as_ref())
+ .filter(|(_segments, public, private)| !public.is_empty() || !private.is_empty())
+ .map(|(segments, public, private)| {
+ (self.fields.output_directory.join(segments.join("/")), public.as_ref(), private.as_ref())
})
- .collect::<Vec<(PathBuf, &[Kernel])>>();
+ .collect::<Vec<(PathBuf, &[Kernel], &[KernelName])>>();
- kernels_bindgen.sort_by(|(a_path, _a_kernels), (b_path, _b_kernels)| a_path.cmp(b_path));
+ kernels_bindgen.sort_by(|(a_path, ..), (b_path, ..)| a_path.cmp(b_path));
- let bindgen_tokens = T::bindgen_global(&kernels_bindgen).context("cannot bindgen global")?;
+ let bindgen_tokens = T::bindgen_global(&self.fields, &kernels_bindgen).context("cannot bindgen global")?;
write_tokens(bindgen_tokens, self.fields.output_directory.with_extension("rs"))
.context("cannot write global bindgen file")?;
Ok(kernels
.into_iter()
- .filter(|(_, kernels)| !kernels.is_empty())
- .map(|(segments, kernels)| (segments.iter().map(|segment| segment.to_string()).collect(), kernels))
+ .filter(|(_, kernels, _)| !kernels.is_empty())
+ .map(|(segments, kernels, _)| (segments.iter().map(|segment| segment.to_string()).collect(), kernels))
.collect())
}
}
diff --git a/crates/uzu-engine/build/slang/compiler_internal.rs b/crates/uzu-engine/build/slang/compiler_internal.rs
index 0f03ee17f..b16515bbe 100644
--- a/crates/uzu-engine/build/slang/compiler_internal.rs
+++ b/crates/uzu-engine/build/slang/compiler_internal.rs
@@ -6,41 +6,63 @@ use std::{
iter::once,
marker::PhantomData,
path::{Path, PathBuf},
- sync::Arc,
};
use anyhow::Context;
-use itertools::Itertools;
use proc_macro2::TokenStream;
use serde::{Deserialize, Serialize};
use shader_slang::{
- CompilerOptions, ComponentType, GlobalSession, ModifierID, OptimizationLevel, Session, SessionDesc, TargetDesc,
+ CompilerOptions, ComponentType, GlobalSession, Module, OptimizationLevel, Session, SessionDesc, TargetDesc,
};
use crate::{
- common::{caching, codegen::write_tokens, gpu_type_paths::GpuTypePaths, kernel::Kernel},
+ common::{caching, identifiers::KernelName, kernel::Kernel},
debug_log,
- slang::{reflection::SlangKernel, slang_sys_ext::SessionLoadModuleWithDiagnosticsExt, wrapper},
+ slang::{SlangGpuTypes, reflection::SlangKernel, slang_sys_ext::SessionLoadModuleWithDiagnosticsExt},
};
pub trait SlangTarget: Send + Sync + Clone + 'static {
const TARGET_NAME: &'static str;
- const OUTPUT_EXTENSION: &'static str;
+ const SOURCE_DIRECTORY: &'static str;
+ const PRIVATE_GPU_TYPES: Option<&'static str> = None;
+ const SESSION_DEFINES: &'static [&'static [(&'static str, &'static str)]] = &[&[]];
+
+ fn compiler_options(
+ _global_session: &GlobalSession,
+ options: CompilerOptions,
+ ) -> CompilerOptions {
+ options
+ }
fn create_target_desc<'a>(global_session: &'a GlobalSession) -> TargetDesc<'a>;
- fn validate_output(path: &Path) -> anyhow::Result<()>;
+ fn specialization_type(slang_type: &str) -> &str;
+
+ fn axis_guard(axes: &[(String, String)]) -> (String, Vec<String>);
+
+ fn entry_point_prologue(entry_point: &str) -> String;
- fn bindgen_file(
- linked_component: &ComponentType,
+ fn wrapper(
+ fields: &SlangCompilerFields<Self>,
+ source_path: &Path,
+ module: &Module,
kernels: &[SlangKernel],
- gpu_type_map: &HashMap<String, String>,
- gpu_type_paths: &GpuTypePaths,
- constants: &HashMap<String, String>,
- object_file: &Path,
- ) -> anyhow::Result<TokenStream>;
+ ) -> anyhow::Result<String>;
- fn bindgen_global(kernels: &[(impl AsRef<Path>, &[Kernel])]) -> anyhow::Result<TokenStream>;
+ fn emit(
+ compiler: &BlockingSlangCompiler<Self>,
+ gpu_types: &SlangGpuTypes,
+ module: &Module,
+ kernels: &[SlangKernel],
+ descriptors: &[Kernel],
+ linked: &ComponentType,
+ output_base: &Path,
+ ) -> anyhow::Result<()>;
+
+ fn bindgen_global(
+ fields: &SlangCompilerFields<Self>,
+ modules: &[(PathBuf, &[Kernel], &[KernelName])],
+ ) -> anyhow::Result<TokenStream>;
}
#[derive(Clone)]
@@ -48,27 +70,36 @@ pub struct SlangCompilerFields<T: SlangTarget> {
pub source_directory: PathBuf,
pub output_directory: PathBuf,
pub optimization_level: OptimizationLevel,
+ pub buildsystem_hash: [u8; blake3::OUT_LEN],
_phantom: PhantomData<T>,
}
impl<T: SlangTarget> SlangCompilerFields<T> {
pub fn new() -> anyhow::Result<Self> {
let source_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?)
- .join("src/backends/slang/kernel");
+ .join(T::SOURCE_DIRECTORY);
println!("cargo::rerun-if-changed={}", source_directory.display());
let output_directory = PathBuf::from(env::var("OUT_DIR").context("missing OUT_DIR")?).join(T::TARGET_NAME);
- let optimization_level = match env::var("OPT_LEVEL").context("missing OPT_LEVEL")?.as_str() {
+ let opt_level = env::var("OPT_LEVEL").context("missing OPT_LEVEL")?;
+ let optimization_level = match opt_level.as_str() {
"0" => OptimizationLevel::Default,
_ => OptimizationLevel::High,
};
+ let buildsystem_hash = *blake3::Hasher::new()
+ .update(caching::build_system_hash().context("cannot get build system hash")?.as_bytes())
+ .update(opt_level.as_bytes())
+ .finalize()
+ .as_bytes();
+
Ok(Self {
source_directory,
output_directory,
optimization_level,
+ buildsystem_hash,
_phantom: PhantomData,
})
}
@@ -80,10 +111,11 @@ struct Cached {
compiler_version: String,
dependency_hashes: HashMap<String, [u8; blake3::OUT_LEN]>,
public_kernels: Box<[Kernel]>,
+ private_kernels: Box<[KernelName]>,
}
pub struct BlockingSlangCompiler<T: SlangTarget> {
- session: Session,
+ sessions: Vec<Session>,
global_session: GlobalSession,
fields: SlangCompilerFields<T>,
}
@@ -94,36 +126,75 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
pub fn new(fields: SlangCompilerFields<T>) -> anyhow::Result<Self> {
let global_session = GlobalSession::new().context("cannot create global session")?;
- let compiler_options = CompilerOptions::default()
- .optimization(fields.optimization_level)
- .emit_spirv_directly(true)
- .vulkan_use_entry_point_name(true);
+ let search_path_strings = [CString::new(fields.source_directory.to_string_lossy().as_bytes())
+ .context("cannot convert search path to CString")?];
+ let search_paths = search_path_strings.iter().map(|path| path.as_ptr()).collect::<Vec<_>>();
- let search_path = CString::new(fields.source_directory.to_string_lossy().as_bytes())
- .context("cannot convert src_dir to CString")?;
- let search_paths = [search_path.as_ptr()];
+ let sessions = T::SESSION_DEFINES
+ .iter()
+ .map(|defines| {
+ let compiler_options = CompilerOptions::default().optimization(fields.optimization_level);
+ let compiler_options = defines
+ .iter()
+ .fold(T::compiler_options(&global_session, compiler_options), |compiler_options, (name, value)| {
+ compiler_options.macro_define(name, value)
+ });
- let target_desc = T::create_target_desc(&global_session);
- let targets = [target_desc];
+ let targets = [T::create_target_desc(&global_session)];
- let session_desc =
- SessionDesc::default().options(&compiler_options).search_paths(&search_paths).targets(&targets);
+ let session_desc =
+ SessionDesc::default().options(&compiler_options).search_paths(&search_paths).targets(&targets);
- let session = global_session.create_session(&session_desc).context("cannot create session")?;
+ global_session.create_session(&session_desc).context("cannot create session")
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
Ok(Self {
- session,
+ sessions,
global_session,
fields,
})
}
+ pub fn link(
+ &self,
+ session: usize,
+ path: &Path,
+ ) -> anyhow::Result<ComponentType> {
+ let session = &self.sessions[session];
+ let (wrapper_module, wrapper_diagnostics) =
+ session.load_module_with_diagnostics(path).context("cannot load wrapper module")?;
+
+ for wrapper_diagnostics_line in wrapper_diagnostics.iter().flat_map(|diagnostics| diagnostics.lines()) {
+ println!("cargo::warning={wrapper_diagnostics_line}");
+ }
+
+ let entry_points = wrapper_module.entry_points().map(ComponentType::from).collect::<Vec<_>>();
+
+ let composite_component = session
+ .create_composite_component_type(&once(wrapper_module.into()).chain(entry_points).collect::<Vec<_>>())
+ .context("cannot create composite component")?;
+
+ composite_component.link().context("cannot link wrapper module")
+ }
+
+ fn rerun_if_changed<'a>(
+ &self,
+ dependencies: impl IntoIterator<Item = &'a String>,
+ ) {
+ for dependency in dependencies {
+ let path = Path::new(dependency);
+ if !path.starts_with(&self.fields.source_directory) && !path.starts_with(&self.fields.output_directory) {
+ println!("cargo::rerun-if-changed={dependency}");
+ }
+ }
+ }
+
pub fn compile(
&self,
source_path: PathBuf,
- gpu_type_map: Arc<HashMap<String, String>>,
- gpu_type_paths: &GpuTypePaths,
- ) -> anyhow::Result<(Box<[Box<str>]>, Box<[Kernel]>)> {
+ gpu_types: &SlangGpuTypes,
+ ) -> anyhow::Result<(Box<[Box<str>]>, Box<[Kernel]>, Box<[KernelName]>)> {
let source_path_relative =
source_path.strip_prefix(&self.fields.source_directory).context("source is not in src_dir")?;
let source_path_relative_str = source_path_relative.to_str().unwrap();
@@ -140,12 +211,9 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
.context("cannot create output directory")?;
let wrapper_file = output_base_path.with_extension("slang");
- let output_file = output_base_path.with_extension(T::OUTPUT_EXTENSION);
- let bindgen_file = output_base_path.with_extension("rs");
let cached_file = output_base_path.with_extension("cached");
- let buildsystem_hash: &[u8; blake3::OUT_LEN] =
- caching::build_system_hash().context("cannot get build system hash")?.as_bytes();
+ let buildsystem_hash = &self.fields.buildsystem_hash;
if let Ok(cached_contents) = fs::read(&cached_file)
&& let Ok(cached) = serde_json::from_slice::<Cached>(&cached_contents)
@@ -158,11 +226,12 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
})
{
debug_log!("compile cached: {source_path_relative_str}");
- return Ok((source_path_relative_segments, cached.public_kernels));
+ self.rerun_if_changed(cached.dependency_hashes.keys());
+ return Ok((source_path_relative_segments, cached.public_kernels, cached.private_kernels));
}
let (source_module, source_diagnostics) =
- self.session.load_module_with_diagnostics(&source_path).context("cannot load source module")?;
+ self.sessions[0].load_module_with_diagnostics(&source_path).context("cannot load source module")?;
if let Some(source_diagnostics) = source_diagnostics {
for source_diagnostics_line in source_diagnostics.lines() {
@@ -175,82 +244,47 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
.map(|d| Ok((d.into(), blake3::hash(&fs::read(d).with_context(|| format!("cannot read {d}"))?).into())))
.collect::<anyhow::Result<HashMap<String, [u8; blake3::OUT_LEN]>>>()
.context("cannot hash dependencies")?;
+ self.rerun_if_changed(dependency_hashes.keys());
- let common_gpu_type_map = gpu_type_map.keys().map(|name| (name.clone(), name.clone())).collect();
+ let common_gpu_type_map =
+ gpu_types.paths.entries().map(|(name, _)| (name.to_owned(), name.to_owned())).collect();
let kernels = source_module
.module_reflection()
.children()
.filter_map(|decl| SlangKernel::from_reflection(decl, &common_gpu_type_map).transpose())
.collect::<anyhow::Result<Vec<SlangKernel>>>()
.context("cannot collect kernels")?;
+ let descriptors = kernels
+ .iter()
+ .map(|slang_kernel| {
+ slang_kernel
+ .to_common(&common_gpu_type_map)
+ .with_context(|| format!("cannot convert {} to common kernel", slang_kernel.name))
+ })
+ .collect::<anyhow::Result<Vec<Kernel>>>()?;
if !kernels.is_empty() {
- let constants = source_module
- .module_reflection()
- .children()
- .filter_map(|decl| decl.as_variable())
- .filter(|variable| variable.find_modifier(ModifierID::SlangModifierConst).is_some())
- .filter_map(|variable| Some((variable.name()?.to_owned(), variable.default_value_int()?.to_string())))
- .collect();
- let wrapper_blocks = kernels
- .iter()
- .map(|kernel| {
- wrapper::kernel_wrappers(kernel)
- .with_context(|| format!("cannot generate wrappers for kernel '{}'", kernel.name))
- })
- .collect::<anyhow::Result<Vec<_>>>()?
- .into_iter()
- .flatten();
-
- let wrapper_contents = once(format!("#include {source_path:?}")).chain(wrapper_blocks).join("\n\n");
+ let wrapper_contents =
+ T::wrapper(&self.fields, &source_path, &source_module, &kernels).context("cannot generate wrappers")?;
fs::write(&wrapper_file, wrapper_contents.as_bytes()).context("cannot write wrapper file")?;
- let (wrapper_module, wrapper_diagnostics) =
- self.session.load_module_with_diagnostics(&wrapper_file).context("cannot load wrapper module")?;
-
- if let Some(wrapper_diagnostics) = wrapper_diagnostics {
- for wrapper_diagnostics_line in wrapper_diagnostics.lines() {
- println!("cargo::warning={wrapper_diagnostics_line}");
- }
- }
-
- let entry_points =
- wrapper_module.entry_points().map(|entry_point| entry_point.into()).collect::<Vec<ComponentType>>();
-
- let wrapper_component: ComponentType = wrapper_module.into();
-
- let composite_component = self
- .session
- .create_composite_component_type(
- &once(wrapper_component).chain(entry_points).collect::<Vec<ComponentType>>(),
- )
- .context("cannot create composite component")?;
+ let linked_component = self.link(0, &wrapper_file)?;
- let linked_component = composite_component.link().context("cannot link wrapper module")?;
-
- let linked_blob = linked_component.target_code(0).context("cannot get target code")?;
-
- fs::write(&output_file, linked_blob.as_slice()).context("cannot write output file")?;
-
- T::validate_output(&output_file).with_context(|| format!("cannot validate {}", output_file.display()))?;
-
- let bindgen_tokens =
- T::bindgen_file(&linked_component, &kernels, &gpu_type_map, gpu_type_paths, &constants, &output_file)
- .context("cannot generate bindings")?;
-
- write_tokens(bindgen_tokens, &bindgen_file).context("cannot write bindgen file")?;
+ T::emit(self, gpu_types, &source_module, &kernels, &descriptors, &linked_component, &output_base_path)
+ .context("cannot emit kernels")?;
}
let public_kernels = kernels
.iter()
- .filter_map(|slang_kernel| {
- slang_kernel
- .to_common(&common_gpu_type_map)
- .with_context(|| format!("cannot convert {} to common kernel", slang_kernel.name))
- .transpose()
- })
- .collect::<anyhow::Result<Box<[Kernel]>>>()?;
+ .zip(descriptors)
+ .filter_map(|(slang_kernel, descriptor)| slang_kernel.public.then_some(descriptor))
+ .collect::<Box<[Kernel]>>();
+ let private_kernels = kernels
+ .iter()
+ .filter(|slang_kernel| !slang_kernel.public)
+ .map(|slang_kernel| KernelName::from(slang_kernel.name.as_str()))
+ .collect::<Box<[KernelName]>>();
fs::write(
&cached_file,
@@ -259,6 +293,7 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
compiler_version: self.global_session.build_tag_string().to_owned(),
dependency_hashes,
public_kernels: public_kernels.clone(),
+ private_kernels: private_kernels.clone(),
})
.context("cannot serialize cache")?,
)
@@ -266,6 +301,6 @@ impl<T: SlangTarget> BlockingSlangCompiler<T> {
debug_log!("compile end: {source_path_relative_str}");
- Ok((source_path_relative_segments, public_kernels))
+ Ok((source_path_relative_segments, public_kernels, private_kernels))
}
}
diff --git a/crates/uzu-engine/build/slang/gpu_types/mod.rs b/crates/uzu-engine/build/slang/gpu_types/mod.rs
index ee5d99a39..d2be16c92 100644
--- a/crates/uzu-engine/build/slang/gpu_types/mod.rs
+++ b/crates/uzu-engine/build/slang/gpu_types/mod.rs
@@ -1,12 +1,13 @@
use std::{
- collections::{HashMap, hash_map::Entry},
+ collections::{BTreeMap, HashSet},
+ fs,
path::Path,
};
-use anyhow::{Context, bail};
+use anyhow::Context;
use itertools::Itertools;
-use crate::common::gpu_types::{GpuType, GpuTypeFile, GpuTypes};
+use crate::common::gpu_types::{GpuType, GpuTypes};
mod gpu_type_constant;
mod gpu_type_enum;
@@ -20,39 +21,36 @@ use gpu_type_struct::gpu_type_gen_struct;
pub fn gpu_type_gen(
gpu_types_dir: &Path,
- gpu_types: &GpuTypes,
-) -> anyhow::Result<HashMap<String, String>> {
- let mut gpu_types_map = HashMap::new();
+ gpu_types: &[&GpuTypes],
+) -> anyhow::Result<()> {
+ let mut files: BTreeMap<&str, Vec<&GpuType>> = BTreeMap::new();
+ for gpu_type_file in gpu_types.iter().flat_map(|gpu_types| &gpu_types.files) {
+ files.entry(&gpu_type_file.name).or_default().extend(&gpu_type_file.types);
+ }
- for gpu_type_file in &gpu_types.files {
- gpu_type_gen_file(&gpu_types_dir.join(gpu_type_file.name.as_ref()).with_extension("slang"), gpu_type_file)
- .with_context(|| format!("Cannot generate gpu types for {}", gpu_type_file.name.as_ref()))?;
- for gpu_type in &gpu_type_file.types {
- let name: &str = match gpu_type {
- GpuType::Enum(gpu_type_enum) => gpu_type_enum.name.as_ref(),
- GpuType::Struct(gpu_type_struct) => gpu_type_struct.name.as_ref(),
- GpuType::OptionSet(gpu_type_option_set) => gpu_type_option_set.name.as_ref(),
- GpuType::Constant(_) => continue,
- };
+ fs::create_dir_all(gpu_types_dir).context("cannot create output directory")?;
+ let mut written = HashSet::new();
+ for (name, types) in files {
+ let file_path = gpu_types_dir.join(name).with_extension("slang");
+ gpu_type_gen_file(&file_path, &types).with_context(|| format!("Cannot generate gpu types for {name}"))?;
+ written.insert(file_path);
+ }
- match gpu_types_map.entry(name.to_string()) {
- Entry::Occupied(_) => bail!("{name} is duplicated"),
- Entry::Vacant(vacant) => {
- vacant.insert(format!("crate::backends::common::gpu_types::{}::{}", gpu_type_file.name, name))
- },
- };
+ for entry in fs::read_dir(gpu_types_dir).context("cannot list generated gpu types")? {
+ let path = entry?.path();
+ if !written.contains(&path) {
+ fs::remove_file(&path).with_context(|| format!("cannot remove {}", path.display()))?;
}
}
- Ok(gpu_types_map)
+ Ok(())
}
fn gpu_type_gen_file(
file_path: &Path,
- gpu_types_file: &GpuTypeFile,
+ types: &[&GpuType],
) -> anyhow::Result<()> {
- let new_contents = gpu_types_file
- .types
+ let new_contents = types
.iter()
.map(|gpu_type| match gpu_type {
GpuType::Constant(gpu_type_constant) => gpu_type_gen_constant(gpu_type_constant)
@@ -67,9 +65,8 @@ fn gpu_type_gen_file(
.process_results(|mut it| it.join("\n\n"))?;
// Avoid advancing mtime if the contents are the same
- if !std::fs::read(file_path).is_ok_and(|old_contents| old_contents == new_contents.as_bytes()) {
- std::fs::create_dir_all(file_path.parent().unwrap()).context("cannot create output directory")?;
- std::fs::write(file_path, new_contents).context("cannot write output")?;
+ if !fs::read(file_path).is_ok_and(|old_contents| old_contents == new_contents.as_bytes()) {
+ fs::write(file_path, new_contents).context("cannot write output")?;
}
Ok(())
diff --git a/crates/uzu-engine/build/slang/mod.rs b/crates/uzu-engine/build/slang/mod.rs
index 0aa78c058..39a683364 100644
--- a/crates/uzu-engine/build/slang/mod.rs
+++ b/crates/uzu-engine/build/slang/mod.rs
@@ -1,14 +1,18 @@
-// TODO: gigaslop, clean up
-
+mod axis_expression;
mod compiler;
mod compiler_internal;
mod gpu_types;
mod reflection;
+mod slang_gpu_types;
mod slang_sys_ext;
mod types;
mod wrapper;
+pub use axis_expression::slang_axis_expr;
pub use compiler::SlangCompiler;
-pub use compiler_internal::SlangTarget;
-pub use reflection::{SlangArgumentType, SlangBufferAccess, SlangKernel, SlangParameterType};
+pub use compiler_internal::{BlockingSlangCompiler, SlangCompilerFields, SlangTarget};
+pub use gpu_types::gpu_type_gen;
+pub use reflection::{SlangArgumentType, SlangKernel, SlangParameterType};
+pub use slang_gpu_types::SlangGpuTypes;
pub use types::{Specializer, slang2rust};
+pub use wrapper::{kernel_wrappers, specialization_name};
diff --git a/crates/uzu-engine/build/slang/reflection/argument.rs b/crates/uzu-engine/build/slang/reflection/argument.rs
index b826e5f03..d7ff7e611 100644
--- a/crates/uzu-engine/build/slang/reflection/argument.rs
+++ b/crates/uzu-engine/build/slang/reflection/argument.rs
@@ -1,26 +1,22 @@
use std::collections::{HashMap, hash_map::Entry};
-use anyhow::{Context, anyhow, bail};
-use shader_slang::reflection::{UserAttribute, Variable};
+use anyhow::{Context, anyhow, bail, ensure};
+use shader_slang::{
+ TypeKind,
+ reflection::{UserAttribute, Variable},
+};
use crate::{
common::{
identifiers::ArgumentName,
kernel::{KernelArgument, KernelArgumentType, KernelBufferAccess, KernelParameter, KernelParameterType},
},
- slang::types::slang2rust,
+ slang::{reflection::attribute_arguments::string_arguments, types::slang2rust},
};
-#[derive(Debug)]
-pub enum SlangBufferAccess {
- Read,
- ReadWrite,
-}
-
#[derive(Debug)]
pub enum SlangArgumentType {
Buffer {
- access_type: SlangBufferAccess,
condition: Option<String>,
},
Uniform {
@@ -48,6 +44,7 @@ pub struct SlangArgument {
pub slang_type: String,
pub argument_type: SlangArgumentType,
pub binding_type: Option<KernelArgumentType>,
+ pub pipeline_variants: bool,
}
impl SlangArgument {
@@ -55,15 +52,15 @@ impl SlangArgument {
variable: &Variable,
gpu_type_map: &HashMap<String, String>,
) -> anyhow::Result<Self> {
- let name = variable.name().unwrap().to_string();
+ let name = variable.name().context("argument has no name")?.to_string();
- let ty = variable.ty().unwrap();
+ let ty = variable.ty().with_context(|| format!("argument {name} has no type"))?;
- let type_name = ty.name().unwrap();
- let type_full_name = ty.full_name().unwrap().as_str().unwrap().to_string();
+ let type_name = ty.name().with_context(|| format!("type of argument {name} has no name"))?;
+ let type_full_name = ty.full_name()?.as_str()?.to_string();
let mut user_attributes = variable.user_attributes().try_fold(HashMap::new(), |mut acc, user_attributes| {
- match acc.entry(user_attributes.name().unwrap()) {
+ match acc.entry(user_attributes.name().context("attribute has no name")?) {
Entry::Occupied(occupied) => Err(anyhow!("duplicate {} attribute", occupied.key())),
Entry::Vacant(vacant) => {
vacant.insert(user_attributes);
@@ -72,16 +69,13 @@ impl SlangArgument {
}
})?;
- let get_condition = |user_attributes: &mut HashMap<&str, &UserAttribute>| {
+ let get_condition = |user_attributes: &mut HashMap<&str, &UserAttribute>| -> anyhow::Result<Option<String>> {
let Some(optional_attribute) = user_attributes.remove("Optional") else {
return Ok(None);
};
- if optional_attribute.argument_count() != 1 {
- bail!("optional expected 1 argument, found {}", optional_attribute.argument_count());
- }
-
- Ok(Some(optional_attribute.argument_value_string(0).unwrap().to_string()))
+ let [condition] = string_arguments::<1>(optional_attribute)?;
+ Ok(Some(condition.to_string()))
};
let no_attributes = |user_attributes: &HashMap<&str, &UserAttribute>, name: &str| {
@@ -93,10 +87,9 @@ impl SlangArgument {
};
let mut binding_type = None;
+ let mut pipeline_variants = false;
let argument_type = if let Some(specialize_attribute) = user_attributes.remove("Specialize") {
- if specialize_attribute.argument_count() != 0 {
- bail!("specialize expected no argument, found {}", specialize_attribute.argument_count());
- }
+ string_arguments::<0>(specialize_attribute)?;
let condition = get_condition(&mut user_attributes)?;
no_attributes(&user_attributes, "specialize")?;
@@ -105,12 +98,7 @@ impl SlangArgument {
condition,
}
} else if let Some(axis_attribute) = user_attributes.remove("Axis") {
- if axis_attribute.argument_count() != 2 {
- bail!("axis expected 2 argument, found {}", axis_attribute.argument_count());
- }
-
- let threads = axis_attribute.argument_value_string(0).unwrap().to_string();
- let threads_in_group = axis_attribute.argument_value_string(1).unwrap().to_string();
+ let [threads, threads_in_group] = string_arguments::<2>(axis_attribute)?.map(str::to_string);
no_attributes(&user_attributes, "axis")?;
@@ -119,11 +107,7 @@ impl SlangArgument {
threads_in_group,
}
} else if let Some(groups_attribute) = user_attributes.remove("Groups") {
- if groups_attribute.argument_count() != 1 {
- bail!("groups expected 1 argument, found {}", groups_attribute.argument_count());
- }
-
- let groups = groups_attribute.argument_value_string(0).unwrap().to_string();
+ let [groups] = string_arguments::<1>(groups_attribute)?.map(str::to_string);
no_attributes(&user_attributes, "groups")?;
@@ -131,11 +115,7 @@ impl SlangArgument {
groups,
}
} else if let Some(threads_attribute) = user_attributes.remove("Threads") {
- if threads_attribute.argument_count() != 1 {
- bail!("threads expected 1 argument, found {}", threads_attribute.argument_count());
- }
-
- let threads = threads_attribute.argument_value_string(0).unwrap().to_string();
+ let [threads] = string_arguments::<1>(threads_attribute)?.map(str::to_string);
no_attributes(&user_attributes, "threads")?;
@@ -146,6 +126,40 @@ impl SlangArgument {
no_attributes(&user_attributes, "thread context")?;
SlangArgumentType::ThreadContext
+ } else if matches!(ty.kind(), TypeKind::Pointer) {
+ let condition = get_condition(&mut user_attributes)?;
+ let (pointee, access_type) = type_full_name
+ .strip_prefix("Ptr<")
+ .and_then(|ty| {
+ ty.strip_suffix(", AddressSpace.Device>")
+ .or_else(|| ty.strip_suffix(", AddressSpace.Device, DefaultDataLayout>"))
+ })
+ .and_then(|ty| ty.rsplit_once(", Access."))
+ .and_then(|(pointee, access)| match access {
+ "Read" => Some((pointee, KernelBufferAccess::Read)),
+ "ReadWrite" => Some((pointee, KernelBufferAccess::ReadWrite)),
+ _ => None,
+ })
+ .with_context(|| {
+ format!("pointer argument doesn't match Ptr<T, Access, AddressSpace.Device>: {type_full_name}")
+ })?;
+ binding_type = Some(if user_attributes.remove("Constant").is_some() {
+ ensure!(access_type == KernelBufferAccess::Read, "constant pointer {name} is not read-only");
+ KernelArgumentType::Value(
+ slang2rust(&format!("{pointee}[]"), gpu_type_map)
+ .with_context(|| format!("cannot convert slang {type_full_name} to rust"))?
+ .into_owned()
+ .into_boxed_str(),
+ )
+ } else {
+ KernelArgumentType::Buffer(access_type)
+ });
+
+ no_attributes(&user_attributes, "pointer")?;
+
+ SlangArgumentType::Buffer {
+ condition,
+ }
} else if type_name == "StructuredBuffer" {
let condition = get_condition(&mut user_attributes)?;
binding_type = Some(if user_attributes.remove("Constant").is_some() {
@@ -166,7 +180,6 @@ impl SlangArgument {
no_attributes(&user_attributes, "buffer (read-only)")?;
SlangArgumentType::Buffer {
- access_type: SlangBufferAccess::Read,
condition,
}
} else if type_name == "RWStructuredBuffer" {
@@ -176,11 +189,12 @@ impl SlangArgument {
no_attributes(&user_attributes, "buffer (read-write)")?;
SlangArgumentType::Buffer {
- access_type: SlangBufferAccess::ReadWrite,
condition,
}
} else {
let condition = get_condition(&mut user_attributes)?;
+ pipeline_variants = user_attributes.remove("PipelineVariants").is_some();
+ ensure!(!pipeline_variants || condition.is_none(), "pipeline variants {name} cannot be optional");
no_attributes(&user_attributes, "uniform")?;
binding_type = Some(KernelArgumentType::Value(
@@ -200,6 +214,7 @@ impl SlangArgument {
slang_type: type_full_name,
argument_type,
binding_type,
+ pipeline_variants,
})
}
diff --git a/crates/uzu-engine/build/slang/reflection/attribute_arguments.rs b/crates/uzu-engine/build/slang/reflection/attribute_arguments.rs
new file mode 100644
index 000000000..9640773d9
--- /dev/null
+++ b/crates/uzu-engine/build/slang/reflection/attribute_arguments.rs
@@ -0,0 +1,16 @@
+use anyhow::{Context, ensure};
+use shader_slang::reflection::UserAttribute;
+
+pub fn string_arguments<const N: usize>(attribute: &UserAttribute) -> anyhow::Result<[&str; N]> {
+ let name = attribute.name().context("attribute has no name")?;
+ let count = attribute.argument_count();
+ ensure!(count as usize == N, "{name} expects {N} arguments, found {count}");
+
+ let mut arguments = [""; N];
+ for (index, argument) in arguments.iter_mut().enumerate() {
+ *argument = attribute
+ .argument_value_string(index as u32)
+ .with_context(|| format!("{name} argument {index} has no string value"))?;
+ }
+ Ok(arguments)
+}
diff --git a/crates/uzu-engine/build/slang/reflection/kernel.rs b/crates/uzu-engine/build/slang/reflection/kernel.rs
index 62aff65d5..ffc3ca739 100644
--- a/crates/uzu-engine/build/slang/reflection/kernel.rs
+++ b/crates/uzu-engine/build/slang/reflection/kernel.rs
@@ -1,6 +1,6 @@
use std::collections::HashMap;
-use anyhow::{Context, bail};
+use anyhow::{Context, ensure};
use itertools::Itertools;
use shader_slang::{
DeclKind,
@@ -14,7 +14,7 @@ use crate::{
},
slang::{
SlangParameterType,
- reflection::{SlangArgument, SlangParameter},
+ reflection::{SlangArgument, SlangParameter, attribute_arguments::string_arguments},
},
};
@@ -24,6 +24,8 @@ pub struct SlangKernel {
pub public: bool,
pub name: String,
pub arguments: Vec<SlangArgument>,
+ pub preconditions: Vec<(String, String)>,
+ pub required_subgroup_size: Option<String>,
}
impl SlangKernel {
@@ -32,7 +34,8 @@ impl SlangKernel {
gpu_type_map: &HashMap<String, String>,
) -> anyhow::Result<Option<Self>> {
let (generic_decl, function_decl) = if toplevel_decl.kind() == DeclKind::Generic {
- (Some(toplevel_decl), toplevel_decl.as_generic().unwrap().inner_decl().unwrap())
+ let generic = toplevel_decl.as_generic().context("generic declaration has no reflection")?;
+ (Some(toplevel_decl), generic.inner_decl().context("generic declaration has no inner declaration")?)
} else {
(None, toplevel_decl)
};
@@ -41,7 +44,7 @@ impl SlangKernel {
return Ok(None);
}
- let function = function_decl.as_function().unwrap();
+ let function = function_decl.as_function().context("function declaration has no reflection")?;
let function_attributes = function.user_attributes().collect::<Vec<&UserAttribute>>();
if !function_attributes.iter().any(|user_attribute| user_attribute.name() == Some("Kernel")) {
@@ -55,17 +58,8 @@ impl SlangKernel {
.iter()
.map(|user_attribute| {
if user_attribute.name() == Some("Constraint") {
- if user_attribute.argument_count() != 1 {
- bail!("expected 1 argument, found {}", user_attribute.argument_count());
- }
-
- Ok(Some(
- user_attribute
- .argument_value_string(0)
- .context("cannot get name argument string value")?
- .trim()
- .to_string(),
- ))
+ let [constraint] = string_arguments::<1>(user_attribute)?;
+ Ok(Some(constraint.trim().to_string()))
} else {
Ok(None)
}
@@ -76,7 +70,30 @@ impl SlangKernel {
let public = function_attributes.iter().any(|user_attribute| user_attribute.name() == Some("Public"));
- let name = function.name().unwrap().to_string();
+ let name = function.name().context("kernel has no name")?.to_string();
+
+ let preconditions = function_attributes
+ .iter()
+ .filter(|user_attribute| user_attribute.name() == Some("Precondition"))
+ .map(|user_attribute| {
+ let phase = user_attribute.argument_value_string(0).context("precondition has no phase")?;
+ let condition = user_attribute.argument_value_string(1).context("precondition has no condition")?;
+ ensure!(matches!(phase, "new" | "encode"), "precondition phase {phase} is neither new nor encode");
+ ensure!(!condition.trim().is_empty(), "empty {phase} precondition");
+ Ok((phase.to_string(), condition.to_string()))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()
+ .context("cannot collect preconditions")?;
+
+ let required_subgroup_size = function_attributes
+ .iter()
+ .find(|user_attribute| user_attribute.name() == Some("RequiredSubgroupSize"))
+ .map(|user_attribute| {
+ anyhow::Ok(
+ user_attribute.argument_value_string(0).context("required subgroup size has no size")?.to_string(),
+ )
+ })
+ .transpose()?;
let arguments = function
.parameters()
@@ -90,6 +107,8 @@ impl SlangKernel {
public,
name,
arguments,
+ preconditions,
+ required_subgroup_size,
}))
}
@@ -135,12 +154,8 @@ impl SlangKernel {
pub fn to_common(
&self,
gpu_type_map: &HashMap<String, String>,
- ) -> anyhow::Result<Option<Kernel>> {
- if !self.public {
- return Ok(None);
- }
-
- Ok(Some(Kernel {
+ ) -> anyhow::Result<Kernel> {
+ Ok(Kernel {
name: self.name.clone().into(),
parameters: self
.parameters
@@ -164,6 +179,6 @@ impl SlangKernel {
.filter_map(|argument| argument.to_common_argument(&mut indirect_used))
.collect::<Box<[KernelArgument]>>()
},
- }))
+ })
}
}
diff --git a/crates/uzu-engine/build/slang/reflection/mod.rs b/crates/uzu-engine/build/slang/reflection/mod.rs
index ff3cc7a23..2334df393 100644
--- a/crates/uzu-engine/build/slang/reflection/mod.rs
+++ b/crates/uzu-engine/build/slang/reflection/mod.rs
@@ -1,7 +1,8 @@
mod argument;
+mod attribute_arguments;
mod kernel;
mod parameter;
-pub use argument::{SlangArgument, SlangArgumentType, SlangBufferAccess};
+pub use argument::{SlangArgument, SlangArgumentType};
pub use kernel::SlangKernel;
pub use parameter::{SlangParameter, SlangParameterType};
diff --git a/crates/uzu-engine/build/slang/reflection/parameter.rs b/crates/uzu-engine/build/slang/reflection/parameter.rs
index 49d2d1e54..493434b1a 100644
--- a/crates/uzu-engine/build/slang/reflection/parameter.rs
+++ b/crates/uzu-engine/build/slang/reflection/parameter.rs
@@ -5,7 +5,7 @@ use shader_slang::reflection::{Decl, UserAttribute};
use crate::{
common::kernel::{KernelParameter, KernelParameterType},
- slang::types::slang2rust,
+ slang::{reflection::attribute_arguments::string_arguments, types::slang2rust},
};
#[derive(Debug)]
@@ -29,42 +29,48 @@ pub struct SlangParameter {
pub ty: SlangParameterType,
}
+enum ParameterAttributeType<'a> {
+ Variants {
+ variants: Vec<&'a str>,
+ },
+ GroupShared {
+ length: &'a str,
+ },
+}
+
+struct ParameterAttribute<'a> {
+ name: &'a str,
+ ty: ParameterAttributeType<'a>,
+}
+
+enum ParameterGenericType {
+ Type {
+ constraints: Vec<String>,
+ },
+ Value {
+ value_type: String,
+ },
+}
+
+struct ParameterGeneric<'a> {
+ name: &'a str,
+ ty: ParameterGenericType,
+}
+
impl SlangParameter {
pub fn from_reflection(
function_attributes: &[&UserAttribute],
generic_decl: Option<&Decl>,
) -> anyhow::Result<Vec<Self>> {
- enum ParameterAttributeType<'a> {
- Variants {
- variants: Vec<&'a str>,
- },
- GroupShared {
- length: &'a str,
- },
- }
-
- struct ParameterAttribute<'a> {
- name: &'a str,
- ty: ParameterAttributeType<'a>,
- }
-
let parameters_attributes = function_attributes
.iter()
.map(|user_attribute| {
Ok(match user_attribute.name() {
Some("Variants") => {
- if user_attribute.argument_count() != 2 {
- bail!("expected 2 arguments, found {}", user_attribute.argument_count());
- }
-
- let name = user_attribute
- .argument_value_string(0)
- .context("cannot get name argument string value")?
- .trim();
+ let [name, variants] = string_arguments::<2>(user_attribute)?;
+ let name = name.trim();
- let variants = user_attribute
- .argument_value_string(1)
- .context("cannot get variants argument string value")?
+ let variants = variants
.split(',')
.map(|variant| variant.trim())
.filter(|variant| !variant.is_empty())
@@ -78,19 +84,9 @@ impl SlangParameter {
})
},
Some("GroupShared") => {
- if user_attribute.argument_count() != 2 {
- bail!("expected 2 arguments, found {}", user_attribute.argument_count());
- }
-
- let name = user_attribute
- .argument_value_string(0)
- .context("cannot get name argument string value")?
- .trim();
-
- let length = user_attribute
- .argument_value_string(1)
- .context("cannot get length argument string value")?
- .trim();
+ let [name, length] = string_arguments::<2>(user_attribute)?;
+ let name = name.trim();
+ let length = length.trim();
Some(ParameterAttribute {
name,
@@ -106,61 +102,43 @@ impl SlangParameter {
.collect::<anyhow::Result<Vec<_>>>()
.context("failed to collect parameter attributes")?;
- enum ParameterGenericType {
- Type {
- constraints: Vec<String>,
- },
- Value {
- value_type: String,
- },
- }
-
- struct ParameterGeneric<'a> {
- name: &'a str,
- ty: ParameterGenericType,
- }
-
let parameters_generics = generic_decl
.map(|generic_decl| -> anyhow::Result<_> {
- let generic = generic_decl.as_generic().unwrap();
+ let generic = generic_decl.as_generic().context("generic declaration has no reflection")?;
let mut generics_unordered = generic
.type_parameters()
.map(|type_parameter| {
- (
- type_parameter.name().unwrap(),
+ Ok((
+ type_parameter.name().context("type parameter has no name")?,
ParameterGenericType::Type {
constraints: (0..generic.type_parameter_constraint_count(type_parameter))
.map(|i| {
- generic
+ Ok(generic
.type_parameter_constraint_by_index(type_parameter, i)
- .unwrap()
- .full_name()
- .unwrap()
- .as_str()
- .unwrap()
- .to_string()
+ .context("type parameter constraint has no type")?
+ .full_name()?
+ .as_str()?
+ .to_string())
})
- .collect(),
+ .collect::<anyhow::Result<_>>()?,
},
- )
+ ))
})
.chain(generic.value_parameters().map(|value_parameter| {
- (
- value_parameter.name().unwrap(),
+ Ok((
+ value_parameter.name().context("value parameter has no name")?,
ParameterGenericType::Value {
value_type: value_parameter
.ty()
- .unwrap()
- .full_name()
- .unwrap()
- .as_str()
- .unwrap()
+ .context("value parameter has no type")?
+ .full_name()?
+ .as_str()?
.to_string(),
},
- )
+ ))
}))
- .collect::<HashMap<&str, ParameterGenericType>>();
+ .collect::<anyhow::Result<HashMap<&str, ParameterGenericType>>>()?;
let mut generics = Vec::with_capacity(generics_unordered.len());
diff --git a/crates/uzu-engine/build/slang/slang_gpu_types.rs b/crates/uzu-engine/build/slang/slang_gpu_types.rs
new file mode 100644
index 000000000..e34135bbc
--- /dev/null
+++ b/crates/uzu-engine/build/slang/slang_gpu_types.rs
@@ -0,0 +1,7 @@
+use crate::common::{gpu_type_paths::GpuTypePaths, gpu_types::GpuTypes};
+
+pub struct SlangGpuTypes<'a> {
+ pub paths: GpuTypePaths,
+ #[cfg_attr(not(feature = "vulkan"), allow(dead_code))]
+ pub definitions: Vec<&'a GpuTypes>,
+}
diff --git a/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs b/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs
index 3d6bf2ba4..5b9635347 100644
--- a/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs
+++ b/crates/uzu-engine/build/slang/slang_sys_ext/load_module_with_diagnostics.rs
@@ -5,7 +5,7 @@ use std::{
ptr::{NonNull, null_mut},
};
-use anyhow::anyhow;
+use anyhow::{Context, anyhow};
use shader_slang::{Blob, Interface, Module, Session};
pub trait SessionLoadModuleWithDiagnosticsExt {
@@ -20,14 +20,14 @@ impl SessionLoadModuleWithDiagnosticsExt for Session {
&self,
path: &Path,
) -> anyhow::Result<(Module, Option<String>)> {
- let path_cstr = CString::new(path.to_str().unwrap()).unwrap();
+ let path_cstr = CString::new(path.to_str().context("Slang module path is not UTF-8")?)?;
let mut diagnostics_ptr = null_mut();
let module_ptr = vcall!(self, loadModule(path_cstr.as_ptr(), &mut diagnostics_ptr));
let diagnostics = NonNull::new(diagnostics_ptr as *mut c_void)
.map(|diagnostics_ptr_nn| -> Blob { unsafe { mem::transmute(diagnostics_ptr_nn) } })
- .map(|blob| blob.as_str().unwrap().to_owned());
+ .map(|blob| String::from_utf8_lossy(blob.as_slice()).into_owned());
let Some(module_ptr_nn) = NonNull::new(module_ptr as *mut c_void) else {
return Err(anyhow!("{}", diagnostics.as_deref().unwrap_or("<no diagnostics>")));
diff --git a/crates/uzu-engine/build/slang/types.rs b/crates/uzu-engine/build/slang/types.rs
index 5ed6f8d59..30db0213f 100644
--- a/crates/uzu-engine/build/slang/types.rs
+++ b/crates/uzu-engine/build/slang/types.rs
@@ -39,7 +39,7 @@ pub fn slang2rust<'a>(
"int64_t" => Some(Cow::Borrowed("i64")),
"uint64_t" => Some(Cow::Borrowed("u64")),
"half" => Some(Cow::Borrowed("f16")),
- "BFloat16" => Some(Cow::Borrowed("bf16")),
+ "BFloat16" | "bf16" => Some(Cow::Borrowed("bf16")),
"float" => Some(Cow::Borrowed("f32")),
"double" => Some(Cow::Borrowed("f64")),
_ if let Some(ty_translated) = gpu_type_map.get(ty) => Some(Cow::Borrowed(ty_translated)),
diff --git a/crates/uzu-engine/build/slang/wrapper.rs b/crates/uzu-engine/build/slang/wrapper.rs
index 2e5bb7402..869976dc6 100644
--- a/crates/uzu-engine/build/slang/wrapper.rs
+++ b/crates/uzu-engine/build/slang/wrapper.rs
@@ -1,32 +1,85 @@
-use std::{borrow::Cow, iter::repeat_n};
+use std::{borrow::Cow, collections::HashSet, iter::repeat_n};
-use anyhow::bail;
+use anyhow::{Context, bail};
use itertools::Itertools;
+use regex::Regex;
+use shader_slang::{DeclKind, Module};
use crate::{
common::mangling,
slang::{
+ SlangTarget, Specializer,
reflection::{SlangArgumentType, SlangKernel, SlangParameterType},
- types::Specializer,
+ slang_axis_expr,
},
};
-pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
+pub fn specialization_name(
+ kernel: &str,
+ argument: &str,
+) -> String {
+ format!("{kernel}_specialize_{argument}")
+}
+
+pub fn kernel_wrappers<T: SlangTarget>(
+ module: &Module,
+ kernels: &[SlangKernel],
+) -> anyhow::Result<Vec<String>> {
+ let module_globals = module
+ .module_reflection()
+ .children()
+ .filter(|decl| matches!(decl.kind(), DeclKind::Variable))
+ .filter_map(|decl| decl.as_variable()?.name())
+ .collect::<HashSet<_>>();
+ let wrappers = kernels
+ .iter()
+ .map(|kernel| {
+ kernel_wrapper::<T>(kernel, &module_globals)
+ .with_context(|| format!("cannot generate wrappers for kernel '{}'", kernel.name))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ Ok(wrappers.into_iter().flatten().collect())
+}
+
+fn kernel_wrapper<T: SlangTarget>(
+ kernel: &SlangKernel,
+ module_globals: &HashSet<&str>,
+) -> anyhow::Result<Vec<String>> {
let inner_function_name = kernel.name.as_str();
+ let specialized = |argument_type: &SlangArgumentType, pipeline_variants: bool| {
+ matches!(argument_type, SlangArgumentType::Specialize { .. }) || pipeline_variants
+ };
+ let sizes = kernel
+ .arguments
+ .iter()
+ .filter_map(|argument| match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads_in_group: size,
+ ..
+ }
+ | SlangArgumentType::Threads {
+ threads: size,
+ } => Some(size.as_str()),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
let mut wrappers = Vec::new();
let mut wrapper = Vec::new();
- for specialize in &kernel.arguments {
- let SlangArgumentType::Specialize {
- ..
- } = &specialize.argument_type
- else {
+ for argument in &kernel.arguments {
+ let name = specialization_name(&kernel.name, &argument.name);
+ if !specialized(&argument.argument_type, argument.pipeline_variants) || module_globals.contains(name.as_str()) {
continue;
+ }
+ let mentioned = Regex::new(&format!(r"\b{}\b", regex::escape(&argument.name)))?;
+ let default = if sizes.iter().any(|size| mentioned.is_match(size)) {
+ " = 1"
+ } else {
+ ""
};
-
wrapper.push("[SpecializationConstant]".to_string());
- wrapper.push(format!("const {} {}_specialize_{};", specialize.slang_type, kernel.name, specialize.name));
+ wrapper.push(format!("const {} {name}{default};", T::specialization_type(&argument.slang_type)));
wrapper.push(String::new());
}
wrappers.push(wrapper.into_iter().join("\n"));
@@ -38,7 +91,7 @@ pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
.arguments
.iter()
.filter(|argument| matches!(argument.argument_type, SlangArgumentType::Specialize { .. }))
- .map(|argument| (argument.name.as_str(), format!("{}_specialize_{}", kernel.name, argument.name)))
+ .map(|argument| (argument.name.as_str(), specialization_name(&kernel.name, &argument.name)))
.collect::<Vec<_>>();
let substitutions = variant
.iter()
@@ -113,7 +166,7 @@ pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
},
SlangArgumentType::Uniform {
..
- } => {
+ } if !argument.pipeline_variants => {
wrapper.push(format!(
" uniform {} {},",
specializer.specialize(&argument.slang_type),
@@ -147,21 +200,29 @@ pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
}
wrapper.push(") {".to_string());
+ let prologue = T::entry_point_prologue(&outer_function_name);
+ if !prologue.is_empty() {
+ wrapper.push(prologue);
+ }
+ let axes = kernel
+ .arguments
+ .iter()
+ .filter_map(|argument| match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads,
+ threads_in_group,
+ } => Some((
+ specializer.specialize(&slang_axis_expr(threads, kernel)).into_owned(),
+ specializer.specialize(threads_in_group).into_owned(),
+ )),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ let mut axis_indices = Vec::new().into_iter();
if has_axis {
- let axis_guards = kernel
- .arguments
- .iter()
- .filter_map(|argument| match &argument.argument_type {
- SlangArgumentType::Axis {
- threads,
- threads_in_group: _,
- } => Some(specializer.specialize(&slang_axis_expr(threads, kernel)).into_owned()),
- _ => None,
- })
- .zip(["x", "y", "z"])
- .map(|(threads, axis)| format!("__dsl_axis_idx.{axis} >= uint({threads})"))
- .join(" || ");
- wrapper.push(format!(" if ({axis_guards}) {{ return; }}"));
+ let (guard, indices) = T::axis_guard(&axes);
+ wrapper.push(guard);
+ axis_indices = indices.into_iter();
}
let inner_function_parameters = kernel
@@ -180,35 +241,46 @@ pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
})
.collect::<Vec<_>>();
- let mut group_axis_letters = ["x", "y", "z"].iter();
- let mut thread_axis_letters = ["x", "y", "z"].iter();
+ let mut group_letters = ["x", "y", "z"].iter();
+ let mut thread_letters = ["x", "y", "z"].iter();
let inner_function_arguments = kernel
.arguments
.iter()
- .map(|argument| match &argument.argument_type {
- SlangArgumentType::Buffer {
- ..
- }
- | SlangArgumentType::Uniform {
- ..
- } => argument.name.to_string(),
- SlangArgumentType::Specialize {
- ..
- } => {
- format!("{}_specialize_{}", kernel.name, argument.name)
- },
- SlangArgumentType::Axis {
- ..
- } => format!("__dsl_axis_idx.{}", group_axis_letters.next().unwrap()),
- SlangArgumentType::Groups {
- ..
- } => format!("__dsl_groups_idx.{}", group_axis_letters.next().unwrap()),
- SlangArgumentType::Threads {
- ..
- } => format!("__dsl_threads_idx.{}", thread_axis_letters.next().unwrap()),
- SlangArgumentType::ThreadContext => "ThreadContext()".to_string(),
+ .map(|argument| {
+ Ok(match &argument.argument_type {
+ SlangArgumentType::Buffer {
+ ..
+ } => argument.name.to_string(),
+ SlangArgumentType::Uniform {
+ ..
+ } if !argument.pipeline_variants => argument.name.to_string(),
+ SlangArgumentType::Specialize {
+ ..
+ }
+ | SlangArgumentType::Uniform {
+ ..
+ } => {
+ let constant = specialization_name(&kernel.name, &argument.name);
+ let slang_type = specializer.specialize(&argument.slang_type);
+ if T::specialization_type(&slang_type) == slang_type {
+ constant
+ } else {
+ format!("{slang_type}({constant})")
+ }
+ },
+ SlangArgumentType::Axis {
+ ..
+ } => axis_indices.next().context("more Axis arguments than guarded axes")?,
+ SlangArgumentType::Groups {
+ ..
+ } => format!("__dsl_groups_idx.{}", group_letters.next().context("more than three Groups")?),
+ SlangArgumentType::Threads {
+ ..
+ } => format!("__dsl_threads_idx.{}", thread_letters.next().context("more than three Threads")?),
+ SlangArgumentType::ThreadContext => "ThreadContext()".to_string(),
+ })
})
- .collect::<Vec<_>>();
+ .collect::<anyhow::Result<Vec<_>>>()?;
if inner_function_parameters.is_empty() {
wrapper.push(format!(" {inner_function_name}({});", inner_function_arguments.into_iter().join(", ")));
@@ -227,70 +299,3 @@ pub fn kernel_wrappers(kernel: &SlangKernel) -> anyhow::Result<Vec<String>> {
Ok(wrappers)
}
-
-fn slang_axis_expr(
- expr: &str,
- kernel: &SlangKernel,
-) -> String {
- let expr = rewrite_slang_method(expr, "unwrap_or", |receiver, fallback| {
- let condition = kernel
- .arguments
- .iter()
- .find_map(|argument| {
- if argument.name != receiver {
- return None;
- }
- match &argument.argument_type {
- SlangArgumentType::Uniform {
- condition,
- } => condition.as_deref(),
- _ => None,
- }
- })
- .expect("unwrap_or receiver must be an optional constant");
- format!("(({condition}) ? ({receiver}) : ({fallback}))")
- });
- let expr = rewrite_slang_method(&expr, "div_ceil", |receiver, argument| {
- format!("(({receiver}) / ({argument}) + uint(({receiver}) % ({argument}) != 0))")
- });
- let expr =
- rewrite_slang_method(&expr, "saturating_mul", |receiver, argument| format!("(({receiver}) * ({argument}))"));
-
- rewrite_slang_method(&expr, "saturating_sub", |receiver, argument| {
- format!("(({receiver}) > ({argument}) ? ({receiver}) - ({argument}) : 0)")
- })
-}
-
-fn rewrite_slang_method(
- expr: &str,
- method: &str,
- rewrite: impl Fn(&str, &str) -> String,
-) -> String {
- let pattern = format!(".{method}(");
- let Some(dot) = expr.find(&pattern) else {
- return expr.to_string();
- };
-
- let receiver_start = expr[..dot].rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).map_or(0, |idx| idx + 1);
- let argument_start = dot + pattern.len();
- let mut depth = 1;
- let mut argument_end = argument_start;
- for (offset, ch) in expr[argument_start..].char_indices() {
- match ch {
- '(' => depth += 1,
- ')' => {
- depth -= 1;
- if depth == 0 {
- argument_end = argument_start + offset;
- break;
- }
- },
- _ => (),
- }
- }
-
- let receiver = &expr[receiver_start..dot];
- let argument = &expr[argument_start..argument_end];
- let rewritten = rewrite(receiver, argument);
- format!("{}{}{}", &expr[..receiver_start], rewritten, &expr[argument_end + 1..])
-}
diff --git a/crates/uzu-engine/build/vulkan/bindgen.rs b/crates/uzu-engine/build/vulkan/bindgen.rs
new file mode 100644
index 000000000..715896cfa
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/bindgen.rs
@@ -0,0 +1,1060 @@
+use std::{
+ collections::{BTreeSet, HashMap},
+ iter::once,
+ path::{Path, PathBuf},
+};
+
+use anyhow::{Context, bail, ensure};
+use itertools::Itertools;
+use proc_macro2::{TokenStream, TokenTree};
+use quote::{ToTokens, format_ident, quote};
+use shader_slang::ScalarType;
+use syn::{Expr, GenericArgument, Ident, PathArguments, Type, parse_quote};
+
+use crate::{
+ common::{
+ expr_rewrite::{qualify_enum_path, rewrite_paths_with},
+ gpu_type_paths::{GpuTypeKind, GpuTypePaths},
+ gpu_types::{GpuType, GpuTypeEnum, GpuTypeStructFieldType, GpuTypes},
+ kernel::{Kernel, KernelArgumentType, KernelBufferAccess, KernelParameterType},
+ },
+ slang::{SlangArgumentType, SlangKernel, slang2rust, specialization_name},
+ vulkan::{SlangEntryPointAbi, SlangEntryPointVariant, SlangFieldAbi, vulkan_target::AXIS_FOLD_GROUPS},
+};
+
+pub fn binding_file(
+ output_base: &Path,
+ kernel_name: &str,
+) -> PathBuf {
+ output_base.with_file_name(binding_module(kernel_name).to_string()).with_extension("rs")
+}
+
+pub fn bindgen_umbrella(bindings: &[(String, String, bool)]) -> TokenStream {
+ let modules = bindings.iter().map(|(file, kernel_name, _)| {
+ let module = binding_module(kernel_name);
+ let ty = format_ident!("{kernel_name}VulkanKernel");
+ quote! {
+ #[path = #file]
+ mod #module;
+ pub use #module::#ty;
+ }
+ });
+ let kernel_types = bindings.iter().filter(|(.., public)| *public).map(|(_, kernel_name, _)| {
+ let kernel_trait = format_ident!("{kernel_name}Kernel");
+ let ty = format_ident!("{kernel_name}VulkanKernel");
+ quote! { type #kernel_trait = crate::backends::vulkan::#ty; }
+ });
+ quote! {
+ #(#modules)*
+
+ macro_rules! autogen_kernels {
+ () => {
+ #(#kernel_types)*
+ }
+ }
+ }
+}
+
+pub fn bindgen(
+ info: &SlangKernel,
+ kernel: &Kernel,
+ variants: &[SlangEntryPointVariant],
+ gpu_type_paths: &GpuTypePaths,
+ gpu_types: &[&GpuTypes],
+) -> anyhow::Result<TokenStream> {
+ let kernel_name: &str = &kernel.name;
+ let struct_name = format_ident!("{kernel_name}VulkanKernel");
+ let first = variants.first().context("kernel has no entry points")?;
+ let abi = &first.abi;
+ let layout = |abi: &SlangEntryPointAbi| {
+ let fields = abi.fields.iter().map(|field| (field.name.clone(), field.offset, field.size)).collect::<Vec<_>>();
+ (abi.block_size, abi.group_size, abi.specialization_ids.clone(), fields)
+ };
+ ensure!(
+ variant_abis(variants).all(|other| layout(other) == layout(abi)),
+ "{kernel_name}: variants differ in layout"
+ );
+ ensure!(abi.block_size <= 256, "{kernel_name}: push-constant block of {} bytes exceeds 256", abi.block_size);
+
+ let type_parameters = kernel
+ .parameters
+ .iter()
+ .filter(|parameter| matches!(parameter.ty, KernelParameterType::Type))
+ .map(|parameter| format_ident!("{}", parameter.name.as_ref()))
+ .collect::<Vec<_>>();
+ let specializations = specialization_constants(kernel_name, kernel, abi, gpu_type_paths)?;
+ let pipeline_variants = pipeline_variant_argument(kernel_name, info, kernel, abi, gpu_types, gpu_type_paths)?;
+ let mut layout_checks = stride_checks(kernel, variants, gpu_type_paths)?;
+ ensure!(
+ kernel.arguments.len() == abi.fields.len() + usize::from(pipeline_variants.is_some()),
+ "{kernel_name}: arguments and reflected fields differ"
+ );
+ let ArgumentEncoding {
+ parameters,
+ packing,
+ reads,
+ writes,
+ } = encode_arguments(
+ kernel_name,
+ kernel,
+ variants,
+ abi,
+ pipeline_variants.as_ref(),
+ gpu_types,
+ gpu_type_paths,
+ &mut layout_checks,
+ )?;
+ let (conditions, specialization_conditions) = presence_checks(kernel_name, info, gpu_type_paths)?;
+ let (new_preconditions, encode_preconditions) =
+ preconditions(kernel_name, kernel, info, gpu_types, gpu_type_paths)?;
+ let Dispatch {
+ grid,
+ group_sizes,
+ axis_sizes,
+ dimensions,
+ } = dispatch_plan(kernel_name, info, abi, gpu_type_paths)?;
+ let grid_count = grid.len();
+
+ let host_expressions = quote! { #(#conditions)* #(#encode_preconditions)* #(#grid)* #axis_sizes };
+ let references = |name: &Ident| find_ident(host_expressions.clone(), &|ident| ident == name).is_some();
+ let (referenced, referenced_types): (Vec<_>, Vec<_>) = specializations
+ .iter()
+ .filter(|specialization| references(&specialization.name))
+ .map(|specialization| (&specialization.name, &specialization.ty))
+ .unzip();
+ let (specialization_names, specialization_types): (Vec<_>, Vec<_>) =
+ specializations.iter().map(|specialization| (&specialization.name, &specialization.ty)).unzip();
+
+ let required_subgroup_size = match info
+ .required_subgroup_size
+ .as_deref()
+ .map(|text| host_expression(kernel_name, gpu_type_paths, text))
+ .transpose()?
+ {
+ Some(size) => quote! { Some(#size) },
+ None => quote! { None },
+ };
+ let PipelineCode {
+ field: pipeline_field,
+ construction,
+ lookup: pipeline,
+ } = pipeline_code(
+ pipeline_variants.as_ref(),
+ &specializations,
+ &referenced,
+ abi.block_size,
+ &required_subgroup_size,
+ )?;
+ let block_size = abi.block_size;
+ let read_count = reads.len();
+ let write_count = writes.len();
+
+ let new_fn = if info.public {
+ format_ident!("create")
+ } else {
+ format_ident!("new")
+ };
+ let encode_fn = if info.public {
+ format_ident!("encode_ranges")
+ } else {
+ format_ident!("encode")
+ };
+ let entry_selection = select_entry(kernel_name, &type_parameters, first, variants)?;
+ let trait_impl = if info.public {
+ public_trait_impl(
+ kernel_name,
+ kernel,
+ gpu_type_paths,
+ &struct_name,
+ &type_parameters,
+ &specializations,
+ &new_fn,
+ &encode_fn,
+ )?
+ } else {
+ quote! {}
+ };
+
+ Ok(quote! {
+ use crate::backends::vulkan::{
+ Error, VkBuffer, VkCommandBufferEncoding, VkComputePipeline, VkComputePipelineKey, VkContext,
+ check_work_group,
+ };
+
+
+ #(#layout_checks)*
+
+ #[allow(non_snake_case)]
+ pub struct #struct_name {
+ #pipeline_field,
+ #(#referenced: #referenced_types,)*
+ }
+
+ impl #struct_name {
+ #[allow(non_snake_case, clippy::too_many_arguments)]
+ pub fn #new_fn(
+ context: &std::sync::Arc<VkContext>
+ #(, #type_parameters: crate::data_type::DataType)*
+ #(, #specialization_names: #specialization_types)*
+ ) -> Result<Self, Error> {
+ let (entry_point, spirv) = #entry_selection;
+ #(#specialization_conditions)*
+ #(#new_preconditions)*
+ check_work_group(
+ context.physical_device(),
+ #kernel_name,
+ [#(#group_sizes),*],
+ #required_subgroup_size,
+ )?;
+ #construction
+ }
+
+ #[allow(non_snake_case, clippy::too_many_arguments)]
+ pub unsafe fn #encode_fn(
+ &self,
+ #(#parameters,)*
+ command_buffer: &mut VkCommandBufferEncoding,
+ ) {
+ #(let #referenced = self.#referenced;)*
+ #(#conditions)*
+ #(#encode_preconditions)*
+ let __dsl_grid: [u32; #grid_count] = [#(#grid),*];
+ if __dsl_grid.contains(&0) {
+ return;
+ }
+ let mut __dsl_block = [0u8; #block_size];
+ #(#packing)*
+ let __dsl_reads: [Option<(&std::sync::Arc<VkBuffer>, std::ops::Range<u64>)>; #read_count] = [#(#reads),*];
+ let __dsl_writes: [Option<(&std::sync::Arc<VkBuffer>, std::ops::Range<u64>)>; #write_count] = [#(#writes),*];
+ unsafe {
+ command_buffer.encode_dispatch(
+ #kernel_name,
+ #pipeline,
+ &__dsl_block,
+ #dimensions,
+ __dsl_reads.into_iter().flatten(),
+ __dsl_writes.into_iter().flatten(),
+ )
+ }
+ }
+ }
+
+ #trait_impl
+ })
+}
+
+struct Specialization {
+ name: Ident,
+ ty: Type,
+ value: TokenStream,
+ id: u32,
+}
+
+struct PipelineVariants {
+ selector: Ident,
+ paths: Vec<TokenStream>,
+ id: u32,
+}
+
+struct ArgumentEncoding {
+ parameters: Vec<TokenStream>,
+ packing: Vec<TokenStream>,
+ reads: Vec<TokenStream>,
+ writes: Vec<TokenStream>,
+}
+
+struct Dispatch {
+ grid: Vec<Expr>,
+ group_sizes: Vec<Expr>,
+ axis_sizes: Option<TokenStream>,
+ dimensions: TokenStream,
+}
+
+struct PipelineCode {
+ field: TokenStream,
+ construction: TokenStream,
+ lookup: TokenStream,
+}
+
+fn specialization_constants(
+ kernel_name: &str,
+ kernel: &Kernel,
+ abi: &SlangEntryPointAbi,
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<Vec<Specialization>> {
+ let mut specializations = Vec::new();
+ for parameter in &kernel.parameters {
+ let KernelParameterType::Value(text) = &parameter.ty else {
+ continue;
+ };
+ let name = format_ident!("{}", parameter.name.as_ref());
+ let ty: Type = gpu_type_paths.resolve_type(text)?;
+ let value = match option_inner(&ty) {
+ Some(inner) => match syn::parse2(word(kernel_name, gpu_type_paths, &name, inner, &["u32"])?)? {
+ Expr::Paren(inner) => {
+ let inner = inner.expr;
+ quote! { #name.map_or(0, |#name| #inner) }
+ },
+ _ => quote! { #name.unwrap_or(0) },
+ },
+ None => word(kernel_name, gpu_type_paths, &name, &ty, &["u32", "bool"])?,
+ };
+ let id = specialization_id(kernel_name, abi, &parameter.name)?;
+ specializations.push(Specialization {
+ name,
+ ty,
+ value,
+ id,
+ });
+ }
+ Ok(specializations)
+}
+
+fn pipeline_variant_argument(
+ kernel_name: &str,
+ info: &SlangKernel,
+ kernel: &Kernel,
+ abi: &SlangEntryPointAbi,
+ gpu_types: &[&GpuTypes],
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<Option<PipelineVariants>> {
+ let mut pipeline_variants = None;
+ for argument in info.arguments.iter().filter(|argument| argument.pipeline_variants) {
+ let name = argument.name.as_str();
+ let Some(KernelArgumentType::Value(text)) =
+ kernel.arguments.iter().find(|candidate| candidate.name.as_ref() == name).map(|argument| &argument.ty)
+ else {
+ bail!("{kernel_name}: PipelineVariants argument '{name}' is not a uniform");
+ };
+ let ty = gpu_type_paths.resolve_type(text)?;
+ let short =
+ (gpu_type_paths.kind_for(text) == Some(GpuTypeKind::Enum)).then_some(&**text).with_context(|| {
+ format!("{kernel_name}: PipelineVariants argument '{name}' has type '{text}', not a canonical GPU enum")
+ })?;
+ let canonical =
+ canonical_enum(gpu_types, short).with_context(|| format!("{kernel_name}: no canonical enum '{short}'"))?;
+ let paths = canonical
+ .variants
+ .iter()
+ .map(|variant| {
+ let variant = format_ident!("{}", variant.name.as_ref());
+ quote! { #ty::#variant }
+ })
+ .collect::<Vec<_>>();
+ pipeline_variants = Some(PipelineVariants {
+ selector: format_ident!("{name}"),
+ paths,
+ id: specialization_id(kernel_name, abi, name)?,
+ });
+ }
+ Ok(pipeline_variants)
+}
+
+fn stride_checks(
+ kernel: &Kernel,
+ variants: &[SlangEntryPointVariant],
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<Vec<TokenStream>> {
+ let mut strides = BTreeSet::new();
+ for abi in variant_abis(variants) {
+ for field in &abi.fields {
+ let buffer = kernel.arguments.iter().any(|argument| {
+ argument.name.as_ref() == field.name && matches!(argument.ty, KernelArgumentType::Buffer(_))
+ });
+ if buffer
+ && let Some(pointee) = &field.layout
+ && gpu_type_paths.kind_for(&pointee.name) != Some(GpuTypeKind::Struct)
+ {
+ strides.insert((data_type(&pointee.name)?.to_string(), pointee.stride));
+ }
+ }
+ }
+ Ok(strides
+ .iter()
+ .map(|(data_type, stride)| {
+ let data_type = format_ident!("{data_type}");
+ quote! { const _: () = assert!(crate::data_type::DataType::#data_type.size_in_bytes() == #stride); }
+ })
+ .collect())
+}
+
+fn canonical_struct<'a>(
+ kernel_name: &str,
+ variants: &[SlangEntryPointVariant],
+ gpu_types: &[&GpuTypes],
+ gpu_type_paths: &'a GpuTypePaths,
+ field: &SlangFieldAbi,
+ layout_checks: &mut Vec<TokenStream>,
+) -> anyhow::Result<Option<(&'a str, Type, usize, usize)>> {
+ let Some(layout) = &field.layout else {
+ return Ok(None);
+ };
+ let pointee = &layout.name;
+ let Some(path) =
+ gpu_type_paths.full_path_for(pointee).filter(|_| gpu_type_paths.kind_for(pointee) == Some(GpuTypeKind::Struct))
+ else {
+ return Ok(None);
+ };
+ let name = &field.name;
+ ensure!(
+ variant_abis(variants).all(|other| other.fields.iter().any(|other| other == field)),
+ "{kernel_name}: variants differ in the layout of '{name}'"
+ );
+ let canonical = canonical_types(gpu_types)
+ .find_map(|candidate| match candidate {
+ GpuType::Struct(candidate) if candidate.name.as_ref() == pointee => Some(candidate),
+ _ => None,
+ })
+ .with_context(|| format!("{kernel_name}: no canonical struct '{pointee}'"))?;
+ let fields = &layout.fields;
+ ensure!(
+ canonical.fields.iter().map(|canonical| canonical.name.as_ref()).eq(fields.iter().map(|field| &field.name)),
+ "{kernel_name}: '{pointee}' fields differ from the canonical struct"
+ );
+ let scalar = |text: &str| match text {
+ "u32" => Some(ScalarType::Uint32),
+ "f32" => Some(ScalarType::Float32),
+ _ => None,
+ };
+ for (canonical, reflected) in canonical.fields.iter().zip(fields) {
+ let (element, length) = match &canonical.ty {
+ GpuTypeStructFieldType::Scalar(element) => (element, None),
+ GpuTypeStructFieldType::Array {
+ element,
+ length,
+ } => (element, Some((*length, 4))),
+ };
+ ensure!(
+ scalar(element) == Some(reflected.scalar) && reflected.array == length,
+ "{kernel_name}: field {pointee}.{} is {element} {length:?} in Rust but {:?} {:?} in Slang",
+ reflected.name,
+ reflected.scalar,
+ reflected.array
+ );
+ }
+ let ty: Type = syn::parse_str(path)?;
+ let message = format!("{kernel_name}: {path} does not have the layout Slang reflects");
+ let stride = layout.stride;
+ let alignment = layout.alignment;
+ layout_checks.push(quote! {
+ const _: () = assert!(size_of::<#ty>() == #stride && align_of::<#ty>() == #alignment, #message);
+ });
+ for (canonical, reflected) in canonical.fields.iter().zip(fields) {
+ let field_type: Type = match &canonical.ty {
+ GpuTypeStructFieldType::Scalar(element) => syn::parse_str(element)?,
+ GpuTypeStructFieldType::Array {
+ element,
+ length,
+ } => syn::parse_str(&format!("[{element}; {length}]"))?,
+ };
+ let field_name = format_ident!("{}", reflected.name);
+ let offset = reflected.offset;
+ let size = reflected.size;
+ layout_checks.push(quote! {
+ const _: () = assert!(
+ std::mem::offset_of!(#ty, #field_name) == #offset && size_of::<#field_type>() == #size,
+ #message
+ );
+ });
+ }
+ Ok(Some((path, ty, stride, alignment)))
+}
+
+fn encode_arguments(
+ kernel_name: &str,
+ kernel: &Kernel,
+ variants: &[SlangEntryPointVariant],
+ abi: &SlangEntryPointAbi,
+ pipeline_variants: Option<&PipelineVariants>,
+ gpu_types: &[&GpuTypes],
+ gpu_type_paths: &GpuTypePaths,
+ layout_checks: &mut Vec<TokenStream>,
+) -> anyhow::Result<ArgumentEncoding> {
+ let mut parameters = Vec::new();
+ let mut packing = Vec::new();
+ let mut reads = Vec::new();
+ let mut writes = Vec::new();
+ for argument in &kernel.arguments {
+ let name = format_ident!("{}", argument.name.as_ref());
+ if let Some(PipelineVariants {
+ selector,
+ ..
+ }) = pipeline_variants
+ && let KernelArgumentType::Value(text) = &argument.ty
+ && *selector == name
+ {
+ let ty: Type = gpu_type_paths.resolve_type(text)?;
+ parameters.push(quote! { #name: #ty });
+ continue;
+ }
+ let field = abi
+ .fields
+ .iter()
+ .find(|field| field.name == argument.name.as_ref())
+ .with_context(|| format!("{kernel_name}: no reflected field for '{name}'"))?;
+ let start = field.offset;
+ let end = start + field.size;
+ let canonical = canonical_struct(kernel_name, variants, gpu_types, gpu_type_paths, field, layout_checks)?;
+ let (argument_type, bytes) = match (&argument.ty, canonical) {
+ (KernelArgumentType::Buffer(access), _) => {
+ ensure!(field.size == 8 && field.layout.is_some(), "{kernel_name}: '{name}' is not a device address");
+ let declared = if argument.conditional {
+ quote! { #name.clone() }
+ } else {
+ quote! { Some(#name.clone()) }
+ };
+ match access {
+ KernelBufferAccess::Read => reads.push(declared),
+ KernelBufferAccess::ReadWrite => writes.push(declared),
+ }
+ let address = if argument.conditional {
+ quote! { #name.as_ref().map_or(0, |(buffer, range)| buffer.device_address() + range.start) }
+ } else {
+ quote! { (#name.0.device_address() + #name.1.start) }
+ };
+ (quote! { (&std::sync::Arc<VkBuffer>, std::ops::Range<u64>) }, quote! { #address.to_ne_bytes() })
+ },
+ (KernelArgumentType::Value(text), Some((path, ty, stride, _)))
+ if gpu_type_paths.full_path_for(text) == Some(path) =>
+ {
+ ensure!(field.size == stride, "{kernel_name}: '{name}' of {} bytes is not one {path}", field.size);
+ let cast = quote! { bytemuck::cast::<#ty, [u8; #stride]> };
+ let bytes = if argument.conditional {
+ quote! { #name.map_or([0; #stride], #cast) }
+ } else {
+ quote! { #cast(#name) }
+ };
+ (quote! { #ty }, bytes)
+ },
+ (KernelArgumentType::Value(text), Some((path, ty, _, alignment))) => {
+ ensure!(
+ field.size == 8
+ && !argument.conditional
+ && gpu_type_paths.resolve_type(text)? == parse_quote! { &[#ty] },
+ "{kernel_name}: '{name}' of type '{text}' is not a device address of a canonical '{path}' slice"
+ );
+ ensure!(alignment <= 64, "{kernel_name}: '{path}' needs alignment {alignment} above 64");
+ packing.push(quote! { let #name = command_buffer.upload(#name); });
+ reads.push(quote! { #name.as_ref().map(|(buffer, range)| (buffer, range.clone())) });
+ let address =
+ quote! { #name.as_ref().map_or(0, |(buffer, range)| buffer.device_address() + range.start) };
+ (quote! { &[#ty] }, quote! { #address.to_ne_bytes() })
+ },
+ (KernelArgumentType::Value(text), _) => {
+ ensure!(field.size == 4 && field.layout.is_none(), "{kernel_name}: '{name}' is not a 4-byte {text}");
+ let ty: Type = gpu_type_paths.resolve_type(text)?;
+ let value = word(kernel_name, gpu_type_paths, &name, &ty, &["u32", "i32", "f32", "bool"])?;
+ let bytes = if argument.conditional {
+ quote! { #name.map_or([0; 4], |#name| #value.to_ne_bytes()) }
+ } else {
+ quote! { #value.to_ne_bytes() }
+ };
+ (quote! { #ty }, bytes)
+ },
+ };
+ parameters.push(if argument.conditional {
+ quote! { #name: Option<#argument_type> }
+ } else {
+ quote! { #name: #argument_type }
+ });
+ packing.push(quote! { __dsl_block[#start..#end].copy_from_slice(&#bytes); });
+ }
+ Ok(ArgumentEncoding {
+ parameters,
+ packing,
+ reads,
+ writes,
+ })
+}
+
+fn presence_checks(
+ kernel_name: &str,
+ info: &SlangKernel,
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<(Vec<TokenStream>, Vec<TokenStream>)> {
+ let mut conditions = Vec::new();
+ let mut specialization_conditions = Vec::new();
+ for argument in &info.arguments {
+ let (SlangArgumentType::Buffer {
+ condition,
+ ..
+ }
+ | SlangArgumentType::Uniform {
+ condition,
+ }
+ | SlangArgumentType::Specialize {
+ condition,
+ }) = &argument.argument_type
+ else {
+ continue;
+ };
+ let Some(condition) = condition else {
+ continue;
+ };
+ let name = format_ident!("{}", argument.name);
+ let condition = host_expression(kernel_name, gpu_type_paths, condition)?;
+ let message =
+ format!("{kernel_name}: argument '{name}' must be present exactly when {}", quote! { #condition });
+ let check = quote! { assert_eq!(#name.is_some(), #condition, "{}", #message); };
+ match argument.argument_type {
+ SlangArgumentType::Specialize {
+ ..
+ } => specialization_conditions.push(check),
+ _ => conditions.push(check),
+ }
+ }
+ Ok((conditions, specialization_conditions))
+}
+
+fn preconditions(
+ kernel_name: &str,
+ kernel: &Kernel,
+ info: &SlangKernel,
+ gpu_types: &[&GpuTypes],
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<(Vec<TokenStream>, Vec<TokenStream>)> {
+ let names = |constants: bool| {
+ let parameters = kernel.parameters.iter().filter(|parameter| match parameter.ty {
+ KernelParameterType::Value(_) => true,
+ KernelParameterType::Type => !constants,
+ });
+ let parameters = parameters.map(|parameter| parameter.name.as_ref());
+ let uniforms =
+ kernel.arguments.iter().filter(|argument| constants && matches!(argument.ty, KernelArgumentType::Value(_)));
+ parameters.chain(uniforms.map(|argument| argument.name.as_ref())).map(str::to_string).collect::<BTreeSet<_>>()
+ };
+ let is_variant = |path: &syn::Path| {
+ let segments = path.segments.iter().map(|segment| segment.ident.to_string());
+ segments.collect_tuple().is_some_and(|(head, variant): (String, String)| {
+ canonical_enum(gpu_types, &head)
+ .is_some_and(|candidate| candidate.variants.iter().any(|known| *known.name == *variant))
+ })
+ };
+ let capability = |path: &syn::Path| path.segments.len() == 2 && path.segments[0].ident == "VkDeviceCapabilities";
+ let is_constant = |path: &syn::Path| {
+ let text = path.to_token_stream().to_string().replace(' ', "");
+ gpu_types.iter().any(|types| {
+ types.files.iter().any(|file| {
+ file.types.iter().any(|ty| {
+ matches!(ty, GpuType::Constant(constant)
+ if text == format!("{}::{}::{}", types.module_path, file.name, constant.name))
+ })
+ })
+ })
+ };
+ let mut new_preconditions = Vec::new();
+ let mut encode_preconditions = Vec::new();
+ for (phase, text) in &info.preconditions {
+ let phase = phase.as_str();
+ let text = text.as_str();
+ let construction = phase == "new";
+ let mut known = names(!construction);
+ if construction {
+ known.insert("context".to_owned());
+ }
+ let mut unknown = Vec::new();
+ let mut parsed = syn::parse_str::<Expr>(text)
+ .with_context(|| format!("{kernel_name}: malformed {phase} Precondition '{text}'"))?;
+ rewrite_paths_with(&mut parsed, |path| {
+ let single = path.get_ident().is_some_and(|ident| known.contains(&ident.to_string()));
+ if !single && !is_variant(path) && !is_constant(path) && !(construction && capability(path)) {
+ unknown.push(path.to_token_stream().to_string());
+ }
+ None
+ });
+ ensure!(unknown.is_empty(), "{kernel_name}: {phase} Precondition '{text}' names unknown {unknown:?}");
+ let mut condition = host_expression(kernel_name, gpu_type_paths, text)?;
+ rewrite_paths_with(&mut condition, |path| {
+ capability(path).then(|| parse_quote! { crate::backends::vulkan::#path })
+ });
+ match phase {
+ "new" => new_preconditions.push(quote! {
+ if !(#condition) {
+ return Err(crate::backends::vulkan::VkKernelError::KernelPrecondition {
+ kernel: #kernel_name,
+ condition: #text,
+ }.into());
+ }
+ }),
+ _ => {
+ let message = format!("{kernel_name}: precondition {text} violated");
+ encode_preconditions.push(quote! { assert!(#condition, "{}", #message); });
+ },
+ }
+ }
+ Ok((new_preconditions, encode_preconditions))
+}
+
+fn dispatch_plan(
+ kernel_name: &str,
+ info: &SlangKernel,
+ abi: &SlangEntryPointAbi,
+ gpu_type_paths: &GpuTypePaths,
+) -> anyhow::Result<Dispatch> {
+ let mut axes = Vec::new();
+ let mut groups = Vec::new();
+ let mut group_sizes = Vec::new();
+ for argument in &info.arguments {
+ match &argument.argument_type {
+ SlangArgumentType::Axis {
+ threads: total,
+ threads_in_group: size,
+ } => {
+ axes.push(host_expression(kernel_name, gpu_type_paths, total)?);
+ group_sizes.push(host_expression(kernel_name, gpu_type_paths, size)?);
+ },
+ SlangArgumentType::Groups {
+ groups: count,
+ } => groups.push(host_expression(kernel_name, gpu_type_paths, count)?),
+ SlangArgumentType::Threads {
+ threads: size,
+ } => group_sizes.push(host_expression(kernel_name, gpu_type_paths, size)?),
+ SlangArgumentType::Buffer {
+ ..
+ }
+ | SlangArgumentType::Uniform {
+ ..
+ }
+ | SlangArgumentType::Specialize {
+ ..
+ }
+ | SlangArgumentType::ThreadContext => {},
+ }
+ }
+ let axis = !axes.is_empty();
+ let grid = if axis {
+ axes
+ } else {
+ groups
+ };
+ while group_sizes.len() < 3 {
+ group_sizes.push(parse_quote! { 1u32 });
+ }
+ ensure!(group_sizes.len() == 3, "{kernel_name}: workgroup has more than three dimensions");
+ let counts = (0..3)
+ .map(|index| match (index < grid.len(), abi.group_size[index]) {
+ (true, _) if axis => {
+ let size = &group_sizes[index];
+ Ok(quote! { __dsl_grid[#index].div_ceil(#size) })
+ },
+ (true, _) => Ok(quote! { __dsl_grid[#index] }),
+ (false, size) if !axis || size == 1 => Ok(quote! { 1 }),
+ (false, size) => bail!("{kernel_name}: reflected group size {size} on undispatched axis {index}"),
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ let dimensions = if axis && grid.len() == 1 {
+ let groups = &counts[0];
+ let fold = AXIS_FOLD_GROUPS;
+ quote! {{
+ let __dsl_groups: u32 = #groups;
+ if __dsl_groups > #fold { [#fold, __dsl_groups.div_ceil(#fold), 1] } else { [__dsl_groups, 1, 1] }
+ }}
+ } else {
+ quote! { [#(#counts),*] }
+ };
+ let axis_sizes = axis.then(|| quote! { #(#group_sizes)* });
+ Ok(Dispatch {
+ grid,
+ group_sizes,
+ axis_sizes,
+ dimensions,
+ })
+}
+
+fn pipeline_code(
+ pipeline_variants: Option<&PipelineVariants>,
+ specializations: &[Specialization],
+ referenced: &[&Ident],
+ block_size: usize,
+ required_subgroup_size: &TokenStream,
+) -> anyhow::Result<PipelineCode> {
+ let block_size = u32::try_from(block_size)?;
+ let specialization = specializations
+ .iter()
+ .map(|specialization| {
+ let id = specialization.id;
+ let value = &specialization.value;
+ quote! { (#id, #value) }
+ })
+ .collect::<Vec<_>>();
+ let key = |variant: Option<TokenStream>| {
+ quote! {
+ VkComputePipelineKey {
+ spirv,
+ entry_point,
+ specialization: vec![#(#specialization,)* #variant],
+ push_constant_size: #block_size,
+ required_subgroup_size: #required_subgroup_size,
+ }
+ }
+ };
+ Ok(match pipeline_variants {
+ None => {
+ let key = key(None);
+ PipelineCode {
+ field: quote! { pipeline: std::sync::Arc<VkComputePipeline> },
+ construction: quote! {
+ let pipeline = context.compute_pipeline(#key)?;
+ Ok(Self {
+ pipeline,
+ #(#referenced,)*
+ })
+ },
+ lookup: quote! { &self.pipeline },
+ }
+ },
+ Some(PipelineVariants {
+ selector,
+ paths,
+ id,
+ }) => {
+ let count = paths.len();
+ let indices = 0..count;
+ let keys = paths.iter().map(|path| key(Some(quote! { (#id, #path as u32) })));
+ PipelineCode {
+ field: quote! { pipelines: [std::sync::Arc<VkComputePipeline>; #count] },
+ construction: quote! {
+ let pipelines = [#(context.compute_pipeline(#keys)?),*];
+ Ok(Self {
+ pipelines,
+ #(#referenced,)*
+ })
+ },
+ lookup: quote! { match #selector { #(#paths => &self.pipelines[#indices],)* } },
+ }
+ },
+ })
+}
+
+fn select_entry(
+ kernel_name: &str,
+ type_parameters: &[Ident],
+ first: &SlangEntryPointVariant,
+ variants: &[SlangEntryPointVariant],
+) -> anyhow::Result<TokenStream> {
+ if type_parameters.is_empty() {
+ let entry_point = &first.abi.name;
+ let spirv = entry_spirv(&first.spirv, &first.native_bf16);
+ return Ok(quote! { (#entry_point, #spirv) });
+ }
+ let entry_arms = variants
+ .iter()
+ .map(|variant| {
+ let data_types = variant.types.iter().map(|ty| data_type(ty)).collect::<Result<Vec<_>, _>>()?;
+ let entry_point = &variant.abi.name;
+ let spirv = entry_spirv(&variant.spirv, &variant.native_bf16);
+ Ok(quote! { (#(crate::data_type::DataType::#data_types,)*) => (#entry_point, #spirv) })
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ Ok(quote! {
+ match (#(#type_parameters,)*) {
+ #(#entry_arms,)*
+ _ => return Err(crate::backends::vulkan::VkKernelError::KernelVariant {
+ kernel: #kernel_name,
+ data_types: Box::new([#(#type_parameters),*]),
+ }.into()),
+ }
+ })
+}
+
+fn public_trait_impl(
+ kernel_name: &str,
+ kernel: &Kernel,
+ gpu_type_paths: &GpuTypePaths,
+ struct_name: &Ident,
+ type_parameters: &[Ident],
+ specializations: &[Specialization],
+ new_fn: &Ident,
+ encode_fn: &Ident,
+) -> anyhow::Result<TokenStream> {
+ let kernel_trait = format_ident!("{kernel_name}Kernel");
+ let new_parameters = kernel
+ .parameters
+ .iter()
+ .map(|parameter| {
+ let name = format_ident!("{}", parameter.name.as_ref());
+ Ok(match &parameter.ty {
+ KernelParameterType::Type => quote! { #name: crate::data_type::DataType },
+ KernelParameterType::Value(text) => {
+ let ty: Type = gpu_type_paths.resolve_type(text)?;
+ quote! { #name: #ty }
+ },
+ })
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ let mut trait_arguments = Vec::new();
+ let mut conversions = Vec::new();
+ let mut call_arguments = Vec::new();
+ for argument in &kernel.arguments {
+ let name = format_ident!("{}", argument.name.as_ref());
+ let ty = match &argument.ty {
+ KernelArgumentType::Buffer(access) => {
+ let reference = match access {
+ KernelBufferAccess::Read => quote! { crate::backends::common::BufferRef },
+ KernelBufferAccess::ReadWrite => quote! { crate::backends::common::BufferMut },
+ };
+ let resolve = quote! {{
+ let (buffer, range) = #reference::parts(#name);
+ VkBuffer::resolve(buffer, range)
+ }};
+ conversions.push(if argument.conditional {
+ quote! { let #name = #name.map(|#name| #resolve); }
+ } else {
+ quote! { let #name = #resolve; }
+ });
+ quote! { impl #reference<Backend = crate::backends::vulkan::Vulkan> }
+ },
+ KernelArgumentType::Value(text) => {
+ let ty: Type = gpu_type_paths.resolve_type(text)?;
+ quote! { #ty }
+ },
+ };
+ trait_arguments.push(if argument.conditional {
+ quote! { #name: Option<#ty> }
+ } else {
+ quote! { #name: #ty }
+ });
+ call_arguments.push(name);
+ }
+ let specialization_names = specializations.iter().map(|specialization| &specialization.name);
+ Ok(quote! {
+ #[allow(clippy::style, clippy::complexity, clippy::perf)]
+ impl crate::backends::common::kernel::#kernel_trait for #struct_name {
+ type Backend = crate::backends::vulkan::Vulkan;
+
+ #[allow(non_snake_case)]
+ fn new(context: &VkContext #(, #new_parameters)*) -> Result<Self, Error> {
+ #struct_name::#new_fn(&context.arc() #(, #type_parameters)* #(, #specialization_names)*)
+ }
+
+ fn encode(&self, #(#trait_arguments,)* command_buffer: &mut VkCommandBufferEncoding) {
+ #(#conversions)*
+ unsafe { #struct_name::#encode_fn(self, #(#call_arguments,)* command_buffer) }
+ }
+ }
+ })
+}
+
+fn canonical_types<'a>(gpu_types: &[&'a GpuTypes]) -> impl Iterator<Item = &'a GpuType> {
+ gpu_types.iter().flat_map(|types| types.files.iter()).flat_map(|file| &file.types)
+}
+
+fn canonical_enum<'a>(
+ gpu_types: &[&'a GpuTypes],
+ short: &str,
+) -> Option<&'a GpuTypeEnum> {
+ canonical_types(gpu_types).find_map(|candidate| match candidate {
+ GpuType::Enum(candidate) if candidate.name.as_ref() == short => Some(candidate),
+ _ => None,
+ })
+}
+
+fn variant_abis(variants: &[SlangEntryPointVariant]) -> impl Iterator<Item = &SlangEntryPointAbi> {
+ variants.iter().flat_map(|variant| once(&variant.abi).chain(variant.native_bf16.iter().map(|(abi, _)| abi)))
+}
+
+fn specialization_id(
+ kernel_name: &str,
+ abi: &SlangEntryPointAbi,
+ argument: &str,
+) -> anyhow::Result<u32> {
+ let constant = specialization_name(kernel_name, argument);
+ abi.specialization_ids
+ .iter()
+ .find_map(|(name, id)| (*name == constant).then_some(*id))
+ .with_context(|| format!("{kernel_name}: no specialization constant '{constant}'"))
+}
+
+fn host_expression(
+ kernel_name: &str,
+ gpu_type_paths: &GpuTypePaths,
+ text: &str,
+) -> anyhow::Result<Expr> {
+ let mut expression =
+ syn::parse_str::<Expr>(text).with_context(|| format!("{kernel_name}: malformed host expression '{text}'"))?;
+ rewrite_paths_with(&mut expression, |path| qualify_enum_path(path, gpu_type_paths));
+ Ok(expression)
+}
+
+fn word(
+ kernel_name: &str,
+ gpu_type_paths: &GpuTypePaths,
+ name: &Ident,
+ ty: &Type,
+ scalars: &[&str],
+) -> anyhow::Result<TokenStream> {
+ let text = ty.to_token_stream().to_string().replace(" :: ", "::");
+ match text.as_str() {
+ _ if canonical_enum_name(gpu_type_paths, &text).is_some() => Ok(quote! { (#name as u32) }),
+ "bool" if scalars.contains(&"bool") => Ok(quote! { u32::from(#name) }),
+ scalar if scalars.contains(&scalar) => Ok(quote! { #name }),
+ other => bail!("{kernel_name}: unsupported type '{other}' for '{name}'"),
+ }
+}
+
+fn entry_spirv(
+ object: &str,
+ native: &Option<(SlangEntryPointAbi, String)>,
+) -> TokenStream {
+ match native {
+ Some((_, native)) => quote! {
+ if context.physical_device().capabilities.contains(crate::backends::vulkan::VkDeviceCapabilities::BF16_TYPE) {
+ include_bytes!(#native) as &[u8]
+ } else {
+ include_bytes!(#object) as &[u8]
+ }
+ },
+ None => quote! { include_bytes!(#object) as &[u8] },
+ }
+}
+
+fn data_type(slang_type: &str) -> anyhow::Result<Ident> {
+ slang2rust(slang_type, &HashMap::new())
+ .map(|rust_type| format_ident!("{}", rust_type.to_uppercase()))
+ .with_context(|| format!("no DataType for GPU type '{slang_type}'"))
+}
+
+fn binding_module(kernel_name: &str) -> Ident {
+ let mut module = String::new();
+ for (index, character) in kernel_name.chars().enumerate() {
+ if character.is_ascii_uppercase() && index > 0 {
+ module.push('_');
+ }
+ module.push(character.to_ascii_lowercase());
+ }
+ format_ident!("{module}_vulkan_kernel")
+}
+
+fn option_inner(ty: &Type) -> Option<&Type> {
+ let Type::Path(path) = ty else {
+ return None;
+ };
+ let segment = path.path.segments.iter().exactly_one().ok().filter(|segment| segment.ident == "Option")?;
+ let PathArguments::AngleBracketed(arguments) = &segment.arguments else {
+ return None;
+ };
+ match arguments.args.iter().exactly_one().ok()? {
+ GenericArgument::Type(inner) => Some(inner),
+ _ => None,
+ }
+}
+
+fn canonical_enum_name<'a>(
+ gpu_type_paths: &GpuTypePaths,
+ path: &'a str,
+) -> Option<&'a str> {
+ let (_, short) = path.rsplit_once("::")?;
+ (gpu_type_paths.full_path_for(short) == Some(path) && gpu_type_paths.kind_for(short) == Some(GpuTypeKind::Enum))
+ .then_some(short)
+}
+
+fn find_ident(
+ tokens: TokenStream,
+ predicate: &impl Fn(&Ident) -> bool,
+) -> Option<Ident> {
+ tokens.into_iter().find_map(|token| match token {
+ TokenTree::Ident(ident) => Some(ident).filter(predicate),
+ TokenTree::Group(group) => find_ident(group.stream(), predicate),
+ _ => None,
+ })
+}
diff --git a/crates/uzu-engine/build/vulkan/mod.rs b/crates/uzu-engine/build/vulkan/mod.rs
new file mode 100644
index 000000000..9f214183b
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/mod.rs
@@ -0,0 +1,15 @@
+mod bindgen;
+mod slang_entry_point_abi;
+mod slang_entry_point_variant;
+mod slang_field_abi;
+mod slang_pointee_abi;
+mod slang_struct_field_abi;
+mod spirv_hash;
+mod vulkan_target;
+
+pub use slang_entry_point_abi::SlangEntryPointAbi;
+pub use slang_entry_point_variant::SlangEntryPointVariant;
+pub use slang_field_abi::SlangFieldAbi;
+pub use slang_pointee_abi::SlangPointeeAbi;
+pub use slang_struct_field_abi::SlangStructFieldAbi;
+pub use vulkan_target::VulkanTarget;
diff --git a/crates/uzu-engine/build/vulkan/slang_entry_point_abi.rs b/crates/uzu-engine/build/vulkan/slang_entry_point_abi.rs
new file mode 100644
index 000000000..3241882a5
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/slang_entry_point_abi.rs
@@ -0,0 +1,151 @@
+use std::collections::BTreeMap;
+
+use anyhow::{Context, bail, ensure};
+use itertools::Itertools;
+use shader_slang::{
+ ParameterCategory, ScalarType, TypeKind,
+ reflection::{EntryPoint, Shader},
+};
+
+use crate::vulkan::{SlangFieldAbi, SlangPointeeAbi, SlangStructFieldAbi};
+
+#[derive(Debug)]
+pub struct SlangEntryPointAbi {
+ pub name: String,
+ pub group_size: [u32; 3],
+ pub block_size: usize,
+ pub fields: Vec<SlangFieldAbi>,
+ pub specialization_ids: Vec<(String, u32)>,
+}
+
+impl SlangEntryPointAbi {
+ pub fn from_reflection(
+ program: &Shader,
+ entry_point: &EntryPoint,
+ declared: &BTreeMap<String, ScalarType>,
+ ) -> anyhow::Result<Self> {
+ let name = entry_point.name().context("Slang entry point has no name")?.to_owned();
+ let block = entry_point.type_layout().context("Slang entry point has no layout")?;
+ let block_size = if block.categories().any(|category| matches!(category, ParameterCategory::PushConstantBuffer))
+ {
+ ensure!(matches!(block.kind(), TypeKind::ConstantBuffer), "'{name}': push constants are not a block");
+ block
+ .element_type_layout()
+ .context("push-constant block has no element layout")?
+ .size(ParameterCategory::Uniform)
+ } else {
+ 0
+ };
+
+ let mut fields = Vec::new();
+ for parameter in entry_point.parameters() {
+ let parameter_name = parameter.name().context("Slang entry point parameter has no name")?;
+ let layout = parameter.type_layout().context("Slang entry point parameter has no layout")?;
+ match layout.categories().collect::<Vec<_>>().as_slice() {
+ [] if parameter.semantic_name().is_some() => continue,
+ [ParameterCategory::Uniform] => {},
+ categories => bail!("'{name}': parameter '{parameter_name}' has unsupported categories {categories:?}"),
+ }
+ let described = match layout.kind() {
+ TypeKind::Pointer => Some(layout.element_type_layout().context("pointer has no pointee layout")?),
+ TypeKind::Struct => Some(layout),
+ TypeKind::Scalar | TypeKind::Enum => None,
+ kind => bail!("'{name}': parameter '{parameter_name}' has unsupported kind {kind:?}"),
+ };
+ let described = match described {
+ Some(pointee) => {
+ let stride = pointee.stride(ParameterCategory::Uniform);
+ let alignment = usize::try_from(pointee.alignment(ParameterCategory::Uniform))?;
+ ensure!(
+ alignment > 0 && stride > 0 && stride.is_multiple_of(alignment),
+ "'{name}': pointee of '{parameter_name}' has stride {stride} and alignment {alignment}"
+ );
+ let fields = pointee
+ .fields()
+ .map(|field| {
+ let field_name = field.name().context("pointee field has no name")?.to_owned();
+ let layout = field.type_layout().context("pointee field has no layout")?;
+ let (element, array) = match layout.kind() {
+ TypeKind::Scalar => (layout, None),
+ TypeKind::Array => {
+ let element =
+ layout.element_type_layout().context("array has no element layout")?;
+ let count = layout.element_count().context("array has no element count")?;
+ (element, Some((count, layout.element_stride(ParameterCategory::Uniform))))
+ },
+ kind => bail!(
+ "'{name}': field '{field_name}' of '{parameter_name}' has unsupported kind {kind:?}"
+ ),
+ };
+ ensure!(
+ matches!(element.kind(), TypeKind::Scalar),
+ "'{name}': field '{field_name}' of '{parameter_name}' is not of scalars"
+ );
+ Ok(SlangStructFieldAbi {
+ name: field_name,
+ offset: field.offset(ParameterCategory::Uniform),
+ size: layout.size(ParameterCategory::Uniform),
+ scalar: element.scalar_type().context("scalar has no type")?,
+ array,
+ })
+ })
+ .collect::<anyhow::Result<_>>()?;
+ let name = pointee.name().context("pointee has no name")?.to_owned();
+ Some(SlangPointeeAbi {
+ name,
+ stride,
+ alignment,
+ fields,
+ })
+ },
+ None => None,
+ };
+ fields.push(SlangFieldAbi {
+ name: parameter_name.to_owned(),
+ offset: parameter.offset(ParameterCategory::Uniform),
+ size: layout.size(ParameterCategory::Uniform),
+ layout: described,
+ });
+ }
+ let mut end = 0;
+ for field in fields.iter().sorted_by_key(|field| field.offset) {
+ ensure!(field.size > 0 && field.offset >= end, "'{name}': argument '{}' overlaps another", field.name);
+ end = field.offset + field.size;
+ }
+ ensure!(end <= block_size && block_size.is_multiple_of(4), "'{name}': block of {block_size} bytes holds {end}");
+
+ let specialization_ids = program
+ .parameters()
+ .map(|parameter| {
+ let parameter_name = parameter.name().context("Slang global parameter has no name")?;
+ let layout = parameter.type_layout().context("Slang global parameter has no layout")?;
+ let wire = declared.get(parameter_name).with_context(|| {
+ format!("'{name}': global '{parameter_name}' is not a specialization of a kernel in this module")
+ })?;
+ ensure!(
+ matches!(
+ layout.categories().collect::<Vec<_>>().as_slice(),
+ [ParameterCategory::SpecializationConstant]
+ ) && layout.scalar_type() == Some(*wire),
+ "'{name}': global '{parameter_name}' is not a {wire:?} specialization constant"
+ );
+ Ok((
+ parameter_name.to_owned(),
+ u32::try_from(parameter.offset(ParameterCategory::SpecializationConstant))?,
+ ))
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ if let Some(global) = specialization_ids.iter().map(|(global, _)| global).duplicates().next() {
+ bail!("'{name}': global '{global}' is linked as more than one specialization constant");
+ }
+
+ let [x, y, z] = entry_point.compute_thread_group_size();
+ Ok(Self {
+ name,
+ group_size: [u32::try_from(x)?, u32::try_from(y)?, u32::try_from(z)?],
+ block_size,
+ fields,
+ specialization_ids,
+ })
+ }
+}
diff --git a/crates/uzu-engine/build/vulkan/slang_entry_point_variant.rs b/crates/uzu-engine/build/vulkan/slang_entry_point_variant.rs
new file mode 100644
index 000000000..c9188413f
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/slang_entry_point_variant.rs
@@ -0,0 +1,8 @@
+use crate::vulkan::SlangEntryPointAbi;
+
+pub struct SlangEntryPointVariant {
+ pub types: Vec<String>,
+ pub abi: SlangEntryPointAbi,
+ pub spirv: String,
+ pub native_bf16: Option<(SlangEntryPointAbi, String)>,
+}
diff --git a/crates/uzu-engine/build/vulkan/slang_field_abi.rs b/crates/uzu-engine/build/vulkan/slang_field_abi.rs
new file mode 100644
index 000000000..58c492e39
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/slang_field_abi.rs
@@ -0,0 +1,9 @@
+use crate::vulkan::SlangPointeeAbi;
+
+#[derive(Debug, PartialEq)]
+pub struct SlangFieldAbi {
+ pub name: String,
+ pub offset: usize,
+ pub size: usize,
+ pub layout: Option<SlangPointeeAbi>,
+}
diff --git a/crates/uzu-engine/build/vulkan/slang_pointee_abi.rs b/crates/uzu-engine/build/vulkan/slang_pointee_abi.rs
new file mode 100644
index 000000000..ee90921a5
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/slang_pointee_abi.rs
@@ -0,0 +1,9 @@
+use crate::vulkan::SlangStructFieldAbi;
+
+#[derive(Debug, PartialEq)]
+pub struct SlangPointeeAbi {
+ pub name: String,
+ pub stride: usize,
+ pub alignment: usize,
+ pub fields: Vec<SlangStructFieldAbi>,
+}
diff --git a/crates/uzu-engine/build/vulkan/slang_struct_field_abi.rs b/crates/uzu-engine/build/vulkan/slang_struct_field_abi.rs
new file mode 100644
index 000000000..28134680a
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/slang_struct_field_abi.rs
@@ -0,0 +1,10 @@
+use shader_slang::ScalarType;
+
+#[derive(Debug, PartialEq)]
+pub struct SlangStructFieldAbi {
+ pub name: String,
+ pub offset: usize,
+ pub size: usize,
+ pub scalar: ScalarType,
+ pub array: Option<(usize, usize)>,
+}
diff --git a/crates/uzu-engine/build/vulkan/spirv_hash.rs b/crates/uzu-engine/build/vulkan/spirv_hash.rs
new file mode 100644
index 000000000..5b1277e13
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/spirv_hash.rs
@@ -0,0 +1,16 @@
+use std::{fs, path::Path};
+
+use anyhow::Context;
+use walkdir::WalkDir;
+
+pub fn export_spirv_hash(output_directory: &Path) -> anyhow::Result<()> {
+ let mut spirv = blake3::Hasher::new();
+ for entry in WalkDir::new(output_directory).sort_by_file_name() {
+ let path = entry.with_context(|| format!("cannot walk {}", output_directory.display()))?.into_path();
+ if path.extension().is_some_and(|extension| extension == "spv") {
+ spirv.update(&fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?);
+ }
+ }
+ println!("cargo::rustc-env=UZU_VULKAN_SPIRV_HASH={}", &spirv.finalize().to_hex()[..16]);
+ Ok(())
+}
diff --git a/crates/uzu-engine/build/vulkan/vulkan_target.rs b/crates/uzu-engine/build/vulkan/vulkan_target.rs
new file mode 100644
index 000000000..0aa1932e0
--- /dev/null
+++ b/crates/uzu-engine/build/vulkan/vulkan_target.rs
@@ -0,0 +1,341 @@
+use std::{
+ collections::{BTreeMap, HashSet},
+ fs,
+ iter::once,
+ path::{Path, PathBuf},
+};
+
+use anyhow::Context;
+use itertools::Itertools;
+use proc_macro2::TokenStream;
+use shader_slang::{
+ Blob, CompileTarget, CompilerOptions, ComponentType, GlobalSession, Module, ScalarType, TargetDesc,
+};
+use spirv::{Capability, Op};
+use syn::{BinOp, Expr};
+
+use crate::{
+ common::{codegen::write_tokens, identifiers::KernelName, kernel::Kernel, mangling::static_mangle},
+ slang::{
+ BlockingSlangCompiler, SlangArgumentType, SlangCompilerFields, SlangGpuTypes, SlangKernel, SlangParameterType,
+ SlangTarget, kernel_wrappers, specialization_name,
+ },
+ vulkan::{SlangEntryPointAbi, SlangEntryPointVariant, bindgen, spirv_hash::export_spirv_hash},
+};
+
+const DEVICE_CAPABILITIES: [Capability; 15] = [
+ Capability::Shader,
+ Capability::Float16,
+ Capability::Int16,
+ Capability::Int8,
+ Capability::GroupNonUniform,
+ Capability::GroupNonUniformArithmetic,
+ Capability::GroupNonUniformBallot,
+ Capability::GroupNonUniformShuffle,
+ Capability::SignedZeroInfNanPreserve,
+ Capability::RoundingModeRTE,
+ Capability::VulkanMemoryModel,
+ Capability::VulkanMemoryModelDeviceScope,
+ Capability::PhysicalStorageBufferAddresses,
+ Capability::DotProductInput4x8BitPacked,
+ Capability::DotProduct,
+];
+const GATED_CAPABILITIES: [(Capability, &[&str]); 4] = [
+ (
+ Capability::CooperativeMatrixKHR,
+ &["BF16_TENSOR_CORES", "INT8_TENSOR_CORES_K32", "INT8_TENSOR_CORES_K16", "float_tensor_cores"],
+ ),
+ (Capability::BFloat16TypeKHR, &["BF16_TENSOR_CORES", "float_tensor_cores"]),
+ (Capability::BFloat16CooperativeMatrixKHR, &["BF16_TENSOR_CORES", "float_tensor_cores"]),
+ (Capability::CooperativeMatrixPerElementOperationsNV, &["INT8_ELEMENT_FOLD"]),
+];
+
+pub const AXIS_FOLD_GROUPS: u32 = 65_535;
+
+#[derive(Clone)]
+pub struct VulkanTarget;
+
+impl SlangTarget for VulkanTarget {
+ const TARGET_NAME: &'static str = "vulkan";
+ const SOURCE_DIRECTORY: &'static str = "src/backends/vulkan/kernel";
+ const PRIVATE_GPU_TYPES: Option<&'static str> = Some("vulkan");
+ const SESSION_DEFINES: &'static [&'static [(&'static str, &'static str)]] = &[&[], &[("NATIVE_BF16", "1")]];
+
+ fn compiler_options(
+ global_session: &GlobalSession,
+ options: CompilerOptions,
+ ) -> CompilerOptions {
+ options
+ .emit_spirv_directly(true)
+ .vulkan_use_entry_point_name(true)
+ .capability(global_session.find_capability("spvGroupNonUniform"))
+ .capability(global_session.find_capability("spvGroupNonUniformArithmetic"))
+ .capability(global_session.find_capability("spvGroupNonUniformBallot"))
+ .capability(global_session.find_capability("spvGroupNonUniformShuffle"))
+ .capability(global_session.find_capability("spvCooperativeMatrixKHR"))
+ .capability(global_session.find_capability("spvBFloat16KHR"))
+ .capability(global_session.find_capability("sm_5_0"))
+ }
+
+ fn create_target_desc<'a>(global_session: &'a GlobalSession) -> TargetDesc<'a> {
+ TargetDesc::default().format(CompileTarget::Spirv).profile(global_session.find_profile("spirv_1_6"))
+ }
+
+ fn specialization_type(slang_type: &str) -> &str {
+ match slang_type {
+ "bool" => "bool",
+ _ => "uint",
+ }
+ }
+
+ fn axis_guard(axes: &[(String, String)]) -> (String, Vec<String>) {
+ if let [(total, size)] = axes {
+ let index = format!("__dsl_axis_idx.x + __dsl_axis_idx.y * ({AXIS_FOLD_GROUPS}u * ({size}))");
+ let guard = format!(" let __dsl_axis = {index};\n if (__dsl_axis >= ({total})) return;");
+ return (guard, vec!["__dsl_axis".to_owned()]);
+ }
+ let (guards, indices): (Vec<_>, Vec<_>) = axes
+ .iter()
+ .zip(["x", "y", "z"])
+ .map(|((total, _), axis)| {
+ (format!(" if (__dsl_axis_idx.{axis} >= ({total})) return;"), format!("__dsl_axis_idx.{axis}"))
+ })
+ .unzip();
+ (guards.join("\n"), indices)
+ }
+
+ fn entry_point_prologue(entry_point: &str) -> String {
+ format!(
+ " spirv_asm {{\n OpCapability RoundingModeRTE;\n OpCapability SignedZeroInfNanPreserve;\n \
+ OpExtension \"SPV_KHR_float_controls\";\n \
+ OpExecutionMode ${entry_point} RoundingModeRTE 16;\n \
+ OpExecutionMode ${entry_point} RoundingModeRTE 32;\n \
+ OpExecutionMode ${entry_point} SignedZeroInfNanPreserve 16;\n \
+ OpExecutionMode ${entry_point} SignedZeroInfNanPreserve 32;\n }};"
+ )
+ }
+
+ fn wrapper(
+ fields: &SlangCompilerFields<Self>,
+ source_path: &Path,
+ module: &Module,
+ kernels: &[SlangKernel],
+ ) -> anyhow::Result<String> {
+ kernels.iter().try_for_each(check_bindable)?;
+ let wrappers = kernel_wrappers::<Self>(module, kernels)?;
+ let generated = fields.source_directory.join("generated");
+ let imports = once("definitions".to_owned())
+ .chain(module.dependency_file_paths().filter_map(|path| {
+ let path = Path::new(path);
+ (path.parent() == Some(&generated))
+ .then(|| Some(format!("generated.{}", path.file_stem()?.to_str()?)))
+ .flatten()
+ }))
+ .sorted()
+ .map(|module| format!("import {module};\n"))
+ .chain(once(format!("import {source_path:?};")))
+ .collect::<String>();
+ Ok(once(imports).chain(wrappers).join("\n\n"))
+ }
+
+ fn emit(
+ compiler: &BlockingSlangCompiler<Self>,
+ gpu_types: &SlangGpuTypes,
+ _module: &Module,
+ kernels: &[SlangKernel],
+ descriptors: &[Kernel],
+ linked: &ComponentType,
+ output_base: &Path,
+ ) -> anyhow::Result<()> {
+ let mut declared = BTreeMap::new();
+ for kernel in kernels {
+ for argument in &kernel.arguments {
+ if matches!(argument.argument_type, SlangArgumentType::Specialize { .. }) || argument.pipeline_variants
+ {
+ let wire = match Self::specialization_type(&argument.slang_type) {
+ "bool" => ScalarType::Bool,
+ _ => ScalarType::Uint32,
+ };
+ declared.insert(specialization_name(&kernel.name, &argument.name), wire);
+ }
+ }
+ }
+ let native = compiler.link(1, &output_base.with_extension("slang"))?;
+ for (kernel, descriptor) in kernels.iter().zip(descriptors) {
+ let required = kernel
+ .preconditions
+ .iter()
+ .filter(|(phase, _)| phase == "new")
+ .map(|(_, condition)| {
+ let condition = syn::parse_str(condition)
+ .with_context(|| format!("{}: malformed Precondition '{condition}'", kernel.name))?;
+ anyhow::Ok(required_capabilities(&condition, false))
+ })
+ .flatten_ok()
+ .collect::<anyhow::Result<HashSet<_>>>()?;
+ let variants = kernel
+ .variants()
+ .map(|variant| {
+ let types = variant.iter().map(|(_, ty)| ty.to_string()).collect::<Vec<_>>();
+ let name = static_mangle(&kernel.name, &types);
+ let (abi, spirv) = entry_point(linked, &name, &declared)?;
+ let spirv = spirv()?;
+ check_capabilities(&name, &required, spirv.as_slice(), false)?;
+ let object_file = output_base.with_file_name(&name).with_extension("spv");
+ fs::write(&object_file, spirv.as_slice())?;
+ let (native_abi, native_spirv) = entry_point(&native, &name, &declared)?;
+ let stores_bf16 = types.iter().any(|ty| ty == "bf16")
+ || native_abi
+ .fields
+ .iter()
+ .any(|field| field.layout.as_ref().is_some_and(|layout| layout.name == "bf16"));
+ let native_file = object_file.with_extension("bf16.spv");
+ let native = match stores_bf16.then(native_spirv).transpose()? {
+ Some(native) if native.as_slice() != spirv.as_slice() => {
+ check_capabilities(&name, &required, native.as_slice(), true)?;
+ fs::write(&native_file, native.as_slice())?;
+ Some((native_abi, artifact_path(&native_file)?))
+ },
+ _ => {
+ if native_file.exists() {
+ fs::remove_file(&native_file)?;
+ }
+ None
+ },
+ };
+ Ok(SlangEntryPointVariant {
+ types,
+ abi,
+ spirv: artifact_path(&object_file)?,
+ native_bf16: native,
+ })
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ write_tokens(
+ bindgen::bindgen(kernel, descriptor, &variants, &gpu_types.paths, &gpu_types.definitions)?,
+ bindgen::binding_file(output_base, &kernel.name),
+ )
+ .with_context(|| format!("cannot write {} binding", kernel.name))?;
+ }
+ Ok(())
+ }
+
+ fn bindgen_global(
+ fields: &SlangCompilerFields<Self>,
+ modules: &[(PathBuf, &[Kernel], &[KernelName])],
+ ) -> anyhow::Result<TokenStream> {
+ export_spirv_hash(&fields.output_directory)?;
+ let mut bindings = Vec::new();
+ for (output_base, public, private) in modules {
+ let names =
+ public.iter().map(|kernel| (&kernel.name, true)).chain(private.iter().map(|name| (name, false)));
+ for (name, is_public) in names {
+ let file = bindgen::binding_file(output_base, name);
+ bindings.push((
+ file.to_str().context("binding path is not UTF-8")?.to_owned(),
+ name.to_string(),
+ is_public,
+ ));
+ }
+ }
+ Ok(bindgen::bindgen_umbrella(&bindings))
+ }
+}
+
+fn check_capabilities(
+ entry_point: &str,
+ required: &HashSet<String>,
+ spirv: &[u8],
+ native_bf16: bool,
+) -> anyhow::Result<()> {
+ let words = spirv.as_chunks::<4>().0.iter().map(|word| u32::from_le_bytes(*word)).collect::<Vec<_>>();
+ let mut at = 5;
+ while at < words.len() {
+ let (count, opcode) = ((words[at] >> 16) as usize, words[at] & 0xffff);
+ anyhow::ensure!(count > 0 && at + count <= words.len(), "{entry_point}: malformed SPIR-V");
+ if Op::from_u32(opcode) == Some(Op::Capability) {
+ let Some(capability) = Capability::from_u32(words[at + 1]) else {
+ anyhow::bail!("{entry_point}: unknown SPIR-V capability {}", words[at + 1]);
+ };
+ let gated = GATED_CAPABILITIES.iter().find(|(value, _)| *value == capability);
+ let allowed = DEVICE_CAPABILITIES.contains(&capability)
+ || (native_bf16 && capability == Capability::BFloat16TypeKHR)
+ || gated.is_some_and(|(_, gates)| gates.iter().any(|gate| required.contains(*gate)));
+ anyhow::ensure!(
+ allowed,
+ "{entry_point}: SPIR-V capability {capability:?} is neither enabled on every device nor gated by a precondition"
+ );
+ }
+ at += count;
+ }
+ Ok(())
+}
+
+fn required_capabilities(
+ condition: &Expr,
+ flags: bool,
+) -> Vec<String> {
+ match condition {
+ Expr::Binary(binary) if matches!((&binary.op, flags), (BinOp::And(_), false) | (BinOp::BitOr(_), true)) => {
+ [&binary.left, &binary.right].into_iter().flat_map(|term| required_capabilities(term, flags)).collect()
+ },
+ Expr::Paren(paren) => required_capabilities(&paren.expr, flags),
+ Expr::MethodCall(call) if !flags && call.method == "float_tensor_cores" => vec![call.method.to_string()],
+ Expr::MethodCall(call) if !flags && call.method == "contains" => {
+ call.args.iter().flat_map(|flag| required_capabilities(flag, true)).collect()
+ },
+ Expr::Path(path)
+ if flags && path.path.segments.len() == 2 && path.path.segments[0].ident == "VkDeviceCapabilities" =>
+ {
+ vec![path.path.segments[1].ident.to_string()]
+ },
+ _ => Vec::new(),
+ }
+}
+
+fn entry_point<'a>(
+ compiled: &'a ComponentType,
+ name: &str,
+ declared: &BTreeMap<String, ScalarType>,
+) -> anyhow::Result<(SlangEntryPointAbi, impl FnOnce() -> anyhow::Result<Blob> + 'a)> {
+ let program = compiled.layout(0).context("linked Slang program has no layout")?;
+ let entry_point = program.find_entry_point_by_name(name).context("entry point not linked")?;
+ let index =
+ program.entry_points().position(|entry| entry.name() == Some(name)).context("entry point has no index")?;
+ let spirv = move || compiled.entry_point_code(index as i64, 0).context("cannot emit entry point SPIR-V");
+ Ok((SlangEntryPointAbi::from_reflection(program, entry_point, declared)?, spirv))
+}
+
+fn artifact_path(file: &Path) -> anyhow::Result<String> {
+ Ok(file.to_str().context("Slang artifact path is not UTF-8")?.to_owned())
+}
+
+fn check_bindable(kernel: &SlangKernel) -> anyhow::Result<()> {
+ if let Some(parameter) =
+ kernel.parameters.iter().find(|parameter| matches!(parameter.ty, SlangParameterType::GroupShared { .. }))
+ {
+ anyhow::bail!("kernel '{}': GroupShared {} has no Vulkan binding", kernel.name, parameter.name);
+ }
+ let has =
+ |kind: fn(&SlangArgumentType) -> bool| kernel.arguments.iter().any(|argument| kind(&argument.argument_type));
+ anyhow::ensure!(
+ !has(|kind| matches!(kind, SlangArgumentType::ThreadContext)),
+ "kernel '{}': ThreadContext has no Vulkan binding",
+ kernel.name
+ );
+ let variants = kernel.arguments.iter().filter(|argument| argument.pipeline_variants).count();
+ anyhow::ensure!(
+ variants <= 1,
+ "kernel '{}' marks {variants} arguments PipelineVariants; at most one may be",
+ kernel.name
+ );
+ let axis = has(|kind| matches!(kind, SlangArgumentType::Axis { .. }));
+ let groups = has(|kind| matches!(kind, SlangArgumentType::Groups { .. }));
+ let threads = has(|kind| matches!(kind, SlangArgumentType::Threads { .. }));
+ anyhow::ensure!(
+ groups == threads && (axis || groups),
+ "kernel '{}' needs either Axis or both Groups and Threads",
+ kernel.name
+ );
+ Ok(())
+}
diff --git a/crates/uzu-engine/build/webgpu/bindgen_file.rs b/crates/uzu-engine/build/webgpu/bindgen_file.rs
index 2f3f06e8e..f1026579b 100644
--- a/crates/uzu-engine/build/webgpu/bindgen_file.rs
+++ b/crates/uzu-engine/build/webgpu/bindgen_file.rs
@@ -18,7 +18,7 @@ use crate::{
kernel::{KernelArgumentType, KernelBufferAccess, KernelParameterType},
mangling::static_mangle,
},
- slang::{SlangArgumentType, SlangBufferAccess, SlangKernel, SlangParameterType, Specializer, slang2rust},
+ slang::{SlangArgumentType, SlangKernel, SlangParameterType, Specializer, slang2rust, specialization_name},
};
pub fn bindgen_file(
@@ -60,6 +60,14 @@ fn bindgen_kernel(
let kernel_trait_name = format_ident!("{}Kernel", kernel.name.as_str());
let kernel_struct_name = format_ident!("{}WebGPUKernel", kernel.name.as_str());
+ ensure!(
+ kernel.preconditions.is_empty()
+ && kernel.required_subgroup_size.is_none()
+ && !kernel.arguments.iter().any(|argument| argument.pipeline_variants),
+ "{}: the WebGPU binding implements no Precondition, RequiredSubgroupSize or PipelineVariants",
+ kernel.name
+ );
+
let globals = shader.global_params_type_layout().unwrap();
struct SpecializationConstant {
@@ -119,7 +127,7 @@ fn bindgen_kernel(
condition,
} = &argument.argument_type
{
- let slang_name = format!("{}_specialize_{}", kernel.name, argument.name.as_str());
+ let slang_name = specialization_name(&kernel.name, &argument.name);
let wgsl_idx = globals
.field_by_index(globals.find_field_index_by_name(&slang_name) as u32)
.unwrap()
@@ -416,7 +424,6 @@ fn bindgen_kernel(
match parameter_category {
ParameterCategory::DescriptorTableSlot => {
let SlangArgumentType::Buffer {
- access_type,
condition,
} = &kernel_argument.unwrap().argument_type
else {
@@ -431,9 +438,10 @@ fn bindgen_kernel(
let buffer_name = parameter_name.to_string();
- let read_only = matches!(access_type, SlangBufferAccess::Read);
+ let binding_type = kernel_argument.unwrap().binding_type.as_ref().unwrap();
+ let read_only = !matches!(binding_type, KernelArgumentType::Buffer(KernelBufferAccess::ReadWrite));
- let source_type = match kernel_argument.unwrap().binding_type.as_ref().unwrap() {
+ let source_type = match binding_type {
KernelArgumentType::Value(_) => {
let element_type = parameter.type_layout().unwrap().resource_result_type().unwrap();
let element_type_layout =
diff --git a/crates/uzu-engine/build/webgpu/mod.rs b/crates/uzu-engine/build/webgpu/mod.rs
index 2c4b5684f..def3bb929 100644
--- a/crates/uzu-engine/build/webgpu/mod.rs
+++ b/crates/uzu-engine/build/webgpu/mod.rs
@@ -1,16 +1,22 @@
-use std::{collections::HashMap, fs, path::Path};
+use std::{
+ collections::HashMap,
+ fs,
+ iter::once,
+ path::{Path, PathBuf},
+};
use anyhow::Context;
+use itertools::Itertools;
use naga::{
front::wgsl,
valid::{Capabilities, ValidationFlags, Validator},
};
use proc_macro2::TokenStream;
-use shader_slang::{CompileTarget, ComponentType, GlobalSession, TargetDesc};
+use shader_slang::{CompileTarget, ComponentType, GlobalSession, ModifierID, Module, TargetDesc};
use crate::{
- common::gpu_type_paths::GpuTypePaths,
- slang::{SlangKernel, SlangTarget},
+ common::{codegen::write_tokens, identifiers::KernelName, kernel::Kernel},
+ slang::{BlockingSlangCompiler, SlangCompilerFields, SlangGpuTypes, SlangKernel, SlangTarget, kernel_wrappers},
};
mod bindgen_file;
@@ -19,14 +25,7 @@ mod bindgen_global;
#[derive(Clone)]
pub struct WebGPU;
-impl SlangTarget for WebGPU {
- const TARGET_NAME: &'static str = "webgpu";
- const OUTPUT_EXTENSION: &'static str = "wgsl";
-
- fn create_target_desc<'a>(_global_session: &'a GlobalSession) -> TargetDesc<'a> {
- TargetDesc::default().format(CompileTarget::Wgsl)
- }
-
+impl WebGPU {
fn validate_output(path: &Path) -> anyhow::Result<()> {
let source = fs::read_to_string(path).with_context(|| format!("cannot read {path:?}"))?;
@@ -44,19 +43,93 @@ impl SlangTarget for WebGPU {
Ok(())
}
+}
+
+impl SlangTarget for WebGPU {
+ const TARGET_NAME: &'static str = "webgpu";
+ const SOURCE_DIRECTORY: &'static str = "src/backends/slang/kernel";
+
+ fn create_target_desc<'a>(_global_session: &'a GlobalSession) -> TargetDesc<'a> {
+ TargetDesc::default().format(CompileTarget::Wgsl)
+ }
+
+ fn specialization_type(slang_type: &str) -> &str {
+ slang_type
+ }
+
+ fn axis_guard(axes: &[(String, String)]) -> (String, Vec<String>) {
+ let (guards, indices): (Vec<_>, Vec<_>) = axes
+ .iter()
+ .zip(["x", "y", "z"])
+ .map(|((total, _), axis)| {
+ (format!("__dsl_axis_idx.{axis} >= uint({total})"), format!("__dsl_axis_idx.{axis}"))
+ })
+ .unzip();
+ (format!(" if ({}) {{ return; }}", guards.join(" || ")), indices)
+ }
+
+ fn entry_point_prologue(_entry_point: &str) -> String {
+ String::new()
+ }
- fn bindgen_file(
- linked_component: &ComponentType,
+ fn wrapper(
+ _fields: &SlangCompilerFields<Self>,
+ source_path: &Path,
+ module: &Module,
kernels: &[SlangKernel],
- gpu_type_map: &HashMap<String, String>,
- gpu_type_paths: &GpuTypePaths,
- constants: &HashMap<String, String>,
- object_file: &Path,
- ) -> anyhow::Result<TokenStream> {
- bindgen_file::bindgen_file(linked_component, kernels, gpu_type_map, gpu_type_paths, constants, object_file)
+ ) -> anyhow::Result<String> {
+ let wrapper_blocks = kernel_wrappers::<Self>(module, kernels)?;
+ Ok(once(format!("#include {source_path:?}")).chain(wrapper_blocks).join("\n\n"))
}
- fn bindgen_global(kernels: &[(impl AsRef<Path>, &[crate::common::kernel::Kernel])]) -> anyhow::Result<TokenStream> {
- bindgen_global::bindgen_global(kernels)
+ fn emit(
+ _compiler: &BlockingSlangCompiler<Self>,
+ gpu_types: &SlangGpuTypes,
+ module: &Module,
+ kernels: &[SlangKernel],
+ _descriptors: &[Kernel],
+ linked: &ComponentType,
+ output_base: &Path,
+ ) -> anyhow::Result<()> {
+ let constants = module
+ .module_reflection()
+ .children()
+ .filter_map(|decl| decl.as_variable())
+ .filter(|variable| variable.find_modifier(ModifierID::SlangModifierConst).is_some())
+ .filter_map(|variable| Some((variable.name()?.to_owned(), variable.default_value_int()?.to_string())))
+ .collect::<HashMap<_, _>>();
+
+ let output_file = output_base.with_extension("wgsl");
+
+ let linked_blob = linked.target_code(0).context("cannot get target code")?;
+
+ fs::write(&output_file, linked_blob.as_slice()).context("cannot write output file")?;
+
+ Self::validate_output(&output_file).with_context(|| format!("cannot validate {}", output_file.display()))?;
+
+ let bindgen_tokens = bindgen_file::bindgen_file(
+ linked,
+ kernels,
+ &gpu_types.paths.entries().map(|(name, path)| (name.to_owned(), path.to_owned())).collect(),
+ &gpu_types.paths,
+ &constants,
+ &output_file,
+ )
+ .context("cannot generate bindings")?;
+
+ write_tokens(bindgen_tokens, output_base.with_extension("rs")).context("cannot write bindgen file")
+ }
+
+ fn bindgen_global(
+ _fields: &SlangCompilerFields<Self>,
+ modules: &[(PathBuf, &[Kernel], &[KernelName])],
+ ) -> anyhow::Result<TokenStream> {
+ let kernels = modules
+ .iter()
+ .filter(|(_, public, _)| !public.is_empty())
+ .map(|(output_base, public, _)| (output_base.with_extension("rs"), *public))
+ .collect::<Vec<_>>();
+
+ bindgen_global::bindgen_global(&kernels)
}
}
diff --git a/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang b/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang
index 633875d54..2d99b627f 100644
--- a/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang
+++ b/crates/uzu-engine/src/backends/slang/kernel/definitions/dsl.slang
@@ -25,6 +25,17 @@ struct PublicAttribute;
[[__AttributeUsage(_AttributeTargets.Function)]]
struct KernelAttribute;
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct RequiredSubgroupSizeAttribute {
+ string size;
+};
+
+[[__AttributeUsage(_AttributeTargets.Function)]]
+struct PreconditionAttribute {
+ string phase;
+ string condition;
+};
+
// Kernel argument annotation
[[__AttributeUsage(_AttributeTargets.Param)]]
@@ -53,3 +64,6 @@ struct GroupsAttribute {
struct ThreadsAttribute {
string threads;
};
+
+[[__AttributeUsage(_AttributeTargets.Param)]]
+struct PipelineVariantsAttribute;