Files
metal2vulkan/crates/metal2vulkan/src/cache/codec.rs
T
Anees Iqbal 27a6c1ebd3 Translator and runtime: the interface items no path makes since the resident core went are deleted
0ce2f39b71 deleted the resident core: every device compiles the identity domains, which read a
texture's presence, out-of-bounds alpha, swizzle, border texels and level count, and a sampler's
state, from the resource ID's words. The interface items the resident core stated for them stayed,
with nothing left that makes them:

- SpecKey's Presence, OutOfBoundsAlpha, TextureSwizzle, OffsetBaseAxes, NearestPixelSampler and
  BorderTexels: no lowering declares them.
- RuntimeFact's ResourcePresence, OutOfBoundsAlpha, StorageTextureLevels, StorageTextureLevelViews,
  OpenClLineTexture and BorderTexels: no plan states them.
- PushField::ControlPointIndexOffset: no plan places it. identity_pushes (lower/select.rs) named
  it on its false side; that arm goes, and lower/push.rs's shape arm with it.
- PrecisionNote::F16IntConvDoubleRounding (metal2vulkan-degrade-f16-int-conv-double-rounding): no
  lowering records it. Its catalogue entry in docs/API.md goes, with the conformance crate's
  Degradation and the validation comparison's allowance and reach arms.
- Feature's LocalSize, TexelBuffer and GroupCount: no site constructs them (docs/REFUSALS.md listed
  each with no site). Their reach.tsv rows go.
- CombinedSampler's unnormalized field, with_unnormalized, heap_index and from_heap_index: the field
  was set only from lower::sampler's BindingKey::unnormalized, which no selection sets (none picks
  PixelPosition::Unnormalized or UnnormalizedTexel) and finish() refuses as an invariant, and the
  two index methods had no caller. sampler_use() now makes the use from the comparison and the
  texel class alone. The runtime's DrawInputCause::UnnormalizedSampler and its two checks (a
  constexpr sampler of a draw or dispatch with the field set) go with it.

The device sampler of unnormalized coordinates stays: SamplerUse::unnormalized, vk_sampler's
unnormalized form and SamplerDesc::unnormalized are what the runtime's linear pixel samplers'
twins are made with.

Tests: device/tests/mechanism.rs covers the 56 facts left; the assertions that a plan states none
of the deleted facts, and the spec values set for deleted keys, go; engine_spec_bits labels its
constant SamplerMinLevel; cache/tests.rs's round trip of OffsetBaseAxes goes; api_tests.rs's
SpecializationLayout round trip names SamplerMinLevel.

The consumer names none of them: in reims at 7d016acc9c, and at 8f3ca9df99, git grep finds 0 hits
each for unnormalized, Unnormalized, heap_index, F16IntConvDoubleRounding,
f16-int-conv-double-rounding, LocalSize, GroupCount, SpecKey::, RuntimeFact::, PushField::,
ControlPointIndexOffset, NearestPixelSampler, OffsetBaseAxes, ResourcePresence,
StorageTextureLevel, OpenClLineTexture, BorderTexels and OutOfBoundsAlpha. TexelBuffer's 2 hits
are maxTexelBufferElements and the runtime's TexelBufferTooLarge, DrawInputCause's 1 is
DrawInputCause::Slot, Feature::'s 10 are other variants and another crate's Feature, and
TextureSwizzle's 66 are Metal's MTLTextureSwizzle.

ARTIFACT_FORMAT_VERSION 612 -> 613 (renumbered at landing): the codec's lists are positional, and
SpecKey, PushField, RuntimeFact, PrecisionNote and CombinedSampler lose members. SEMANTICS_VERSION
stays: nothing that compiles changes. runtime-sources.sha256 moves without a RUNTIME_VERSION bump:
device/mechanism.rs loses the arms of the deleted facts, which no run reached. docs/REFUSALS.md and
the signature table are regenerated; the metal and conformance coverage docs regenerate unchanged.

Verified, on the CPU with no device:
- m3-max-86143, at this commit: clippy (plain, all targets and features) passes; the mechanism,
  spec-bits, round-trip and texture-level tests ran 64 tests, all passed, 2,571 skipped.
- m3-max-86179, at the series' tip (the two cleanup commits and the README line): fmt, the
  refusal surface's, the signatures', both coverage docs' and scripts/api-docs' checks, clippy
  (plain, --cfg m2v_gpu, --cfg m2v_cpu_icd), Rustdoc, private docs (metal2vulkan and
  metal2vulkan-runtime) and doctests pass. The metal2vulkan suites ran 3,492 tests: 3,491 passed,
  24 skipped, and the failure is golden_hashes_match_the_table, which fails at the base too (a
  bless due at the next pin). Validation ran 1,343 tests, all passed, 2 skipped; conformance ran
  1,061, all passed.
- m3-max-86194 and m3-max-86213, at the tip and at its base db7bedc60d: the golden table's changed
  lines are the same 5,114 at both, line for line, so no cell moves.
2026-12-03 16:57:32 -08:00

1429 lines
55 KiB
Rust

//! The artifact body encoding: a canonical, self-delimiting byte encoding of every type an encoded
//! `CompiledFunction` or pipeline artifact carries. It needs no `serde`.
//!
//! - Integers are fixed-width little-endian; `bool` is one byte, 0 or 1.
//! - A sequence (vector, string, byte slice, map, set) is a `u32` count, then its items. A count
//! is checked against the bytes left before anything is reserved, so hostile input cannot
//! allocate more than its own size.
//! - Maps and sets are written in order and must decode strictly increasing (one encoding per
//! value).
//! - A struct is its fields in declaration order. An enum is its variant name, then the
//! variant's fields; names keep the encoding stable when variants are reordered.
//!
//! Every impl is generated by `codec_struct!` or `codec_enum!`, which destructure and match
//! without wildcards: a field or variant added to a type without a line here is a compile error,
//! so the encoding stays total by construction.
//!
//! The same impls give each value's node in a content digest ([`Codec::digest`], `digest`): structs
//! and enum variants by their field and variant names, so a digest survives an added field whose
//! value is zero and reordered or inserted variants.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use crate::device::profile::Independence;
use crate::device::requirements::{
ApiVersion, FloatControl, FloatWidth, FormatUsage, Requirements, ResolveMode, SpirvCapability,
SpirvExtension, StageCreateFlag, SubgroupOp, VkExtension, VkFeature, VkLimit, VkProperty,
};
use crate::device::subgroup::SubgroupRequirement;
use crate::library::{FunctionArtifact, FunctionCompileKey, KernelFacts};
use crate::metal;
use crate::metal::format::{ExtendedRange, WordAttachment, WordField};
use crate::metal::{CompareFunction, TextureWriteRoundingMode};
use crate::pipeline::artifact::{
ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence,
RenderPipeline, RuntimeDependency, SpecConstant, SpecializationLayout, StageModule,
StrategyCensus, StrategyUse,
};
use crate::pipeline::descriptor::TessellationDescriptor;
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::graphics::{
BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, LineBandState,
TessellationState,
};
use crate::pipeline::interface::{
AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, NumberedSampler, PatchDomain,
PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerSlot, SlotInterface,
StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot,
ThreadgroupArgument, Window,
};
use crate::pipeline::layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
};
use crate::pipeline::lower_inputs::{
ChannelWrite, ExtendedRangeColor, ExtendedUnormBlend, ExtendedUnormColor, FactorLane,
VertexFetch,
};
use crate::pipeline::stage_io::{
CoverageLoop, CoverageLoopRefusal, DepthCompares, DepthMode, Interpolation as IoInterpolation,
IoNumeric, IoRole, IoType, IoVariable, PulledInput, Sampling as IoSampling, StageBuiltin,
StageInFetch, StageInInput, StageIo,
};
use crate::pipeline::sym::{
AccelerationStructureLevel, AirUserKey, Axis, CombinedSampler, HandleClass, ImageAccess,
ImageDim, ImageHandleClass, PushField, ResourceKind, ResourceSlot, SampledType, SamplerRef,
SlotClass, SlotRef, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding, VaryingKey,
};
use crate::pipeline::vertex::{
PulledAttribute, VertexAttribute, VertexBinding, VertexInputState, VertexStride,
};
use crate::reflection::{
ArrayType, Binding as ReflectionBinding, BindingKind, BufferBinding, DirectArgumentUse,
LinkedUseAnswers, LinkedUseGap, ObjectPayloadBinding, PointerType, RenderPipelineReflection,
SlotWritability, SlotWrite, SlotWriteGap, StageReflection, StructMember, StructType,
TextureBinding, TextureReferenceType, ThreadgroupBinding, TypeDetail, UnwrittenFragmentInputs,
};
use crate::spirv::serialize::RelocatableModule;
use crate::vk;
use crate::vk::{ComponentMapping, SamplerDesc};
use super::digest::Node;
use super::PipelineKey;
/// The bytes do not decode as the expected value (always a corrupt artifact).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Malformed;
/// An append-only byte sink: the whole encoding in `bytes`, or with a `sink`, handed to it a
/// chunk at a time (`bytes` holding at most [`CHUNK`] bytes not yet handed over).
#[derive(Default)]
pub(crate) struct Writer<'a> {
pub(crate) bytes: Vec<u8>,
sink: Option<&'a mut dyn FnMut(&[u8])>,
}
/// The most bytes a chunked [`Writer`] holds before handing them to its sink.
pub(crate) const CHUNK: usize = 64 * 1024;
impl<'a> Writer<'a> {
/// A writer that hands the encoding to `sink` a chunk at a time; [`Writer::finish`] hands
/// over the rest.
pub(crate) fn chunked(sink: &'a mut dyn FnMut(&[u8])) -> Writer<'a> {
Writer {
bytes: Vec::with_capacity(CHUNK),
sink: Some(sink),
}
}
/// Hand the bytes not yet handed over to the sink.
pub(crate) fn finish(self) {
if let Some(sink) = self.sink {
sink(&self.bytes);
}
}
fn raw(&mut self, b: &[u8]) {
match self.sink.as_mut() {
Some(sink) if self.bytes.len().saturating_add(b.len()) > CHUNK => {
sink(&self.bytes);
self.bytes.clear();
if b.len() >= CHUNK {
sink(b);
} else {
self.bytes.extend_from_slice(b);
}
}
_ => self.bytes.extend_from_slice(b),
}
}
/// A sequence count. Every in-memory sequence this crate encodes is far below `u32::MAX`
/// items (the budgets cap modules at `SPIRV_WORDS`); a larger one saturates, which decodes as
/// `Malformed` because fewer items follow than the count names.
fn count(&mut self, n: usize) {
self.raw(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes());
}
}
/// A cursor over untrusted bytes.
pub(crate) struct Reader<'a> {
bytes: &'a [u8],
}
impl<'a> Reader<'a> {
pub(crate) fn new(bytes: &'a [u8]) -> Reader<'a> {
Reader { bytes }
}
/// The bytes not yet read.
pub(crate) fn remaining(&self) -> usize {
self.bytes.len()
}
pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Malformed> {
if n > self.bytes.len() {
return Err(Malformed);
}
let (head, tail) = self.bytes.split_at(n);
self.bytes = tail;
Ok(head)
}
fn array<const N: usize>(&mut self) -> Result<[u8; N], Malformed> {
let mut out = [0u8; N];
out.copy_from_slice(self.take(N)?);
Ok(out)
}
/// A sequence count of items each at least `min_item` bytes long, checked against the bytes
/// left.
fn count(&mut self, min_item: usize) -> Result<usize, Malformed> {
let n = u32::from_le_bytes(self.array()?) as usize;
if n.saturating_mul(min_item.max(1)) > self.bytes.len() {
return Err(Malformed);
}
Ok(n)
}
}
/// A value with a canonical byte encoding.
///
/// Adding a field to an encoded struct: content digests omit a field whose value is zero (its
/// encoding all zero bytes: `0`, `false`, `None`, empty), so a new field must hold its zero value
/// exactly when the artifact means what it meant before the field existed. If its zero would mean
/// new behaviour for existing pipelines, the addition must also bump the runtime version or the
/// validation executor's ABI (ask the orchestrator): the digest cannot see it (`digest`,
/// `docs/VALIDATION.md`).
pub(crate) trait Codec: Sized {
/// The fewest bytes one encoded value takes (bounds sequence counts before reserving).
const MIN_BYTES: usize = 1;
/// Whether the value holds no struct or enum, so its content-digest node is the leaf of its
/// whole encoding ([`Codec::digest`]).
const LEAF: bool = true;
fn put(&self, w: &mut Writer);
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed>;
/// The value's node in a content digest: the leaf of its encoding, unless the value is or holds
/// a struct or an enum, whose impls give their named nodes.
fn digest(&self) -> Node {
leaf(self)
}
/// The items of a sequence, one after another (a byte sequence's bytes at once).
fn put_items(items: &[Self], w: &mut Writer) {
for v in items {
v.put(w);
}
}
/// The `n` items of a sequence (a byte sequence's bytes at once).
fn get_items(r: &mut Reader<'_>, n: usize) -> Result<Vec<Self>, Malformed> {
let mut out = Vec::with_capacity(n);
for _ in 0..n {
out.push(Self::get(r)?);
}
Ok(out)
}
/// The `n` items of a shared sequence (a byte sequence's bytes copied once).
fn get_shared(r: &mut Reader<'_>, n: usize) -> Result<Arc<[Self]>, Malformed> {
Self::get_items(r, n).map(Arc::from)
}
}
/// Encode one value.
pub(crate) fn encode<T: Codec>(v: &T) -> Vec<u8> {
let mut w = Writer::default();
v.put(&mut w);
w.bytes
}
/// Encode one value into `sink`, a chunk at a time: the bytes [`encode`] gives, never held whole.
pub(crate) fn encode_chunked<T: Codec>(v: &T, sink: &mut dyn FnMut(&[u8])) {
let mut w = Writer::chunked(sink);
v.put(&mut w);
w.finish();
}
/// The leaf node of `v`'s whole encoding, streamed.
fn leaf<T: Codec>(v: &T) -> Node {
Node::leaf(|sink| encode_chunked(v, sink))
}
/// The node of a sequence `whole` of `items`: the leaf of its encoding when the items are leaves,
/// else the sequence of their nodes.
fn sequence<C: Codec, T: Codec>(whole: &C, items: &[T]) -> Node {
if T::LEAF {
leaf(whole)
} else {
Node::sequence(items.iter().map(Codec::digest))
}
}
/// Decode one value that must use every byte.
pub(crate) fn decode<T: Codec>(bytes: &[u8]) -> Result<T, Malformed> {
let mut r = Reader::new(bytes);
let v = T::get(&mut r)?;
if r.remaining() != 0 {
return Err(Malformed);
}
Ok(v)
}
// ---- Primitives ----
macro_rules! codec_int {
// The `n` values `r` holds next, every byte of them taken at once.
(@items $t:ty, $r:ident, $n:ident) => {{
const N: usize = std::mem::size_of::<$t>();
let bytes = $r.take($n.checked_mul(N).ok_or(Malformed)?)?;
bytes.as_chunks::<N>().0.iter().map(|b| <$t>::from_le_bytes(*b))
}};
($($t:ty),*) => {$(
impl Codec for $t {
const MIN_BYTES: usize = std::mem::size_of::<$t>();
fn put(&self, w: &mut Writer) {
w.raw(&self.to_le_bytes());
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(<$t>::from_le_bytes(r.array()?))
}
// A module's words are most of an artifact's bytes: taken in one step, not an
// item at a time.
fn get_items(r: &mut Reader<'_>, n: usize) -> Result<Vec<Self>, Malformed> {
Ok(codec_int!(@items $t, r, n).collect())
}
fn get_shared(r: &mut Reader<'_>, n: usize) -> Result<Arc<[Self]>, Malformed> {
Ok(codec_int!(@items $t, r, n).collect())
}
}
)*};
}
codec_int!(u16, u32, u64, i32, i64);
impl Codec for u8 {
fn put(&self, w: &mut Writer) {
w.raw(&[*self]);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(r.array::<1>()?[0])
}
fn put_items(items: &[u8], w: &mut Writer) {
w.raw(items);
}
fn get_items(r: &mut Reader<'_>, n: usize) -> Result<Vec<u8>, Malformed> {
Ok(r.take(n)?.to_vec())
}
fn get_shared(r: &mut Reader<'_>, n: usize) -> Result<Arc<[u8]>, Malformed> {
Ok(Arc::from(r.take(n)?))
}
}
impl Codec for bool {
fn put(&self, w: &mut Writer) {
w.raw(&[u8::from(*self)]);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
match u8::get(r)? {
0 => Ok(false),
1 => Ok(true),
_ => Err(Malformed),
}
}
}
/// By its bits, so every value (NaN payloads included) round-trips exactly.
impl Codec for f32 {
const MIN_BYTES: usize = 4;
fn put(&self, w: &mut Writer) {
self.to_bits().put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(f32::from_bits(u32::get(r)?))
}
}
impl Codec for String {
const MIN_BYTES: usize = 4;
fn put(&self, w: &mut Writer) {
w.count(self.len());
w.raw(self.as_bytes());
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let n = r.count(1)?;
let bytes = r.take(n)?;
String::from_utf8(bytes.to_vec()).map_err(|_| Malformed)
}
}
impl<T: Codec> Codec for Vec<T> {
const MIN_BYTES: usize = 4;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
sequence(self, self)
}
fn put(&self, w: &mut Writer) {
w.count(self.len());
T::put_items(self, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let n = r.count(T::MIN_BYTES)?;
T::get_items(r, n)
}
}
impl<T: Codec> Codec for Box<[T]> {
const MIN_BYTES: usize = 4;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
sequence(self, self)
}
fn put(&self, w: &mut Writer) {
w.count(self.len());
T::put_items(self, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(Vec::<T>::get(r)?.into_boxed_slice())
}
}
impl<T: Codec> Codec for Arc<[T]> {
const MIN_BYTES: usize = 4;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
sequence(self, self)
}
fn put(&self, w: &mut Writer) {
w.count(self.len());
T::put_items(self, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let n = r.count(T::MIN_BYTES)?;
T::get_shared(r, n)
}
}
impl<T: Codec> Codec for Arc<T> {
const MIN_BYTES: usize = T::MIN_BYTES;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
T::digest(self)
}
fn put(&self, w: &mut Writer) {
T::put(self, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(Arc::new(T::get(r)?))
}
}
impl<T: Codec> Codec for Box<T> {
const MIN_BYTES: usize = T::MIN_BYTES;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
T::digest(self)
}
fn put(&self, w: &mut Writer) {
T::put(self, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(Box::new(T::get(r)?))
}
}
impl<T: Codec> Codec for Option<T> {
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
match self {
_ if T::LEAF => leaf(self),
None => Node::ZERO,
Some(v) => Node::some(v.digest()),
}
}
fn put(&self, w: &mut Writer) {
match self {
None => false.put(w),
Some(v) => {
true.put(w);
v.put(w);
}
}
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
if bool::get(r)? {
Ok(Some(T::get(r)?))
} else {
Ok(None)
}
}
}
impl<A: Codec, B: Codec> Codec for (A, B) {
const MIN_BYTES: usize = A::MIN_BYTES + B::MIN_BYTES;
const LEAF: bool = A::LEAF && B::LEAF;
fn digest(&self) -> Node {
if Self::LEAF {
leaf(self)
} else {
Node::tuple([self.0.digest(), self.1.digest()])
}
}
fn put(&self, w: &mut Writer) {
self.0.put(w);
self.1.put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok((A::get(r)?, B::get(r)?))
}
}
impl<T: Codec, const N: usize> Codec for [T; N] {
const MIN_BYTES: usize = T::MIN_BYTES * N;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
if T::LEAF {
leaf(self)
} else {
Node::tuple(self.iter().map(Codec::digest))
}
}
fn put(&self, w: &mut Writer) {
for v in self {
v.put(w);
}
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let mut out = Vec::with_capacity(N);
for _ in 0..N {
out.push(T::get(r)?);
}
out.try_into().map_err(|_| Malformed)
}
}
impl<K: Codec + Ord, V: Codec> Codec for BTreeMap<K, V> {
const MIN_BYTES: usize = 4;
const LEAF: bool = K::LEAF && V::LEAF;
/// The sequence of its entries, each the pair of its key's and value's nodes.
fn digest(&self) -> Node {
if Self::LEAF {
leaf(self)
} else {
Node::sequence(
self.iter()
.map(|(k, v)| Node::tuple([k.digest(), v.digest()])),
)
}
}
fn put(&self, w: &mut Writer) {
w.count(self.len());
for (k, v) in self {
k.put(w);
v.put(w);
}
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let n = r.count(K::MIN_BYTES + V::MIN_BYTES)?;
let mut out = BTreeMap::new();
for _ in 0..n {
let k = K::get(r)?;
if out.last_key_value().is_some_and(|(last, _)| *last >= k) {
return Err(Malformed);
}
let v = V::get(r)?;
out.insert(k, v);
}
Ok(out)
}
}
impl<T: Codec + Ord> Codec for BTreeSet<T> {
const MIN_BYTES: usize = 4;
const LEAF: bool = T::LEAF;
fn digest(&self) -> Node {
if T::LEAF {
leaf(self)
} else {
Node::sequence(self.iter().map(Codec::digest))
}
}
fn put(&self, w: &mut Writer) {
w.count(self.len());
for v in self {
v.put(w);
}
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let n = r.count(T::MIN_BYTES)?;
let mut out = BTreeSet::new();
for _ in 0..n {
let v = T::get(r)?;
if out.last().is_some_and(|last| *last >= v) {
return Err(Malformed);
}
out.insert(v);
}
Ok(out)
}
}
/// An enum variant's name tag.
fn put_tag(w: &mut Writer, name: &str) {
let len = u8::try_from(name.len()).unwrap_or(u8::MAX);
w.raw(&[len]);
w.raw(name.as_bytes());
}
fn get_tag<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], Malformed> {
let len = u8::get(r)?;
r.take(usize::from(len))
}
// ---- Generated impls ----
/// A struct as its fields in declaration order. The pattern names every field and has no `..`,
/// so a new field fails to compile until it is added here. Its digest node names each field.
macro_rules! codec_struct {
($($ty:ident { $($f:ident),* $(,)? })*) => {$(
impl Codec for $ty {
const LEAF: bool = false;
fn digest(&self) -> Node {
let $ty { $($f),* } = self;
Node::fields(&mut [$((stringify!($f), Codec::digest($f))),*])
}
fn put(&self, w: &mut Writer) {
let $ty { $($f),* } = self;
$(Codec::put($f, w);)*
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
$(let $f = Codec::get(r)?;)*
Ok($ty { $($f),* })
}
}
)*};
}
/// A one-field tuple struct as its field, in its encoding and its digest node.
macro_rules! codec_newtype {
($($ty:ident),* $(,)?) => {$(
impl Codec for $ty {
const LEAF: bool = false;
fn digest(&self) -> Node {
let $ty(v) = self;
Codec::digest(v)
}
fn put(&self, w: &mut Writer) {
let $ty(v) = self;
Codec::put(v, w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok($ty(Codec::get(r)?))
}
}
)*};
}
/// An enum as its variant name, then the variant's fields. The match has no wildcard, so a new
/// variant fails to compile until it is added here. Its digest node names the variant and each
/// field: a tuple variant's fields by the names written here (`f0`, `f1`, ...).
macro_rules! codec_enum {
($($ty:ident {
$($v:ident $(( $($t:ident),* ))? $({ $($f:ident),* })?),* $(,)?
})*) => {$(
impl Codec for $ty {
const LEAF: bool = false;
fn digest(&self) -> Node {
match self {
$($ty::$v $(( $($t),* ))? $({ $($f),* })? => Node::variant(
stringify!($v),
&mut [
$($((stringify!($t), Codec::digest($t)),)*)?
$($((stringify!($f), Codec::digest($f)),)*)?
],
),)*
}
}
fn put(&self, w: &mut Writer) {
match self {
$($ty::$v $(( $($t),* ))? $({ $($f),* })? => {
put_tag(w, stringify!($v));
$($(Codec::put($t, w);)*)?
$($(Codec::put($f, w);)*)?
})*
}
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let tag = get_tag(r)?;
$(if tag == stringify!($v).as_bytes() {
$($(let $t = Codec::get(r)?;)*)?
$($(let $f = Codec::get(r)?;)*)?
return Ok($ty::$v $(( $($t),* ))? $({ $($f),* })?);
})*
Err(Malformed)
}
}
)*};
}
/// A registry newtype over its raw number (`vk_enum!`/`vk_flags!`: every raw value is a value).
macro_rules! codec_vk_raw {
($($ty:ident: $raw:ty),* $(,)?) => {$(
impl Codec for vk::$ty {
const MIN_BYTES: usize = std::mem::size_of::<$raw>();
fn put(&self, w: &mut Writer) {
self.as_raw().put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(vk::$ty::from_raw(<$raw>::get(r)?))
}
}
)*};
}
codec_vk_raw!(
Format: i32,
DescriptorType: i32,
VertexInputRate: i32,
PrimitiveTopology: i32,
DynamicState: i32,
BlendFactor: i32,
BlendOp: i32,
LogicOp: i32,
Filter: i32,
SamplerMipmapMode: i32,
SamplerAddressMode: i32,
CompareOp: i32,
BorderColor: i32,
SamplerReductionMode: i32,
ComponentSwizzle: i32,
PipelineShaderStageCreateFlags: u32,
DescriptorSetLayoutCreateFlags: u32,
ShaderStageFlags: u32,
DescriptorBindingFlags: u32,
SampleCountFlags: u32,
ColorComponentFlags: u32,
);
/// Exactly one named stage bit (`vk_bit!`).
impl Codec for vk::ShaderStage {
const MIN_BYTES: usize = 4;
fn put(&self, w: &mut Writer) {
self.as_raw().put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
vk::ShaderStage::from_raw(u32::get(r)?).ok_or(Malformed)
}
}
/// A Metal enum over its checked raw ordinal (`metal_enum!`).
macro_rules! codec_metal_enum {
($($ty:ident),* $(,)?) => {$(
impl Codec for metal::$ty {
const MIN_BYTES: usize = 4;
fn put(&self, w: &mut Writer) {
self.as_raw().put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
metal::$ty::try_from(u32::get(r)?).map_err(|_| Malformed)
}
}
)*};
}
codec_metal_enum!(
PixelFormat,
BlendFactor,
BlendOperation,
TextureType,
VertexFormat,
VertexStepFunction,
AttributeFormat,
StepFunction,
IndexType,
TessellationFactorStepFunction,
TessellationControlPointIndexType,
TessellationPartitionMode,
TessellationFactorFormat,
Winding,
DataType,
BindingType,
BindingAccess,
SamplerAddressMode,
);
/// A SPIR-V capability by its grammar number; one the grammar does not name is malformed, since
/// only the builder writes these.
impl Codec for SpirvCapability {
const MIN_BYTES: usize = 4;
fn put(&self, w: &mut Writer) {
self.as_raw().put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
let c = SpirvCapability::from_raw(u32::get(r)?);
c.known().map(|_| c).ok_or(Malformed)
}
}
/// The module statistics, encoded in full and digested as zero: every count is a function of the
/// module's words, which the digest already covers, so including them would move every artifact's
/// digest without telling it anything. The destructuring is exhaustive, so a field added to
/// [`ModuleStats`] fails to compile until it is written here.
impl Codec for ModuleStats {
const LEAF: bool = false;
fn digest(&self) -> Node {
let ModuleStats {
functions: _,
blocks: _,
reachable_blocks: _,
instructions: _,
constructs: _,
loops: _,
inert: _,
entry_weight: _,
} = self;
Node::ZERO
}
fn put(&self, w: &mut Writer) {
let ModuleStats {
functions,
blocks,
reachable_blocks,
instructions,
constructs,
loops,
inert,
entry_weight,
} = self;
functions.put(w);
blocks.put(w);
reachable_blocks.put(w);
instructions.put(w);
constructs.put(w);
loops.put(w);
inert.put(w);
entry_weight.put(w);
}
fn get(r: &mut Reader<'_>) -> Result<Self, Malformed> {
Ok(ModuleStats {
functions: Codec::get(r)?,
blocks: Codec::get(r)?,
reachable_blocks: Codec::get(r)?,
instructions: Codec::get(r)?,
constructs: Codec::get(r)?,
loops: Codec::get(r)?,
inert: Codec::get(r)?,
entry_weight: Codec::get(r)?,
})
}
}
// Sampler state carries floats; `vk::SamplerDesc` compares them by bits, as `f32`'s codec
// round-trips them.
codec_struct! {
SamplerDesc {
mag_filter, min_filter, mipmap_mode, address_mode_u, address_mode_v, address_mode_w,
mip_lod_bias, max_anisotropy, compare, min_lod, max_lod, border_color, reduction,
border_components, unnormalized,
}
ComponentMapping { r, g, b, a }
}
// ---- Link symbols (`pipeline::sym`) ----
codec_struct! {
SlotRef { stage, class, index }
ImageHandleClass { dim, arrayed, multisampled, sampled_type, depth_compare, access, format }
CombinedSampler { sampler, compare, integer }
ResourceSlot { stage, kind, index }
}
codec_newtype!(AirUserKey, VaryingKey, PipelineKey, FunctionCompileKey);
codec_enum! {
Stage { Vertex, Fragment, Kernel, Object, Mesh }
Axis { X, Y, Z }
SlotClass { Buffer, Texture, Sampler }
ImageDim { D1, D2, D3, Cube, Buffer }
SampledType { Float, Sint, Uint, Uint64 }
ImageAccess { Sampled, Storage }
StorageFormatClass { NotStorage, Unknown, Format(f0) }
HandleClass { Image(f0), Sampler { compare, integer }, FunctionTable }
SyntheticBinding {
Imageblock, FunctionTableDirectory, TileMemory, FunctionTableSnapshot,
}
ResourceKind {
Buffer, Heap(f0), Synthetic(f0), AccelerationStructure(f0), TileAttachment(f0),
}
AccelerationStructureLevel { Primitive, Instance }
SamplerRef { Slot(f0), Constexpr(f0) }
SpecKey {
LocalSize(f0), FlatLocalSize, MultiRegion, TgLength(f0), SampleCount,
AmplificationCount, ImageblockWidth, ImageblockHeight,
RenderAreaWidth, RenderAreaHeight, TgOffset(f0),
TileThreadgroupLength, TileGridWidth,
ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0),
DeepThreadgroup,
WorkgroupSize(f0), TexelBufferWords { stage, handles },
}
PushField {
RootTableAddress, DispatchRegion, BaseVertexInstance,
SlotBindOffset(f0), SlotGuestBase(f0), VertexBufferStride(f0), StageInRegion,
TessellationFactorOffset, TessellationFactorInstanceStride, TessellationFactorScale,
TextureLevels(f0), InstanceCount(f0), ReplayRegionAddress,
ViewportCount, RenderTargetArrayLength,
PatchIndexOffset, PatchIndexBound, StageInStride(f0),
AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset,
DepthClampRange,
CaptureLayout,
CaptureIndexAddress,
TextureIntegerChannels(f0),
BicubicTexels(f0),
VerticesPerPrimitive,
MergedDrawAddress,
AlphaTestReference,
LineBand,
ArgumentTableAddress,
ConstexprSampler(f0),
TessellationFactorAddress,
PrivateArenaAddress,
SlotBounds(f0),
ZeroAddress,
FetchedColor { color, texels },
TailWord,
IndirectRange,
IndirectSequence,
IndirectBase,
TextureLevelBase(f0),
StencilBit,
PatchIndexAddress,
ControlPointIndexAddress,
DepthRangeFold,
}
Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) }
}
// ---- Requirements (`device::requirements`) ----
codec_struct! {
ApiVersion { major, minor }
Requirements {
api_version, spirv_capabilities, spirv_extensions, features, extensions, properties,
limits, formats, stage_flags, denorm_independence, rounding_independence,
}
SubgroupRequirement { size, full_subgroups, local_size_multiple, varying }
}
codec_enum! {
VkFeature {
RobustImageAccess, RobustImageAccess2, NullDescriptor, ShaderInt8, ShaderInt16,
ShaderInt64, ShaderFloat16, ShaderFloat64,
StorageBuffer8BitAccess, UniformAndStorageBuffer8BitAccess, StoragePushConstant8,
StorageBuffer16BitAccess, UniformAndStorageBuffer16BitAccess, StoragePushConstant16,
StorageInputOutput16, ShaderBufferInt64Atomics, ShaderSharedInt64Atomics,
ShaderImageInt64Atomics, ShaderBufferFloat32Atomics, ShaderBufferFloat32AtomicAdd,
ShaderBufferFloat32AtomicMinMax, ShaderSharedFloat32Atomics, ShaderSharedFloat32AtomicAdd,
ShaderSharedFloat32AtomicMinMax, ShaderImageFloat32Atomics, ShaderImageFloat32AtomicAdd,
ShaderImageFloat32AtomicMinMax, BufferDeviceAddress, ScalarBlockLayout,
UniformBufferStandardLayout, VulkanMemoryModel, VulkanMemoryModelDeviceScope,
WorkgroupMemoryExplicitLayout, WorkgroupMemoryExplicitLayout8BitAccess,
WorkgroupMemoryExplicitLayout16BitAccess, ShaderZeroInitializeWorkgroupMemory,
VertexPipelineStoresAndAtomics, FragmentStoresAndAtomics, ShaderDrawParameters,
GeometryShader, TessellationShader, SampleRateShading, DualSrcBlend, IndependentBlend,
ShaderClipDistance, ShaderCullDistance, ShaderOutputLayer, ShaderOutputViewportIndex,
Multiview, FragmentShaderBarycentric, FragmentShaderPixelInterlock,
FragmentShaderSampleInterlock, ShaderDemoteToHelperInvocation, ShaderTerminateInvocation,
DynamicRenderingLocalRead, RasterizationOrderColorAttachmentAccess,
RasterizationOrderDepthAttachmentAccess, RasterizationOrderStencilAttachmentAccess,
VertexAttributeInstanceRateDivisor, VertexAttributeInstanceRateZeroDivisor,
DrawIndirectFirstInstance, MultiDrawIndirect, DepthClamp, FillModeNonSolid,
ImageCubeArray, ShaderImageGatherExtended, ShaderResourceMinLod, SamplerAnisotropy,
SamplerFilterMinmax, SamplerMirrorClampToEdge, ShaderStorageImageMultisample,
ShaderStorageImageExtendedFormats, ShaderStorageImageReadWithoutFormat,
ShaderStorageImageWriteWithoutFormat, RuntimeDescriptorArray,
DescriptorBindingPartiallyBound, DescriptorBindingVariableDescriptorCount,
DescriptorBindingSampledImageUpdateAfterBind, DescriptorBindingStorageImageUpdateAfterBind,
DescriptorBindingStorageBufferUpdateAfterBind,
DescriptorBindingUniformTexelBufferUpdateAfterBind,
DescriptorBindingStorageTexelBufferUpdateAfterBind,
ShaderSampledImageArrayNonUniformIndexing, ShaderStorageImageArrayNonUniformIndexing,
ShaderStorageBufferArrayNonUniformIndexing,
ShaderUniformTexelBufferArrayNonUniformIndexing,
ShaderStorageTexelBufferArrayNonUniformIndexing, SubgroupSizeControl,
ComputeFullSubgroups, ShaderSubgroupExtendedTypes, ShaderMaximalReconvergence,
ShaderSubgroupUniformControlFlow, ComputeDerivativeGroupQuads,
ComputeDerivativeGroupLinear, Maintenance4, Synchronization2, ExtendedDynamicState,
ShaderUniformBufferArrayDynamicIndexing, ShaderSampledImageArrayDynamicIndexing,
ShaderStorageBufferArrayDynamicIndexing, ShaderStorageImageArrayDynamicIndexing,
ShaderUniformTexelBufferArrayDynamicIndexing, ShaderStorageTexelBufferArrayDynamicIndexing,
ShaderInputAttachmentArrayDynamicIndexing, ShaderBufferFloat16Atomics,
ShaderBufferFloat16AtomicAdd, ShaderBufferFloat16AtomicMinMax, ShaderSharedFloat16Atomics,
ShaderSharedFloat16AtomicAdd, ShaderSharedFloat16AtomicMinMax, ShaderBufferFloat64Atomics,
ShaderBufferFloat64AtomicAdd, ShaderBufferFloat64AtomicMinMax, ShaderSharedFloat64Atomics,
ShaderSharedFloat64AtomicAdd, ShaderSharedFloat64AtomicMinMax,
WorkgroupMemoryExplicitLayoutScalarBlockLayout, ShaderSubgroupRotate,
ShaderSubgroupRotateClustered, MultiViewport, Maintenance8, BorderColorSwizzle,
BorderColorSwizzleFromImage, RayQuery, AccelerationStructure, MultiviewTessellationShader,
DepthBiasClamp, ConstantAlphaColorBlendFactors, VertexAttributeAccessBeyondStride,
SamplerMipLodBias, MutableComparisonSamplers, ShaderSampleRateInterpolationFunctions,
ShaderResourceResidency,
ShaderFmaFloat32,
Maintenance5,
OcclusionQueryPrecise, DepthBiasControl, FloatRepresentation, DepthBiasExact,
MultisampleArrayImage, ImageView2DOn3DImage, SeparateStencilMaskRef, FullDrawIndexUint32,
DepthClipEnable, DepthClampControl, PrimitiveTopologyListRestart,
PrimitiveTopologyPatchListRestart,
ImageViewFormatSwizzle, TaskShader, MeshShader,
DescriptorBindingUpdateUnusedWhilePending,
ExtendedDynamicState2,
ShaderQuadControl,
ShaderTessellationAndGeometryPointSize, MultiviewGeometryShader,
AttachmentFeedbackLoopLayout, ExtendedDynamicState3ColorWriteMask,
ShaderFmaFloat16,
ProvokingVertexLast, LogicOp, DrawIndirectCount,
AlphaToOne,
BresenhamLines,
WideLines,
MultiDraw,
ShaderFloat8,
PointPolygons,
PipelineRobustness,
}
VkExtension {
ExtRobustness2, ExtImageRobustness, ExtShaderAtomicFloat, ExtShaderAtomicFloat2,
ExtShaderImageAtomicInt64, ExtShaderStencilExport, ExtShaderDemoteToHelperInvocation,
ExtShaderViewportIndexLayer, ExtFragmentShaderInterlock, ExtSubgroupSizeControl,
ExtRasterizationOrderAttachmentAccess, ExtVertexAttributeDivisor, ExtExternalMemoryHost,
ExtExtendedDynamicState, ExtMutableDescriptorType, ExtDescriptorBuffer, ExtMeshShader,
KhrShaderTerminateInvocation, KhrShaderMaximalReconvergence,
KhrShaderSubgroupUniformControlFlow, KhrFragmentShaderBarycentric,
KhrComputeShaderDerivatives, KhrWorkgroupMemoryExplicitLayout,
KhrZeroInitializeWorkgroupMemory, KhrDynamicRenderingLocalRead, KhrVertexAttributeDivisor,
KhrPushDescriptor, KhrMaintenance4, KhrSynchronization2, KhrShaderUntypedPointers,
KhrCooperativeMatrix, KhrShaderBfloat16, KhrRayQuery, QcomTileShading,
KhrShaderSubgroupRotate, KhrMaintenance8, KhrMaintenance5, ExtTextureCompressionAstcHdr,
ImgFormatPvrtc, ExtBorderColorSwizzle, ExtCustomBorderColor, KhrPortabilitySubset,
KhrDynamicRendering, KhrAccelerationStructure, KhrDeferredHostOperations, KhrShaderFma,
ExtDepthRangeUnrestricted,
ExtDepthBiasControl,
ExtDepthClipEnable, ExtDepthClampControl, ExtSampleLocations,
ExtPrimitiveTopologyListRestart,
ExtExtendedDynamicState2,
KhrShaderQuadControl,
ExtAttachmentFeedbackLoopLayout, ExtExtendedDynamicState3,
KhrFormatFeatureFlags2,
ExtProvokingVertex, ExtPostDepthCoverage,
ExtLineRasterization,
Ext4444Formats,
ExtMultiDraw,
ExtShaderFloat8,
ExtPipelineRobustness,
}
SubgroupOp { Basic, Vote, Arithmetic, Ballot, Shuffle, ShuffleRelative, Clustered, Quad }
FloatWidth { F16, F32, F64 }
FloatControl {
DenormPreserve, DenormFlushToZero, RoundingModeRte, RoundingModeRtz,
SignedZeroInfNanPreserve,
}
ResolveMode { SampleZero, Average, Min, Max }
VkProperty {
SubgroupStage(f0), SubgroupOperation(f0), SubgroupQuadOperationsInAllStages,
RequiredSubgroupSizeStage(f0), FloatControl(f0, f1), FilterMinmaxSingleComponentFormats,
DenormIndependence32BitOnly, DenormIndependenceAll, RoundingIndependence32BitOnly,
RoundingIndependenceAll, Rgba4OpaqueBlackSwizzled, FramebufferColorSampleCount(f0),
FramebufferIntegerColorSampleCount(f0), FramebufferDepthSampleCount(f0),
FramebufferStencilSampleCount(f0), FramebufferNoAttachmentsSampleCount(f0),
InterpolateAtOffsetCentered, StorageImageSampleCount(f0),
DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve,
ColorAttachmentSampleCount(f0, f1),
DeviceSampling,
InterpolateAtOffsetFromSevenSixteenths,
}
VkLimit {
MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations,
MaxComputeSharedMemorySize, MaxComputeWorkgroupSubgroups, MinSubgroupSize,
MaxSubgroupSize, MaxPushConstantsSize, MaxPushDescriptors, MaxBoundDescriptorSets,
MaxPerStageDescriptorSamplers, MaxPerStageDescriptorUniformBuffers,
MaxPerStageDescriptorStorageBuffers, MaxPerStageDescriptorSampledImages,
MaxPerStageDescriptorStorageImages, MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers,
MaxDescriptorSetStorageBuffers, MaxDescriptorSetSampledImages,
MaxDescriptorSetStorageImages,
MaxDescriptorSetUpdateAfterBindSamplers, MaxDescriptorSetUpdateAfterBindSampledImages,
MaxDescriptorSetUpdateAfterBindStorageImages,
MaxPerStageDescriptorUpdateAfterBindSamplers,
MaxPerStageDescriptorUpdateAfterBindSampledImages,
MaxPerStageDescriptorUpdateAfterBindStorageImages, MaxPerStageUpdateAfterBindResources,
MaxStorageBufferRange, MaxUniformBufferRange, MinStorageBufferOffsetAlignment,
MinUniformBufferOffsetAlignment, MinTexelBufferOffsetAlignment, MaxTexelBufferElements,
MaxSamplerLodBias, MaxSamplerAnisotropy, MinTexelOffset, MaxTexelOffset,
MinTexelGatherOffset, MaxTexelGatherOffset, MinInterpolationOffset,
MaxInterpolationOffset, MaxImageDimension1D, MaxImageDimension2D, MaxImageDimension3D,
MaxImageDimensionCube, MaxImageArrayLayers, MaxVertexInputAttributes,
MaxVertexInputBindings, MaxVertexInputAttributeOffset, MaxVertexInputBindingStride,
MaxVertexOutputComponents, MaxTessellationGenerationLevel,
MaxTessellationEvaluationOutputComponents, MaxFragmentInputComponents,
MaxFragmentOutputAttachments,
MaxFragmentDualSrcAttachments, MaxFragmentCombinedOutputResources, MaxColorAttachments,
MaxClipDistances, MaxCullDistances, MaxCombinedClipAndCullDistances,
MaxVertexAttribDivisor, MaxMultiviewViewCount, MaxMultiviewInstanceIndex,
MaxPerStageDescriptorAccelerationStructures, MaxDescriptorSetAccelerationStructures,
MaxFramebufferWidth, MaxFramebufferHeight, MaxFramebufferLayers,
MaxDrawIndexedIndexValue, MaxTessellationPatchSize, FunctionStorageBytesPerThread,
MaxMeshOutputVertices, MaxMeshOutputPrimitives, MaxMeshOutputComponents,
MaxTaskSharedMemorySize, MaxMeshSharedMemorySize, MaxMeshWorkGroupCount(f0),
MaxMeshWorkGroupTotalCount, MaxMeshWorkGroupSize(f0), MaxMeshWorkGroupInvocations,
MaxMeshOutputLayers, MaxTaskWorkGroupCount(f0), MaxTaskWorkGroupTotalCount,
MaxTaskWorkGroupSize(f0), MaxTaskWorkGroupInvocations, MaxTaskPayloadSize,
MaxTaskPayloadAndSharedMemorySize, MaxMeshPayloadAndSharedMemorySize,
MaxGeometryInputComponents, MaxGeometryOutputComponents, MaxGeometryTotalOutputComponents,
}
FormatUsage {
VertexBuffer, UniformTexelBuffer, StorageTexelBuffer, StorageTexelBufferAtomic,
SampledImage, SampledImageFilterLinear, SampledImageFilterMinmax, StorageImage,
StorageImageAtomic, ColorAttachment, ColorAttachmentBlend, DepthStencilAttachment,
StorageImageReadWithoutFormat, StorageImageWriteWithoutFormat,
StorageTexelBufferReadWithoutFormat, StorageTexelBufferWriteWithoutFormat,
}
SpirvExtension {
KhrTerminateInvocation, ExtDemoteToHelperInvocation, ExtFragmentShaderInterlock,
KhrFragmentShaderBarycentric, ExtShaderStencilExport, ExtShaderViewportIndexLayer,
ExtShaderAtomicFloatAdd, ExtShaderAtomicFloatMinMax, ExtShaderImageInt64,
KhrWorkgroupMemoryExplicitLayout, KhrComputeShaderDerivatives,
KhrSubgroupUniformControlFlow, KhrMaximalReconvergence, KhrFloatControls,
KhrVulkanMemoryModel, KhrShaderDrawParameters, KhrPhysicalStorageBuffer,
ExtDescriptorIndexing, ExtShaderAtomicFloat16Add, KhrSubgroupRotate, KhrRayQuery, KhrFma,
ExtMeshShader,
KhrQuadControl,
KhrPostDepthCoverage,
ExtFloat8,
}
StageCreateFlag { RequireFullSubgroups, AllowVaryingSubgroupSize }
Independence { Only32Bit, All, None }
}
// ---- Function interface (`pipeline::{interface, stage_io, facts, lower_inputs}`) ----
codec_struct! {
CommandWrites { operations, primitive_types, kinds }
StageInterface {
stage, slots, threadgroup, push, descriptors, spec, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures,
reads_unbound_resources, writes_unbound_resources, unbound_storage_textures,
numbered_samplers, own_pixel_textures,
private_bytes,
}
TessellationStage { domain, control_points }
TessellationDescriptor {
max_tessellation_factor, partition_mode, factor_format, factor_step_function,
output_winding_order, control_point_index_type, factor_scale_enabled,
}
BufferSlot { access, window, form, kind }
TextureSlot {
texture_type, sampled_type, depth_compare, access, storage, declared_format,
level_zero_samplers,
}
TextureAccess { sample, read, write }
SamplerSlot { compare, coordinate_sensitive }
AccessSet { read, write }
StageDescriptor { slot, ty, count }
StageSpec { key, size, default, unread_bits }
PushPlacement { stage, fields, push_range, argument_table_size, tail_word }
PlacedField { field, loc, size }
ThreadgroupArgument { stage, index, alignment }
StageIo {
inputs, outputs, builtins, pulled, stage_in, multisampled, varyings_at_pixel,
position_depth, coverage_loop, color_writes, rounded_colors, primitive_inputs,
early_fragment_tests, extended_range_colors, extended_unorm_colors, unattached_colors,
sample_mask,
rotated_colors, rotated_factors, rotated_blends, decoded_fetches,
texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes,
half_blend_colors, half_fast_colors, float_blend_colors, zero_indices,
word_colors, alpha_in_red_colors, alpha_test, depth_compares,
}
DepthCompares { samplers, clamped }
WordField { shift, bits }
ExtendedRangeColor { form, blended, nearest_even }
ExtendedUnormColor { pixel_format, blend }
ExtendedUnormBlend {
source_rgb, destination_rgb, rgb_operation, source_alpha, destination_alpha,
alpha_operation,
}
PulledInput { index, ty, fetch }
StageInInput { index, ty, fetch }
StageInFetch { format, buffer_index, offset, stride, step_function, step_rate, index }
IoVariable { key, role, ty }
IoType { numeric, components, source_bits }
}
codec_enum! {
BindingKind { Plain, Buffer(f0), Threadgroup(f0), Texture(f0), ObjectPayload(f0) }
TypeDetail { Plain, Struct(f0), Array(f0), TextureReference(f0), Pointer(f0) }
SlotInterface { Buffer(f0), Texture(f0), Sampler(f0) }
NumberedSampler { Constexpr(f0), Read, Write }
PatchDomain { Triangle, Quad }
Window { Bounded { start, len }, Whole }
BufferForm { Descriptor, Psb }
BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable }
PushLoc { Push { offset }, ArgumentTable { offset } }
IoRole {
Attribute { index }, Varying { user, interpolation },
Color { attachment, index },
ViewportIndex, RenderTargetArrayIndex, PrimitiveVarying { user },
PrimitiveId, MergedCommand,
}
IoInterpolation { Flat, Smooth { sampling, perspective } }
IoSampling { Center, Centroid, Sample, Interpolant { center, centroid, sample } }
CoverageLoop { NotNeeded, Looped, Unlooped, Refused(f0) }
ChannelWrite {
Unorm { bits }, Snorm { bits, blended }, Srgb, FloatTowardZero { mantissa, signed }, Device,
FloatNearestEven { mantissa, signed }, BlendedNearestEven { mantissa, signed },
HalfUnorm { bits },
}
ExtendedRange {
Bgr10 { srgb }, Bgra10 { srgb }, Planes { srgb }, R10X6, Rg10X12, R10X6Srgb, Rg10X12Srgb,
R16Bfloat, Rg16Bfloat, Rgba16Bfloat, Rgb10A2Srgb,
}
WordAttachment { Packed16 { fields }, Srgb8 { fields }, Rgb9e5 }
FactorLane { Zero, One, Output(f0) }
TextureWriteRoundingMode { TowardZero, NearestEven }
CompareFunction { Never, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always }
CoverageLoopRefusal {
EarlyFragmentTests, Discard, QuadOperations, Attachments, InterpolationFunctions,
}
IoNumeric { Float, Uint, Sint }
StageBuiltin {
VertexIndex, InstanceIndex, Position { invariant }, PointSize { default },
ClipDistance { count }, Layer, ViewportIndex, FragCoord, FrontFacing, PointCoord,
SampleId, SampleMaskIn, PrimitiveId, FragDepth(f0), StencilRef, SampleMaskOut,
BaseInstance, BaryCoord { perspective }, ViewIndex, BaseVertex, DrawIndex,
}
DepthMode { Any, Greater, Less }
VertexFetch {
FixedFunction,
SignedFixedFunction,
Pulled { format, buffer_index, offset, step_function, step_rate },
}
RuntimeFact {
ThreadsPerThreadgroup, ThreadgroupMemoryLength { index },
LocalSizeConstraint { multiple }, LocalSizeLimits, DispatchGrid, IndirectGroupCount,
SampleCount, ImageViewShape { slot },
VertexFetch { attr }, VertexBufferStride { layout }, BaseVertexInstance,
DeviceAddresses { slot }, FramebufferFetch { color },
SimdgroupEmulation { bytes_per_simdgroup, arena }, AmplificationCount,
EmulatedSimdgroups,
ImageblockSize { cell_bytes },
RenderTargetArrayLength { layer_dropped }, StageInRegion,
StageInStride { layout },
TileFunction, TileAttachmentFormat { color, format },
StorageTextureNumericType { slot },
AccelerationStructureInstanceCount { slot },
PredicationVote, ViewportCount,
AliasedImageblock { data_size },
CallStackDepth { depth },
OpenClMode,
FlatGrid,
CallThreadgroups,
TileThreadgroupMemory { index },
TextureSwizzle { slot },
TileImageblock { data_size, alignment },
AmplificationDraws { layered, viewports },
FoldedGroups,
ReplayBindings,
ZeroedColor { color, format },
DroppedColor { color },
DepthClampRange,
RotatedWeights,
FunctionTableRange { addressed },
TileThreadgroup { tile_sized },
ObjectThreadgroupArena { static_bytes, payload },
MergedDraws,
QuadPrimitiveIds,
PrivateList,
PartialObjectThreadgroups,
RegionViewports,
PartialThreadgroups,
AddressAlignment { slot, align },
GridTiles,
PrivateArena { slot_bytes },
StencilBitDraws,
RobustStorageBuffers,
DepthRangeFold,
}
Mechanism {
Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant,
Builtin, PlanTimeCheck, BinderView, KeyProjection, RegionSelected,
RenderPassContract, None, PipelineStateOrPushConstant,
PipelineState,
}
}
// ---- Artifacts (`library`, `pipeline::artifact`) ----
codec_struct! {
RelocatableModule { words, relocs, requirements }
FunctionArtifact {
key, module, interface, facts, subgroup, reconvergence, precision, strategies,
requirements, variant_bits, profile, kernel, reflection, slot_writes, stats,
}
StageReflection { bindings, attributes }
SlotWrite { name, parameter, binding_type, index, count, used, access, writes }
RenderPipelineReflection { vertex, fragment, tile, object, mesh }
LinkedUseAnswers {
vertex_returns_value, fragment_writes_depth_unattached, stages_using_direct_arguments,
unwritten_fragment_inputs,
}
DirectArgumentUse { stage, gap }
UnwrittenFragmentInputs { names, gap }
ReflectionBinding { name, binding_type, access, index, used, argument, kind }
BufferBinding { alignment, data_size, data_type, struct_type, pointer_type }
ThreadgroupBinding { alignment, data_size }
ObjectPayloadBinding { alignment, data_size }
TextureBinding { texture_type, data_type, depth, array_length }
StructType { members }
StructMember { name, offset, data_type, argument_index, detail }
ArrayType { element_type, array_length, stride, argument_index_stride, element }
PointerType { element_type, access, alignment, data_size, element_is_argument_buffer, element }
TextureReferenceType { data_type, texture_type, access, depth }
KernelFacts {
max_total_threads, work_group_size, flat_local_size, static_threadgroup_bytes,
partition_oblivious, partition_simdgroups, image_only,
}
StrategyCensus { entries }
StrategyUse { uses, words }
ComputePipeline {
key, profile, stage, layout, dependencies, interface, metal_info, requirements,
variant_bits,
}
RenderPipeline {
key, profile, stages, layout, vertex_input, graphics, dependencies, interface,
requirements, variant_bits,
}
StageModule {
stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags,
reconvergence, precision_notes, strategies, rounded_colors, own_pixel_textures,
private_bytes, stats,
}
SpecializationLayout { constants }
SpecConstant { id, key, size, default, unread_bits }
RuntimeDependency { fact, mechanism }
ComputePipelineMetalInfo {
max_total_threads_per_threadgroup, thread_execution_width,
static_threadgroup_memory_length, support_indirect_command_buffers,
metal_max_total_threads_per_threadgroup,
}
PipelineInterface {
slots, threadgroup, push,
reaches_command_buffers, command_writes, texture_writing_stages,
reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, writes_memory,
numbered_samplers, stage_in,
}
PipelineLayout { sets, push_constants }
DescriptorSetLayout { set, bindings, flags }
DescriptorBinding {
binding, ty, count, stages, source, flags, variables,
}
PushConstantRange { stages, offset, size }
VertexInputState { bindings, attributes, pulled }
VertexBinding { binding, buffer_index, input_rate, divisor, stride }
VertexAttribute { location, binding, format, offset }
PulledAttribute { attribute, buffer_index, format, offset, step_function, step_rate, stride }
GraphicsState {
topology, color_attachments, depth_format, stencil_format, rasterization_samples,
alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states,
max_vertex_amplification_count, declares_layer,
tessellation, vertex_writes_memory, writes_viewport_index, writes_point_size, writes_depth,
reads_barycentric_coord, reads_primitive_id, interpolates_at_sample,
fragment_writes_memory, color_outputs,
sample_mask, logic_op, line_band,
}
TessellationState {
patch_control_points, domain, control_points, factor_step_function, push_offset,
control_point_index_type,
}
LineBandState { push_offset, primitive }
ColorAttachmentState { format, write_mask, blend }
BlendState { src_color, dst_color, color_op, src_alpha, dst_alpha, alpha_op }
}
codec_enum! {
Reconvergence { Guaranteed, ImplementationDefined }
LinkedUseGap { EndlessLoop, StackMemory, GatedOffMeshBuiltin, UnmeasuredColorWrite }
SlotWritability { Never, Maybe, Unknown(f0) }
SlotWriteGap { UnresolvedIndex, UnmeasuredPayloadStage, MemberRole }
BandPrimitive { Lines, Triangles }
PrecisionNote {
F16FmaDoubleRounding, GradFromBias,
DeviceTranscendentals, ReductionOrder, DeviceDenormals,
PixelSamplerScaling, DeviceArithmetic, DeviceSignedZeroInfNan, DeviceRayIntersection,
FastMathRewrites,
TessellationWinding, TessellationFactorEdgeCases, TessellationFactorScale,
TessellationFactorInstance,
Fp8Value,
MultisamplePosition,
BicubicFilterArithmetic,
DeviceNanEncoding,
RestrictedDepthRange,
CubeGradientFootprint,
HalfTexelConversion,
SrgbTexelDecode,
FunctionStorageAssumed,
QuadsCountedBeforeDiscard,
ViewBaseTexelOffset,
DeviceColorConversion,
DeviceInterpolation,
QuadsSplitByClipping,
FragmentSimdgroupGrouping,
BlendedWriteRounding,
RotatedBlendRounding,
LinkedSamplerNumbering,
ArgumentPixelSamplerScaling,
HalfOutputPrecision,
DevicePointSize,
ClippedCoverageSplit,
LoopedSampleOutputs,
HalfOutputFastMathBlend,
DeviceSampling,
NativeTranscendentals,
NativeDivision,
NativeFma,
DeviceTexelConversion,
NativeHalfConversion,
NativeHalfQuantize,
NativeNanEncoding,
NativeMinMax,
NativeDot,
NativeMix,
DevicePackConversion,
TessellationTriangleOrder,
UnmeasuredGroupSpeculation,
DeviceSampleLevel,
CoverageReadsRoundedAlpha,
DeviceVertexConversion,
DeviceAlphaCoverage,
DeviceInterpolationOffset,
ExtrapolatedInterpolation,
UnorderedFetchWithinDraw,
NativeLogicOperation,
CappedLodBias,
DeviceReconvergence,
SnormMinimumKept,
DeviceDepthBias,
DepthDenormals,
DeviceFilteredMipmaps,
TessellationFractionalSpacing,
CompressedTexelDecode,
SharedExponentKept,
DeviceRoundedResolve,
SwizzledOpaqueBlackBorder,
SimdgroupAccessOrder,
DeviceLineRasterization,
DeviceFragmentRuns,
DeviceOcclusionCount,
VertexSimdgroupGrouping,
RestrictedDepthUpload,
StencilOutputOverlap,
DeviceHalfDenormals,
RoundedSampleDepthCopy,
ExtendedRangeBlend,
ExtendedRangeBlendWindow,
}
BindingSource {
Buffer(f0), Synthetic { stage, binding }, IdentityArray,
AccelerationStructure { slot, level }, TileAttachment(f0),
}
VertexStride { Static(f0), PerBind }
}
#[cfg(test)]
mod tests;