Translator: the binder's plan goes, with everything only it reaches, and the TexelRows and YCbCrInPlace forms

The runtime never made a plan (it binds each draw and dispatch by the pipeline's interface), and
since the census digests each pipeline's content alone (two commits back) nothing in the tree calls
one. What only the plan reached goes with it:

- bind: BindState, BindShape and their shapes, BindingPlan and its instantiation
  (DispatchCommands, DrawCommands, push, descriptor and root-table templates and writes),
  plan.rs and plan/ (compute, resources, slots), instantiate.rs, resident.rs, the neutral
  resources' plan side, the heap's member planning and table bytes, the mesh arguments pass
  (MeshArguments, MeshArgumentsForm, fold_object_grid, metal_object_grid), ExecutionStatus and
  StatusBits as public items, TextureShape::Buffer, IndirectRef with the four indirect call
  variants (Dispatch::ThreadgroupsIndirect, DrawCall::Indirect, PatchesIndirect,
  MeshThreadgroupsIndirect) and IndexBufferRef::fetch_end. Dispatch, DrawCall and IndexBufferRef
  stay: validation states its cases' calls with them.
- error::BindError leaves the public surface; a crate-private BindError of three variants stays
  as the error of the heap's view derivation, which lower::texture::slot's storage-read check
  reads (bind::heap::tier_read_gaps). That check keeps only the storage view's format: the
  sampled-view branch and ImageViewDesc were reached by the plan alone.
- vk::DrawCommand, the plan's draw output.
- pipeline: ComputePipeline::plan, RenderPipeline::plan; cache: VariantKey::covers and
  large_buffer_form.
- The TexelRows form (bind::texel_rows, LoweringInputs::texel_rows, RuntimeFact and PushField
  TexelRows) and the YCbCrInPlace form (bind::ycbcr_in_place, lower/sampler/in_place.rs,
  LoweringInputs::ycbcr_in_place and ycbcr_planes_sampled, RuntimeFact and PushField
  YCbCrInPlace, PrecisionNote FloatSampleFilter and HalfSampleFilter, Routine::Quad). Only the
  binder set those inputs.
- The tests of the deleted items, and the plan halves of mixed tests. Of 6810 tests (`#[test]`
  functions in the workspace) 309 leave and 11 come in their place: the lowering halves of mixed
  tests, kept without the plan (the heap layout, the stage-in stride and region facts, the
  emulated-simdgroup and bicubic facts, the iris-xe storage classes), and the kept tests of the two
  renamed files. 50 others are edited to drop a plan half or a deleted item (the api_surface round
  trips; the simd_emulated, extended-range, recursion, dynamic-root, handles, heap-storage-read
  and mesh lowering cases). 6512 remain. engine_graphics_binder.rs and engine_heap_binder.rs keep
  one and two tests and are renamed engine_unattached_colors.rs and engine_heap_groups.rs.
- The runtime guard test's list of files the runtime inputs reach without being inputs drops the
  seven no input reaches since the cut: cache/digest.rs, lower/simd/divergent.rs,
  lower/simd/workgroup.rs, pipeline/artifact.rs, pipeline/layout.rs, pipeline/stage_io.rs and
  pipeline/vertex.rs; three of its reasons that named the plan or the binder say what reaches the file now.

559 public items leave (api_signatures.tsv: 55 structs, 26 enums, 140 variants, 245 fields,
52 methods, 24 associated constants, 7 constants, 5 functions, 5 impls). Consumer search, the
consumer's development at 92ffbed817, `git grep -w NAME` of each of the 112 removed names: 0 hits
for 105; the others are the consumer's own items: TessellationFactors 4 (its
Bound::TessellationFactors), YCbCrMatrix 3 (its own string and doc), texel_rows 2 (its own fn),
ThreadgroupsIndirect 6 (its own Dispatch enums and rt::Dispatch::Indirect), DrawIndexed 1 (a doc
naming MTLIndirectCommandType values), covers 109 and plan 105 (generic words; the `.covers(`
calls are its Extent's, the `.plan(` calls its video encoder's rate.plan). Its one import of
metal2vulkan::bind is the argument-buffer layout types, which stay.

The forms' audit. A texture over a buffer: the runtime's
tests::over::every_device_holds_a_texture_over_a_buffer_in_place. A two-plane YCbCr sample: no
runtime test; the runtime makes no texture of a two-plane YCbCr format (Gap::TextureFormat, the
runtime README's "A format is made where the translator's format table maps it" row), the
conformance cases ycbcr_gathers and ycbcr_textures record Metal's answers, and
known-gaps-rt.tsv lists the runtime's refusals (ycbcr-gathers-*, ycbcr-texel-reads-420v).

Versions:
- RUNTIME_VERSION 2550: it covers plan instantiation and the binder's run-time data. Nothing calls
  those since step 2: the runtime never used the binder, and the own-context executor is gone. A
  run of an unchanged artifact does nothing different, so the guard hash (runtime-sources.sha256)
  moves alone, and the RUNTIME_VERSION doc is rewritten to name what it still covers.
- SEMANTICS_VERSION 2273: no output changes for any input that still exists. The TexelRows and
  YCbCrInPlace forms, their facts, push fields and the two notes were reachable only through
  LoweringInputs::ycbcr_in_place, ycbcr_planes_sampled and texel_rows. Only the binder set those;
  the runtime sets none. The function key appended each of them only when set, so every surviving
  key hashes the same bytes. Two type declarations stay where they were, so module words do not
  move: bool in the bicubic types, uvec4 in the bicubic routines. Byte-identical modules are
  expected, not verified here; the 252-row hash probe is the check.
- ARTIFACT_FORMAT_VERSION 591: the codec tags enum variants by name. The removed RuntimeFact,
  PushField and PrecisionNote variants leave their tags unused, which cache/mod.rs's rule says
  needs no bump: an old entry holding one fails to decode, which is a miss. No codec_struct field
  is removed. That is why SamplerDesc.ycbcr stays.

The guard hash (crates/metal2vulkan-validation/runtime-sources.sha256) moves for the bind/
sources this deletes and edits and for vk/draw.rs, which leaves its list. No run of an unchanged
artifact changes: what stays in bind/ computes what it did (the heap's tier check takes the same
storage format; its removed sampled branch had no caller).

Docs: docs/API.md (section 5 is the interface; the binding and plan sections go), README.md,
docs/ARCHITECTURE.md, docs/HOWTO.md, docs/VALIDATION.md, the runtime README's DrawInput and
identity-domain rows, docs/REFUSALS.md (regenerated; the binder's section goes),
api_reference.md, api_signatures.tsv (blessed: removals only), tests/api_surface.rs, the
signatures floor (5000), the bind modules' own docs, and the public field docs of PushField,
RuntimeFact and SpecKey that named BindState, BindShape or BindingPlan. AGENTS.md: the project
table names pipelines and their interfaces, not binding plans; its "core lives in" line stays
true (bind/ still holds what the lowering reads).

Verified on 31692939d4, this commit's tree (steelbrain/cutbinder-probe-6): job m3-max-68107,
fmt, signatures, refusal surface, clippy -D warnings (workspace plain, --cfg m2v_gpu,
--cfg m2v_cpu_icd; the translator with no feature and with each alone; the AIR crate alone),
workspace Rustdoc -D warnings, each crate's private intra-doc links at 0, api-docs; job
m3-max-68109, the product, validation and conformance suites, doctests, and on lavapipe the
validation and runtime suites under --cfg m2v_cpu_icd, the conformance replay and the public
cases' qualification.
This commit is contained in:
Anees Iqbal committed 2026-11-22 10:15:34 -08:00
1 parent 6938e0dfc6
commit a7dd2e846e
182 files changed
+1913 -52117

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ manifest at the root) of seven crates under `crates/`:
| Crate | Published | What it is |
|---|---|---|
| `crates/metal2vulkan` | yes | The translator: Metal AIR to SPIR-V through a Metal-shaped API (device, library, pipelines, binding plans), and the `metal2vulkan` command (feature `cli`) |
| `crates/metal2vulkan` | yes | The translator: Metal AIR to SPIR-V through a Metal-shaped API (device, library, pipelines and their interfaces), and the `metal2vulkan` command (feature `cli`) |
| `crates/metal2vulkan-runtime` | yes | The runtime: the Metal API on Vulkan with one path for every device, built only on the translator's public API |
| `crates/metal2vulkan-air` | yes | The AIR front end: container, bitstream, bitcode, typed IR, metadata ABI, intrinsics, canonicalization, `graph`, `budget` |
| `crates/metal2vulkan-validation` | no | Authored semantic cases, Metal and Vulkan execution, harvest, the corpus index and audits |
+2 -2
View File
@@ -13,7 +13,7 @@ of a Vulkan device.
| Crate | Directory | What it is |
|---|---|---|
| `metal2vulkan` | [`crates/metal2vulkan`](crates/metal2vulkan) | The translator. A Metal-shaped API (device, library, pipeline descriptors, binding plans) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push constants. The `cli` feature builds the `metal2vulkan` command. |
| `metal2vulkan` | [`crates/metal2vulkan`](crates/metal2vulkan) | The translator. A Metal-shaped API (device, library, pipeline descriptors) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and the interface a consumer binds each draw and dispatch by. The `cli` feature builds the `metal2vulkan` command. |
| `metal2vulkan-runtime` | [`crates/metal2vulkan-runtime`](crates/metal2vulkan-runtime) | The Metal API on Vulkan, with one path for every device: devices, memory blocks and buffers, textures, sampler states, command queues, command buffers and events, encoders and pipeline states, run on a Vulkan device through `ash`. It uses only the translator's public API. |
| `metal2vulkan-air` | [`crates/metal2vulkan-air`](crates/metal2vulkan-air) | The AIR front end: the metallib container, the bitcode reader, a typed IR, AIR's metadata ABI, intrinsics and canonicalization. For tools that read AIR without translating it. |
| `metal2vulkan-validation` | [`crates/metal2vulkan-validation`](crates/metal2vulkan-validation) | Not published. Authored cases run on Metal and on Vulkan and compared, and bounded audits over a private corpus. |
@@ -121,7 +121,7 @@ let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
let pipeline = device.compile_compute_pipeline(&descriptor, &Budget::standard())?;
// pipeline.stage.spirv, pipeline.layout, pipeline.interface: create the Vulkan objects from these,
// then pipeline.plan(...) and plan.instantiate_dispatch(...) per dispatch.
// and bind each dispatch by the interface, as metal2vulkan-runtime does.
```
[docs/API.md](docs/API.md) walks the whole flow on a runnable example,
@@ -412,8 +412,8 @@ impl Case for PixelDownscales {
// These are the kinds a run provoked (see `pixel_samplers`): the device reads the pixel
// coordinate divided by the size, not Metal's `1/256` cell of it. A venue that announces
// another reads as divergent there until someone names it with a run. The device's own
// filter and sRGB decode (`float-sample-filter`, `srgb-texel-decode`) are native notes the
// suite declares for every case (`crate::replay::NATIVE_NOTES`).
// sRGB decode (`srgb-texel-decode`) is a native note the suite declares for every case
// (`crate::replay::NATIVE_NOTES`).
//
// **Each is a declaration and loosens nothing.** Each sits at the notices site alone, so
// a texel that differs still fails the case wherever it differs.
@@ -30,8 +30,7 @@
//! reads in its own arithmetic: at a sub-texel step it may read the neighbouring step, which the
//! runtime announces on every device (`pixel-sampler-scaling`, and
//! `argument-pixel-sampler-scaling` for `arg`). The `slot` site announces it under a nearest
//! state too, as the function does not know the bound state. A device that converts an 8-bit texel to a float
//! its own way announces `float-sample-filter`.
//! state too, as the function does not know the bound state.
//! Each notice is declared at the notices site alone, so a texel that differs still fails the case
//! where it differs, and is a `known-gaps-rt.tsv` row naming the note.
//!
@@ -950,11 +950,6 @@ impl Case for SamplerCrossings {
// a border colour, a level clamp and a comparison -- so nothing is emulated; what is
// declared is what a device announces about its own sampling.
//
// Where the device filters a float texture its own way (`float-sample-filter`, the
// address-mode triples and the three mip-filter rows on llvmpipe and the 5080), the note is
// the device's own answer, which the suite declares for every case
// (`crate::replay::NATIVE_NOTES`).
//
// The `compare-filters` row's `Depth32Float` texture: on every device (no runtime enables
// `VK_EXT_depth_range_unrestricted`) the comparing stage records that its texels hold no
// value outside [0, 1] (`restricted-depth-range`). Its depths all lie in [0, 1], so the
@@ -863,11 +863,6 @@ impl Case for SamplerFiltering {
// notices site is the whole of the difference. The other families provoke no notice and
// declare none, so a notice any of them starts announcing reads as divergent at once.
//
// Where the device filters a float texture its own way (`float-sample-filter`,
// `sampler-mip-linear` and `sampler-r-address-modes` on llvmpipe and the 5080), the note
// is the device's own answer, which the suite declares for every case
// (`crate::replay::NATIVE_NOTES`).
//
// And every family samples through the runtime sampler at `[[sampler(0)]]`, which the
// runtime's pipelines note as scaled (`crate::replay::pixel_sampler_scaling_notice` holds
// why). Measured through the rt side on lavapipe, the Radeon 780M and the RX 550: it fired
@@ -77,12 +77,8 @@ pub enum Degradation {
CubeGradientFootprint,
/// `metal2vulkan-degrade-half-texel-conversion`.
HalfTexelConversion,
/// `metal2vulkan-degrade-half-sample-filter`.
HalfSampleFilter,
/// `metal2vulkan-degrade-srgb-texel-decode`.
SrgbTexelDecode,
/// `metal2vulkan-degrade-float-sample-filter`.
FloatSampleFilter,
/// `metal2vulkan-degrade-function-storage-assumed`.
FunctionStorageAssumed,
/// `metal2vulkan-degrade-quads-counted-before-discard`.
@@ -213,9 +209,7 @@ impl Degradation {
Degradation::RestrictedDepthRange,
Degradation::CubeGradientFootprint,
Degradation::HalfTexelConversion,
Degradation::HalfSampleFilter,
Degradation::SrgbTexelDecode,
Degradation::FloatSampleFilter,
Degradation::FunctionStorageAssumed,
Degradation::QuadsCountedBeforeDiscard,
Degradation::ViewBaseTexelOffset,
@@ -314,9 +308,7 @@ impl Degradation {
Degradation::RestrictedDepthRange => "metal2vulkan-degrade-restricted-depth-range",
Degradation::CubeGradientFootprint => "metal2vulkan-degrade-cube-gradient-footprint",
Degradation::HalfTexelConversion => "metal2vulkan-degrade-half-texel-conversion",
Degradation::HalfSampleFilter => "metal2vulkan-degrade-half-sample-filter",
Degradation::SrgbTexelDecode => "metal2vulkan-degrade-srgb-texel-decode",
Degradation::FloatSampleFilter => "metal2vulkan-degrade-float-sample-filter",
Degradation::FunctionStorageAssumed => "metal2vulkan-degrade-function-storage-assumed",
Degradation::QuadsCountedBeforeDiscard => {
"metal2vulkan-degrade-quads-counted-before-discard"
@@ -423,9 +415,7 @@ impl Degradation {
PrecisionNote::RestrictedDepthRange => Degradation::RestrictedDepthRange,
PrecisionNote::CubeGradientFootprint => Degradation::CubeGradientFootprint,
PrecisionNote::HalfTexelConversion => Degradation::HalfTexelConversion,
PrecisionNote::HalfSampleFilter => Degradation::HalfSampleFilter,
PrecisionNote::SrgbTexelDecode => Degradation::SrgbTexelDecode,
PrecisionNote::FloatSampleFilter => Degradation::FloatSampleFilter,
PrecisionNote::FunctionStorageAssumed => Degradation::FunctionStorageAssumed,
PrecisionNote::QuadsCountedBeforeDiscard => Degradation::QuadsCountedBeforeDiscard,
PrecisionNote::ViewBaseTexelOffset => Degradation::ViewBaseTexelOffset,
@@ -460,9 +460,8 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool {
/// - **texel, vertex and colour conversions**: `device-texel-conversion`,
/// `half-texel-conversion`, `srgb-texel-decode`, the device's fixed-function conversion of a
/// normalized vertex attribute (`device-vertex-conversion`), `device-color-conversion`;
/// - **sampling and filtering**: `device-sampling`, `device-sample-level`, the device's filter of a
/// generated mipmap chain (`device-filtered-mipmaps`), and Vulkan's Y′CbCr model filtering a
/// two-plane texture's planes read in place (`half-sample-filter`, `float-sample-filter`);
/// - **sampling and filtering**: `device-sampling`, `device-sample-level`, and the device's filter
/// of a generated mipmap chain (`device-filtered-mipmaps`);
/// - **logic operations**: the device's `logicOp` on a 10-bit or signed normalized format's own
/// codes (`native-logic-operation`, where Metal operates on 10-bit codes widened to 16 bits, and
/// reads and stores a signed lowest code as the code above it);
@@ -519,8 +518,6 @@ pub const NATIVE_NOTES: &[crate::degradation::Degradation] = {
D::DeviceSampling,
D::DeviceSampleLevel,
D::DeviceFilteredMipmaps,
D::HalfSampleFilter,
D::FloatSampleFilter,
D::NativeLogicOperation,
D::DeviceRoundedResolve,
D::DeviceAlphaCoverage,
+4 -5
View File
@@ -3049,9 +3049,8 @@ cache is answered compile-required on both.
- a value from the encoder that the function reads and the identity domains do not source ("an
encoder value the function reads as F", `F` the `PushField`: a texture buffer's bind offset,
`SlotBindOffset`; a texture's level count, `TextureLevels`; the draw's `InstanceCount` or
`BaseVertexInstance`; a stage-in stride, `StageInStride`; a two-plane texture read in place,
`YCbCrInPlace`, which `tests::engine_ycbcr_in_place` asserts; and the others the translator
pushes beside the identity fields): no other test yet;
`BaseVertexInstance`; a stage-in stride, `StageInStride`; and the others the translator
pushes beside the identity fields): no test yet;
- a buffer argument not reached through its device address ("a buffer argument not reached
through its device address"): no test yet;
- a texture argument of a type the identity arrays hold no element of, or whose bound texture's
@@ -3066,7 +3065,7 @@ cache is answered compile-required on both.
- other state of a bound texture or sampler beyond its resource ID ("state of a bound texture
or sampler beyond its resource ID (F)", `F` the `RuntimeFact`), among them an argument
buffer's texture that the function only queries (`HeapNumericType`):
`tests::engine_heap_binder`'s
`tests::engine_heap_groups`'s
`a_query_only_argument_buffer_texture_is_refused_naming_its_numeric_type` asserts the text
for a 2D texture and a cube array, and the golden table holds the refusal's class for
`engine/tail_cases`' `tail_heap_cube_queries`;
@@ -3484,7 +3483,7 @@ cache is answered compile-required on both.
other than the sample and
amplification counts, dynamic state beyond Vulkan 1.3's (a vertex buffer layout whose stride is
set per bind among it), a feature or extension device creation does not enable, and a function
that reads what a draw does not supply (`DrawInput`: a function table, a table the binder builds,
that reads what a draw does not supply (`DrawInput`: a function table, a pointer or handle translation table,
a parameter block past the push range, a push field or bind-time fact the encoder does not fill,
an unnormalized constexpr sampler). Of the replay streams' contents that translate, every one
reads only its slots' addresses, resource IDs and constexpr sampler indices. The
+1 -1
View File
@@ -594,7 +594,7 @@ fn draw_input() -> Error {
/// through ([`RenderCompiled::numbered`]), and what a draw of it supplies.
///
/// Err: [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`] for a pipeline that reads
/// what a draw does not supply: a function table, a table the binder builds, a parameter block
/// what a draw does not supply: a function table, a pointer or handle translation table, a parameter block
/// longer than a ring chunk, push bytes past the device's push `window`
/// (`DeviceProfile::push_window`), a push field or bind-time fact the encoder does not fill, or an
/// unnormalized constexpr sampler.
+5 -5
View File
@@ -113,8 +113,9 @@ fn main() {
// The product's runtime: the modules that act on a compiled pipeline after the compile, whose
// behaviour C3's currency holds to `metal2vulkan::cache::RUNTIME_VERSION` beside an artifact's
// content digest. That is the binder (`src/bind`: planning, instantiation, the device replay,
// resident sets, status decoding), the device a run opens and what it enables (`src/device`,
// content digest. That is `src/bind` (argument-buffer layouts, the texel decoders, rate maps,
// indirect-command records, the device replay's helpers, the heap classes and status words),
// the device a run opens and what it enables (`src/device`,
// `src/ash_interop`), the Vulkan and Metal vocabularies the runtime maps (`src/vk`,
// `src/metal`, and the AIR front end's `metal2vulkan-air/src/metal`, whose `MTLDataType`
// `metal` re-exports), the record and table formats it writes (indirect commands, the rate and
@@ -127,7 +128,7 @@ fn main() {
// encode the YCbCr write takes from `air.pack`'s lowering (`src/lower/arith/pack.rs`), and
// half-float conversion. The translator's paths above are below its crate (`metal2vulkan/src/...`). Each
// path is a product file below the workspace's crates/ directory, this crate's parent: those
// listed here and the binder's Rust sources under `metal2vulkan/src/bind/`, test modules aside
// listed here and the Rust sources under `metal2vulkan/src/bind/`, test modules aside
// (`runtime_files`, so a file added there joins), all sorted as strings. The guard test in
// `candidate::engine::artifact` requires this hash to be the one validation pins
// (`runtime-sources.sha256`), and the inputs to be closed over the module files their non-test
@@ -182,7 +183,6 @@ fn main() {
"metal2vulkan/src/metal/vertex.rs",
"metal2vulkan/src/pipeline/table.rs",
"metal2vulkan/src/pipeline/tile_map.rs",
"metal2vulkan/src/vk/draw.rs",
"metal2vulkan/src/vk/generated.rs",
"metal2vulkan/src/vk/mod.rs",
"metal2vulkan/src/vk/structs.rs",
@@ -227,7 +227,7 @@ fn crate_files(root: &Path) -> Vec<PathBuf> {
/// Every Rust source below `relative` under `product` but test modules (a `tests` directory, a
/// `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to `product` with
/// `/` separators: the binder's (`metal2vulkan/src/bind/`), whose non-test code reads no data file
/// `/` separators: those of `metal2vulkan/src/bind/`, whose non-test code reads no data file
/// (its `.txt` files are its tests' measured answers). Cargo reruns this script when anything
/// under the directory changes, so a file added there joins the runtime's inputs.
fn runtime_files(product: &Path, relative: &Path, output: &mut Vec<String>) {
@@ -1 +1 @@
d4a8dbf255778b56f0fc58f50a8556378c56517877849831693afc7ee8721453
2cd56ba56f3577740c3c7f9d88157c79eb4d0c751a739358d48e877b0dd881ed
@@ -109,7 +109,7 @@ fn the_runtime_sources_are_the_committed_ones() {
let compile = "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests";
let values = "the compiled pipeline's value types; the artifact digests their values";
let spirv = "the SPIR-V builder: the binder's files reach it only through the merged draw's reads (bind/replay), which the compile emits into the merged variant; what they emit is in the pipeline the artifact digests";
let spirv = "the SPIR-V builder: the bind module's files reach it only through the merged draw's reads (bind/replay), which the compile emits into the merged variant; what they emit is in the pipeline the artifact digests";
let packed = "compile-time translation, reached only through lower/arith/pack.rs's pack and unpack intrinsics, which the compile emits; the runtime's YCbCr write takes that file's sRGB encode (srgb_encode), which reaches none of it";
let not_runtime = BTreeMap::from([
("metal2vulkan-air/src/abi/mod.rs", compile),
@@ -119,12 +119,11 @@ fn the_runtime_sources_are_the_committed_ones() {
("metal2vulkan-air/src/intrinsics/mod.rs", packed),
("metal2vulkan-air/src/ir/mod.rs", compile),
("metal2vulkan-air/src/lib.rs", compile),
("metal2vulkan/src/cache/digest.rs", "the content digest, which defines the artifact rather than acting on it"),
("metal2vulkan/src/cache/mod.rs", "the plan's specialization and variant keys, whose values the plan digest holds, and RUNTIME_VERSION itself, which cannot be among the sources it versions"),
("metal2vulkan/src/cache/mod.rs", "the `Hash256` re-export device/derive.rs names a profile's fingerprint with, and RUNTIME_VERSION itself, which cannot be among the sources it versions"),
("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"),
("metal2vulkan/src/lower/access/imageblock.rs", compile),
("metal2vulkan/src/lower/access/mod.rs", "compile-time translation, reached only from lower/dispatch.rs's kernel plan, which asks `identity` whether the profile takes the identity domains; what it produces is in the pipeline the artifact digests"),
("metal2vulkan/src/lower/access/tile.rs", "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests; the tile staging format reaches a run through the plan"),
("metal2vulkan/src/lower/access/tile.rs", "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests"),
("metal2vulkan/src/lower/arith/aggregate.rs", compile),
// The block decode (`bind/block_decode.rs`) and its exact division
// (`lower/arith/exact_division.rs`) reach the numeric forms and the constant emission at
@@ -138,8 +137,6 @@ fn the_runtime_sources_are_the_committed_ones() {
("metal2vulkan/src/lower/mesh/mod.rs", "compile-time translation, reached only from the compile-time part of lower/dispatch.rs (plan_kernel's mesh wrapper builtins) and as the parent of its work-buffer layout (lower/mesh/work.rs, an input); what it produces is in the pipeline the artifact digests"),
("metal2vulkan/src/lower/push.rs", "the push window's lowering, reached only from device/derive.rs, which reads `LEAST_BYTES`, Vulkan's least maxPushConstantsSize, to refuse a description below it before any pipeline exists, and from device/profile.rs, whose `push_window` reads `MOST_BYTES` to cap the device's window; what the lowering makes of the window is in the pipeline the artifact digests"),
("metal2vulkan/src/lower/select.rs", compile),
("metal2vulkan/src/lower/simd/divergent.rs", "compile-time translation (the predicated walk); the runtime reads only VOTE_BYTES, the vote word's size, which the compile also adds to the static threadgroup length the artifact reports, so a change to it moves the artifact digest"),
("metal2vulkan/src/lower/simd/workgroup.rs","binding-plan construction; the artifact digests the plan it makes (the workgroup arena size)"),
("metal2vulkan/src/memory/abi_index.rs", compile),
("metal2vulkan/src/memory/contain.rs", "the containment encoding, a function of the device profile (the venue's profile key holds it), shared by compile and the vertex layout"),
("metal2vulkan/src/memory/leaf.rs", compile),
@@ -148,7 +145,6 @@ fn the_runtime_sources_are_the_committed_ones() {
("metal2vulkan/src/memory/union_find.rs", compile),
("metal2vulkan/src/memory/views.rs", compile),
("metal2vulkan/src/metal/resource_word.rs", "the gpuResourceID texture word of the runtime's ID spec (docs/RESOURCE-ID.md); the product's run-time files reach it only as a child of metal/mod.rs and call none of it"),
("metal2vulkan/src/pipeline/artifact.rs", values),
("metal2vulkan/src/pipeline/compile.rs", compile),
("metal2vulkan/src/pipeline/compile/key.rs", "the compile's cache key, which the artifact digest excludes"),
("metal2vulkan/src/pipeline/compile/partition.rs", "compile-time translation, reached only from the compile-time part of lower/dispatch.rs (plan_kernel's grid edge: whether a kernel observes its threadgroup partition, decided from its AIR); what it produces is in the pipeline the artifact digests"),
@@ -156,12 +152,9 @@ fn the_runtime_sources_are_the_committed_ones() {
("metal2vulkan/src/pipeline/facts.rs", values),
("metal2vulkan/src/pipeline/graphics.rs", "the compiled pipeline's value types; the artifact digests their values (the graphics state)"),
("metal2vulkan/src/pipeline/interface.rs", values),
("metal2vulkan/src/pipeline/layout.rs", values),
("metal2vulkan/src/pipeline/lower_inputs.rs", "the compiled pipeline's value types; the artifact digests their values (the storage image classes)"),
("metal2vulkan/src/pipeline/mod.rs", values),
("metal2vulkan/src/pipeline/stage_io.rs", "the compiled pipeline's value types; the artifact digests their values (a kernel's `[[stage_in]]` fetches, which its binding plan carries for the stage-in reach the binder decides)"),
("metal2vulkan/src/pipeline/sym.rs", "the compiled pipeline's value types; the artifact digests their values (slots, push fields, handle classes)"),
("metal2vulkan/src/pipeline/vertex.rs", "the compiled pipeline's value types; the artifact digests their values (the vertex layout)"),
("metal2vulkan/src/spirv/builder/constructs.rs", spirv),
("metal2vulkan/src/spirv/builder/mod.rs", spirv),
("metal2vulkan/src/spirv/error.rs", spirv),
@@ -1,6 +1,5 @@
//! The Vulkan graphics pipeline of an engine `RenderPipeline`: one builder that L4 driver
//! acceptance ([`super::acceptance`]) and the render executor ([`super::render`]) share, so a
//! pipeline the sweep creates is the pipeline the executor draws with.
//! The Vulkan graphics pipeline of an engine `RenderPipeline`, as L4 driver acceptance
//! ([`super::acceptance`]) creates it.
//!
//! Everything comes from the artifact's graphics state and vertex input: the render pass
//! ([`create_render_pass`]: every color attachment at its Metal index, each framebuffer-fetch
@@ -1,6 +1,6 @@
//! The render pass's render target array length both executors draw a case with: the Metal oracle's
//! `MTLRenderPassDescriptor.renderTargetArrayLength` and the engine candidate's
//! `BindState::render_target_array_length`, derived once, so the two agree.
//! `MTLRenderPassDescriptor.renderTargetArrayLength` and the runtime candidate's
//! `RenderPassDescriptor::render_target_array_length`, derived once, so the two agree.
use crate::air::meta::{parse_air_fragment_meta, parse_air_vertex_meta, FragRole, VertOutRole};
use crate::case::Stage;
@@ -1,7 +1,7 @@
//! How both executors fetch a kernel case's `[[stage_in]]` data: the Metal oracle's
//! `MTLStageInputOutputDescriptor` and `setStageInRegion:`, and the engine candidate's
//! `ComputePipelineDescriptor::stage_input` and `BindState::stage_in_region`, derived once here, so
//! the two agree.
//! `ComputePipelineDescriptor::stage_input` and stage-in region, derived once here, so the two
//! agree.
//!
//! Each authored stage input's data is its own buffer at the slot the shared slot rule gives its
//! location ([`stage_input_slots`]), read as the case's format at offset 0 with the case's stride,
@@ -1,8 +1,8 @@
//! How both executors draw a tessellation case: the Metal oracle's `MTLRenderPipelineDescriptor`
//! tessellation fields, `setTessellationFactorBuffer:offset: instanceStride:`, `setCullMode:`, and
//! `drawPatches:...`, and the engine candidate's `RenderPipelineDescriptor::tessellation`,
//! `BindState::tessellation_factors`, cull mode, and `DrawCall::Patches`, derived once here, so the
//! two agree.
//! tessellation factor buffer, cull mode, and `DrawCall::Patches`, derived once here, so the two
//! agree.
//!
//! A case's patches are drawn from patch 0 with no patch index buffer, as many instances as the
//! case states from base instance 0, `numberOfPatchControlPoints` the function's
@@ -188,15 +188,9 @@ impl UlpTable {
/// - `HalfTexelConversion`: unbounded: a format whose conversion to `half` is not measured keeps
/// the device's quantize of its `f32` texel, so a lane can differ from Metal's by any amount (an
/// sRGB texel's decode).
/// - `HalfSampleFilter`: unbounded: a filtered `half` sample of a two-plane YCbCr texture whose
/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's
/// sum on the format's grid, which no tolerance is derived from.
/// - `SrgbTexelDecode`: unbounded: an 8-bit sRGB texel the device decodes where Metal decodes its
/// raw code through a twelve-bit table; Vulkan bounds the device's decode only by its precision
/// rules, and Metal's `float` gathers of sRGB texels are not measured.
/// - `FloatSampleFilter`: unbounded: a filtered `float` sample of a two-plane YCbCr texture whose
/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's
/// sum on the format's grid, which no tolerance is derived from.
/// - `QuadsCountedBeforeDiscard`: unbounded: a non-quad simdgroup operation before a discard, in a
/// shape whose placement by Metal's compiler is not known, takes, among its lanes, the quads the
/// discard drops, which moves a count, a ballot, or a reduction by whole lanes.
@@ -291,9 +285,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
| N::RestrictedDepthRange
| N::CubeGradientFootprint
| N::HalfTexelConversion
| N::HalfSampleFilter
| N::SrgbTexelDecode
| N::FloatSampleFilter
| N::QuadsCountedBeforeDiscard
| N::DeviceInterpolation
| N::ExtrapolatedInterpolation
@@ -60,9 +60,7 @@ fn every_precision_note_has_its_table_row() {
(N::RestrictedDepthRange, Allowance::Unbounded),
(N::CubeGradientFootprint, Allowance::Unbounded),
(N::HalfTexelConversion, Allowance::Unbounded),
(N::HalfSampleFilter, Allowance::Unbounded),
(N::SrgbTexelDecode, Allowance::Unbounded),
(N::FloatSampleFilter, Allowance::Unbounded),
(N::FunctionStorageAssumed, Allowance::Recorded),
(N::ViewBaseTexelOffset, Allowance::Recorded),
(N::DeviceColorConversion, Allowance::Recorded),
+20 -148
View File
@@ -10,33 +10,26 @@
//! fixtures are committed as LLVM text, so the example assembles them with `llvm-as` (LLVM 21 or
//! newer) from `PATH` first, as a consumer holding `.ll` would.
//!
//! It compiles a kernel for the committed `moltenvk-m3` profile under the resident-table domains,
//! the policy the translator's binder plans (and the same kernel as a bare
//! module's entry, linked alone), prints its pipeline interface, layout, and binding plan,
//! instantiates one dispatch, round-trips the pipeline through its cache encoding, answers a
//! pipeline-input request, shows a typed refusal on `runtime-floor`, dispatches a kernel with
//! `[[stage_in]]`, and compiles, plans, and draws a render pipeline and a tessellation pipeline. `tests/api_preview_example.rs` runs it in the gate and checks that
//! every code block of `docs/API.md` is quoted from it.
//! It compiles a kernel for the committed `moltenvk-m3` profile under the runtime's policy (and the
//! same kernel as a bare module's entry, linked alone), prints its pipeline interface and layout,
//! round-trips the pipeline through its cache encoding, answers a pipeline-input request, shows a
//! typed refusal on `runtime-floor`, compiles a kernel with `[[stage_in]]`, and compiles a render
//! pipeline and a tessellation pipeline. `tests/api_preview_example.rs` runs it in the gate and
//! checks that every code block of `docs/API.md` is quoted from it.
use std::path::{Path, PathBuf};
use std::process::Command;
use metal2vulkan::bind::{
BindState, BoundBuffer, BoundSampler, BoundTexture, Dispatch, DrawCall, SamplerDescriptor,
StageInRegion, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
};
use metal2vulkan::cache::PipelineArtifact;
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::error::{BindError, Error, Needs, RuntimeInput};
use metal2vulkan::error::{Error, Needs, RuntimeInput};
use metal2vulkan::library::{
CompiledFunction, FunctionConstantValue, FunctionConstantValues, Library,
};
use metal2vulkan::metal::{
AttributeFormat, DataType, PixelFormat, StepFunction, TextureType, VertexFormat,
};
use metal2vulkan::metal::{AttributeFormat, DataType, PixelFormat, StepFunction, VertexFormat};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, ComputePipeline, ComputePipelineDescriptor, EntryDescriptor,
EntryRef, FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, Stage,
EntryRef, FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor,
StageInputAttributeDescriptor, StageInputDescriptor, StageInputLayoutDescriptor, StageSource,
TessellationDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor,
VertexDescriptor,
@@ -77,7 +70,7 @@ fn profile_json(stem: &str) -> Result<String> {
}
/// The device a runtime compiles for on committed profile `stem`: the default policy, the
/// identity domains. The runtime binds what such a device's pipelines push itself.
/// identity domains.
fn runtime_device(stem: &str) -> Result<Device> {
let json = profile_json(stem)?;
let description = DeviceDescription::from_khronos_json(&json, None)?;
@@ -85,42 +78,14 @@ fn runtime_device(stem: &str) -> Result<Device> {
Ok(device)
}
/// The tour's device for committed profile `stem`: the resident-table domains, the policy the
/// translator's binder plans (step 5 and the stage-in, render and tessellation walks), which a
/// runtime's device does not take ([`runtime_device`]).
fn committed_device(stem: &str) -> Result<Device> {
let json = profile_json(stem)?;
let description = DeviceDescription::from_khronos_json(&json, None)?;
let device = Device::from_queries(description, DevicePolicy::RESIDENT_TABLES)?;
Ok(device)
}
/// A buffer bound at `offset` in a `length`-byte allocation whose Metal `gpuAddress` and Vulkan
/// device address are both `0x1_0000`, as the runtime makes them.
fn buffer(length: u64, offset: u64) -> BoundBuffer {
BoundBuffer::Buffer {
length,
offset,
gpu_address: 0x1_0000,
device_address: Some(0x1_0000),
attribute_stride: None,
}
}
/// Lowercase hex of a digest.
fn hex(digest: &[u8]) -> String {
digest.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn main() -> Result<()> {
// 1. A device: what the consumer enabled, and its policy. A runtime's device takes the
// default policy; the tour's takes the resident-table domains, which its binding plans need.
let runtime = runtime_device("moltenvk-m3")?;
println!(
"runtime's device: profile {}",
hex(&runtime.profile().fingerprint())
);
let device = committed_device("moltenvk-m3")?;
// 1. A device: what the consumer enabled, and its policy, the runtime's default.
let device = runtime_device("moltenvk-m3")?;
let enables = device.required_enables();
println!(
"device: profile {}, {} features and {} extensions to enable",
@@ -193,43 +158,7 @@ pub fn main() -> Result<()> {
println!(" precision notes: {:?}", pipeline.stage.precision_notes);
println!(" Metal info: {:?}", pipeline.metal_info);
// 5. What is bound (Metal-shaped), the plan for its shape, and one dispatch.
let mut table = StageTable::default();
table.buffers.insert(0, buffer(4096, 0));
let facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm);
let texture = BoundTexture::Texture {
facts,
resource_id: None,
};
table.textures.insert(0, texture);
let sampler = BoundSampler::new(SamplerDescriptor::new());
table.samplers.insert(0, sampler);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
let plan = pipeline.plan(&device, &state.shape())?;
assert!(plan.variant.is_empty(), "this shape needs no other variant");
for write in &plan.descriptors {
println!(
" write set {} binding {}[{}] {:?}: {:?}",
write.set, write.binding, write.array_element, write.ty, write.source
);
}
let dispatch = Dispatch::Threads {
threads: [100, 1, 1],
threads_per_group: [32, 1, 1],
};
let commands = plan.instantiate_dispatch(&state, &dispatch)?;
for region in &commands.regions {
println!(
" region: {:?} groups, specialization {:?}",
region.group_count, region.specialization
);
}
println!(" descriptor ranges: {:?}", commands.descriptor_ranges);
println!(" push holes: {:?}", commands.push_holes);
// 6. The cache: a pipeline encodes under its key and decodes for the same device.
// 5. The cache: a pipeline encodes under its key and decodes for the same device.
let bytes = pipeline.to_bytes();
let cached = ComputePipeline::from_bytes_for_key(&bytes, &pipeline.key, &device)?;
assert_eq!(cached, pipeline);
@@ -255,7 +184,7 @@ pub fn main() -> Result<()> {
bytes.len()
);
// 7. A function-constant value, supplied by index. A constant left undefined compiles too, as
// 6. A function-constant value, supplied by index. A constant left undefined compiles too, as
// Metal's does: `is_function_constant_defined` names it false, and a value of it alone is zero.
let library = Library::from_air(&fixture_bitcode("kernel_vector_function_constant")?)?;
let function = library.function("kernel_vector_function_constant")?;
@@ -270,9 +199,9 @@ pub fn main() -> Result<()> {
assert_ne!(undefined.key, specialized.key);
println!("function constant supplied: {:?}", specialized.key);
// 8. A typed refusal: fragment function `sample_min_lod` clamps its level of detail, which
// 7. A typed refusal: fragment function `sample_min_lod` clamps its level of detail, which
// needs `shaderResourceMinLod`; the `runtime-floor` profile lacks it.
let floor = committed_device("runtime-floor")?;
let floor = runtime_device("runtime-floor")?;
let min_lod = FunctionDescriptor::new(sampling.function("sample_min_lod")?);
match floor.compile_function(&min_lod, &LoweringInputs::new(), &Budget::standard()) {
Err(Error::Unsupported(refusal)) => match (&refusal.feature, &refusal.needs) {
@@ -290,8 +219,8 @@ pub fn main() -> Result<()> {
tessellation(&device)
}
/// A kernel with `[[stage_in]]` on `device`: the stage-input descriptor it asks for, the kernel
/// compiled on its own under it, and a dispatch that needs the encoder's stage-in region.
/// A kernel with `[[stage_in]]` on `device`: the stage-input descriptor it asks for, and the kernel
/// compiled on its own under it.
fn stage_in(device: &Device, budget: &Budget) -> Result<()> {
let library = Library::from_air(&fixture_bitcode("kernel_stage_in")?)?;
let kernel = FunctionDescriptor::new(library.function("stage_in_region")?);
@@ -318,30 +247,10 @@ fn stage_in(device: &Device, budget: &Budget) -> Result<()> {
let mut linked = descriptor.clone();
linked.kernel = StageSource::Compiled(compiled);
assert_eq!(device.compile_compute_pipeline(&linked, budget)?, pipeline);
let mut table = StageTable::default();
table.buffers.insert(0, buffer(4096, 0));
table.buffers.insert(1, buffer(256, 0));
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
let plan = pipeline.plan(device, &state.shape())?;
let dispatch = Dispatch::Threads {
threads: [64, 1, 1],
threads_per_group: [32, 1, 1],
};
match plan.instantiate_dispatch(&state, &dispatch) {
Err(BindError::MissingStageInRegion) => {}
other => return Err(format!("expected a missing stage-in region: {other:?}").into()),
}
state.stage_in_region = Some(StageInRegion::new([0, 0, 0], [64, 1, 1]));
let commands = plan.instantiate_dispatch(&state, &dispatch)?;
for region in &commands.regions {
println!(" region push constants: {:?}", region.push_constants);
}
Ok(())
}
/// A render pipeline on `device`: compile, plan, and one draw.
/// A render pipeline on `device`: its stages and its vertex input.
fn render(device: &Device) -> Result<()> {
let library = Library::from_air(&fixture_bitcode("stage_io")?)?;
let vertex = FunctionDescriptor::new(library.function("stage_io_vertex")?);
@@ -378,27 +287,10 @@ fn render(device: &Device) -> Result<()> {
);
}
println!(" vertex input: {:?}", pipeline.vertex_input);
let mut table = StageTable::default();
table.buffers.insert(0, buffer(24 * 64, 0));
table.buffers.insert(1, buffer(256, 16));
let mut state = BindState::default();
state.stages.insert(Stage::Vertex, table);
let plan = pipeline.plan(device, &state.shape())?;
let draw = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 6,
instance_count: 1,
base_instance: 0,
};
let commands = plan.instantiate_draw(&state, &draw)?;
println!(" draw: {:?}", commands.draw);
println!(" vertex buffer offsets: {:?}", commands.buffer_offsets);
println!(" push constants: {:?}", commands.push_constants);
Ok(())
}
/// A tessellation pipeline on `device`: a post-tessellation vertex function, and a patch draw.
/// A tessellation pipeline on `device`: a post-tessellation vertex function.
fn tessellation(device: &Device) -> Result<()> {
let library = Library::from_air(&fixture_bitcode("tessellation")?)?;
let vertex = FunctionDescriptor::new(library.function("tess_quad_buffer")?);
@@ -408,25 +300,5 @@ fn tessellation(device: &Device) -> Result<()> {
let stages: Vec<_> = pipeline.stages.iter().map(|stage| stage.stage).collect();
println!("tessellation pipeline {:?}: {stages:?}", pipeline.key);
println!(" {:?}", pipeline.graphics.tessellation);
let mut table = StageTable::default();
table.buffers.insert(0, buffer(4096, 0));
let mut state = BindState::default();
state.stages.insert(Stage::Vertex, table);
let factors = TessellationFactorBuffer::new(4096, 0, 0);
state.tessellation_factors = TessellationFactors::new(Some(factors), 1.0);
let plan = pipeline.plan(device, &state.shape())?;
let draw = DrawCall::Patches {
control_points: 4,
patch_start: 0,
patch_count: 16,
patch_index: None,
instance_count: 1,
base_instance: 0,
control_point_index: None,
};
let commands = plan.instantiate_draw(&state, &draw)?;
println!(" draw: {:?}", commands.draw);
println!(" push constants: {:?}", commands.push_constants);
Ok(())
}
+9 -15
View File
@@ -1,7 +1,7 @@
metal2vulkan: the API (reference)
Metal AIR in; Vulkan SPIR-V, pipeline layouts, and per-draw binding instructions out, through an
API shaped like Metal's object lifecycle. The consumer never parses AIR, never parses or patches
Metal AIR in; Vulkan SPIR-V, pipeline layouts, and the interface a runtime binds them by out,
through an API shaped like Metal's object lifecycle. The consumer never parses AIR, never parses or patches
SPIR-V, never infers binding numbers from Metal indices, and never classifies errors by message
text.
@@ -23,8 +23,8 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn
`new`, `Default`, or their constants and assign fields, and match enums with a wildcard arm.
The exceptions are exhaustive by design, because their fields are their identity or are fixed
by Vulkan: [`pipeline::SlotRef`], [`pipeline::ResourceSlot`], [`pipeline::AirUserKey`],
[`pipeline::VaryingKey`], [`device::ApiVersion`], [`device::OpBits`], [`bind::StatusBits`],
[`bind::ExecutionStatus`], [`vk::ComponentMapping`], and [`vk::SpecializationMapEntry`].
[`pipeline::VaryingKey`], [`device::ApiVersion`], [`device::OpBits`],
[`vk::ComponentMapping`], and [`vk::SpecializationMapEntry`].
- **Semver.** The crate is `0.x`: a breaking change bumps the minor version.
- **Everything else is internal.** An item this reference does not show is not API: every
submodule of `library`, `pipeline`, `bind`, and `device` (name a type by its root path,
@@ -45,18 +45,13 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn
[`pipeline::RenderPipelineDescriptor`]) and compile it with
[`device::Device::compile_compute_pipeline`] or [`device::Device::compile_render_pipeline`]:
SPIR-V per stage, one pipeline layout, vertex input and fixed-function state, and the
[`pipeline::PipelineInterface`].
4. **A plan.** Describe what is bound, keyed by Metal slot ([`bind::BindState`]), and plan the
pipeline for its shape ([`bind::BindingPlan`]): the descriptor writes, vertex buffers, and
resource uses. Memoize it per shape.
5. **Commands.** Instantiate the plan per dispatch or draw ([`bind::DispatchCommands`],
[`bind::DrawCommands`]): descriptor ranges, push-constant bytes, table uploads, and the Vulkan
dispatches or draw to record. The binder never calls Vulkan.
6. **Caching.** Keys are known before compiling ([`cache::PipelineKey`],
[`pipeline::PipelineInterface`] (what each Metal slot binds as), and the bind-time state the
pipeline depends on (its `dependencies`), which a runtime binds, pushes or specializes.
4. **Caching.** Keys are known before compiling ([`cache::PipelineKey`],
[`library::FunctionCompileKey`]), and artifacts encode and decode through
[`cache::PipelineArtifact`]. The crate keeps no cache.
Failures are typed ([`error::Error`], [`error::BindError`]): a refusal
Failures are typed ([`error::Error`]): a refusal
([`error::Unsupported`]) names the Metal feature and what would make it translatable, and a
pipeline input the compile needs ([`error::RuntimeInput`]) is asked for, never guessed. Where an
output accepts a documented difference from Metal, its stage says so
@@ -72,8 +67,7 @@ The library needs none of them.
- `ash`: `From` conversions between [`vk`] values and `ash::vk`, and
`DeviceDescription::query`, which reads a physical device into a description (`ash_interop`).
- `serde`: `Serialize` and `Deserialize` on the plain-data values: device descriptions and
policies, bind states and shapes, plans and commands, pipeline interfaces and layouts, and the
Metal and Vulkan enums. Not on artifacts, which have their own encoding
policies, pipeline interfaces and layouts, and the Metal and Vulkan enums. Not on artifacts, which have their own encoding
([`cache::PipelineArtifact`]), nor on descriptors that hold a library.
- `cli`: the `metal2vulkan` command-line tool (`cargo install metal2vulkan --features cli`), which
compiles one pipeline with this API and writes its SPIR-V. It enables `serde` and adds nothing
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-861
View File
@@ -1,861 +0,0 @@
//! Per-draw and per-dispatch instantiation outputs shared by draws and dispatches, and the
//! arithmetic both share: descriptor ranges and residual bind offsets (`descriptor_range`), and the
//! resident root table ([`RootTable`]), and the buffer-slot, push-field, and texel-buffer
//! instantiation both share (`bind_buffers`, `slot_field`, `put`, `texel_ranges`). A push
//! field's bytes are held in place ([`FieldBytes`]), so a draw's fields allocate nothing.
use crate::bind::plan::compute::internal;
use crate::bind::plan::{BoundKind, PlannedBuffer, ResourceTemplate};
pub(crate) use crate::bind::resident::RootEntry;
use crate::bind::state::{BindState, BoundBuffer, BoundTexture};
use crate::error::{BindError, Feature, Unsupported};
use crate::memory::roots::{
BIND_OFFSET, ENTRY_BYTES, GUEST, HOST, RESIDENT_COUNT, RESIDENT_FIRST, SINK_ROOT, SIZE,
};
use crate::pipeline::interface::{BufferForm, PushLoc, Window};
use crate::pipeline::sym::{PushField, SlotRef};
use crate::vk;
/// Push-constant bytes for one stage range (`vkCmdPushConstants`).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PushConstantWrite {
pub stages: vk::ShaderStageFlags,
pub offset: u32,
pub bytes: Vec<u8>,
}
/// Bytes the consumer uploads into the buffer behind a plan binding (argument table, handle
/// table) before recording the draw or dispatch.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DescriptorBytes {
pub set: u32,
pub binding: u32,
pub bytes: Vec<u8>,
}
/// The byte window of one bound buffer slot that this draw or dispatch can touch: the staging and
/// writeback window. `window` is relative to the bind offset, as in the interface.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BufferExtent {
pub slot: SlotRef,
pub window: Window,
}
/// A push-constant field the consumer fills after uploading `descriptor_bytes`: a declared field,
/// not a patch.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PushHole {
/// The device address of the uploaded resident root table ([`RootTable`]), as a `u64` at
/// `offset` (absolute, in the push-constant block) of every region's push bytes.
RootTableAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of the command buffer's `ExecutionStatus` buffer (a function that counts
/// resident-set misses, reaches it by address), as a `u64` at `offset` of every region's push
/// bytes.
ExecutionStatusAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of the replayed indirect command buffer's record storage (its header), as
/// a `u64` at `offset` of the device replay's preprocess push bytes.
CommandRecordsAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of the region record a device-replay variant's dispatch reads: the
/// dispatch's command and region's in the replay's scratch, as a `u64` at `offset` of the
/// variant's push bytes. A flat variant's dispatch outside a
/// replay (`BindingPlan::instantiate_dispatch`) reads the record its preprocess wrote beside
/// the group counts. A mesh draw of a folded object function (`TASK_EXT`) reads its scratch's
/// region record: the arguments pass's (`DrawCommands::mesh_arguments`) or the uploaded fold's
/// (`DrawCommands::object_fold`), at the scratch's first byte.
ReplayRegionAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of a de-indexed draw's first index (`VariantKey::primitive_id_indices`),
/// as a `u64` at `offset` of the variant's vertex push bytes: the draw's index buffer's
/// address plus its index offset, which the binder requires to be a multiple of the index
/// size, in a buffer of `SHADER_DEVICE_ADDRESS` usage whose address is a multiple of 4; or a
/// private list form draw's list (`VariantKey::private_list`). The draw reads its indices
/// there in the vertex stage (`DrawCommands::uses`, as storage); a `u16` index is read in the
/// aligned 4-byte word that holds it, which lies inside the `VkBuffer` an `IndexBufferRef`
/// describes.
CaptureIndexAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of a merged draw replay's header in the replay's scratch, as a `u64` at `offset` of a merged variant's vertex push bytes
/// (`VariantKey::merged_draws`, `PushField::MergedDrawAddress`).
MergedDrawAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
}
/// A consumer-owned indirect-argument buffer and the byte offset of the arguments.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndirectRef {
/// The consumer's id for the buffer.
pub token: u32,
pub offset: u64,
}
/// A consumer-owned index buffer.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndexBufferRef {
/// The consumer's id for the buffer.
pub token: u32,
/// The end of the buffer's bytes (`MTLBuffer.length`), against which a draw's indices are
/// bounded ([`IndexBufferRef::fetch_end`]), in the offsets the draw binds the `VkBuffer` at
/// (the length itself where the consumer binds the buffer from its start). The buffer's byte 0
/// lies at a multiple of 4 bytes of those offsets, and the `VkBuffer` behind it holds at least
/// the length rounded up to 16 bytes (the padding).
pub length: u64,
}
impl IndexBufferRef {
/// The consumer's index buffer `token`, `length` bytes long.
pub fn new(token: u32, length: u64) -> IndexBufferRef {
IndexBufferRef { token, length }
}
/// Where Metal's index fetch from `index_offset` stops reading bytes at their position: the
/// length rounded up to 4 bytes where the offset lies before the length, so a partial last
/// index reads the bytes past the length up to there (the padding, or a heap's bytes after a
/// placed buffer); the length otherwise, where no byte lies inside from the offset. A position
/// from there on reads index 0. Measured on an Apple M4 (macOS 27.0.1) from offsets that are
/// multiples of 4; from an offset at or past the length Metal reads the memory past the buffer,
/// which the bound replaces with index 0, a contained near-equivalent.
pub fn fetch_end(&self, index_offset: u64) -> u64 {
if index_offset < self.length {
self.length
.checked_next_multiple_of(4)
.unwrap_or(self.length)
} else {
self.length
}
}
}
/// A byte range of a buffer: `range` bytes from `offset`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BufferRange {
pub offset: u64,
pub range: u64,
}
/// The range a buffer descriptor of the plan binds for this draw or dispatch. For a
/// `WriteSource::Buffer`, `range.offset` is from the start of the bound allocation; for a
/// `WriteSource::InlineBytes`, from the start of the consumer's upload of the bytes, which the
/// consumer places at an offset aligned to the descriptor type's `min*BufferOffsetAlignment`.
/// The consumer binds exactly this range, never more. It is at least 16 bytes, inside the
/// allocation padded to 16 bytes, and its offset is a multiple of the alignment. For a
/// `WriteSource::TexelBuffer`, the bytes the texel buffer view of the binding's array element
/// `element` views in the bound texture buffer's `VkBuffer` (`texel_ranges`): element 0 for one
/// view, and element `k` for part `k` of a texture buffer bound through its parts
/// (`bind::texel_parts`).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DescriptorRange {
pub set: u32,
pub binding: u32,
/// The binding's array element the range is bound at: 0 but for a texture buffer's parts.
#[cfg_attr(feature = "serde", serde(default))]
pub element: u32,
pub range: BufferRange,
}
/// The resident root table of a draw or dispatch: 32-byte entries `{host, guest, size,
/// bind_offset}: u64`, little-endian.
///
/// Entry 0 is the null root (zero). Entry 1 is the sink: its `host` field (at
/// [`RootTable::SINK_HOST_OFFSET`]) is left 0 for the consumer to fill with the device address of
/// its `NeutralResource::Sink`; its `guest` and `size` fields hold the resident set's first root
/// `R0` and entry count `N`. Entry `2 + n` is the `BufferForm::Psb` slot `[[buffer(n)]]` (zero
/// when unbound, so every access through it is contained). Entries `R0 .. R0 + N` are the
/// resident set, sorted by guest address and disjoint, each with `bind_offset = 0`. The consumer
/// writes the sink address, uploads the bytes to memory with a 16-byte-aligned device address,
/// and fills `PushHole::RootTableAddress` with that address.
///
/// `R0` counts 32-byte entries from the table's own address, modulo `2^64`, so a consumer may
/// point the table at a resident set it uploaded elsewhere: the table and the set
/// 32-byte-aligned, and the set holding at least the table's own ranges, it writes the set's address and its entry count over the
/// sink entry's `guest` and `size` fields.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RootTable {
pub bytes: Vec<u8>,
}
impl RootTable {
/// Byte offset of the sink entry's `host` field, which the consumer fills.
pub const SINK_HOST_OFFSET: u32 = (SINK_ROOT * ENTRY_BYTES + HOST) as u32;
/// The table with `statics` (entry `2 + n` for each `(n, entry)`, every `n < first - 2`) and
/// the resident set `resident` (already coalesced,
/// [`resident_set`](crate::bind::resident::resident_set)) from root `first`.
pub(crate) fn build(statics: &[(u32, RootEntry)], first: u64, resident: &[RootEntry]) -> Self {
let count = first as usize + resident.len();
let mut bytes = vec![0u8; count * ENTRY_BYTES as usize];
let mut put = |root: u64, field: u64, value: u64| {
let at = (root * ENTRY_BYTES + field) as usize;
bytes[at..at + 8].copy_from_slice(&value.to_le_bytes());
};
put(SINK_ROOT, RESIDENT_FIRST, first);
put(SINK_ROOT, RESIDENT_COUNT, resident.len() as u64);
let statics = statics.iter().map(|(n, e)| (2 + u64::from(*n), e));
let resident = (first..).zip(resident);
for (root, e) in statics.chain(resident) {
put(root, HOST, e.host);
put(root, GUEST, e.guest);
put(root, SIZE, e.size);
put(root, BIND_OFFSET, e.bind_offset);
}
RootTable { bytes }
}
}
/// One allocation of a resident set.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ResidentRange {
/// Its Vulkan device address.
pub host: u64,
/// Its Metal address.
pub guest: u64,
/// Its length in bytes, which a set pads to a multiple of 16.
pub length: u64,
}
/// `n` rounded up to a multiple of 16 (the allocation padding contract).
pub(crate) fn padded(n: u64) -> u64 {
n.saturating_add(15) & !15
}
/// Why [`descriptor_range`] has no range to bind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RangeError {
/// The allocation is empty: nothing can back a descriptor.
Empty,
/// The range exceeds the descriptor type's maximum (`needed` bytes).
TooLarge { needed: u64 },
}
/// The descriptor range and the `SlotBindOffset` residual of a descriptor-form slot, in checked
/// `i128` arithmetic, for an allocation of `length` bytes (padded to 16) bound at `bind_offset`,
/// with the slot's proven `window`, the descriptor base `alignment` `A` (at least 4 is used; a
/// Metal buffer slot's plan gives `max(minStorageBufferOffsetAlignment, 16)`, so a descriptor byte is
/// congruent to its Metal address modulo 16), and the view's maximum range `max_range`.
///
/// - `Bounded{start, len}`: from `align_down(max(0, bind_offset + start), A)` to
/// `round_up(bind_offset + start + len, 16)`; `Whole`: from `align_down(bind_offset, A)` to the
/// padded end. The end is clamped to the padded allocation.
/// - A range shorter than 16 bytes (a window at or past the end of the allocation) is widened to
/// 16 bytes inside the allocation (its start moves down to an aligned offset), so a bound range
/// is never empty and a contained load of word 0 stays inside it.
/// - The residual is `bind_offset` minus the range's start, modulo `2^32`: a leaf reads byte
/// `residual + m` of the range for the `u32` Metal offset `m` from the bind offset.
pub(crate) fn descriptor_range(
bind_offset: u64,
length: u64,
window: Window,
alignment: u64,
max_range: u64,
) -> Result<(BufferRange, u32), RangeError> {
let end = i128::from(padded(length));
if end == 0 {
return Err(RangeError::Empty);
}
let a = i128::from(alignment.max(4));
let down = |x: i128| x - x.rem_euclid(a);
let b = i128::from(bind_offset);
let (mut lo, hi) = match window {
Window::Bounded { start, len } => {
let s = b + i128::from(start);
(down(s.max(0)), (s + i128::from(len) + 15) & !15)
}
Window::Whole => (down(b), end),
};
let mut hi = hi.min(end);
if hi - lo < 16 {
lo = lo.min(down(end - 16));
hi = hi.max(lo + 16);
}
// `0 <= lo < hi <= end <= 2^64`: both fit `u64`.
let range = (hi - lo) as u64;
if range > max_range {
return Err(RangeError::TooLarge { needed: range });
}
let residual = (b - lo).rem_euclid(1 << 32) as u32;
Ok((
BufferRange {
offset: lo as u64,
range,
},
residual,
))
}
/// The descriptor range and the `SlotBindOffset` residual of a slot of `window` read at its
/// residual, bound at `bind_offset` of an allocation of `length` bytes (padded to 16), for the
/// descriptor base alignment `alignment` (at least 4 used) and the view's maximum range
/// `max_range`: a range that a run of bind offsets of the allocation shares, so a draw or dispatch
/// that moves only the slot's offset binds the same descriptor (and keeps its set 0) and moves
/// only its residual. For a `Bounded` window, `M` the smaller of `max_range` and `2^32` (a `u32`
/// residual and offset reach no further): the padded allocation whole where it fits `M`, from 0,
/// its residual the bind offset; else the block of `h` bytes the window's first byte lies in (`h`
/// the largest power of two at most half of `M`, a multiple of the alignment), to `M` past the
/// block's start or the padded end. A window of at most `M - h` bytes (at least half of `M`) that
/// starts in a block ends before `M` past the block's start, so it never straddles its block's
/// range; a longer one takes no block. Like [`descriptor_range`]'s, the range starts at a multiple of the
/// alignment, holds at least 16 bytes inside the padded allocation, and holds each byte `m` of
/// the window inside the allocation at `residual + m` (modulo `2^32`). `None` where no such range
/// holds the window (a `Whole` one, one at or past the padded end, one longer than its block
/// allows): the caller takes [`descriptor_range`]'s.
pub(crate) fn shared_range(
bind_offset: u64,
length: u64,
window: Window,
alignment: u64,
max_range: u64,
) -> Option<(BufferRange, u32)> {
let Window::Bounded { start, len } = window else {
return None;
};
let end = i128::from(padded(length));
let b = i128::from(bind_offset);
if b >= end {
return None;
}
let first = (b + i128::from(start)).max(0);
let last = (b + i128::from(start) + i128::from(len)).min(end);
// No range past `2^32` bytes: a `u32` residual and offset reach no further.
let max_range = max_range.min(1 << 32);
let (lo, hi) = if end <= i128::from(max_range) {
(0, end)
} else {
let a = alignment.max(4);
let block = 1u64 << (max_range / 2).checked_ilog2()?;
// The window's size limit: starting in the block, it ends inside the block's range.
if block < a || !block.is_multiple_of(a) || len > max_range - block {
return None;
}
let block = i128::from(block);
let lo = first - first.rem_euclid(block);
(lo, (lo + i128::from(max_range)).min(end))
};
debug_assert!(last <= hi, "a window past its shared range");
let residual = b - lo;
if first >= hi || hi - lo < 16 || residual.abs() >= 1 << 32 {
return None;
}
// `0 <= lo < hi <= end <= 2^64`: both fit `u64`.
let range = BufferRange {
offset: lo as u64,
range: (hi - lo) as u64,
};
Some((range, residual.rem_euclid(1 << 32) as u32))
}
/// The descriptor range and the `SlotBindOffset` residual of planned buffer slot `pb` bound at
/// `bind_offset` of an allocation of `length` bytes. Its function reads byte `residual + m` of the
/// range for the Metal offset `m`, the byte it read of the range from the bind offset, so a slot
/// binds a range its bind offsets share:
///
/// - a `Whole` window takes its range from the start of the bound buffer's space (offset 0) to the
/// padded end, its residual the bind offset, so every bind offset of one buffer binds one
/// descriptor and a draw or dispatch that moves only the offset keeps its set 0 (a dynamic one's
/// offset moves with the space alone); the bytes before the bind offset, which the window does
/// not state, are reachable as Metal's own memory is. Where that range would exceed the view's
/// `max_range` or reach past `2^32` (a `u32` residual and offset), or the bind offset lies at or
/// past the padded end, it takes [`descriptor_range`]'s range;
/// - a `Bounded` window takes [`shared_range`]'s, where it holds the window;
/// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down
/// to the descriptor base alignment.
pub(crate) fn planned_range(
pb: &PlannedBuffer,
bind_offset: u64,
length: u64,
) -> Result<(BufferRange, u32), RangeError> {
let end = padded(length);
let from_start =
pb.window == Window::Whole && bind_offset < end && end <= pb.max_range && end <= 1 << 32;
if !from_start {
let shared = shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range);
return match shared {
Some(shared) => Ok(shared),
None => descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range),
};
}
// `bind_offset < end <= 2^32`: the residual is the bind offset.
let range = BufferRange {
offset: 0,
range: end,
};
Ok((range, bind_offset as u32))
}
/// The bound buffer at `slot` of `state`, checked against the plan's shape.
pub(crate) fn bound_buffer(
state: &BindState,
slot: SlotRef,
expected: BoundKind,
) -> Result<Option<&BoundBuffer>, BindError> {
let table = state.stages.get(&slot.stage);
let b = table.and_then(|t| t.buffers.get(&slot.index));
// The kind alone is compared, which no offset class changes, its length classed as the
// table's buffer ranges class it in the shape.
let ranges = table.map(|t| t.buffer_ranges).unwrap_or_default();
let kind = BoundKind::of_bound(b, ranges);
debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(ranges)).as_ref()));
if kind != expected {
return Err(internal(format!(
"the bind state's shape differs from the plan's at {slot:?}"
)));
}
Ok(b)
}
/// What a draw or dispatch binds for the plan's buffer slots beside their descriptor ranges and
/// extents ([`bind_buffers`]).
pub(crate) struct BoundBuffers {
/// The `SlotBindOffset` residual of every bound descriptor-form slot.
pub residuals: Residuals,
/// The root entry of every bound device-address slot.
pub statics: Vec<(SlotRef, RootEntry)>,
}
/// The `SlotBindOffset` residuals a [`BoundBuffers`] holds that are kept in place, so a draw or
/// dispatch of no more descriptor-form slots allocates none.
const INLINE_RESIDUALS: usize = 8;
/// The `SlotBindOffset` residual of every bound descriptor-form slot, in the order they were
/// added: the first [`INLINE_RESIDUALS`] in place, the rest after them.
#[derive(Default)]
pub(crate) struct Residuals {
inline: [Option<(SlotRef, u32)>; INLINE_RESIDUALS],
rest: Vec<(SlotRef, u32)>,
}
impl Residuals {
/// Add `slot`'s residual last.
pub(crate) fn push(&mut self, slot: SlotRef, residual: u32) {
match self.inline.iter_mut().find(|r| r.is_none()) {
Some(free) => *free = Some((slot, residual)),
None => self.rest.push((slot, residual)),
}
}
/// The first residual added for `slot`.
fn of(&self, slot: SlotRef) -> Option<u32> {
(self.inline.iter().flatten())
.chain(&self.rest)
.find(|(s, _)| *s == slot)
.map(|r| r.1)
}
}
/// Instantiate `buffers` for `state`: each descriptor-form slot's range, pushed onto
/// `descriptor_ranges`, and residual (checked `i128`, `DescriptorRangeExceeded` above the view's
/// limit, an empty allocation `Unsupported{BufferRange}`), each bound device-address slot's root
/// entry, and each bound buffer's extent, pushed onto `extents`.
pub(crate) fn bind_buffers(
buffers: &[PlannedBuffer],
state: &BindState,
descriptor_ranges: &mut Vec<DescriptorRange>,
extents: &mut Vec<BufferExtent>,
) -> Result<BoundBuffers, BindError> {
let mut out = BoundBuffers {
residuals: Residuals::default(),
statics: Vec::new(),
};
for pb in buffers {
let bound = bound_buffer(state, pb.slot, pb.bound)?;
let (bind_offset, length) = match bound {
Some(&BoundBuffer::Buffer { length, offset, .. }) => {
extents.push(BufferExtent {
slot: pb.slot,
window: pb.window,
});
(offset, length)
}
// `set*Bytes` data: the consumer uploads it at an aligned offset of its own.
Some(&BoundBuffer::Bytes { len, .. }) => (0, u64::from(len.max(1))),
None => continue,
};
match (pb.form, pb.binding) {
(BufferForm::Descriptor, Some((set, binding))) => {
let (range, residual) =
planned_range(pb, bind_offset, length).map_err(|e| match e {
RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded {
slot: pb.slot,
needed,
limit: pb.max_range,
},
RangeError::Empty => BindError::Unsupported(
Unsupported::not_representable(Feature::BufferRange),
),
})?;
descriptor_ranges.push(DescriptorRange {
set,
binding,
element: 0,
range,
});
out.residuals.push(pb.slot, residual);
}
(BufferForm::Psb, _) => {
if let Some(&BoundBuffer::Buffer {
length,
offset,
gpu_address,
device_address: Some(host),
..
}) = bound
{
out.statics.push((
pb.slot,
RootEntry {
host,
guest: gpu_address,
size: padded(length),
bind_offset: offset,
},
));
}
}
_ => return Err(internal(format!("{:?} without its descriptor", pb.slot))),
}
}
Ok(out)
}
/// The bytes of one push field ([`put`]): held in place up to [`FieldBytes::INLINE`] bytes, as
/// every field of a few words is, so writing a draw's or a dispatch's fields allocates nothing;
/// a longer one on the heap.
pub(crate) enum FieldBytes {
/// The first `len` bytes of `bytes`.
Inline {
len: u8,
bytes: [u8; FieldBytes::INLINE],
},
Heap(Vec<u8>),
}
impl FieldBytes {
/// The most bytes a field holds in place: eight words.
pub(crate) const INLINE: usize = 32;
/// A field of `bytes`.
pub(crate) fn of(bytes: &[u8]) -> FieldBytes {
match bytes.len() <= Self::INLINE {
true => {
let mut inline = [0; Self::INLINE];
inline[..bytes.len()].copy_from_slice(bytes);
FieldBytes::Inline {
len: bytes.len() as u8,
bytes: inline,
}
}
false => FieldBytes::Heap(bytes.to_vec()),
}
}
/// A field of `words`, each little-endian.
pub(crate) fn words(words: impl IntoIterator<Item = u32>) -> FieldBytes {
words.into_iter().flat_map(u32::to_le_bytes).collect()
}
}
impl std::ops::Deref for FieldBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
FieldBytes::Inline { len, bytes } => &bytes[..usize::from(*len)],
FieldBytes::Heap(bytes) => bytes,
}
}
}
/// Bytes collected in place while they fit, else on the heap.
impl FromIterator<u8> for FieldBytes {
fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> FieldBytes {
let mut inline = [0; Self::INLINE];
let mut len = 0;
let mut iter = iter.into_iter();
for byte in iter.by_ref() {
if len == Self::INLINE {
let mut heap = inline.to_vec();
heap.push(byte);
heap.extend(iter);
return FieldBytes::Heap(heap);
}
inline[len] = byte;
len += 1;
}
FieldBytes::Inline {
len: len as u8,
bytes: inline,
}
}
}
/// The bytes of a slot push field (`SlotBindOffset`: the residual, 0 unbound; `SlotGuestBase`: the
/// slot's word of its `gpu_address + offset`, of 0 (Metal's `nil`) unbound ([`guest_word`]);
/// `TextureLevels`: the level count the plan bound; `InstanceCount`: the bound structure's instance
/// count), or `None` for another field. Planning refuses a `SlotGuestBase` of a `set*Bytes` slot
/// (`MissingGuestAddress`), so no inline-bytes slot is written as null here.
pub(crate) fn slot_field(
field: PushField,
residuals: &Residuals,
resources: &crate::bind::plan::ResourceTemplate,
state: &BindState,
) -> Option<FieldBytes> {
match field {
// The bound structure's instance count, 0 for an unbound slot.
PushField::InstanceCount(slot) => {
let count = state
.stages
.get(&slot.stage)
.and_then(|t| t.acceleration_structures.get(&slot.index))
.map_or(0, |s| s.instance_count);
Some(FieldBytes::of(&count.to_le_bytes()))
}
// The in-place planes of the texture bound at the slot, zeros where none is (the plan
// names the slot's variant only where one is).
PushField::YCbCrInPlace(slot) => {
let words = match state
.stages
.get(&slot.stage)
.and_then(|t| t.textures.get(&slot.index))
{
Some(BoundTexture::Texture { facts, .. }) => facts
.ycbcr_in_place
.map_or([0; crate::bind::YCbCrInPlace::WORDS], |p| p.words()),
_ => [0; crate::bind::YCbCrInPlace::WORDS],
};
let mut bytes = [0u8; 4 * crate::bind::YCbCrInPlace::WORDS];
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
chunk.copy_from_slice(&word.to_le_bytes());
}
Some(FieldBytes::of(&bytes))
}
// The rows of the texture bound at the slot in its texel buffer view, zeros where none
// is (the plan names the slot's variant only where one is).
PushField::TexelRows(slot) => {
let words = match state
.stages
.get(&slot.stage)
.and_then(|t| t.textures.get(&slot.index))
{
Some(BoundTexture::Texture { facts, .. }) => facts
.texel_rows
.map_or([0; crate::bind::TexelRows::WORDS], |r| r.words()),
_ => [0; crate::bind::TexelRows::WORDS],
};
let mut bytes = [0u8; 4 * crate::bind::TexelRows::WORDS];
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
chunk.copy_from_slice(&word.to_le_bytes());
}
Some(FieldBytes::of(&bytes))
}
// The level count the plan bound.
PushField::TextureLevels(slot) => resources
.texture_levels
.iter()
.find(|(s, _)| *s == slot)
.map(|(_, levels)| FieldBytes::of(&levels.to_le_bytes())),
// The integer channel widths of the texture the plan bound.
PushField::TextureIntegerChannels(slot) => resources
.texture_integer_channels
.iter()
.find(|(s, _)| *s == slot)
.map(|(_, word)| FieldBytes::of(&word.to_le_bytes())),
PushField::SlotBindOffset(slot) => Some(FieldBytes::of(&slot_bind_offset(residuals, slot))),
PushField::SlotGuestBase(slot) => Some(FieldBytes::of(&slot_guest_base(
state,
slot,
resources.biased_slot_words,
))),
PushField::SlotBounds(slot) => Some(FieldBytes::of(&slot_bounds(state, slot))),
_ => None,
}
}
/// The bytes of `PushField::SlotBindOffset(slot)` ([`slot_field`]): the slot's residual, 0
/// unbound.
fn slot_bind_offset(residuals: &Residuals, slot: SlotRef) -> [u8; 4] {
residuals.of(slot).unwrap_or(0).to_le_bytes()
}
/// The `SlotGuestBase` word of Metal address `address`: the address, or where `biased` (a plan of a
/// device compiling under the identity domains, `ResourceTemplate::biased_slot_words`) the address
/// less [`SLOT_ADDRESS_BIAS`](crate::lower::access::SLOT_ADDRESS_BIAS), modulo 2^64, which the
/// pipeline's accesses add back.
pub(crate) fn guest_word(address: u64, biased: bool) -> u64 {
match biased {
true => address.wrapping_sub(crate::lower::access::SLOT_ADDRESS_BIAS),
false => address,
}
}
/// The bytes of `PushField::SlotGuestBase(slot)` ([`slot_field`]): the word ([`guest_word`]) of the
/// slot's `gpu_address + offset`, of 0 (Metal's `nil`) where it binds no buffer.
pub(crate) fn slot_guest_base(state: &BindState, slot: SlotRef, biased: bool) -> [u8; 8] {
let base = match state
.stages
.get(&slot.stage)
.and_then(|t| t.buffers.get(&slot.index))
{
Some(&BoundBuffer::Buffer {
gpu_address,
offset,
..
}) => gpu_address.wrapping_add(offset),
_ => 0,
};
guest_word(base, biased).to_le_bytes()
}
/// The bytes of `PushField::SlotBounds(slot)` ([`slot_field`]): the bound buffer's bytes before
/// its bind offset, then its length, each at most `u32::MAX`; 0 and 0 where the slot binds no
/// buffer.
fn slot_bounds(state: &BindState, slot: SlotRef) -> [u8; 8] {
let (before, length) = match state
.stages
.get(&slot.stage)
.and_then(|t| t.buffers.get(&slot.index))
{
Some(&BoundBuffer::Buffer { length, offset, .. }) => (offset, length),
_ => (0, 0),
};
let word = |v: u64| u32::try_from(v).unwrap_or(u32::MAX).to_le_bytes();
let mut bytes = [0; 8];
bytes[..4].copy_from_slice(&word(before));
bytes[4..].copy_from_slice(&word(length));
bytes
}
/// A field's bytes at its placed location: the push bytes (relative to the push range's start
/// `push_start`) or the argument table.
#[inline]
pub(crate) fn put(
push: &mut [u8],
push_start: u32,
table: &mut [u8],
loc: PushLoc,
bytes: &[u8],
) -> Result<(), BindError> {
let (buf, at) = match loc {
PushLoc::Push { offset } => (push, offset.checked_sub(push_start)),
PushLoc::ArgumentTable { offset } => (table, Some(offset)),
};
let at = at.ok_or_else(|| internal("a push field before its range"))? as usize;
buf.get_mut(at..at + bytes.len())
.ok_or_else(|| internal("a push field outside its range or table"))?
.copy_from_slice(bytes);
Ok(())
}
/// The texel-buffer view ranges of every bound texture buffer the plan writes: the view starts at
/// the texture buffer's offset, which must be a multiple of `minTexelBufferOffsetAlignment` (the
/// shader indexes from element 0 of the view; an unaligned offset is `Unsupported{TexelBuffer,
/// NotRepresentable}`), and spans the whole texel blocks of its length
/// (`VUID-VkBufferViewCreateInfo-range-00929`: a multiple of the view format's block size; bytes
/// past the last whole block hold no texel). Its element count, `⌊length / block size⌋ × texels per
/// block`, must be at most `maxTexelBufferElements` (`VUID-VkBufferViewCreateInfo-range-00930`),
/// else `TexelBufferTooLarge`; a view without a whole block is `Unsupported{TexelBuffer,
/// NotRepresentable}`. A texture buffer the plan binds through its parts (`PlannedTexel::parts`,
/// `bind::texel_parts`) takes one range per part, at its array element: part `k` from the
/// offset plus `k · P` texels, `P` texels long but the last, which holds the rest; one of a
/// format of blocks of several texels is `TexelBufferTooLarge` too.
pub(crate) fn texel_ranges(
t: &ResourceTemplate,
state: &BindState,
) -> Result<Vec<DescriptorRange>, BindError> {
let mut out = Vec::new();
for pt in &t.texel_buffers {
let bound = state
.stages
.get(&pt.slot.stage)
.and_then(|s| s.textures.get(&pt.slot.index));
let Some(&BoundTexture::Buffer { offset, length, .. }) = bound else {
return Err(internal(format!(
"the bind state's shape differs from the plan's at {:?}",
pt.slot
)));
};
if offset % pt.alignment != 0 {
return Err(BindError::Unsupported(Unsupported::not_representable(
Feature::TexelBuffer,
)));
}
let block = pt.block_size.max(1);
let blocks = length / block;
if blocks == 0 {
return Err(BindError::Unsupported(Unsupported::not_representable(
Feature::TexelBuffer,
)));
}
let elements = blocks.saturating_mul(pt.texels_per_block);
let too_large = BindError::TexelBufferTooLarge {
slot: pt.slot,
elements,
limit: pt.max_elements,
};
let range = |element: u32, offset: u64, range: u64| DescriptorRange {
set: pt.set,
binding: pt.binding,
element,
range: BufferRange { offset, range },
};
if pt.parts <= 1 {
if elements > pt.max_elements {
return Err(too_large);
}
out.push(range(0, offset, blocks * block));
continue;
}
// Parts of `P` texels of one block each: every part but the last full, the last holding
// at least one texel.
let (part, parts) = (pt.part_texels, u64::from(pt.parts));
if pt.texels_per_block != 1 || part == 0 {
return Err(too_large);
}
if elements > part.saturating_mul(parts) || elements <= part.saturating_mul(parts - 1) {
return Err(internal(format!(
"{elements} texels of a texture buffer at {:?} in {parts} parts of {part}",
pt.slot
)));
}
for k in 0..pt.parts {
let first = part * u64::from(k);
let texels = part.min(elements - first);
out.push(range(k, offset + first * block, texels * block));
}
}
Ok(out)
}
#[cfg(test)]
mod tests;
@@ -1,705 +0,0 @@
//! Range arithmetic at extremes, the residual, the resident set, and push fields' bytes.
use super::*;
const MAX: u64 = u64::MAX;
/// The contract every range meets: aligned start, at least 16 bytes, inside the padded
/// allocation, and every Metal-defined byte of the window that lies in the allocation is at
/// `residual + m` inside the range.
fn check(bind_offset: u64, length: u64, window: Window, a: u64) {
let (r, residual) = descriptor_range(bind_offset, length, window, a, MAX)
.unwrap_or_else(|e| panic!("{bind_offset} {length} {window:?} {a}: {e:?}"));
let end = padded(length);
let a4 = a.max(4);
assert_eq!(r.offset % a4, 0, "aligned start");
assert!(r.range >= 16, "at least 16 bytes");
assert!(r.offset + r.range <= end, "inside the padded allocation");
assert_eq!(
u64::from(residual),
bind_offset.wrapping_sub(r.offset) & 0xFFFF_FFFF,
"residual is bind offset minus base, mod 2^32"
);
let (start, len) = match window {
Window::Bounded { start, len } => (i128::from(start), i128::from(len)),
Window::Whole => (0, i128::from(end) - i128::from(bind_offset)),
};
// Probe the window's first and last byte and its middle.
for m in [start, start + len / 2, start + len - 1] {
if len <= 0 {
break;
}
let abs = i128::from(bind_offset) + m;
if abs < 0 || abs >= i128::from(end) {
continue;
}
let rel = (i128::from(residual) + m).rem_euclid(1 << 32);
let expect = abs - i128::from(r.offset);
assert_eq!(rel, expect.rem_euclid(1 << 32), "byte {m} of {window:?}");
assert!(
expect >= 0 && expect < i128::from(r.range),
"byte {m} of {window:?} at {bind_offset} inside [{}, +{})",
r.offset,
r.range
);
}
}
#[test]
fn bounded_windows_bind_the_aligned_padded_window() {
// A 6-byte allocation: the last byte is covered by the 16-byte padded range.
let (r, res) = descriptor_range(0, 6, Window::Bounded { start: 5, len: 1 }, 16, MAX).unwrap();
assert_eq!((r.offset, r.range, res), (0, 16, 0));
// A window starting beyond the alignment block: the base moves up, the residual wraps.
let (r, res) = descriptor_range(
8,
4096,
Window::Bounded {
start: 256,
len: 16,
},
64,
MAX,
)
.unwrap();
assert_eq!(r.offset, 256);
assert_eq!(r.range, 32, "bytes 264..280 round up to 288");
assert_eq!(res, 8u32.wrapping_sub(256));
// A negative start clamps to 0: the residual is the bind offset.
let (r, res) = descriptor_range(
100,
4096,
Window::Bounded {
start: -200,
len: 400,
},
64,
MAX,
)
.unwrap();
assert_eq!((r.offset, res), (0, 100));
assert_eq!(r.range, 304);
// Whole: from the aligned bind offset to the padded end.
let (r, res) = descriptor_range(100, 1000, Window::Whole, 64, MAX).unwrap();
assert_eq!((r.offset, r.range, res), (64, 1008 - 64, 36));
}
#[test]
fn windows_past_the_allocation_still_bind_sixteen_bytes() {
// Bound past the end, or a window entirely outside: 16 bytes inside the allocation.
for (b, len, w) in [
(4096, 4096, Window::Whole),
(1 << 40, 64, Window::Whole),
(
0,
64,
Window::Bounded {
start: 1 << 20,
len: 4,
},
),
(0, 64, Window::Bounded { start: -64, len: 8 }),
(60, 64, Window::Bounded { start: 0, len: 4 }),
] {
let (r, _) = descriptor_range(b, len, w, 16, MAX).unwrap();
assert!(
r.range >= 16 && r.offset + r.range <= padded(len),
"{b} {w:?}"
);
check(b, len, w, 16);
}
assert_eq!(
descriptor_range(0, 0, Window::Whole, 16, MAX),
Err(RangeError::Empty)
);
}
#[test]
fn ranges_hold_at_extremes_of_every_operand() {
let offsets = [
0,
1,
3,
4,
15,
16,
255,
256,
(1 << 32) - 4,
(1 << 32) + 4,
(1 << 40) + 12,
MAX - 4095,
];
let lengths = [1, 6, 10, 16, 17, 4096, 1 << 33, MAX - 64];
let windows = [
Window::Whole,
Window::Bounded { start: 0, len: 1 },
Window::Bounded { start: 5, len: 1 },
Window::Bounded { start: -1, len: 2 },
Window::Bounded {
start: -(1 << 31),
len: 1 << 32,
},
Window::Bounded {
start: i64::MIN,
len: MAX,
},
Window::Bounded {
start: i64::MAX,
len: MAX,
},
Window::Bounded {
start: 1 << 32,
len: 64,
},
];
for &b in &offsets {
for &len in &lengths {
for &w in &windows {
for a in [1, 4, 16, 64, 256] {
check(b, len, w, a);
}
}
}
}
}
#[test]
fn ranges_above_the_descriptor_limit_are_refused() {
let w = Window::Bounded {
start: 0,
len: 1 << 20,
};
assert_eq!(
descriptor_range(0, 1 << 30, w, 16, 65536),
Err(RangeError::TooLarge { needed: 1 << 20 })
);
assert!(descriptor_range(0, 1 << 30, w, 16, 1 << 20).is_ok());
assert_eq!(
descriptor_range(0, 1 << 30, Window::Whole, 16, u64::from(u32::MAX)),
Ok((
BufferRange {
offset: 0,
range: 1 << 30
},
0
))
);
}
/// A planned buffer slot of `window`, under a view base alignment of `alignment` and a range limit
/// of `max_range`.
fn planned(window: Window, alignment: u64, max_range: u64) -> PlannedBuffer {
use crate::pipeline::sym::{SlotClass, Stage};
PlannedBuffer {
slot: SlotRef {
stage: Stage::Vertex,
class: SlotClass::Buffer,
index: 0,
},
window,
form: BufferForm::Descriptor,
access: crate::pipeline::interface::AccessSet::READ_WRITE,
binding: Some((0, 0)),
alignment,
max_range,
bound: BoundKind::Buffer {
device_address: false,
length_class: crate::bind::state::length_class(1 << 12),
},
}
}
/// A storage view of a whole buffer binds its space from 0 to the padded end at every bind offset
/// before the end, its residual the bind offset, so a draw that moves only the offset binds the
/// same descriptor; every byte from the bind offset to the end is at `residual + m`, inside the
/// range, as `descriptor_range` places it.
#[test]
fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() {
const LENGTH: u64 = 4096;
for alignment in [16, 64, 256] {
let pb = planned(Window::Whole, alignment, MAX);
for bind_offset in (0..LENGTH).step_by(4).chain([1, 15, LENGTH - 1]) {
let what = format!("{alignment} {bind_offset}");
let (range, residual) =
planned_range(&pb, bind_offset, LENGTH).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let whole = BufferRange {
offset: 0,
range: LENGTH,
};
assert_eq!((range, u64::from(residual)), (whole, bind_offset), "{what}");
// The byte `descriptor_range`'s range holds at `residual + m` for the Metal offset
// `m` is the same byte of the space here.
let (from_bind, at) =
descriptor_range(bind_offset, LENGTH, Window::Whole, alignment, MAX).unwrap();
for m in [0, (LENGTH - bind_offset) / 2, LENGTH - bind_offset - 1] {
let byte = range.offset + u64::from(residual) + m;
assert!(
byte < range.offset + range.range,
"{what} {m}: inside the range"
);
assert_eq!(byte, from_bind.offset + u64::from(at) + m, "{what} {m}");
}
}
}
// A buffer of 2^32 bytes, bound at its last word: the residual still fits.
let pb = planned(Window::Whole, 16, MAX);
let last = (1 << 32) - 4;
let (range, residual) = planned_range(&pb, last, 1 << 32).unwrap();
assert_eq!(
(range.offset, range.range, residual),
(0, 1 << 32, u32::MAX - 3)
);
}
/// Every other slot takes `descriptor_range`'s range: a storage view's range from 0 past the
/// view's limit or past `2^32`, a bind offset at or past the padded end, a bounded window no
/// shared range holds. A limit the range from the bind offset meets binds; one it does not is
/// refused as before.
#[test]
fn other_slots_bind_the_range_from_their_bind_offset() {
let same = |pb: &PlannedBuffer, bind_offset: u64, length: u64| {
assert_eq!(
planned_range(pb, bind_offset, length),
descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range),
"{:?} {:?} {bind_offset} {length}",
pb.window,
pb.form
);
};
let storage = |max_range| planned(Window::Whole, 64, max_range);
// Past the view's limit: the tail from the bind offset fits; the whole buffer from 0 is
// refused as before, at the range from the bind offset.
let limited = storage(1 << 16);
let length = 1 << 20;
same(&limited, length - 4096, length);
assert!(planned_range(&limited, length - 4096, length).is_ok());
same(&limited, 64, length);
assert_eq!(
planned_range(&limited, 64, length),
Err(RangeError::TooLarge {
needed: length - 64
})
);
// At the limit exactly, from 0.
let (range, _) = planned_range(&storage(length), 64, length).unwrap();
assert_eq!(range.offset, 0);
// Past 2^32 bytes: a residual and an offset of 32 bits could not state the bind offset.
for length in [(1 << 32) + 16, 1 << 33] {
for bind_offset in [0, 64, 1 << 31, (1 << 32) - 64, 1 << 32] {
same(&storage(MAX), bind_offset, length);
}
}
// At or past the padded end, where the range is widened down into the allocation, a whole
// window's or a bounded one's.
for bind_offset in [4096, 4100, 8192, MAX] {
same(&storage(MAX), bind_offset, 4096);
same(&storage(MAX), bind_offset, 4090);
let bounded = Window::Bounded { start: 0, len: 16 };
same(&planned(bounded, 64, MAX), bind_offset, 4096);
}
}
/// The contract every shared range meets where it is given, as `descriptor_range`'s does: an
/// aligned start, at least 16 bytes, inside the padded allocation and the view's limit, and every
/// byte of the window inside the allocation at `residual + m` inside the range.
fn check_shared(bind_offset: u64, length: u64, window: Window, a: u64, max_range: u64) {
let Some((r, residual)) = shared_range(bind_offset, length, window, a, max_range) else {
return;
};
let what = format!("{bind_offset} {length} {window:?} {a} {max_range}");
let end = padded(length);
assert_eq!(r.offset % a.max(4), 0, "{what}: aligned start");
assert!(r.range >= 16, "{what}: at least 16 bytes");
assert!(
r.offset + r.range <= end,
"{what}: inside the padded allocation"
);
assert!(
r.range <= max_range.min(1 << 32),
"{what}: inside the view's limit and 4 GiB"
);
let Window::Bounded { start, len } = window else {
panic!("{what}: a shared range of a whole window");
};
let (start, len) = (i128::from(start), i128::from(len));
for m in [start, start + len / 2, start + len - 1] {
if len <= 0 {
break;
}
let abs = i128::from(bind_offset) + m;
if abs < 0 || abs >= i128::from(end) {
continue;
}
let rel = (i128::from(residual) + m).rem_euclid(1 << 32);
let expect = abs - i128::from(r.offset);
assert_eq!(rel, expect.rem_euclid(1 << 32), "{what}: byte {m}");
assert!(
expect >= 0 && expect < i128::from(r.range),
"{what}: byte {m} inside [{}, +{})",
r.offset,
r.range
);
}
}
#[test]
fn shared_ranges_hold_every_window_byte_at_the_residual() {
let offsets = [
0,
4,
16,
255,
256,
32 * 1024 - 16,
32 * 1024,
65520,
65536,
(1 << 20) - 16,
(1 << 32) - 4,
(1 << 32) + 4,
MAX - 4095,
];
let lengths = [1, 16, 4096, 65536, 65537, 1 << 20, 1 << 33, MAX - 64];
let windows = [
Window::Bounded { start: 0, len: 16 },
Window::Bounded { start: 0, len: 1 },
Window::Bounded { start: -8, len: 40 },
Window::Bounded {
start: 256,
len: 16,
},
Window::Bounded {
start: 0,
len: 40000,
},
Window::Bounded {
start: i64::MIN,
len: MAX,
},
Window::Bounded {
start: 1 << 32,
len: 64,
},
];
for &b in &offsets {
for &len in &lengths {
for &w in &windows {
for a in [4, 16, 64, 256] {
for max_range in [64, 65536, 1 << 27, MAX] {
check_shared(b, len, w, a, max_range);
}
}
}
}
}
}
/// A slot of a bounded window binds one range at every bind offset of a buffer that fits the
/// view's limit, from 0, its residual the bind offset. Past the limit, the bind offsets of one
/// block of half the limit share one; the next block binds the next.
#[test]
fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() {
const CHUNK: u64 = 64 * 1024;
let bounded = Window::Bounded { start: 0, len: 16 };
let limited = planned(bounded, 64, CHUNK);
let storage = planned(bounded, 64, 1 << 27);
let whole = BufferRange {
offset: 0,
range: CHUNK,
};
for bind_offset in (0..CHUNK).step_by(256) {
let shared = (whole, bind_offset as u32);
assert_eq!(
planned_range(&limited, bind_offset, CHUNK),
Ok(shared),
"limited {bind_offset}"
);
assert_eq!(
planned_range(&storage, bind_offset, CHUNK),
Ok(shared),
"storage {bind_offset}"
);
}
// A buffer of 1 MiB, past the view's limit: blocks of 32 KiB.
let length = 1 << 20;
let block = CHUNK / 2;
for bind_offset in (0..length).step_by(256) {
let base = bind_offset - bind_offset % block;
let (range, residual) = planned_range(&limited, bind_offset, length).unwrap();
assert_eq!(
(range.offset, range.range, u64::from(residual)),
(base, CHUNK.min(length - base), bind_offset - base),
"{bind_offset}"
);
}
// A window never straddles its block's range: one of half the limit, starting in a block's
// last 16 bytes, ends inside the block's range; a longer one takes no block, and binds from
// its bind offset.
for start in [0, block - 16, 3 * block - 16] {
let half = Window::Bounded {
start: 0,
len: block,
};
let (range, residual) = shared_range(start, length, half, 64, CHUNK).unwrap();
assert_eq!(range.offset, start - start % block, "{start}");
assert!(
u64::from(residual) + block <= range.range,
"{start}: the window inside its block's range"
);
let longer = Window::Bounded {
start: 0,
len: block + 16,
};
assert_eq!(
shared_range(start, length, longer, 64, CHUNK),
None,
"{start}"
);
let pb = planned(longer, 64, CHUNK);
assert_eq!(
planned_range(&pb, start, length),
descriptor_range(start, length, longer, 64, CHUNK),
"{start}"
);
}
}
fn entry(host: u64, guest: u64, size: u64) -> RootEntry {
RootEntry {
host,
guest,
size,
bind_offset: 0,
}
}
#[test]
fn the_root_table_follows_d76_layout() {
let statics = [(0, entry(0x10, 0x20, 0x30)), (3, entry(0x40, 0x50, 0x60))];
let resident = [entry(0x100, 0x200, 0x300)];
let mut e = statics[1].1;
e.bind_offset = 8;
let statics = [statics[0], (3, e)];
let t = RootTable::build(&statics, 6, &resident);
let word = |root: u64, field: u64| {
let at = (root * ENTRY_BYTES + field) as usize;
u64::from_le_bytes(t.bytes[at..at + 8].try_into().unwrap())
};
assert_eq!(t.bytes.len(), 7 * 32);
assert!(t.bytes[..32].iter().all(|&b| b == 0), "entry 0 is null");
assert_eq!(word(1, HOST), 0, "the consumer fills the sink address");
assert_eq!(RootTable::SINK_HOST_OFFSET, 32);
assert_eq!((word(1, GUEST), word(1, SIZE)), (6, 1), "R0 and N");
assert_eq!(
(word(2, HOST), word(2, GUEST), word(2, SIZE)),
(0x10, 0x20, 0x30)
);
assert_eq!((word(5, HOST), word(5, BIND_OFFSET)), (0x40, 8));
assert!(t.bytes[3 * 32..5 * 32].iter().all(|&b| b == 0), "unbound");
assert_eq!(
(word(6, HOST), word(6, GUEST), word(6, SIZE)),
(0x100, 0x200, 0x300)
);
}
/// A texel-buffer view spans the whole blocks of the bound length and its element count
/// (`⌊length / block size⌋ × texels per block`) is checked exactly against
/// `maxTexelBufferElements`; an unaligned offset or a view without a whole block is not
/// representable.
#[test]
fn texel_views_count_whole_blocks_against_the_element_limit() {
use crate::bind::plan::PlannedTexel;
use crate::bind::state::StageTable;
use crate::pipeline::sym::{SlotClass, Stage};
let slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 3,
};
let block = vk::Format::R32G32B32_SFLOAT.block().expect("block");
let template = ResourceTemplate {
texel_buffers: vec![PlannedTexel {
set: 0,
binding: 5,
slot,
alignment: 16,
max_elements: 100,
block_size: u64::from(block.size),
texels_per_block: u64::from(block.texels),
parts: 1,
part_texels: 96,
}],
..ResourceTemplate::default()
};
let state = |offset: u64, length: u64| {
let mut t = StageTable::default();
t.textures.insert(
3,
BoundTexture::Buffer {
pixel_format: crate::metal::PixelFormat::RGBA32Float,
offset,
length,
bytes_per_row: length,
resource_id: None,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
parts: 1,
},
);
let mut s = BindState::default();
s.stages.insert(Stage::Kernel, t);
s
};
let range = |offset, length| texel_ranges(&template, &state(offset, length));
// 12-byte texels: 100 whole texels fit, the ragged tail is not part of the view.
assert_eq!(range(32, 1200).expect("at the limit")[0].range.range, 1200);
assert_eq!(range(32, 1210).expect("ragged")[0].range.range, 1200);
assert_eq!(range(0, 1211).expect("ragged")[0].range.range, 1200);
assert_eq!(
range(0, 1212),
Err(BindError::TexelBufferTooLarge {
slot,
elements: 101,
limit: 100
})
);
let not_representable = Err(BindError::Unsupported(Unsupported::not_representable(
Feature::TexelBuffer,
)));
assert_eq!(range(0, 11), not_representable, "no whole texel");
assert_eq!(range(8, 120), not_representable, "unaligned offset");
// A compressed block counts all of its texels.
let bc1 = vk::Format::BC1_RGB_UNORM_BLOCK.block().expect("block");
let mut compressed = template.clone();
compressed.texel_buffers[0].block_size = u64::from(bc1.size);
compressed.texel_buffers[0].texels_per_block = u64::from(bc1.texels);
assert!(texel_ranges(&compressed, &state(0, 48)).is_ok());
assert_eq!(
texel_ranges(&compressed, &state(0, 56)),
Err(BindError::TexelBufferTooLarge {
slot,
elements: 112,
limit: 100
})
);
}
/// A texture buffer bound through its parts (`bind::texel_parts`) takes one range per part at its
/// array element: part `k` from the offset plus `k · P` texels, `P` long but the last, which
/// holds the rest; past one view's limit, the same buffer bound as one view is
/// `TexelBufferTooLarge`. A format of blocks of several texels takes no parts, and texels the
/// parts do not hold are the bind state's disagreement with the plan's shape.
#[test]
fn texel_parts_view_the_limit_s_texels_each() {
use crate::bind::plan::PlannedTexel;
use crate::bind::state::StageTable;
use crate::pipeline::sym::{SlotClass, Stage};
let slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 2,
};
// `R32_UINT` texels, 100 to a view, parts of 96 (100 rounded down to the 16-byte alignment's
// 16 texels).
let planned = |parts| ResourceTemplate {
texel_buffers: vec![PlannedTexel {
set: 0,
binding: 4,
slot,
alignment: 16,
max_elements: 100,
block_size: 4,
texels_per_block: 1,
parts,
part_texels: 96,
}],
..ResourceTemplate::default()
};
let state = |length: u64| {
let mut t = StageTable::default();
t.textures.insert(
2,
BoundTexture::Buffer {
pixel_format: crate::metal::PixelFormat::R32Uint,
offset: 64,
length,
bytes_per_row: length,
resource_id: None,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
parts: 2,
},
);
let mut s = BindState::default();
s.stages.insert(Stage::Kernel, t);
s
};
let at = |element, offset, range| DescriptorRange {
set: 0,
binding: 4,
element,
range: BufferRange { offset, range },
};
// 150 texels: 96 in part 0, 54 in part 1 from texel 96.
assert_eq!(
texel_ranges(&planned(2), &state(600)),
Ok(vec![at(0, 64, 384), at(1, 64 + 384, 216)])
);
// 192 texels: two full parts; a ragged tail past the last whole texel is no texel.
assert_eq!(
texel_ranges(&planned(2), &state(770)),
Ok(vec![at(0, 64, 384), at(1, 64 + 384, 384)])
);
// 97 texels: one past the first part, the last holding one.
assert_eq!(
texel_ranges(&planned(2), &state(388)),
Ok(vec![at(0, 64, 384), at(1, 64 + 384, 4)])
);
// The same buffer as one view: past the limit.
assert_eq!(
texel_ranges(&planned(1), &state(600)),
Err(BindError::TexelBufferTooLarge {
slot,
elements: 150,
limit: 100
})
);
// Blocks of two texels take no parts.
let mut blocks = planned(2);
blocks.texel_buffers[0].texels_per_block = 2;
assert_eq!(
texel_ranges(&blocks, &state(600)),
Err(BindError::TexelBufferTooLarge {
slot,
elements: 300,
limit: 100
})
);
// Texels two parts do not hold, too many or too few.
for length in [772, 384] {
assert!(
matches!(
texel_ranges(&planned(2), &state(length)),
Err(BindError::Internal(_))
),
"{length} bytes"
);
}
}
/// A push field's bytes are the bytes it was made of, however they were made: held in place up
/// to `FieldBytes::INLINE` bytes, past it on the heap, a collect that crosses the bound included.
#[test]
fn field_bytes_hold_what_they_were_made_of() {
for len in [0, 1, 4, 31, 32, 33, 64, 200] {
let bytes: Vec<u8> = (0..len).map(|i| (i * 7 + 3) as u8).collect();
let of = FieldBytes::of(&bytes);
let collected: FieldBytes = bytes.iter().copied().collect();
for field in [&of, &collected] {
assert_eq!(&field[..], &bytes[..], "{len} bytes");
let inline = matches!(field, FieldBytes::Inline { .. });
assert_eq!(inline, len <= FieldBytes::INLINE, "{len} bytes");
}
}
let words = FieldBytes::words([1, 0x0403_0201, u32::MAX]);
assert_eq!(&words[..], &[1, 0, 0, 0, 1, 2, 3, 4, 255, 255, 255, 255]);
}
+11 -284
View File
@@ -1,82 +1,15 @@
//! The arguments pass of an indirect mesh draw on a device with `VK_EXT_mesh_shader`.
//! What Metal draws of a mesh grid. The object function's lowering holds the mesh grid an object
//! threadgroup sets to it (`lower::mesh`): past these limits it launches nothing.
//!
//! `drawMeshThreadgroupsWithIndirectBuffer:` reads its group counts (an
//! `MTLDispatchThreadgroupsIndirectArguments`) as it runs. `vkCmdDrawMeshTasksIndirectEXT` requires
//! every count within the device's task or mesh limits, so the draw cannot read Metal's arguments
//! in place: the consumer records an arguments pass first, which reads Metal's three words and
//! writes what the draw reads into a scratch, by the rules below ([`MeshArguments`] names the
//! folded object form's words in it).
//!
//! **What Metal draws**, measured by our probe on an M3 Max (macOS 27.0.1), direct and indirect
//! draws alike, with and without API validation, which stops none of them:
//!
//! - Without an object function the counts are the mesh grid. A grid with an axis past
//! [`METAL_MESH_GRID_AXIS`] (65,535) draws nothing; so does one of exactly 2^20 threadgroups
//! (1024 by 1024, 128 by 128 by 64, 4096 by 256) and every one measured of 2^21 or more. Grids
//! of up to [`METAL_MESH_GRID_TOTAL`] (1,048,575, Apple's limit for the family) draw whole. Past
//! that Metal is erratic (17 by 61,681 and 65,535 by 24 drew, 1025 by 1025 and 33 by 32,768 did
//! not), and the module draws nothing, Metal's answer at 2^20 and above 2^21.
//! - With an object function the counts are the object grid, which Metal runs at every count
//! that its GPU finishes within its watchdog's 5 s. An object function that does next to nothing
//! ran 2^28 threadgroups in 2.4 s and 2^29 in 4.98 s, direct and indirect; 2^30 and 2^32 were
//! discarded at 5 s, as was 2^29 of a costlier function: the command buffer fails with
//! `MTLCommandBufferErrorInternal` (1, "Discarded (victim of GPU error/recovery)"), and nothing
//! of it runs from the draw's encoder on (its clear, its draws before the grid's, the encoders
//! after it; an encoder before it ran), nor does a command buffer of the queue committed while
//! it ran. [`METAL_OBJECT_GRID_TOTAL`] is the most Metal ran; past it the runtime fails the
//! command buffer so (`DrawCommands::discards_command_buffer`, `MESH_GRID_DISCARDED`). Metal's
//! threads per grid along an axis are
//! the axis's threadgroups times its threads per threadgroup wrapped to 32 bits, which its grid
//! builtins report (`threads_per_grid`, and `threadgroups_per_grid` those threads over the
//! threadgroup's, rounded up): an indirect draw runs every threadgroup of its arguments
//! (4,294,970 by 1000 threads ran 4,294,970 threadgroups that each read a grid of 2704 threads,
//! 3 threadgroups), a direct draw only the threadgroups the wrapped threads fill, rounded up
//! (that draw ran 3, 4,194,304 by 1024 none) ([`metal_object_grid`]). The mesh grid an object
//! threadgroup sets follows the rule above (65,536 along `x` or `y`, 1024 by 1024 and 2048 by
//! 1024 launch nothing from it; 1023 by 1025 and 65,535 by 16 launch whole), which the object
//! function's lowering holds it to (`lower::mesh`).
//!
//! **The mesh form's rule** (Metal's limits, its constants, and the device's for the first
//! stage, [`MeshGridLimits`]): where Metal draws nothing, the pass writes zero counts, which draw
//! nothing. Where Metal draws and the counts lie within the
//! device's `maxMeshWorkGroupCount` and `maxMeshWorkGroupTotalCount`, it copies them; every
//! committed profile with the extension holds Metal's mesh grids so. Where they do not, it writes
//! zero counts and sets `MESH_GRID_PAST_LIMITS` in the command buffer's `ExecutionStatus`, which the
//! consumer reports as a command-buffer error.
//!
//! **The folded object form** ([`MeshArgumentsForm::FoldedObject`]) runs any object grid in
//! pieces within the task stage's limits ([`fold_object_grid`], which a direct draw's binder
//! computes on the CPU): on a device that folds object grids (`lower::mesh::folds_object_grids`)
//! the object function is compiled folded (`LoweringInputs::folded_groups`), so a task workgroup
//! counts its Metal threadgroup from its workgroup's position, the dispatch's size and its
//! `DrawIndex`, reads the threadgroups Metal runs and its threads per grid from the 32-byte region
//! record at its `PushField::ReplayRegionAddress`, and launches nothing past Metal's last
//! threadgroup. The pass writes, into the scratch:
//!
//! - the region record: the threadgroups Metal runs along each axis in the base's words (which a
//! folded variant reads in their place, `lower::dispatch`), the packed threads per object
//! threadgroup, and Metal's threads per grid ([`metal_object_grid`]);
//! - the draw count `P` ([`MeshArguments::OBJECT_COUNT`]) and [`MeshArguments::OBJECT_PIECES`]
//! commands of one piece's dispatch ([`MeshArguments::OBJECT_COMMANDS`]), which
//! `vkCmdDrawMeshTasksIndirectCountEXT` reads.
//!
//! A grid with a zero count draws nothing. One of more than [`METAL_OBJECT_GRID_TOTAL`]
//! threadgroups draws nothing and sets `MESH_GRID_DISCARDED`: Metal's GPU discards it. One that
//! more pieces than [`MeshArguments::OBJECT_PIECES`] would take (none on a device of the task
//! limits Vulkan requires) draws nothing and sets `MESH_GRID_PAST_LIMITS`: the device cannot
//! launch it.
//!
//! **The unfolded object form** ([`MeshArgumentsForm::Object`], a device that does not fold
//! object grids) is the mesh form's rule with Metal's discard as its limit: a grid of more than
//! [`METAL_OBJECT_GRID_TOTAL`] threadgroups writes zero counts and sets `MESH_GRID_DISCARDED`;
//! otherwise Metal's counts where they lie within the device's `maxTaskWorkGroupCount` and
//! `maxTaskWorkGroupTotalCount`, else zero counts and `MESH_GRID_PAST_LIMITS`.
//!
//! **Synchronization** (consumer): the source write → `SHADER_READ` in `COMPUTE_SHADER` before
//! the pass; the scratch `SHADER_WRITE` → `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT`, and for the
//! folded object form `SHADER_READ` in `TASK_SHADER`, between the pass and the draw.
use crate::bind::instantiate::{BufferRange, IndirectRef};
//! Measured by our probe on an M3 Max (macOS 27.0.1), direct and indirect draws alike, with and
//! without API validation, which stops none of them: a grid with an axis past
//! [`METAL_MESH_GRID_AXIS`] (65,535) draws nothing; so does one of exactly 2^20 threadgroups (1024
//! by 1024, 128 by 128 by 64, 4096 by 256) and every one measured of 2^21 or more. Grids of up to
//! [`METAL_MESH_GRID_TOTAL`] (1,048,575, Apple's limit for the family) draw whole. Past that Metal
//! is erratic (17 by 61,681 and 65,535 by 24 drew, 1025 by 1025 and 33 by 32,768 did not); nothing
//! is Metal's answer at 2^20 and above 2^21. The mesh grid an object threadgroup sets follows the
//! same rule (65,536 along `x` or `y`, 1024 by 1024 and 2048 by 1024 launch nothing from it; 1023
//! by 1025 and 65,535 by 16 launch whole).
/// The most mesh threadgroups along an axis of a grid Metal draws without an object function
/// (the module docs).
@@ -85,209 +18,3 @@ pub const METAL_MESH_GRID_AXIS: u32 = 65_535;
/// The most mesh threadgroups of a grid Metal draws whole without an object function (the module
/// docs).
pub const METAL_MESH_GRID_TOTAL: u32 = 1_048_575;
/// The most object threadgroups of a draw the runtime runs: the most Metal's GPU ran within its
/// watchdog's 5 seconds, of an object function that does next to nothing (2^29 in 4.98 s on an
/// M3 Max; 2^30 was discarded, the module docs). A larger grid draws nothing and fails the
/// command buffer as Metal's GPU discards it.
pub const METAL_OBJECT_GRID_TOTAL: u32 = 1 << 29;
/// Whether Metal draws nothing for a mesh grid of `groups` without an object function: an axis
/// past [`METAL_MESH_GRID_AXIS`], or more than [`METAL_MESH_GRID_TOTAL`] threadgroups.
pub(crate) fn metal_mesh_grid_draws_nothing(groups: [u32; 3]) -> bool {
let total: u128 = groups.iter().map(|&g| u128::from(g)).product();
groups.iter().any(|&g| g > METAL_MESH_GRID_AXIS) || total > u128::from(METAL_MESH_GRID_TOTAL)
}
/// The first stage of an indirect mesh draw, whose threadgroups Metal's arguments count.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MeshArgumentsForm {
/// The mesh function's, of a pipeline without an object function.
Mesh,
/// The object function's, on a device that does not fold object grids
/// (`lower::mesh::folds_object_grids`): Metal's counts where the device's task stage launches
/// them.
Object,
/// The object function's, compiled folded on a device that folds object grids: the fold of
/// Metal's counts ([`fold_object_grid`]).
FoldedObject,
}
/// A grid's limits: the largest count along each axis, and the largest product.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MeshGridLimits {
/// The largest count along `x`, `y` and `z`.
pub axes: [u32; 3],
/// The largest product of the three counts.
pub total: u32,
}
/// How a draw of an object grid runs on a device that folds object grids (the module docs): the
/// region record its object function reads, one piece's dispatch, and the pieces.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ObjectFold {
/// The 32-byte region record: the threadgroups Metal runs along each axis (in the base's
/// words), the packed threads per object threadgroup, Metal's threads per grid
/// ([`metal_object_grid`]), and 0, or, for a `drawMeshThreads` that leaves a partial object
/// threadgroup, the flag that its last threadgroup along an axis runs only the threads left
/// (`lower::dispatch::NONUNIFORM`, 1).
pub record: [u32; 8],
/// The group counts of each piece's `VkDrawMeshTasksIndirectCommandEXT`, within the task
/// stage's limits.
pub dispatch: [u32; 3],
/// The pieces, each a draw whose `DrawIndex` is its number: 0 for a grid that draws nothing.
pub pieces: u32,
/// The grid has more than [`METAL_OBJECT_GRID_TOTAL`] threadgroups, which Metal's GPU
/// discards: it draws nothing, and the command buffer fails as Metal's does.
pub discarded: bool,
/// The grid takes more than [`MeshArguments::OBJECT_PIECES`] pieces (only on a device of task
/// limits below Vulkan's required least), which the device cannot launch: it draws nothing,
/// and the command buffer fails (not Metal's failure).
pub past: bool,
}
/// Metal's grid of an object draw of `groups` threadgroups of `threads` threads each (the module
/// docs): the threadgroups it runs along each axis, and the threads per grid its builtins report,
/// `groups · threads` wrapped to 32 bits. An indirect draw (`direct` false) runs every threadgroup;
/// a direct one those the wrapped threads fill, rounded up (measured on the M3 Max). `None` where
/// an axis has no thread.
pub fn metal_object_grid(
groups: [u32; 3],
threads: [u32; 3],
direct: bool,
) -> Option<([u32; 3], [u32; 3])> {
if threads.contains(&0) {
return None;
}
let reported: [u32; 3] = std::array::from_fn(|i| groups[i].wrapping_mul(threads[i]));
let runs = match direct {
true => std::array::from_fn(|i| reported[i].div_ceil(threads[i])),
false => groups,
};
Some((runs, reported))
}
/// The fold of an object draw of `groups` threadgroups of `threads` threads each (1 to 1024 an
/// axis), direct or indirect, on a task stage of `task`'s limits (the module docs); `None` when
/// `threads` does not pack. Each piece runs `nx` by `ny` workgroups of the threadgroups Metal runs
/// ([`metal_object_grid`]): `nx` the fewer of those and the axis and total limits, `ny` the
/// fewest rows that cover them within the `y` limit and the total.
pub fn fold_object_grid(
groups: [u32; 3],
threads: [u32; 3],
task: MeshGridLimits,
direct: bool,
) -> Option<ObjectFold> {
let packed = crate::lower::dispatch::pack_nominal(threads)?;
let (runs, reported) = metal_object_grid(groups, threads, direct)?;
fold_runs(runs, reported, packed, 0, task)
}
/// The fold of a direct `drawMeshThreads` of `threads` threads in object threadgroups of `l`
/// threads each, on a task stage of `task`'s limits: the threadgroups the threads fill, rounded
/// up, whose last along an axis runs only the threads left, its record flagged
/// `lower::dispatch::NONUNIFORM` where one does (the partial object threadgroups the object
/// function runs, `RuntimeFact::PartialObjectThreadgroups`); `None` when `l` does not pack.
pub(crate) fn fold_object_threads(
threads: [u32; 3],
l: [u32; 3],
task: MeshGridLimits,
) -> Option<ObjectFold> {
let packed = crate::lower::dispatch::pack_nominal(l)?;
let runs = std::array::from_fn(|i| threads[i].div_ceil(l[i]));
let partial = (0..3).any(|i| !threads[i].is_multiple_of(l[i]));
let flags = match partial {
true => crate::lower::dispatch::NONUNIFORM,
false => 0,
};
fold_runs(runs, threads, packed, flags, task)
}
/// The fold of `runs` threadgroups of Metal's (packed threads per threadgroup `packed`) whose
/// grid builtins report `reported` threads, its record's last word `flags`.
fn fold_runs(
runs: [u32; 3],
reported: [u32; 3],
packed: u32,
flags: u32,
task: MeshGridLimits,
) -> Option<ObjectFold> {
let none = |discarded, past| ObjectFold {
record: [0, 0, 0, packed, 0, 0, 0, 0],
dispatch: [0; 3],
pieces: 0,
discarded,
past,
};
if runs.contains(&0) {
return Some(none(false, false));
}
let n = runs.iter().map(|&c| u64::from(c)).product::<u64>();
if n > u64::from(METAL_OBJECT_GRID_TOTAL) {
return Some(none(true, false));
}
let n = n as u32;
let total = object_total(task);
let nx = n.min(task.axes[0]).min(total).max(1);
let ny = n.div_ceil(nx).min(task.axes[1]).min(total / nx).max(1);
let pieces = n.div_ceil(nx * ny);
if pieces > MeshArguments::OBJECT_PIECES {
return Some(none(false, true));
}
let [rx, ry, rz] = runs;
let [tx, ty, tz] = reported;
Some(ObjectFold {
record: [rx, ry, rz, packed, tx, ty, tz, flags],
dispatch: [nx, ny, 1],
pieces,
discarded: false,
past: false,
})
}
/// The task stage's total for a fold, at most 2^31 so that no division by it is the all-ones
/// integer's; a fold needs at most [`METAL_OBJECT_GRID_TOTAL`].
fn object_total(task: MeshGridLimits) -> u32 {
task.total.min(1 << 31)
}
/// An arguments pass the consumer records before an indirect mesh draw on a device with
/// `VK_EXT_mesh_shader` (the module docs): it reads Metal's arguments at `source` and writes, into
/// a scratch, the mesh form's `VkDrawMeshTasksIndirectCommandEXT`
/// (`DrawCommand::DrawMeshTasksIndirect` at offset 0 reads it; the unfolded object form's too) or
/// the folded object form's region record, draw count and commands
/// (`DrawCommand::DrawMeshTasksIndirectCount` reads them).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MeshArguments {
pub source: IndirectRef,
/// The module of the draw's first stage.
pub form: MeshArgumentsForm,
/// The range of the source buffer the pass reads: from `source.offset` aligned down to `minStorageBufferOffsetAlignment` (and to 4) through the
/// 12 argument bytes.
pub source_range: BufferRange,
/// The push constant bytes (`COMPUTE`, offset 0): the arguments' byte offset inside
/// `source_range`, then the packed threads per object threadgroup (0 but for the folded
/// object form).
pub push_constants: [u8; 8],
}
impl MeshArguments {
/// The folded object form's draw count's byte offset in the scratch.
pub const OBJECT_COUNT: u32 = 32;
/// The folded object form's first command's byte offset in the scratch.
pub const OBJECT_COMMANDS: u32 = 36;
/// The folded object form's commands, the most pieces a draw takes: a piece of `nx` by `ny`
/// workgroups, `ny` the rows of `nx` the task total holds, runs more than half of the 2^22
/// threadgroups every task stage launches per draw (`maxTaskWorkGroupTotalCount`'s required
/// least), so 256 pieces cover [`METAL_OBJECT_GRID_TOTAL`] on every device.
pub const OBJECT_PIECES: u32 = 256;
}
#[cfg(test)]
mod tests;
@@ -1,97 +0,0 @@
//! Metal's object grid on the CPU, as Metal runs it.
use super::*;
/// Metal's object grids, as the M3 Max ran the owned fixture `mesh_object_grid` (macOS 27.0.1):
/// threads per grid wrap to 32 bits along each axis; an indirect draw runs every threadgroup, a
/// direct one those the wrapped threads fill, rounded up.
#[test]
fn metal_s_object_grid_wraps_its_threads_per_grid() {
for (groups, threads, direct, runs, reported) in [
(
[70_000, 1, 1],
[1, 1, 1],
true,
[70_000, 1, 1],
[70_000, 1, 1],
),
(
[300, 300, 2],
[4, 2, 1],
true,
[300, 300, 2],
[1200, 600, 2],
),
(
[4_194_303, 1, 1],
[1024, 1, 1],
true,
[4_194_303, 1, 1],
[4_294_966_272, 1, 1],
),
([4_194_304, 1, 1], [1024, 1, 1], true, [0, 1, 1], [0, 1, 1]),
(
[4_194_304, 1, 1],
[1024, 1, 1],
false,
[4_194_304, 1, 1],
[0, 1, 1],
),
(
[4_194_305, 1, 1],
[1024, 1, 1],
true,
[1, 1, 1],
[1024, 1, 1],
),
(
[4_194_305, 1, 1],
[1024, 1, 1],
false,
[4_194_305, 1, 1],
[1024, 1, 1],
),
(
[4_294_968, 1, 1],
[1000, 1, 1],
true,
[1, 1, 1],
[704, 1, 1],
),
(
[4_294_970, 1, 1],
[1000, 1, 1],
true,
[3, 1, 1],
[2704, 1, 1],
),
(
[4_294_970, 1, 1],
[1000, 1, 1],
false,
[4_294_970, 1, 1],
[2704, 1, 1],
),
(
[2, 4_194_305, 1],
[1, 1024, 1],
true,
[2, 1, 1],
[2, 1024, 1],
),
(
[65536, 64, 1],
[1024, 1, 1],
true,
[65536, 64, 1],
[67_108_864, 64, 1],
),
] {
assert_eq!(
metal_object_grid(groups, threads, direct),
Some((runs, reported)),
"{groups:?} of {threads:?}, direct {direct}"
);
}
assert_eq!(metal_object_grid([3, 1, 1], [0, 1, 1], true), None);
}
+31 -100
View File
@@ -1,58 +1,29 @@
//! The binder: from what the guest bound to what the consumer records, as plain data.
//! What a consumer computes from what the guest bound, as plain data, beside the pipelines.
//!
//! The binder never calls Vulkan. The consumer describes what is bound for one draw or dispatch,
//! keyed by Metal slot, in a [`BindState`]: per [`Stage`](crate::pipeline::Stage) a [`StageTable`]
//! of [`BoundBuffer`]s, [`BoundTexture`]s, [`BoundSampler`]s, and threadgroup memory lengths, the
//! resources made resident with `useResource` or `useHeap` ([`UsedResource`]), the live sampler
//! states an argument buffer can name ([`ArgumentSampler`]), and encoder state
//! such as the compute encoder's stage-in region ([`StageInRegion`]) and the render encoder's
//! tessellation factor buffer ([`TessellationFactors`]). Binding then runs in two levels:
//! The translator binds nothing: a consumer (the runtime) binds each resource itself, under the
//! identity domains, as the pipeline's interface and push fields state. This module holds the
//! pieces of that work the translator's own semantics decide:
//!
//! 1. **Plan, per shape.** [`BindState::shape`] keeps what can change a plan ([`BindShape`]:
//! which slots are bound with what kind of resource, formats, sampler modes, alignment
//! classes, and the like). `ComputePipeline::plan` and `RenderPipeline::plan` turn a pipeline
//! and a shape into a [`BindingPlan`]: one [`DescriptorWrite`] per layout binding (the resource
//! bound at a slot, a buffer the binder synthesizes, or a [`NeutralResource`] where nothing
//! compatible is bound), the vertex buffers, the [`ResourceUse`]s that drive staging,
//! writeback, and barriers, and where push fields go. A plan is a pure function of the
//! pipeline, the device, and the shape: memoize it on `(PipelineKey, BindShape)`.
//! 2. **Instantiate, per command.** [`BindingPlan::instantiate_dispatch`] of a [`Dispatch`] gives
//! [`DispatchCommands`], and [`BindingPlan::instantiate_draw`] of a [`DrawCall`] gives
//! [`DrawCommands`]: the range to bind each buffer descriptor over ([`DescriptorRange`]:
//! exactly that range, never more), the bytes to upload for argument and handle tables
//! ([`DescriptorBytes`]) and for the resident root table ([`RootTable`]), the push-constant
//! bytes with the device addresses the consumer fills in ([`PushHole`]), and the Vulkan
//! dispatches or draw to record. A Metal dispatch can become several Vulkan dispatches
//! ([`DispatchRegion`]), each with its complete specialization constants, so the consumer
//! creates one `VkPipeline` per distinct specialization.
//!
//! A plan whose [`variant`](BindingPlan::variant) is not empty asks for another variant of the
//! pipeline: compile that variant (see [`pipeline`](crate::pipeline)) and plan it for the same
//! shape. Refusals are [`BindError`](crate::error::BindError)s.
//!
//! Per command buffer, bind one [`ExecutionStatus`] buffer: initialize it with [`ExecutionStatus::initial`], and read it
//! back with [`ExecutionStatus::decode`], which reports resident-set misses and the other faults
//! [`StatusReport`] names. A command reaches it by its device address where the device addresses buffers, and
//! through the binding [`WriteSource::ExecutionStatus`] names where it does not. An indirect
//! dispatch reads its group counts from Metal's buffer itself ([`IndirectArgs::Buffer`]).
//! A pass's visibility results are its queries' results copied to their
//! offsets, a `Boolean` one the device's own nonzero value where a sample passed.
//! [`clamped_depth`] is a 32-bit float depth clamped into `[0, 1]`, as a copy into a depth image
//! of a device without `VK_EXT_depth_range_unrestricted` needs it. An ASTC texture
//! on a device without its block is read through a twin of Metal's decode of its blocks
//! ([`AstcDecode`], in the texels [`AstcTexels`] names); a PVRTC texture on a device without its
//! format through a twin of its texels' codes ([`PvrtcDecode`]); an ETC2 or EAC texture on a
//! device without the formats through a twin of its codes or an 11-bit format's values
//! ([`EtcDecode`], in the texels [`EtcTexels`] names).
//! [`sampler_desc`] gives the Vulkan sampler a plan's sampler write needs, and
//! [`FunctionTableSnapshot`] the one buffer of a command's visible-function tables' words. A
//! plan writes an acceleration structure as the top-level structure the consumer builds for it.
//! A [`RasterizationRateMap`] is the consumer's `MTLRasterizationRateMap`: it compiles a
//! [`RateMapDescriptor`], answers the map's queries, and gives the parameter data a
//! `rasterization_rate_map_decoder` reads. An [`ArgumentBufferLayout`] says where an argument
//! encoder (`MTLArgumentEncoder`)
//! writes each argument of an argument buffer: a function's (`Function::argument_buffer_layout`),
//! or one of [`ArgumentDescriptor`]s ([`ArgumentBufferLayout::from_descriptors`]).
//! - An [`ArgumentBufferLayout`] says where an argument encoder (`MTLArgumentEncoder`) writes each
//! argument of an argument buffer: a function's (`Function::argument_buffer_layout`), or one of
//! [`ArgumentDescriptor`]s ([`ArgumentBufferLayout::from_descriptors`]).
//! - An ASTC texture on a device without its block is read through a twin of Metal's decode of its
//! blocks ([`AstcDecode`], in the texels [`AstcTexels`] names); a PVRTC texture on a device
//! without its format through a twin of its texels' codes ([`PvrtcDecode`]); an ETC2 or EAC
//! texture on a device without the formats through a twin of its codes or an 11-bit format's
//! values ([`EtcDecode`], in the texels [`EtcTexels`] names).
//! - [`clamped_depth`] is a 32-bit float depth clamped into `[0, 1]`, as a copy into a depth image
//! of a device without `VK_EXT_depth_range_unrestricted` needs it.
//! - [`alpha_test_code`] is the code a pipeline's private alpha test compares with
//! (`PushField::AlphaTestReference`).
//! - A [`RasterizationRateMap`] is the consumer's `MTLRasterizationRateMap`: it compiles a
//! [`RateMapDescriptor`], answers the map's queries, and gives the parameter data a
//! `rasterization_rate_map_decoder` reads.
//! - [`SamplerDescriptor`] is `MTLSamplerDescriptor`; [`YCbCrPlanesSampler`] the conversion a
//! two-plane YCbCr texture's immutable sampler takes.
//! - [`Dispatch`], [`DrawCall`], [`IndexBufferRef`] and [`StageInRegion`] state a dispatch, a
//! draw, its index buffer and the compute encoder's stage-in region in Metal's terms;
//! [`indirect_commands`] lays out an indirect command buffer's records.
//!
//! The frozen surface is the items named at this root; the submodules are crate-private.
@@ -64,21 +35,16 @@ pub(crate) mod etc_decode;
pub(crate) mod graphics;
pub(crate) mod heap;
pub mod indirect_commands;
pub(crate) mod instantiate;
pub(crate) mod mesh_arguments;
pub(crate) mod neutral;
pub(crate) mod plan;
pub(crate) mod pvrtc_decode;
pub(crate) mod rate_map;
pub(crate) mod replay;
pub(crate) mod resident;
pub(crate) mod state;
pub(crate) mod status;
pub(crate) mod table;
pub(crate) mod texel_parts;
pub(crate) mod texel_rows;
pub(crate) mod ycbcr_convert;
pub(crate) mod ycbcr_in_place;
pub use argument_buffer::{
ArgumentBufferLayout, ArgumentDescriptor, ArgumentLayoutError, ArgumentMember, ArgumentType,
@@ -86,55 +52,20 @@ pub use argument_buffer::{
};
pub use astc_decode::{AstcDecode, AstcTexels};
pub use depth_clamp::clamped_depth;
pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs};
pub use dispatch::Dispatch;
pub use etc_decode::{EtcDecode, EtcTexels};
pub use graphics::{alpha_test_code, DrawCall, DrawCommands, IndexOverrun};
#[cfg(test)]
pub(crate) use heap::heap_classes;
pub use heap::{handle_entry, HeapSource, HANDLE_ENTRY_BYTES};
pub use instantiate::{
BufferExtent, BufferRange, DescriptorBytes, DescriptorRange, IndexBufferRef, IndirectRef,
PushConstantWrite, PushHole, ResidentRange, RootTable,
};
pub use mesh_arguments::{
fold_object_grid, metal_object_grid, MeshArguments, MeshArgumentsForm, MeshGridLimits,
ObjectFold, METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL, METAL_OBJECT_GRID_TOTAL,
};
pub use neutral::NeutralResource;
pub use plan::resources::sampler_desc;
pub use plan::{
AccessClass, BindingPlan, ByteRange, ComputeTemplate, DescriptorWrite, FieldLocation,
GraphicsTemplate, ImageSource, ImageViewDesc, PlanDiagnostic, PushFieldPlacement, PushTemplate,
ResourceUse, SamplerSource, UseTarget, VertexBufferBind, ViewSetup, WriteSource,
};
pub use graphics::{alpha_test_code, DrawCall, IndexBufferRef};
pub use pvrtc_decode::PvrtcDecode;
#[cfg(test)]
pub(crate) use rate_map::RateMapAxis;
pub use rate_map::{
RasterizationRateMap, RateMapDescriptor, RateMapError, RateMapLayerDescriptor, UnpinnedCompile,
MAX_SCREEN_EXTENT,
};
pub use replay::DRAW_ARGUMENT_BYTES;
pub(crate) use replay::{merged_fragment_table, merged_vertex, MergedVertex};
pub use replay::{DRAW_INDEX_ENTRY_BYTES, MERGED_REST_FIRST};
pub use state::{
ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState,
BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture,
BufferRanges, BufferShape, FunctionTablesShape, HeapPlacement, ImageblockSize, ResourceClass,
SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable,
TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape,
TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape,
VertexAmplification, ViewMapping,
};
// How `BindState::shape` classes a buffer: the crate reads it from `state`, and a consumer takes
// shapes from `BindState::shape`; only the crate's tests and validation reach it here.
pub use pvrtc_decode::PvrtcDecode;
pub use status::{ExecutionStatus, StatusBits, StatusReport, StatusWord};
pub use table::FunctionTableSnapshot;
pub use state::{SamplerDescriptor, StageInRegion};
#[cfg(test)]
pub(crate) use table::FunctionTableWords;
pub use texel_parts::part_texels;
pub use texel_rows::TexelRows;
#[cfg(test)]
pub(crate) use ycbcr_convert::YCbCrPlanes;
pub use ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange};
pub use ycbcr_in_place::{YCbCrInPlace, YCbCrPlanesSampler};
pub(crate) use texel_parts::part_texels;
pub use ycbcr_convert::YCbCrPlanesSampler;
pub(crate) use ycbcr_convert::{YCbCrCodes, YCbCrOutput};
+6 -230
View File
@@ -1,139 +1,12 @@
//! Neutral resources: stand-ins for statically used bindings with nothing (compatible) bound.
//!
//! Metal leaves reading an unbound argument undefined; Vulkan requires a valid descriptor of the
//! declared type for every layout binding. A plan therefore writes a neutral of the exact
//! descriptor, view, and numeric type the shader declares ([`NeutralResource::for_image`]).
//!
//! Neutral image and texel-buffer formats are chosen from Vulkan's mandatory format support
//! (`R8G8B8A8_{UNORM,SINT,UINT}` sampled, `D16_UNORM` depth, `R32_{SFLOAT,SINT,UINT}` storage and
//! texel buffers), except typed storage images, which must use exactly their declared format and
//! are listed only where the profile's format table supports it.
//! The numeric type a declaration of a format takes, and the format of a formatless storage
//! declaration's neutral: the stand-in a consumer binds where nothing compatible is bound, which
//! Vulkan requires for every statically used binding and Metal leaves undefined to read. Its
//! formats are of Vulkan's mandatory format support (`R32_{SFLOAT,SINT,UINT}` for storage images
//! and texel buffers).
use crate::device::profile::DeviceProfile;
#[cfg(test)]
use crate::device::requirements::FormatUsage;
use crate::pipeline::sym::{
ImageAccess, ImageDim, ImageHandleClass, SampledType, StorageFormatClass,
};
use crate::pipeline::sym::SampledType;
use crate::vk;
/// A resource the consumer creates once per kind and binds wherever a plan asks for it.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NeutralResource {
/// A zero-filled buffer of at least `min_bytes`, for uniform and storage buffer bindings.
ZeroBuffer { min_bytes: u32 },
/// A write-only buffer of at least `min_bytes` that contained stores are redirected to. No
/// shader ever observes its contents.
Sink { min_bytes: u32 },
/// A 1×1(×1) image with one level and one layer per view layer, viewed as `view_type`.
Image {
view_type: vk::ImageViewType,
/// The numeric type the shader reads; the image format has this numeric type.
sampled_type: SampledType,
/// A depth image for depth-comparison sampling (depth format).
depth_compare: bool,
samples: u32,
/// `Some(format)` for a storage image of exactly this format; `None` for a sampled image.
storage_format: Option<vk::Format>,
},
/// A texel buffer view of this format.
TexelBuffer { format: vk::Format },
/// A sampler; `compare` enables depth comparison.
Sampler { compare: bool },
}
/// Sample count of every multisampled neutral image: Vulkan requires 4 in
/// `sampledImage{Color,Integer,Depth}SampleCounts`.
const NEUTRAL_SAMPLES: u32 = 4;
impl NeutralResource {
/// Bytes of the sink buffer.
pub const SINK_BYTES: u32 = 64;
/// The neutral for an image or texel-buffer binding whose declared type is `class`, or `None`
/// when `class` is not a type the core declares (a 3D array, a multisampled image that is not
/// 2D, a depth-comparison image that is not float, is a storage image, or is not 2D or cube, or
/// a storage format of another numeric type). Depth comparison is limited to 2D and cube
/// (arrayed or not, 2D also multisampled) because Metal has no other depth texture type, and
/// Vulkan does not guarantee a depth format for 1D or 3D images, so a neutral of that shape
/// could fail image creation.
pub fn for_image(class: &ImageHandleClass) -> Option<NeutralResource> {
let storage = class.access == ImageAccess::Storage;
let format = match (storage, class.format) {
(false, StorageFormatClass::NotStorage) => None,
(true, StorageFormatClass::Unknown) => Some(storage_neutral(class.sampled_type)),
(true, StorageFormatClass::Format(f)) if serves(f, class.sampled_type) => Some(f),
_ => return None,
};
if class.depth_compare
&& (storage
|| class.sampled_type != SampledType::Float
|| !matches!(class.dim, ImageDim::D2 | ImageDim::Cube))
{
return None;
}
if class.dim == ImageDim::Buffer {
if class.arrayed || class.multisampled || class.depth_compare {
return None;
}
return Some(NeutralResource::TexelBuffer {
format: format.unwrap_or_else(|| storage_neutral(class.sampled_type)),
});
}
if class.multisampled && class.dim != ImageDim::D2 {
return None;
}
let view_type = match (class.dim, class.arrayed) {
(ImageDim::D1, false) => vk::ImageViewType::TYPE_1D,
(ImageDim::D1, true) => vk::ImageViewType::TYPE_1D_ARRAY,
(ImageDim::D2, false) => vk::ImageViewType::TYPE_2D,
(ImageDim::D2, true) => vk::ImageViewType::TYPE_2D_ARRAY,
(ImageDim::D3, false) => vk::ImageViewType::TYPE_3D,
(ImageDim::Cube, false) => vk::ImageViewType::CUBE,
(ImageDim::Cube, true) => vk::ImageViewType::CUBE_ARRAY,
_ => return None,
};
Some(NeutralResource::Image {
view_type,
sampled_type: class.sampled_type,
depth_compare: class.depth_compare,
samples: if class.multisampled {
NEUTRAL_SAMPLES
} else {
1
},
storage_format: format,
})
}
/// The format of the image or texel buffer the consumer creates, or `None` for buffers and
/// samplers.
pub fn format(&self) -> Option<vk::Format> {
match *self {
NeutralResource::Image {
sampled_type,
depth_compare,
storage_format,
..
} => Some(storage_format.unwrap_or(if depth_compare {
vk::Format::D16_UNORM
} else {
match sampled_type {
SampledType::Sint => vk::Format::R8G8B8A8_SINT,
SampledType::Uint => vk::Format::R8G8B8A8_UINT,
// A `ulong` texture is `RG32Uint`.
SampledType::Uint64 => vk::Format::R32G32_UINT,
_ => vk::Format::R8G8B8A8_UNORM,
}
})),
NeutralResource::TexelBuffer { format } => Some(format),
_ => None,
}
}
}
/// The format of a formatless storage declaration's neutral of a numeric type: its 32-bit
/// single-channel format (mandatory for storage images and both texel-buffer usages), or, for
/// `ulong`, `RG32_UINT`, the view of the only format Metal binds to it, which its slot declares.
@@ -146,15 +19,6 @@ pub(crate) fn storage_neutral(ty: SampledType) -> vk::Format {
}
}
/// Whether a storage image of `format` serves a declaration of numeric type `ty`: the format's
/// own numeric type, or, for `ulong`, `RG32_UINT`.
fn serves(format: vk::Format, ty: SampledType) -> bool {
match ty {
SampledType::Uint64 => format == vk::Format::R32G32_UINT,
_ => numeric_type(format) == Some(ty),
}
}
/// The sampled type a shader declares to read or write `format`: the registry's numeric type of
/// the format's color components, or of its only depth or stencil aspect
/// ([`vk::Format::numeric_type`], generated from `vk.xml`'s `numericFormat`). `None` for a
@@ -169,93 +33,5 @@ pub(crate) fn numeric_type(format: vk::Format) -> Option<SampledType> {
}
}
/// Bytes of the `ZeroBuffer` neutral on `profile`: large enough for any uniform-buffer view
/// (`maxUniformBufferRange`, capped at 64 KiB), a multiple of 16.
pub fn zero_buffer_bytes(profile: &DeviceProfile) -> u32 {
let range = profile
.fields()
.limits
.max_uniform_buffer_range
.min(1 << 16);
(range & !15).max(16)
}
/// Every image type the new core can declare on `profile` (heap classes and per-slot images): each
/// dimension, arrayed-ness, and sample count SPIR-V allows, each numeric type, depth comparison for
/// float 2D and cube images, sampled or storage with each storage format class the profile
/// supports. Cube arrays need `imageCubeArray`; a multisampled image is sampled only (no form of a
/// multisampled storage image is built).
#[cfg(test)]
pub(crate) fn image_classes(profile: &DeviceProfile) -> Vec<ImageHandleClass> {
let f = profile.fields();
let types = [SampledType::Float, SampledType::Sint, SampledType::Uint];
let shapes = [
(ImageDim::D1, false, false),
(ImageDim::D1, true, false),
(ImageDim::D2, false, false),
(ImageDim::D2, true, false),
(ImageDim::D2, false, true),
(ImageDim::D2, true, true),
(ImageDim::D3, false, false),
(ImageDim::Cube, false, false),
(ImageDim::Cube, true, false),
(ImageDim::Buffer, false, false),
];
let mut out = Vec::new();
for (dim, arrayed, multisampled) in shapes {
if dim == ImageDim::Cube && arrayed && !f.images.cube_array {
continue;
}
let class = |sampled_type, depth_compare, access, format| ImageHandleClass {
dim,
arrayed,
multisampled,
sampled_type,
depth_compare,
access,
format,
};
for ty in types {
out.push(class(
ty,
false,
ImageAccess::Sampled,
StorageFormatClass::NotStorage,
));
// Depth textures exist only as 2D (arrayed, multisampled) and cube (arrayed) in
// Metal, and only those shapes are guaranteed a depth format in Vulkan.
if ty == SampledType::Float && matches!(dim, ImageDim::D2 | ImageDim::Cube) {
out.push(class(
ty,
true,
ImageAccess::Sampled,
StorageFormatClass::NotStorage,
));
}
if multisampled {
continue;
}
out.push(class(
ty,
false,
ImageAccess::Storage,
StorageFormatClass::Unknown,
));
let usage = if dim == ImageDim::Buffer {
FormatUsage::StorageTexelBuffer
} else {
FormatUsage::StorageImage
};
for (&format, usages) in &f.storage_formats.formats {
if usages.contains(&usage) && numeric_type(format) == Some(ty) {
let format = StorageFormatClass::Format(format);
out.push(class(ty, false, ImageAccess::Storage, format));
}
}
}
}
out
}
#[cfg(test)]
mod tests;
@@ -1,138 +1,7 @@
//! The neutral resources: the zero buffer covers any uniform view, an undeclarable type has none,
//! and their formats follow the declared type and the registry's numeric formats.
use std::path::PathBuf;
use super::*;
use crate::device::{Device, DeviceDescription, DevicePolicy};
/// A device for every committed profile (`validation/profiles/`, read-only), sorted by stem.
fn committed_devices() -> Vec<(String, Device)> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
let mut out: Vec<(String, Device)> = std::fs::read_dir(&dir)
.expect("validation/profiles is readable")
.map(|e| e.expect("directory entry").path())
.filter(|p| p.extension().is_some_and(|x| x == "json"))
.map(|p| {
let stem = p.file_stem().unwrap().to_string_lossy().into_owned();
let text = std::fs::read_to_string(&p).expect("profile is readable");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("profile parses");
let device =
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device derives");
(stem, device)
})
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
assert!(out.len() >= 13, "committed profiles: {}", out.len());
out
}
#[test]
fn zero_buffer_covers_any_uniform_view_and_is_padded() {
for (stem, device) in committed_devices() {
let bytes = zero_buffer_bytes(device.profile());
let range = device.profile().fields().limits.max_uniform_buffer_range;
assert_eq!(bytes % 16, 0, "{stem}");
assert!(bytes >= range.min(1 << 16) & !15, "{stem}");
assert!(
bytes >= 16384,
"{stem}: Vulkan's minimum maxUniformBufferRange"
);
}
}
fn class(dim: ImageDim, arrayed: bool, multisampled: bool) -> ImageHandleClass {
ImageHandleClass {
dim,
arrayed,
multisampled,
sampled_type: SampledType::Float,
depth_compare: false,
access: ImageAccess::Sampled,
format: StorageFormatClass::NotStorage,
}
}
#[test]
fn undeclarable_types_have_no_neutral() {
let none = [
class(ImageDim::D3, true, false),
class(ImageDim::D1, false, true),
class(ImageDim::Cube, false, true),
class(ImageDim::Buffer, true, false),
ImageHandleClass {
sampled_type: SampledType::Uint,
depth_compare: true,
..class(ImageDim::D2, false, false)
},
ImageHandleClass {
access: ImageAccess::Storage,
depth_compare: true,
format: StorageFormatClass::Unknown,
..class(ImageDim::D2, false, false)
},
// A storage format of another numeric type than the declared one.
ImageHandleClass {
access: ImageAccess::Storage,
format: StorageFormatClass::Format(vk::Format::R32_UINT),
..class(ImageDim::D2, false, false)
},
// Sampled images carry no storage format, storage images always one.
ImageHandleClass {
format: StorageFormatClass::Unknown,
..class(ImageDim::D2, false, false)
},
ImageHandleClass {
access: ImageAccess::Storage,
..class(ImageDim::D2, false, false)
},
];
// Depth comparison exists only for 2D and cube images.
let depth = [
(ImageDim::D1, false),
(ImageDim::D1, true),
(ImageDim::D3, false),
(ImageDim::Buffer, false),
]
.map(|(dim, arrayed)| ImageHandleClass {
depth_compare: true,
..class(dim, arrayed, false)
});
for c in none.into_iter().chain(depth) {
assert_eq!(NeutralResource::for_image(&c), None, "{c:?}");
}
}
#[test]
fn neutral_formats_follow_the_declared_type() {
let mut c = class(ImageDim::D2, true, false);
assert_eq!(
NeutralResource::for_image(&c).and_then(|n| n.format()),
Some(vk::Format::R8G8B8A8_UNORM)
);
c.sampled_type = SampledType::Sint;
assert_eq!(
NeutralResource::for_image(&c).and_then(|n| n.format()),
Some(vk::Format::R8G8B8A8_SINT)
);
c.access = ImageAccess::Storage;
c.format = StorageFormatClass::Unknown;
assert_eq!(
NeutralResource::for_image(&c).and_then(|n| n.format()),
Some(vk::Format::R32_SINT)
);
let texel = ImageHandleClass {
sampled_type: SampledType::Uint,
..class(ImageDim::Buffer, false, false)
};
assert_eq!(
NeutralResource::for_image(&texel),
Some(NeutralResource::TexelBuffer {
format: vk::Format::R32_UINT
})
);
assert_eq!(NeutralResource::Sampler { compare: true }.format(), None);
}
#[test]
fn numeric_types_come_from_the_registry_numeric_formats() {
-938
View File
@@ -1,938 +0,0 @@
//! `BindingPlan`: the shape-level plan of a pipeline.
//!
//! A plan is a pure value of `(pipeline, BindShape)`, memoized by the consumer. It writes every
//! layout binding: a guest resource, a synthetic buffer, or a neutral stand-in of the exact
//! descriptor and view type. Compute planning is `ComputePipeline::plan` (`compute`); graphics
//! planning is `bind::plan::graphics`.
pub(crate) mod compute;
pub(crate) mod resources;
pub(crate) mod slots;
use crate::bind::heap::HeapSource;
use crate::bind::neutral::NeutralResource;
use crate::cache::{SpecializationKey, VariantKey};
use crate::metal::sampler::OpaqueBlackBorder;
use crate::pipeline::artifact::SpecConstant;
use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window};
use crate::pipeline::sym::{
AccelerationStructureLevel, HandleClass, PushField, SlotRef, SpecKey, Stage,
};
use crate::pipeline::vertex::VertexStride;
use crate::vk;
/// The shape-level binding plan of a pipeline.
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BindingPlan {
/// The variant the shape requires: the storage-image choices, `BufferRangeLimit` device-address
/// slots, vertex buffers fixed-function input cannot fetch as bound, and a vertex function's
/// dropped `Layer` output in a pass of one layer. Empty on the common path; otherwise the consumer compiles the pipeline with
/// this variant (its keys `Device::render_variant_key`'s for a render pipeline) and plans that
/// pipeline, whose plan for the same shape states the same key. The descriptors are those of
/// the pipeline planned; a draw of a plan whose variant pulls a vertex buffer the pipeline
/// fetches fixed function is an internal error, and one whose variant drops (or keeps) the
/// vertex `Layer` output the pipeline keeps (or drops) is `BindError::NeedsVariant`.
pub variant: VariantKey,
/// Specialization of the pipeline for this shape: the constants the shape decides
/// (threadgroup lengths, slot presence). Each compute `DispatchRegion` carries the complete
/// key: these, plus its local size and `MultiRegion`.
pub specialization: SpecializationKey,
/// One write per layout binding and array element.
pub descriptors: Vec<DescriptorWrite>,
pub vertex_buffers: Vec<VertexBufferBind>,
/// Staging, writeback, and hazard facts.
pub uses: Vec<ResourceUse>,
/// Which push fields instantiation fills, and where.
pub push: PushTemplate,
pub diagnostics: Vec<PlanDiagnostic>,
/// What `instantiate_dispatch` needs of the pipeline and the device (compute plans only).
pub compute: Option<ComputeTemplate>,
/// What `instantiate_draw` needs of the pipeline and the device (render plans only).
pub graphics: Option<GraphicsTemplate>,
/// The views of a render plan's draws under the shape's vertex amplification; the default, no
/// multiview, for a compute plan.
pub views: ViewSetup,
}
impl BindingPlan {
/// The value this plan's bound resources give `key` where a stage's specialized note alone
/// tests it (`SpecKey::BoundSamplerWord`, the bound sampler's word, and what the command's
/// handles can name), which nothing pushes; `None` for any other key. A pipeline's key carries
/// no such value, so a runtime reads a stage's notes that test it through
/// `StageModule::precision_notes_bound` with this.
pub fn specialized_value(&self, key: SpecKey) -> Option<u64> {
let resources = match (&self.compute, &self.graphics) {
(Some(c), _) => &c.resources,
(None, Some(g)) => &g.resources,
(None, None) => return None,
};
resources
.specialized
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| u64::from(*v))
}
}
// Adding a field to a plan type: a plan's content digest omits a field whose value is zero (`0`,
// `false`, `None`, empty), so a new field must hold its zero value exactly when the plan means what
// it meant before the field existed. If its zero would mean new behaviour for existing plans, the
// addition must also bump the runtime version or the validation executor's ABI (ask the
// orchestrator): the digest cannot see it (`cache::digest`, `docs/VALIDATION.md`).
#[cfg(feature = "serde")]
impl BindingPlan {
/// The plan's content digest: a SHA-256 of everything the plan states, by the rules of
/// `ComputePipeline::content_digest` (fields and enum variants by name, a field at its zero
/// value omitted), taken over its `serde` serialization. A plan names no cache key and no
/// version, so two builds that plan a pipeline for a shape alike give the same digest; it
/// changes whenever a value the plan states changes. Like the pipelines', it identifies content
/// and authenticates nothing. Fails only when a `Serialize` impl reports an error, which none
/// of the plan's types does.
pub fn content_digest(&self) -> Result<crate::cache::Hash256, String> {
crate::cache::digest::node_of(self)
.map(|node| node.root("binding plan"))
.map_err(|error| error.to_string())
}
}
/// How the consumer sets up the views of a render plan's draws. Vertex amplification is multiview:
/// amplification `a` of a draw is view `a`, which reads `a` as its `[[amplification_id]]` and
/// renders into layer `a` of each attachment view. A draw renders into the pass's layers from
/// `base_layer`: `view_mask`'s views of them, or without multiview the one layer there; the
/// default, both 0, renders the pass's every layer as a pass without amplification does.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ViewSetup {
/// The multiview view mask: `(1 << count) - 1` for an amplification count above 1, and 0
/// (no multiview) otherwise. The consumer creates the pipeline with it
/// (`VkPipelineRenderingCreateInfo::viewMask`, or its subpass's) and records the draw in a
/// render pass instance of the same view mask.
pub view_mask: u32,
/// The layer of the pass, counted from its first, that view 0 renders into (the first view
/// mapping's `renderTargetArrayIndexOffset` where it is below the pass's
/// `renderTargetArrayLength`, and 0 where it is not): the consumer's attachment views start
/// there, and view `a` renders into layer `base_layer + a`. Without multiview a draw whose
/// `base_layer` is not 0 renders into that one layer, through attachment views of it alone.
pub base_layer: u32,
}
/// The pipeline and device facts a compute plan instantiates with: per buffer slot its form,
/// window, and descriptor; the specialization layout; the local-size rules; the push placement; and
/// the root-table layout. Opaque to the consumer.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ComputeTemplate {
/// Every statically used buffer slot, by slot.
pub(crate) buffers: Vec<PlannedBuffer>,
/// The stage's specialization constants, in `SpecId` order.
pub(crate) spec: Vec<SpecConstant>,
/// The values the shape decides, by key.
pub(crate) fixed: Vec<(SpecKey, u64)>,
pub(crate) local: LocalRules,
/// Every placed push field, in placement order.
pub(crate) fields: Vec<PlacedField>,
/// `(offset, size)` of the push-constant range.
pub(crate) push_range: Option<(u32, u32)>,
/// `(set, binding, size)` of the stage's `ArgumentTable` uniform buffer.
pub(crate) table: Option<(u32, u32, u32)>,
/// The first root of the resident set (`R0`), when the function reads the root table.
pub(crate) root_first: Option<u32>,
/// The texel buffers the dispatch binds.
pub(crate) resources: ResourceTemplate,
/// Whether the kernel reads the stage-in region (`RuntimeFact::StageInRegion`): a dispatch
/// without a region is `BindError::MissingStageInRegion`.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) stage_in_region: bool,
/// The kernel's `[[stage_in]]` fetches of a thread-position step, whose elements decide each
/// region's `SpecKey::StageInReach` (`dispatch::stage_in_reach`); empty where the kernel
/// declares no such key.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) stage_in_grid: Vec<crate::pipeline::stage_io::StageInFetch>,
}
/// The pipeline and device facts a render plan instantiates with: the buffer slots of both stages,
/// each stage's push placement and tables, the fixed-function vertex buffers, and the texel
/// buffers. Opaque to the consumer.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GraphicsTemplate {
/// Every statically used buffer slot of both stages, by slot.
pub(crate) buffers: Vec<PlannedBuffer>,
/// Each stage, in pipeline order.
pub(crate) stages: Vec<StageTemplate>,
/// Every fixed-function vertex buffer, in binding order.
pub(crate) vertex_buffers: Vec<PlannedVertexBuffer>,
/// `(layout, stride)` of every pulled layout with a static stride, by layout.
pub(crate) pulled_strides: Vec<(u32, u32)>,
pub(crate) resources: ResourceTemplate,
/// What a per-bind vertex stride must meet.
pub(crate) vertex_strides: StrideRules,
/// The device's `maxMultiviewInstanceIndex` when the plan's draws are multiview
/// (`ViewSetup::view_mask` is not 0); `None` otherwise.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) multiview_instance_limit: Option<u32>,
/// The pipeline planned is not the variant its vertex function's render target slice asks
/// for at the shape's render target array length: it writes `Layer` in a pass of one layer, or
/// does not in a pass of more; or not the variant the shape's vertex amplification asks for,
/// drawn as views or one amplification at a time. A draw is `BindError::NeedsVariant` with the
/// plan's `variant`.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) other_layer_variant: bool,
/// A plan whose draws draw one amplification each (`VariantKey::amplification_draws`): the
/// `(render target slice offset, viewport offset)` of each amplification, in order. Each draw
/// is recorded once per entry, after the push writes that make it that amplification's
/// (`DrawCommands::amplifications`). Empty for a plan whose draws are one draw each. A plan
/// whose pipeline is not the variant its amplification asks for sets `other_layer_variant`.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) amplifications: Vec<[u32; 2]>,
/// A tessellation pipeline's: its draws draw patches.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) tessellation: Option<FactorTemplate>,
/// The device lacks `drawIndirectFirstInstance`: an indirect draw's arguments are read on
/// the CPU (`DrawCommands::indirect_needs_arguments`), since Metal's may carry a base
/// instance.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) indirect_first_instance_missing: bool,
/// A mesh render pipeline's mesh stage: its draws are mesh draws, each of its own
/// specialization.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) mesh: Option<MeshTemplate>,
/// A pipeline compiled in the primitive ID's de-indexed form of this index type
/// (`VariantKey::primitive_id_indices`): its indexed draws write `PushField::CaptureLayout`
/// and run without indices.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) deindexed: Option<crate::metal::IndexType>,
/// A pipeline compiled in the private list form (`VariantKey::private_list`): its draws are
/// the consumer's lists of Metal's private primitive types, run without indices, of any
/// draw call.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) private_list: bool,
/// A band variant's (`GraphicsState::line_band`): the byte offset of its evaluation stage's
/// push range, where its draws push `BindState::line_band` (`PushField::LineBand`).
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) line_band: Option<u32>,
}
/// What a mesh draw of a mesh render pipeline instantiates: the pipeline's specialization layout
/// with the values the shape decides, which each draw completes with its threadgroups' sizes, and
/// the device's threadgroup limits of each stage.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct MeshTemplate {
/// Every stage's specialization constants, in `SpecId` order.
pub spec: Vec<SpecConstant>,
/// The values the shape decides, by key.
pub fixed: Vec<(SpecKey, u64)>,
/// Every `LocalSizeConstraint{multiple}` of the pipeline: a threadgroup of either stage must
/// be whole subgroups of the flattened tier's size.
pub multiples: Vec<u32>,
/// The mesh stage's limits (`maxMeshWorkGroup*`).
pub mesh: GroupLimits,
/// The task stage's limits (`maxTaskWorkGroup*`), of a pipeline with an object function.
pub object: Option<GroupLimits>,
/// The object function is compiled folded (`RuntimeFact::FoldedGroups`,
/// `lower::mesh::folds_object_grids`): each draw runs its object grid in pieces within the task
/// stage's limits (`bind::mesh_arguments`).
#[cfg_attr(feature = "serde", serde(default))]
pub folded: bool,
/// The object function runs a partial threadgroup as Metal does
/// (`RuntimeFact::PartialObjectThreadgroups`): a `drawMeshThreads` whose threads leave one
/// draws it, its region flagged `lower::dispatch::NONUNIFORM`.
#[cfg_attr(feature = "serde", serde(default))]
pub partial_groups: bool,
}
/// A stage's threadgroup and grid limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct GroupLimits {
/// `max*WorkGroupSize`.
pub size: [u32; 3],
/// `max*WorkGroupInvocations`.
pub invocations: u32,
/// `max*WorkGroupCount`.
pub count: [u32; 3],
/// `max*WorkGroupTotalCount`.
pub total: u32,
/// The stage the limits are of, which names them.
pub stage: GroupStage,
}
/// The Vulkan stage a mesh draw's threadgroups run in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) enum GroupStage {
/// An object function's (`TASK_EXT`).
Task,
/// A mesh function's (`MESH_EXT`).
Mesh,
}
/// What a patch draw of a tessellation pipeline instantiates: the control stage's push range, the
/// patch and control-point index buffers' descriptor ranges, and the factor buffer's range.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct FactorTemplate {
pub step: crate::metal::TessellationFactorStepFunction,
/// Bytes of one patch's factors.
pub patch_bytes: u32,
/// `minStorageBufferOffsetAlignment`.
pub alignment: u64,
/// `maxStorageBufferRange`.
pub max_range: u64,
/// The `N` of the function's `[[patch(_, N)]]` (0 when unstated).
pub control_points: u32,
/// `(set, binding)` of the patch index buffer, which the control stage reads.
pub patch_indices: (u32, u32),
/// For a pipeline with a control-point index type, `(set, binding)` of the control-point index
/// buffer, which the control stage reads, and the bytes of one index (2 or 4); `None` for a
/// pipeline without one.
pub control_point_indices: Option<((u32, u32), u64)>,
/// The byte offset of the control stage's push range (`TessellationState::push_offset`), which
/// holds the draw's factor and index buffer fields.
pub push_offset: u32,
/// `(set, binding)` of the factor buffer when the plan writes it (a factor buffer is set);
/// `None` when the zero buffer stands in.
pub factor_binding: Option<(u32, u32)>,
}
/// The device's and pipeline's rules for a per-bind vertex stride.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct StrideRules {
/// `maxVertexInputBindingStride`.
pub max: u32,
/// The portability subset's `minVertexInputBindingStrideAlignment`, when the device has one.
pub portability_alignment: Option<u32>,
/// The strides are dynamic state (`VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE`): a nonzero
/// one must cover an element's attributes (`VUID-vkCmdBindVertexBuffers2-pStrides-06209`),
/// and a draw lists every binding's stride.
pub dynamic: bool,
/// The portability subset withholds `vertexAttributeAccessBeyondStride`: a stride, zero
/// included, must cover an element's attributes.
pub within_stride: bool,
}
/// One stage of a render plan.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct StageTemplate {
pub stage: Stage,
pub flags: vk::ShaderStageFlags,
/// Every placed push field, in placement order.
pub fields: Vec<PlacedField>,
/// `(offset, size)` of the stage's push-constant range.
pub push_range: Option<(u32, u32)>,
/// `(set, binding)` of the stage's `ArgumentTable` uniform buffer.
pub table: Option<(u32, u32)>,
/// Bytes of the stage's `ArgumentTable` (0 without one).
pub table_size: u32,
/// The first root of the resident set (`R0`), when the stage reads its root table.
pub root_first: Option<u32>,
}
/// One fixed-function vertex buffer of a render plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct PlannedVertexBuffer {
/// The Vulkan vertex binding.
pub binding: u32,
/// The Metal vertex-stage buffer slot.
pub slot: SlotRef,
/// The pipeline's stride, or `PerBind` (the bind's `attributeStride`, dynamic state).
pub stride: VertexStride,
pub input_rate: vk::VertexInputRate,
/// The instance divisor (1 when not divided).
pub divisor: u32,
/// The largest Vulkan address alignment of the binding's attribute formats: the bind offset
/// and a per-bind stride must be multiples of it.
pub alignment: u32,
/// The bytes of one element the attributes read: the smallest attribute offset and the
/// largest `offset + format size` (`[start, end)`).
pub reads: (u32, u32),
}
/// The texture resources a draw or dispatch instantiates: texel-buffer ranges, and the heap members
/// and handle tables.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct ResourceTemplate {
pub texel_buffers: Vec<PlannedTexel>,
/// Every heap member, in element order: `heap_members[i]` is element `i + 1`.
pub heap_members: Vec<crate::bind::heap::HeapMember>,
/// Each stage's handle table.
pub handle_tables: Vec<crate::bind::heap::PlannedHandleTable>,
/// The level count the binder pushes for each slot whose level count a function reads
/// (`PushField::TextureLevels`): the bound texture's, 0 where a neutral stands in.
#[cfg_attr(feature = "serde", serde(default))]
pub texture_levels: Vec<(SlotRef, u32)>,
/// The integer channel widths of the bound texture, which the binder pushes for each slot
/// whose integer writes read them (`PushField::TextureIntegerChannels`):
/// `metal::format::integer_channels_word` of its format, 0 where a neutral stands in.
#[cfg_attr(feature = "serde", serde(default))]
pub texture_integer_channels: Vec<(SlotRef, u32)>,
/// The value of each key a specialized note's test alone reads (`SpecKey::BoundSamplerWord`,
/// and what the command's handles can name), which nothing pushes (`slots::record_noted`).
#[cfg_attr(feature = "serde", serde(default))]
pub specialized: Vec<(crate::pipeline::sym::SpecKey, u32)>,
/// Each stage's sampler table.
#[cfg_attr(feature = "serde", serde(default))]
pub sampler_tables: Vec<crate::bind::heap::PlannedHandleTable>,
/// The argument samplers' shape the sampler arrays and tables were planned for, when the
/// plan has one.
#[cfg_attr(feature = "serde", serde(default))]
pub argument_samplers: Option<crate::bind::state::ArgumentSamplersShape>,
/// What the sampler arrays and tables admit of a sampler state of a shape
/// `argument_samplers` does not list, as a command buffer lists the states again.
#[cfg_attr(feature = "serde", serde(default))]
pub sampler_admission: crate::bind::heap::SamplerAdmission,
/// Each stage's function-table directory.
#[cfg_attr(feature = "serde", serde(default))]
pub function_table_directories: Vec<crate::bind::heap::PlannedHandleTable>,
/// The tables' shape the function-table directories were planned for, when the plan has one.
#[cfg_attr(feature = "serde", serde(default))]
pub function_tables: Option<crate::bind::state::FunctionTablesShape>,
/// The directories hold each table's device address, not an element or a snapshot offset: the
/// pipeline reads the tables' words there.
#[cfg_attr(feature = "serde", serde(default))]
pub function_table_addresses: bool,
/// Each `SlotGuestBase` word is the slot's address less
/// [`SLOT_ADDRESS_BIAS`](crate::lower::access::SLOT_ADDRESS_BIAS), which the pipeline's
/// accesses add back: the device compiles under the identity domains (docs/API.md section 5).
#[cfg_attr(feature = "serde", serde(default))]
pub biased_slot_words: bool,
}
/// One bound texel buffer of a plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct PlannedTexel {
pub set: u32,
pub binding: u32,
pub slot: SlotRef,
/// `minTexelBufferOffsetAlignment`.
pub alignment: u64,
/// `maxTexelBufferElements`.
pub max_elements: u64,
/// The view format's texel block: bytes and texels per block (`vk::Format::block`).
pub block_size: u64,
pub texels_per_block: u64,
/// The views the binding holds, the elements of its descriptor array: 1, or the parts of a
/// texture buffer bound under its parts variant (`VariantKey::texel_buffer_parts`,
/// `bind::texel_parts`).
#[cfg_attr(feature = "serde", serde(default = "one_view"))]
pub parts: u32,
/// The texels of each part but the last (`bind::part_texels`).
#[cfg_attr(feature = "serde", serde(default))]
pub part_texels: u64,
}
/// The views of a planned texel buffer stated without them: one.
#[cfg(feature = "serde")]
fn one_view() -> u32 {
1
}
/// One statically used buffer slot of a compute plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct PlannedBuffer {
pub slot: SlotRef,
pub window: Window,
pub form: BufferForm,
pub access: AccessSet,
/// `(set, binding)` of a descriptor-form slot.
pub binding: Option<(u32, u32)>,
/// The descriptor base alignment: `minStorageBufferOffsetAlignment`, at least 16
/// (`views::base_alignment`).
pub alignment: u64,
/// `maxStorageBufferRange`.
pub max_range: u64,
/// What the shape binds at the slot.
pub bound: BoundKind,
}
/// What a shape binds at a buffer slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) enum BoundKind {
Unbound,
Buffer {
device_address: bool,
/// The allocation's `BindShape` length class.
length_class: u8,
},
Bytes,
}
/// The local-size rules every dispatch region satisfies.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct LocalRules {
/// The flattened tiers' `(sn, 1, 1)` workgroup (`SpecKey::FlatLocalSize`).
pub flat: bool,
/// The kernel declares `SpecKey::DeepThreadgroup`: a region deeper than
/// [`crate::pipeline::DEEP_THREADGROUP`] runs as one row, checked as the flattened tiers'.
pub deep: bool,
/// Every `LocalSizeConstraint{multiple}` of the pipeline.
pub multiples: Vec<u32>,
pub max_size: [u32; 3],
pub max_invocations: u32,
/// `maxComputeWorkgroupSubgroups`.
pub max_subgroups: u32,
pub max_count: [u32; 3],
pub required_subgroup_size: Option<u32>,
pub stage_flags: vk::PipelineShaderStageCreateFlags,
/// The emulated simdgroups' scratch (`RuntimeFact::SimdgroupEmulation`).
pub scratch: Option<ScratchRule>,
/// A region of one row needs no whole subgroups (`RuntimeFact::RowLockstep`).
pub rows: bool,
/// The masks of axes whose unit-axes variant relieves the kernel's predicated walk
/// (`RuntimeFact::UnitAxes`'s `relief`: bit `m − 1` for mask `m`), 0 where none does or the
/// pipeline is that variant.
pub unit_relief: u8,
/// The pipeline is a tile function (`RuntimeFact::TileFunction`): its threads take Metal's
/// tile-dispatch layout, built for the threadgroups `dispatch::tile_layout_measured` takes,
/// dispatched by threadgroups.
pub tile: bool,
/// The threadgroup Metal answers a tile function whose threadgroup is the tile
/// (`RuntimeFact::TileThreadgroup` with `tile_sized`): the shape's tile, its imageblock size,
/// one deep. Every region of its dispatches carries it as the nominal threadgroup
/// (`MultiRegion` 1) and the grid of its tiles, whatever threads per tile run.
pub tile_threadgroup: Option<[u32; 3]>,
/// The kernel runs its grid in tiles (`RuntimeFact::GridTiles`): a direct dispatch's regions
/// are [`crate::pipeline::grid_tile`]'s tiles of its threads, one workgroup of
/// [`crate::pipeline::GRID_TILE_THREADS`] each.
pub grid_tiles: bool,
}
/// A region of `N` threads takes `fixed + ⌈N / 32⌉ · per_simdgroup` bytes of threadgroup memory,
/// at most `available` (`maxComputeSharedMemorySize`), when the kernel's simdgroups are emulated.
/// `fixed` is the declared arena with its `[[threadgroup(n)]]` regions
/// (`lower::simd::workgroup::arena_bytes`: whole words and at least `MIN_ARENA_BYTES`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct ScratchRule {
pub per_simdgroup: u32,
pub fixed: u64,
pub available: u32,
}
/// One descriptor write.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DescriptorWrite {
pub set: u32,
pub binding: u32,
pub array_element: u32,
pub ty: vk::DescriptorType,
pub source: WriteSource,
}
/// What a descriptor write points at.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WriteSource {
/// The buffer bound at `slot`. The range is derived from the slot's window and bind offset: the
/// consumer binds exactly that range, never more.
Buffer { slot: SlotRef },
/// `set*Bytes` data uploaded by the consumer.
InlineBytes { slot: SlotRef },
/// The texture bound at `slot`, through this view.
Texture { slot: SlotRef, view: ImageViewDesc },
/// A combined image sampler: its image and its sampler.
CombinedImageSampler {
image: ImageSource,
sampler: SamplerSource,
},
/// The planes of the two-plane YCbCr texture bound at `slot`, read in place
/// (`TextureFacts::ycbcr_in_place`): a uniform texel buffer over the planes' bytes in
/// `R8G8_UINT` of 8-bit codes or `R16G16_UINT` of 10-bit ones, from the first byte of the
/// first plane through the last row of codes either plane holds. Only a slot under its
/// in-place variant binds it
/// (`VariantKey::ycbcr_in_place`).
YCbCrInPlace { slot: SlotRef },
/// The planes of the two-plane YCbCr texture bound at `slot`, held as an image the device's
/// own sampler Y′CbCr conversion samples (`TextureShape::Texture::ycbcr_planes_sampler`): a
/// combined image sampler whose image is that image viewed with the conversion
/// (`bind::YCbCrPlanesSampler`) and whose sampler is the binding's immutable one, in
/// `GENERAL`. Only a slot under its planes-image variant binds it
/// (`VariantKey::ycbcr_planes_sampled`, `BindingSource::YCbCrPlanes`).
YCbCrPlanesImage { slot: SlotRef },
/// The rows of the 2D texture bound at `slot`, read and written in place
/// (`TextureFacts::texel_rows`, `bind::texel_rows`): a texel buffer in `format` over the
/// texture's bytes, from its first texel, or before it where the device's texel buffer offset
/// alignment asks, through its last row's last texel; uniform where the slot's function only
/// reads the texture, storage where it writes it. Only a slot under its rows variant binds it
/// (`VariantKey::texel_rows`).
TexelRows { slot: SlotRef, format: vk::Format },
/// The texture buffer bound at `slot`, as a texel buffer view.
TexelBuffer {
slot: SlotRef,
format: vk::Format,
window: Window,
},
/// A `VkSampler` for the sampler bound at `slot`, made for this use: `compare` enables depth
/// comparison and `integer` selects integer border colors (`metal::sampler::SamplerUse`,
/// `bind::sampler_desc`). The plan checks what the shape states
/// (reduction); the rest of the descriptor is per bind. `opaque_black` says how an opaque-black
/// border is made to read Metal's texel through every texture the sampler meets
/// (`metal::sampler::OpaqueBlackBorder`).
Sampler {
slot: SlotRef,
compare: bool,
integer: bool,
opaque_black: OpaqueBlackBorder,
},
/// The stage's argument table; instantiation fills the bytes.
ArgumentTable { stage: Stage, bytes_len: u32 },
/// A handle table of `stage` (its texture table, or its sampler table), a read-only storage
/// buffer of `bytes_len` bytes whose contents instantiation gives (`DescriptorBytes`). The
/// consumer binds exactly `bytes_len` bytes: the shader counts the table's entries from the
/// bound range.
HandleTable { stage: Stage, bytes_len: u32 },
/// The constant blob of `stage`: its `StageModule::constant_blob`, padded to 16 bytes by the
/// consumer.
ConstantBlob { stage: Stage },
/// Element `element` of the set-1 heap array of `class`: the resident texture `source`,
/// through this view. Every write of one texture has one layout: `GENERAL` when some storage
/// array holds it or, for a texture bound at a slot, the slot's own binding is a storage image;
/// `SHADER_READ_ONLY_OPTIMAL` otherwise.
HeapEntry {
class: HandleClass,
element: u32,
source: HeapSource,
view: ImageViewDesc,
},
/// Color attachment `color_index`, as an input attachment.
Attachment { color_index: u32 },
/// A neutral stand-in: statically used, nothing (compatible) bound.
Neutral(NeutralResource),
/// The encoder's tessellation factor buffer (`BindState::tessellation_factors`), a
/// read-only storage buffer of the control stage over the draw's `DescriptorRange`.
TessellationFactors,
/// The top-level structure of the acceleration structure bound at buffer slot `slot`
/// (`setAccelerationStructure:atBufferIndex:`): the bound instance structure itself when
/// `level` is `Instance`, and, when `level` is `Primitive`, the top-level structure of one
/// instance over the bound primitive structure. A slot the guest left unbound takes a
/// top-level structure of no instances, which every ray misses.
AccelerationStructure {
slot: SlotRef,
level: AccelerationStructureLevel,
},
/// The render pass's imageblock storage: the one storage image the consumer creates for the
/// pass instance, in `GENERAL` layout, bound to every tile dispatch whose function's explicit
/// imageblock stands alone, which stages its tile's cells from it and back.
Imageblock,
/// A render pass's color attachment `color_index` as a storage image of a tile dispatch: a 2D
/// view of the attachment's own image, of the pass's layer and level, in `format`, with the
/// identity component mapping, in `GENERAL` layout. The image's format is the tile pipeline
/// descriptor's (`TileRenderPipelineDescriptor::color_attachment_formats`), as Metal requires
/// of the pass, and its extent at least the render area (`BindState::render_area`). `format`
/// is the image's own for an integer format, and for a float format the unsigned-integer
/// format of the same channels and widths (`R16_UINT` for `R16_SFLOAT`), so the dispatch moves
/// the texels' bits: the consumer creates such an image with `MUTABLE_FORMAT` (and
/// `EXTENDED_USAGE` when its own format is not storage-capable).
TileAttachment {
color_index: u32,
format: vk::Format,
},
/// The tile map of the sparse texture bound at texture slot `slot`: a read-only storage
/// buffer of the map's words, a bit per tile of each level and slice set while Metal has the
/// tile mapped, from which a function answers the texture's residency where the device has no
/// shader residency. The consumer binds the map it keeps for that texture, holding the mappings
/// Metal's would hold when the command runs. A slot whose bound texture is not sparse takes the
/// zero buffer instead: the module reads no tile map there.
TileMap { slot: SlotRef },
/// Element `index + 1` of a set-1 sampler array: a `VkSampler` for
/// `BindState::argument_samplers[index]`, made for this use as `Sampler` is
/// (`bind::sampler_desc` with `compare` and `integer`), or the neutral sampler
/// (`NeutralResource::Sampler { compare }`) where the state lists fewer samplers: no handle
/// names that element then. The plan writes every element of its shape's capacity class
/// (`ArgumentSamplersShape::entries`), so the list may grow or shrink within the class
/// without a new plan; the consumer resolves each write against the state it binds.
ArgumentSampler {
index: u32,
compare: bool,
integer: bool,
},
/// A patch draw's patch index buffer (`DrawCall::Patches::patch_index`), a read-only storage
/// buffer of the control stage over the draw's `DescriptorRange`. A draw without one has no range for it, and the consumer binds
/// the zero buffer of `min_bytes` there (`NeutralResource::ZeroBuffer`'s), whose words the
/// stage discards: the draw pushes `PushField::PatchIndexBound` 0.
PatchIndices { min_bytes: u32 },
/// An indexed patch draw's control-point index buffer
/// (`DrawCall::Patches::control_point_index`), a read-only storage buffer of the control
/// stage of a pipeline with a control-point index type over the draw's `DescriptorRange`. Every draw of such a pipeline has one.
ControlPointIndices,
/// The render pass's tile threadgroup memory (`SyntheticBinding::TileMemory`): a storage
/// buffer the consumer keeps for the pass, of at least `bytes` bytes (every tile of the
/// render area, each `SpecKey::TileThreadgroupLength` bytes), zeroed when the pass begins and
/// kept across its tile dispatches, bound whole.
TileMemory { bytes: u64 },
/// The function-table snapshot (`SyntheticBinding::FunctionTableSnapshot`): a read-only
/// storage buffer of the words of `BindState::function_tables`, laid out as
/// [`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot) of the listed sizes gives
/// them, bound whole. The consumer writes it as the command's command buffer commits: the
/// command reads each table's entries as they stand then, where Metal reads them as they
/// stand when the command runs, which differs only for a CPU write racing the GPU. The
/// stage's directory gives each listed id its record's offset, by the same sizes.
FunctionTableSnapshot,
/// The command buffer's execution status (`SyntheticBinding::ExecutionStatus`) of a stage on
/// a device that does not address buffers: a storage buffer of the
/// [`ExecutionStatus`](crate::bind::ExecutionStatus) words, the same buffer every command of
/// the command buffer writes (where the device addresses buffers, the one whose address
/// `PushHole::ExecutionStatusAddress` takes), its
/// [`ExecutionStatus::BYTES`](crate::bind::ExecutionStatus::BYTES) bytes bound, starting all
/// zero ([`ExecutionStatus::initial`](crate::bind::ExecutionStatus::initial)). The consumer
/// reads it once the command buffer completes.
ExecutionStatus,
}
/// The image of a combined image-sampler write.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ImageSource {
/// The texture bound at `slot`, through this view.
Texture { slot: SlotRef, view: ImageViewDesc },
/// A neutral image of the declared type.
Neutral(NeutralResource),
}
/// The sampler of a combined image-sampler write.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SamplerSource {
/// A `VkSampler` for the runtime sampler bound at `slot`, made for this use (as
/// `WriteSource::Sampler`).
Slot {
slot: SlotRef,
compare: bool,
integer: bool,
opaque_black: OpaqueBlackBorder,
},
/// The layout's immutable (constexpr) sampler: the write carries only the image.
Immutable,
/// The neutral sampler: the runtime sampler slot is unbound.
Neutral(NeutralResource),
}
/// The view the consumer creates for a texture write.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ImageViewDesc {
pub view_type: vk::ImageViewType,
/// The view format: the texture's own (an 8-bit sRGB texture's UNORM twin where the device
/// holds one), or the storage alias the variant chose.
pub format: vk::Format,
pub aspect: vk::ImageAspectFlags,
/// The layout the texture is in while the draw or dispatch runs. Every write of one slot's
/// texture or one heap member has the same layout, `GENERAL` when one of them is a storage
/// image; the plan cannot see that two slots or members hold one texture.
pub layout: vk::ImageLayout,
pub components: vk::ComponentMapping,
/// The levels the view holds: `None` every level of the texture, `Some(i)` level `i` alone,
/// an element of a storage slot's level views (`RuntimeFact::StorageTextureLevelViews`). Levels
/// count from the bound texture's own first level: level `i` of a Metal texture view whose
/// first level is its parent's level `b` is the parent's level `b + i`. Every layer either way.
#[cfg_attr(feature = "serde", serde(default))]
pub level: Option<u32>,
/// The function applies the bound texture's swizzle (`MTLTexture.swizzle`) to the texels it
/// reads and writes through the view, so the view takes none: its component mapping is
/// `components` alone. Set for a storage view of a swizzled texture at a slot of
/// `VariantKey::swizzled_storage`, which a Vulkan storage view could not swizzle, and
/// for the sampled view of a swizzled extended-range texture at a slot of it, whose raw codes
/// the view's swizzle would move before the function decodes them, and of a swizzled packed
/// normalized texture, whose codes the function converts by each channel's own scale. Set too,
/// under no variant, for the storage view of a swizzled texture at a slot the function only
/// queries: it reads and writes no texel, and no swizzle reaches what a query answers. `false`
/// for every other view, on which the consumer composes the texture's swizzle with
/// `components` (and a swizzled storage view is the consumer's refusal).
#[cfg_attr(feature = "serde", serde(default))]
pub shader_swizzle: bool,
}
/// A Vulkan vertex buffer binding fed by a Metal vertex-stage buffer slot.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VertexBufferBind {
pub binding: u32,
/// The Metal buffer index in the vertex stage.
pub buffer_index: u32,
/// The stride comes from the bind (`attributeStride`), as dynamic state.
pub per_bind_stride: bool,
}
/// Which push fields instantiation fills.
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PushTemplate {
/// In placement order per stage.
pub fields: Vec<PushFieldPlacement>,
}
/// Where one push field of one stage lives.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PushFieldPlacement {
pub stage: Stage,
pub field: PushField,
pub location: FieldLocation,
pub size: u32,
}
/// A push field's location: the stage's push window, or its spill to the argument table.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FieldLocation {
/// Byte offset in the pipeline's push-constant block.
PushWindow { offset: u32 },
/// Byte offset in the stage's argument table.
ArgumentTable { offset: u32 },
}
/// Something the plan did that the consumer may want to log.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PlanDiagnostic {
/// The resource bound at `slot` does not match the shader's declared type; a neutral of the
/// declared type is written instead (guest undefined behavior).
IncompatibleBinding {
slot: SlotRef,
substituted: NeutralResource,
},
/// The resident texture `source` matches the heap array of `class` in everything but its
/// numeric type, and the array's numeric type is only the default of a heap group that is
/// only queried (`RuntimeFact::HeapNumericType`): element `element` of the array is the
/// neutral, so a query through a handle to `source` answers the neutral's.
IncompatibleHeapEntry {
class: HandleClass,
element: u32,
source: HeapSource,
substituted: NeutralResource,
},
/// The texture bound at `slot` matches the shader's declared type in everything but its
/// numeric type (its format's class, float or signed or unsigned integer, is not the declared
/// one), and the plan has no exact answer for it: plain Metal reads such a texture in its own
/// class and hands back the words as the declared type (and stores a write's lanes' bits as
/// its own class), which the slot's variant (`VariantKey::cross_class`) gives for a color
/// texture where the function's compile states `RuntimeFact::CrossClassReads` (storage slots,
/// texture buffers, multisampled and sparse textures, writes, `short` and `ushort` results and
/// queries among them). A depth, stencil, extended-range or YCbCr texture, a depth slot, an
/// atomic or `ulong` access, a written slot over a swizzled texture and an integer write to an
/// `RGB9E5Float` texture are not measured. A neutral of the declared type is written instead,
/// which the runtime announces (`cross-class-texture-neutral`).
CrossClassNeutral {
slot: SlotRef,
substituted: NeutralResource,
},
/// The resident texture `source`, which the `stage` function reaches, matches the heap array
/// of `class` in everything but its numeric type, and the stage reads that class by an access
/// with no answer for it (`RuntimeFact::HeapCrossClassNeutral`: a sample, gather or LOD
/// query, a write or atomic, a storage or multisampled group's read, a `short`, `ushort` or
/// `ulong` read; or any access, for a depth, stencil, extended-range or two-plane texture):
/// element `element` of the array is the neutral, which such an access reads, where plain
/// Metal reads the texture in its own class. The runtime announces it
/// (`cross-class-texture-neutral`).
CrossClassHeapNeutral {
stage: Stage,
class: HandleClass,
element: u32,
source: HeapSource,
},
/// The texture bound at storage slot `slot` (a function's write, or read and write) is an
/// ASTC texture, whose blocks no storage view stores into: plain Metal completes the
/// function's writes, storing bytes no format defines into the blocks, and reads the blocks'
/// decode through a slot that also reads them. A neutral of the declared type is written
/// instead (its writes dropped, its reads zero, its size queries the neutral's), which leaves
/// the texture's blocks as they were; the runtime announces it (`astc-storage-neutral`).
AstcStorageNeutral {
slot: SlotRef,
substituted: NeutralResource,
},
}
/// How a draw or dispatch uses one resource: staging, writeback, and hazard facts. A plan's `uses`
/// are the shape's (bound slots, used resources); `DrawCommands.uses` and `DispatchCommands.uses`
/// add each command's index buffer and indirect arguments.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ResourceUse {
pub resource: UseTarget,
/// Proven from lowering; unknown access is `READ_WRITE`.
pub access: AccessSet,
pub class: AccessClass,
pub stages: vk::PipelineStageFlags2,
/// `None`: the whole resource from the bound offset. The bound offset of a slot is its bind
/// offset; of the index buffer, the draw's index offset; of the indirect buffer, the
/// arguments' offset.
pub range: Option<ByteRange>,
}
/// The resource a [`ResourceUse`] names.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum UseTarget {
/// The resource bound at a slot.
Slot(SlotRef),
/// A used resource, by consumer token.
Used(u32),
/// The draw's index buffer.
IndexBuffer,
/// The draw's or dispatch's indirect buffer.
Indirect,
/// The encoder's tessellation factor buffer, from its bind offset.
TessellationFactors,
/// The tile map of the sparse texture bound at a texture slot, whole: the consumer's update of
/// the map before the command (a mapping change) needs a barrier to this read.
TileMap(SlotRef),
/// A patch draw's patch index buffer, from the draw's offset into it.
PatchIndices,
/// An indexed patch draw's control-point index buffer, from the draw's offset into it.
ControlPointIndices,
}
/// How a resource is accessed, for barrier stage/access selection.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AccessClass {
Storage,
Sampled,
StorageImage,
VertexInput,
Index,
Indirect,
Attachment,
/// A two-plane YCbCr texture's planes, read in place through the slot's uniform texel buffer
/// (`WriteSource::YCbCrInPlace`) or the image of them the device's conversion samples
/// (`WriteSource::YCbCrPlanesImage`): a read of the planes' bytes, not of the texture's image.
YCbCrPlanes,
/// A 2D texture's rows, read or written in place through the slot's texel buffer
/// (`WriteSource::TexelRows`): a use of the rows' bytes, not of the texture's image.
TexelRows,
}
/// A byte range relative to the bound offset.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ByteRange {
pub offset: u64,
pub len: u64,
}
@@ -1,968 +0,0 @@
//! Compute planning: [`ComputePipeline::plan`].
//!
//! The plan is a pure function of the pipeline, the device it was compiled for, and the shape:
//!
//! - **Descriptors.** Every binding of the pipeline's layout gets one write: a bound buffer slot
//! its `Buffer` (the range comes per dispatch) or `InlineBytes`, an unbound one the `ZeroBuffer`
//! neutral, the stage's `ArgumentTable` UBO, and the pipeline's `ConstantBlob`. Textures,
//! samplers, combined image samplers, and texel buffers go through the shared resource planner
//! (`plan::resources`); the handle table and every element of the set-1 heap arrays up to the
//! heap's members through the heap planner (`bind::heap`).
//! - **Device addresses.** Every `BufferForm::Psb` slot is reached through its root-table entry, so
//! a buffer bound there without a device address, or `set*Bytes` data, is `MissingDeviceAddress`;
//! an unbound one gets a zero entry (every access contained).
//! - **Specialization.** Threadgroup lengths (`TgLength`, Metal's 16-byte rounding applied) and
//! slot presence are fixed here; the specialized threadgroup total
//! `static_threadgroup_memory_length + Σ round_up(len, 16)` must fit
//! `maxComputeSharedMemorySize`. With emulated simdgroups the static part is the arena's own
//! (`RuntimeFact::SimdgroupEmulation`), and every region also fits the scratch of its simdgroups
//! beside the declared arena. A predicated walk's vote word (`RuntimeFact::PredicationVote`) is
//! counted beside the arena too. Local size, `MultiRegion` and `StageInReach` are per region.
//! - **Variant.** The shape's storage-image choices and device-address slots, and the emulated
//! simdgroups of a pipeline compiled for them (`RuntimeFact::EmulatedSimdgroups`); a dispatch
//! adds those where its threadgroups need them (`BindingPlan::dispatch_variant`). The flat grid
//! of a pipeline compiled for one (`RuntimeFact::FlatGrid`), and the folded groups of one
//! compiled for them (`RuntimeFact::FoldedGroups`).
//! - **Imageblocks**. A kernel with an explicit imageblock (`RuntimeFact::ImageblockSize`)
//! specializes its extent from `BindState::imageblock_size`, which must be 1 to 65535 in each
//! axis (`BindError::InvalidImageblockSize`); its `width · height · cell_bytes` bytes are one
//! more 16-byte-aligned region of the threadgroup total, after the static part rounded to 16. A
//! slot receiving imageblock slices takes any pixel format: a narrow element's texel is its lanes
//! and zeros in every format, as Metal writes it.
//! - **Tile functions** (`RuntimeFact::TileFunction`). The render area (`BindState::render_area`,
//! at least one pixel in each axis, `BindError::InvalidRenderArea` otherwise) is specialized, a
//! layered pass is `Unsupported{TileShading, NotImplemented}`, and each attachment the function
//! stages is a `WriteSource::TileAttachment` in the view format its staging reads
//! (`lower::access::tile::staging_format`).
//! - **Tile threadgroup memory** (`RuntimeFact::TileThreadgroupMemory`). A tile function that reads
//! its `[[threadgroup(n)]]` arguments specializes each argument's offset in its tile's memory
//! (`SpecKey::TgOffset`, from `BindState::tile_threadgroup`), the tile's bytes
//! (`SpecKey::TileThreadgroupLength`, the pass's length rounded up to 16) and the tiles across
//! the render area (`SpecKey::TileGridWidth`), and binds the pass's tile memory
//! (`WriteSource::TileMemory`, every tile's bytes). An argument the encoder did not set is
//! `BindError::MissingThreadgroupMemory`. Every offset is placed, as plain Metal takes every
//! offset, at the offset floored to a multiple of 4, which is where plain Metal begins the
//! argument ([`tile_argument_offset`] carries the measurement). An argument's length bounds
//! nothing, as plain Metal's does not. The tile's bytes start the threadgroup total.
//! - **Kept imageblock bytes** (`RuntimeFact::TileImageblock`). A tile function whose explicit
//! imageblock stands alone, in a pass that keeps fewer bytes of its cells than its data
//! (`BindShape::kept_imageblock_bytes`), asks for `VariantKey::kept_imageblock_bytes`: plain
//! Metal reads the other words as zero and drops their writes.
//! - **Stage-in strides**. A layout of a fixed stride reads its own, whatever stride the shape
//! binds its buffer with; one of `MTLBufferLayoutStrideDynamic` (`RuntimeFact::StageInStride`)
//! reads the bound one, which instantiation pushes (`PushField::StageInStride`, 0 for a buffer
//! bound without one). The template keeps each fetch of a thread-position step, from whose
//! elements each region decides `SpecKey::StageInReach`.
//! - **Push fields.** Every placed field is one the binder fills: the root-table and status
//! addresses (holes the consumer fills), `DispatchRegion` (always written), `StageInRegion` (the
//! dispatch's `BindState::stage_in_region`), `StageInStride` (the bound buffer's attribute
//! stride), `SlotBindOffset`, and `SlotGuestBase` (the bound buffer's Metal address; a slot bound
//! with `set*Bytes` has none and is refused as `MissingGuestAddress`).
use super::resources::{separate_samplers, ResourcePlanner};
use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, open_cl_line_variant,
plan_buffer, psb_variant, record_noted, srgb_variant, texel_buffer_parts_variant, used_uses,
ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
};
use super::{
BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules,
PushFieldPlacement, PushTemplate, ResourceUse, ScratchRule, WriteSource,
};
use crate::bind::heap::{planner, HeapPlanner};
use crate::bind::neutral::{zero_buffer_bytes, NeutralResource};
use crate::bind::state::{BindShape, StageShape};
use crate::cache::{SpecializationKey, VariantKey};
use crate::device::requirements::VkLimit;
use crate::device::Device;
use crate::error::{
BindError, Capability, Feature, InternalError, InternalKind, LowerFamily, Unsupported,
};
use crate::lower::simd::divergent::VOTE_BYTES;
use crate::lower::simd::workgroup::arena_bytes;
use crate::pipeline::artifact::{ComputePipeline, RuntimeDependency, SpecConstant};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::{BufferForm, PushLoc, SlotInterface};
use crate::pipeline::layout::BindingSource;
use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding};
use crate::vk;
use std::collections::BTreeMap;
/// Metal rounds every threadgroup-memory length to 16 bytes.
const TG_ALIGN: u64 = 16;
/// What plain Metal floors a tile threadgroup argument's offset to, in bytes
/// ([`tile_argument_offset`] carries the measurement).
const TG_FLOOR: u32 = 4;
pub(crate) fn internal(detail: impl Into<String>) -> BindError {
BindError::Internal(InternalError::new(InternalKind::Invariant, detail))
}
pub(crate) fn not_implemented(feature: Feature) -> BindError {
BindError::Unsupported(Unsupported::not_implemented(feature))
}
/// The largest imageblock extent in either axis: `get_imageblock_width` is a `ushort`.
const MAX_IMAGEBLOCK_EXTENT: u32 = u16::MAX as u32;
/// The bytes of the kernel's explicit imageblock for `shape`'s extent, rounded up to 16; `None`
/// without one. An extent of 0 or above 65535 in either axis is `BindError::InvalidImageblockSize`.
fn imageblock_bytes(p: &ComputePipeline, shape: &BindShape) -> Result<Option<u64>, BindError> {
let Some(cell_bytes) = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::ImageblockSize { cell_bytes } => Some(cell_bytes),
_ => None,
}) else {
return Ok(None);
};
let s = shape.imageblock_size;
let valid = |n: u32| (1..=MAX_IMAGEBLOCK_EXTENT).contains(&n);
if !valid(s.width) || !valid(s.height) {
return Err(BindError::InvalidImageblockSize {
width: s.width,
height: s.height,
});
}
let bytes = u64::from(s.width) * u64::from(s.height) * u64::from(cell_bytes);
Ok(Some(bytes.next_multiple_of(TG_ALIGN)))
}
/// A tile function's pass has a render area (`BindState::render_area` of at least one pixel in each
/// axis; `BindError::InvalidRenderArea` otherwise: the consumer never set it, and the function
/// would stage no pixel), and is not layered: what a tile dispatch of a layered pass runs, and what
/// `[[render_target_array_index]]` reads in it, is not read yet.
fn check_tile_pass(p: &ComputePipeline, shape: &BindShape) -> Result<(), BindError> {
if !is_tile_function(p) {
return Ok(());
}
let [width, height] = shape.render_area;
if width == 0 || height == 0 {
return Err(BindError::InvalidRenderArea { width, height });
}
if shape.render_target_array_length > 1 {
return Err(not_implemented(Feature::TileShading));
}
Ok(())
}
/// A tile or fragment function's tile threadgroup memory as a bind shape places it
/// (`tile_memory`): each tile's bytes (the pass's `threadgroupMemoryLength` rounded up to 16),
/// the pass's tile, the tiles across and down the render area, and each argument's offset by
/// index.
pub(crate) struct TileMemoryPlan {
pub(crate) tile_bytes: u64,
pub(crate) tile: [u32; 2],
pub(crate) grid: [u32; 2],
pub(crate) offsets: BTreeMap<u32, u32>,
}
impl TileMemoryPlan {
/// The buffer's bytes: every tile's, and 16 at least, as a buffer of no bytes cannot be bound
/// (a pass of no threadgroup memory, whose arguments are all empty, reads none of them).
pub(crate) fn bytes(&self) -> u64 {
(u64::from(self.grid[0]) * u64::from(self.grid[1]) * self.tile_bytes).max(TG_ALIGN)
}
/// The value of tile memory specialization constant `key` (`SpecKey::TgOffset`,
/// `TileThreadgroupLength` and `TileGridWidth`; a fragment function's tile, `ImageblockWidth`
/// and `ImageblockHeight`), or `None` for another key or an argument without its fact.
pub(crate) fn spec(&self, key: SpecKey) -> Option<u64> {
match key {
SpecKey::TgOffset(index) => self.offsets.get(&index).map(|&o| u64::from(o)),
SpecKey::TileThreadgroupLength => Some(self.tile_bytes),
SpecKey::TileGridWidth => Some(u64::from(self.grid[0])),
SpecKey::ImageblockWidth => Some(u64::from(self.tile[0])),
SpecKey::ImageblockHeight => Some(u64::from(self.tile[1])),
_ => None,
}
}
}
/// Where an argument the encoder set at byte `offset` of its tile's threadgroup memory begins in
/// the threadgroup arena: `offset` floored to a multiple of 4, which is where plain Metal begins
/// it.
///
/// Plain Metal takes every offset and places it by this one rule, measured on an Apple M3 Max
/// under macOS 27.0.1 over eighteen offsets, each in its own process with Metal's API validation
/// off: with a tile memory of 128 bytes whose word `t` held a value only a seeding dispatch could
/// have written, an argument at byte 0, 2, 4, 8, 16, 17, 20 and 32 began at word 0, 0, 1, 2, 4, 4,
/// 5 and 8. So the floor is to 4 and not to 16, which byte 17 alone cannot tell apart (both place
/// it at byte 16) but bytes 4, 8 and 20 do.
///
/// Nothing is clamped. An offset at or past the tile's memory needs no clamp: every access from it
/// fails the arena's containment, which reads zero and drops the store (`memory::contain`), and
/// bytes 128 and 144 of that 128-byte memory read zero throughout. Nor may it be clamped, because
/// plain Metal's own address arithmetic wraps at 2^32 rather than reading zero from the memory's
/// end on for ever: an argument at `u64::MAX`, which is byte `0xfffffffc` after the truncation the
/// encoder applies, read zero and then the memory's words 0, 1 and 2 as its reads carried past
/// 2^32. The arena's offsets are `u32` and add with wrapping, so such accesses wrap where Metal's
/// do.
///
/// A 4-byte-aligned base is exact here because the threadgroup arena has no 8- or 16-byte unit
/// (`memory::arena::ArenaMem` declares no `Units`), so an 8- or 16-byte access takes `Path::Vec2`'s
/// or `Path::Vec4`'s fallback to its words at `off / 4` rather than a `uvec2` index at `off / 8` or
/// a `uvec4` index at `off / 16` (`memory::leaf`): no access to the arena claims an alignment the
/// base does not hold.
fn tile_argument_offset(offset: u32) -> u32 {
offset - offset % TG_FLOOR
}
/// The tile threadgroup memory of a pipeline of `dependencies` as `shape` places it on `device`;
/// `None` for a pipeline that reads no threadgroup argument (`RuntimeFact::TileThreadgroupMemory`:
/// a tile function's, or a fragment function's). An argument the encoder did not set is
/// `BindError::MissingThreadgroupMemory`. An argument's length takes no part in the layout and
/// bounds no access, and every offset is placed where plain Metal begins the argument
/// ([`tile_argument_offset`]), as plain Metal takes every length and every offset. A shape without
/// a render area or a tile is `InvalidRenderArea` or `InvalidImageblockSize`. A buffer of every
/// tile's memory past the device's `maxStorageBufferRange`, which one descriptor binds at most, is
/// `Unsupported`.
pub(crate) fn tile_memory(
dependencies: &[RuntimeDependency],
device: &Device,
shape: &BindShape,
) -> Result<Option<TileMemoryPlan>, BindError> {
let mut offsets = BTreeMap::new();
let memory = &shape.tile_threadgroup;
for d in dependencies {
let RuntimeFact::TileThreadgroupMemory { index } = d.fact else {
continue;
};
let argument = memory
.arguments
.get(&index)
.ok_or(BindError::MissingThreadgroupMemory { index })?;
offsets.insert(index, tile_argument_offset(argument.offset));
}
if offsets.is_empty() {
return Ok(None);
}
let [width, height] = shape.render_area;
if width == 0 || height == 0 {
return Err(BindError::InvalidRenderArea { width, height });
}
let tile = shape.imageblock_size;
if tile.width == 0 || tile.height == 0 {
return Err(BindError::InvalidImageblockSize {
width: tile.width,
height: tile.height,
});
}
let plan = TileMemoryPlan {
tile_bytes: u64::from(memory.length).next_multiple_of(TG_ALIGN),
tile: [tile.width, tile.height],
grid: [
shape.render_area[0].div_ceil(tile.width),
shape.render_area[1].div_ceil(tile.height),
],
offsets,
};
let available = u64::from(device.profile().fields().limits.max_storage_buffer_range);
if plan.bytes() > available {
return Err(BindError::Unsupported(Unsupported::needs(
Feature::TileShading,
Capability::Limit {
limit: VkLimit::MaxStorageBufferRange,
required: plan.bytes(),
available,
},
)));
}
Ok(Some(plan))
}
/// The bytes of each cell of `p`'s explicit imageblock standing alone
/// (`RuntimeFact::TileImageblock`) that `shape`'s pass keeps (`BindShape::kept_imageblock_bytes`),
/// where they are fewer than its data: `None` for every other pipeline and pass.
fn kept_imageblock_bytes(p: &ComputePipeline, shape: &BindShape) -> Option<u32> {
let data_size = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::TileImageblock { data_size, .. } => Some(data_size),
_ => None,
})?;
shape.kept_imageblock_bytes.filter(|&kept| kept < data_size)
}
/// The threadgroup Metal answers `p`'s tile function in `shape`'s pass where its threadgroup is
/// the tile (`RuntimeFact::TileThreadgroup` with `tile_sized`): the tile, `shape`'s imageblock
/// size, at least 1 in each axis (`BindError::InvalidImageblockSize`). `None` for every other
/// pipeline.
fn tile_threadgroup(p: &ComputePipeline, shape: &BindShape) -> Result<Option<[u32; 3]>, BindError> {
let tile_sized = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::TileThreadgroup { tile_sized: true });
if !tile_sized {
return Ok(None);
}
let tile = shape.imageblock_size;
if tile.width == 0 || tile.height == 0 {
return Err(BindError::InvalidImageblockSize {
width: tile.width,
height: tile.height,
});
}
Ok(Some([tile.width, tile.height, 1]))
}
/// Whether `p` is a tile function's pipeline (`RuntimeFact::TileFunction`).
fn is_tile_function(p: &ComputePipeline) -> bool {
p.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::TileFunction)
}
/// The view format of tile attachment `color` of `p` (`WriteSource::TileAttachment`): the staging
/// format (`lower::access::tile::staging_format`) of the pixel format the tile function stages it
/// in (`RuntimeFact::TileAttachmentFormat`).
fn tile_view_format(p: &ComputePipeline, color: u32) -> Result<crate::vk::Format, BindError> {
let pixel_format = p
.dependencies
.iter()
.find_map(|d| match d.fact {
RuntimeFact::TileAttachmentFormat { color: c, format } if c == color => Some(format),
_ => None,
})
.ok_or_else(|| internal(format!("tile attachment {color} without its format")))?;
let view = crate::lower::access::tile::staging_format(pixel_format);
crate::metal::format::direct_format(view).ok_or_else(|| {
internal(format!(
"tile attachment {color}: no Vulkan format for {view:?}"
))
})
}
impl ComputePipeline {
/// The shape-level binding plan of this pipeline for `shape`: a pure function of the pipeline,
/// `device` (the device that compiled it), and the shape, so the consumer memoizes it on
/// `(PipelineKey, BindShape)`. Per-dispatch bytes come from
/// [`BindingPlan::instantiate_dispatch`].
pub fn plan(&self, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
plan(self, device, shape)
}
}
/// The specialization data of the constants in `layout` that `value` gives a value, in `SpecId`
/// order: each value's low `size` bytes, little-endian, without the bits no stage reads
/// (`SpecConstant::unread_bits`), so values that differ only there give one key, one `VkPipeline`,
/// and one specialization the driver sees. Its two lists are made at once, at the first constant
/// given a value, at the size it and every later constant take; a key of no value makes none.
pub(crate) fn spec_key(
layout: &[SpecConstant],
value: impl Fn(SpecKey) -> Option<u64>,
) -> SpecializationKey {
let mut key = SpecializationKey::new();
spec_key_into(layout, value, &mut key);
key
}
/// [`spec_key`]'s key, written over `key` in the storage its two lists hold: a key written over
/// one of as many constants allocates nothing.
pub(crate) fn spec_key_into(
layout: &[SpecConstant],
value: impl Fn(SpecKey) -> Option<u64>,
key: &mut SpecializationKey,
) {
key.entries.clear();
key.data.clear();
for (at, c) in layout.iter().enumerate() {
let Some(v) = value(c.key) else { continue };
// Room for the rest of the layout at once, rather than growing a push at a time: a
// dispatch's regions each make one.
if key.entries.is_empty() {
let rest = &layout[at..];
key.entries.reserve_exact(rest.len());
(key.data).reserve_exact(rest.iter().map(|c| c.size.min(8) as usize).sum());
}
let v = v & !c.unread_bits;
let size = c.size.min(8);
key.entries.push(vk::SpecializationMapEntry {
constant_id: c.id,
offset: key.data.len() as u32,
size,
});
key.data
.extend_from_slice(&v.to_le_bytes()[..size as usize]);
}
}
fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
check_slots(shape)?;
if p.stage.stage != vk::ShaderStage::COMPUTE {
return Err(internal("a compute pipeline whose stage is not compute"));
}
let f = device.profile().fields();
let limits = &f.limits;
let empty = StageShape::default();
let ks = shape.stages.get(&Stage::Kernel).unwrap_or(&empty);
let bindings = bindings(&p.layout);
// Buffer slots.
let replayed = (p.dependencies.iter()).any(|d| d.fact == RuntimeFact::ReplayBindings);
let mut buffers = Vec::new();
for (&slot, iface) in &p.interface.slots {
let b = match iface {
SlotInterface::Buffer(b) if slot.stage == Stage::Kernel => b,
SlotInterface::Texture(_) | SlotInterface::Sampler(_)
if slot.stage == Stage::Kernel =>
{
continue
}
SlotInterface::Buffer(_) | SlotInterface::Texture(_) | SlotInterface::Sampler(_) => {
return Err(internal(format!("a compute pipeline uses {slot:?}")))
}
};
buffers.push(plan_buffer(
(slot, b, ks.buffers.get(&slot.index)),
replayed,
limits,
&bindings,
)?);
}
let planned = |slot: SlotRef| buffers.iter().find(|b| b.slot == slot);
// Push placement.
let placement = p.interface.push.iter().find(|pl| pl.stage == Stage::Kernel);
let fields = placement.map(|pl| pl.fields.clone()).unwrap_or_default();
let mut push = PushTemplate::default();
let mut reads_root_table = false;
for field in &fields {
let in_push = matches!(field.loc, PushLoc::Push { .. });
match field.field {
PushField::RootTableAddress => reads_root_table = true,
PushField::ExecutionStatusAddress
| PushField::DispatchRegion
| PushField::ReplayRegionAddress
| PushField::StageInRegion => {}
PushField::SlotBindOffset(slot)
if planned(slot).is_some_and(|b| b.binding.is_some()) => {}
// The bound buffer's Metal address; a `set*Bytes` binding has none.
PushField::SlotGuestBase(slot)
if planned(slot).is_some_and(|b| b.bound != BoundKind::Bytes) => {}
PushField::SlotGuestBase(slot) if planned(slot).is_some() => {
return Err(BindError::MissingGuestAddress { slot })
}
// The bound buffer's bytes before its bind offset and its length, which instantiation
// reads from the state.
PushField::SlotBounds(slot) if planned(slot).is_some() => {}
// The identity domains' zero range and private arena are the runtime's own memory, and
// their bicubic slot's format treatment the runtime's own field.
PushField::ZeroAddress
| PushField::BicubicTexels(_)
| PushField::PrivateArenaAddress => {
return Err(not_implemented(Feature::IdentityDomains))
}
// Under the identity domains a texture's or sampler's word is its resource ID and a
// constexpr sampler's the runtime's own sampler: fields the runtime pushes itself,
// which no binding state holds.
PushField::SlotGuestBase(SlotRef {
class: SlotClass::Texture | SlotClass::Sampler,
..
})
| PushField::ConstexprSampler(_) => {
return Err(not_implemented(Feature::IdentityDomains))
}
PushField::SlotBindOffset(SlotRef {
class: SlotClass::Texture,
..
}) => return Err(not_implemented(Feature::TexelBuffer)),
// A storage texture's level count and integer channel widths, which the resource plan
// records.
PushField::TextureLevels(_) | PushField::TextureIntegerChannels(_) => {}
// A structure's instance count, which instantiation reads from the state.
PushField::InstanceCount(_) => {}
// An in-place YCbCr texture's words, and a texture's rows in its texel buffer view,
// which instantiation reads from the state.
PushField::YCbCrInPlace(_) | PushField::TexelRows(_) => {}
// A stage-in buffer's bound stride, which instantiation reads from the state.
PushField::StageInStride(_) => {}
other => return Err(internal(format!("a compute push field {other:?}"))),
}
let per_region = matches!(
field.field,
PushField::RootTableAddress
| PushField::ExecutionStatusAddress
| PushField::DispatchRegion
| PushField::ReplayRegionAddress
);
if per_region && !in_push {
// The placement order puts these first, so a compute window (128 bytes) always holds
// them.
return Err(not_implemented(Feature::Lowering(LowerFamily::Dispatch)));
}
push.fields.push(PushFieldPlacement {
stage: Stage::Kernel,
field: field.field,
location: match field.loc {
PushLoc::Push { offset } => FieldLocation::PushWindow { offset },
PushLoc::ArgumentTable { offset } => FieldLocation::ArgumentTable { offset },
},
size: field.size,
});
}
let root_first = reads_root_table.then(|| {
let top = buffers
.iter()
.filter(|b| b.form == BufferForm::Psb)
.map(|b| b.slot.index + 1)
.max()
.unwrap_or(0);
2 + top
});
// A tile function's tile threadgroup memory.
let tile_memory = tile_memory(&p.dependencies, device, shape)?;
// Descriptors.
let mut resources = ResourcePlanner {
profile: device.profile(),
shape: &shape.stages,
slots: &p.interface.slots,
dependencies: &p.dependencies,
stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER,
variant: VariantKey::new(),
diagnostics: Vec::new(),
uses: Vec::new(),
template: Default::default(),
alpha_red_texels: Default::default(),
};
let mut heap = HeapPlanner::new(device.profile(), &p.layout, &p.dependencies, shape, |_| {
vec![Stage::Kernel]
})?;
let mut descriptors = Vec::new();
let separate = separate_samplers(&p.layout);
let mut table = None;
for set in &p.layout.sets {
for b in &set.bindings {
if let BindingSource::Heap(_) = b.source {
descriptors.extend(planner(&mut heap)?.array(set.set, b)?);
continue;
}
// A constexpr sampler array: the layout's immutable samplers, no write.
if let BindingSource::SamplerArray { .. } = b.source {
continue;
}
// A separate sampler: a constexpr one is the layout's immutable sampler, no write; a
// runtime one the sampler bound at its slot, made for the use.
if let BindingSource::SeparateSampler { stage, sampler } = b.source {
let source =
resources.separate_sampler(stage, sampler, b.immutable_sampler.as_ref())?;
if let Some(source) = source {
descriptors.push(DescriptorWrite {
set: set.set,
binding: b.binding,
array_element: 0,
ty: b.ty,
source,
});
}
continue;
}
if let BindingSource::HeapSampler { stage, sampler } = b.source {
// A constexpr heap sampler is the layout's immutable sampler: no write. A runtime
// one is the sampler bound at its slot, made for the use.
let runtime =
planner(&mut heap)?.sampler(stage, sampler, b.immutable_sampler.as_ref())?;
if let Some(slot) = runtime {
descriptors.push(DescriptorWrite {
set: set.set,
binding: b.binding,
array_element: 0,
ty: b.ty,
source: resources.heap_sampler(slot, sampler)?,
});
}
continue;
}
// A storage slot's level views, or a texture buffer's parts.
if let (0, BindingSource::Texture(slot)) = (set.set, b.source) {
if b.count > 1 {
let views = resources.slot_views(set.set, b.binding, b.ty, slot, b.count)?;
descriptors.extend(views.into_iter().zip(0..).map(|(source, i)| {
DescriptorWrite {
set: set.set,
binding: b.binding,
array_element: i,
ty: b.ty,
source,
}
}));
continue;
}
}
if set.set != 0 || b.count != 1 {
return Err(internal(format!(
"a {:?} binding of {} descriptors in set {}",
b.source, b.count, set.set
)));
}
let source = match b.source {
BindingSource::Buffer(slot) => {
let pb = planned(slot).ok_or_else(|| {
internal(format!("binding of {slot:?} without an interface slot"))
})?;
match pb.bound {
BoundKind::Buffer { .. } => WriteSource::Buffer { slot },
BoundKind::Bytes => WriteSource::InlineBytes { slot },
BoundKind::Unbound => WriteSource::Neutral(NeutralResource::ZeroBuffer {
min_bytes: zero_buffer_bytes(device.profile()),
}),
}
}
BindingSource::Synthetic {
stage: Stage::Kernel,
binding,
} => match binding {
SyntheticBinding::ArgumentTable => {
let size = placement.map_or(0, |pl| pl.argument_table_size);
if size == 0 {
return Err(internal("an ArgumentTable binding without fields"));
}
table = Some((set.set, b.binding, size));
WriteSource::ArgumentTable {
stage: Stage::Kernel,
bytes_len: size,
}
}
SyntheticBinding::ConstantBlob if p.stage.constant_blob.is_some() => {
WriteSource::ConstantBlob {
stage: Stage::Kernel,
}
}
SyntheticBinding::HandleTable => {
planner(&mut heap)?.table(Stage::Kernel, set.set, b.binding)?
}
SyntheticBinding::SamplerTable => {
planner(&mut heap)?.sampler_table(Stage::Kernel, set.set, b.binding)?
}
SyntheticBinding::FunctionTableDirectory => {
planner(&mut heap)?.directory(Stage::Kernel, set.set, b.binding)?
}
// The tables' words on a device without the array's features.
SyntheticBinding::FunctionTableSnapshot => {
planner(&mut heap)?.snapshot(Stage::Kernel, set.set, b.binding)?
}
// The pass's tile threadgroup memory.
SyntheticBinding::TileMemory => match &tile_memory {
Some(memory) => WriteSource::TileMemory {
bytes: memory.bytes(),
},
None => return Err(internal("a tile memory binding without its facts")),
},
// The pass's imageblock storage, a tile function's explicit imageblock.
SyntheticBinding::Imageblock => WriteSource::Imageblock,
// The command buffer's status, on a device that does not address buffers.
SyntheticBinding::ExecutionStatus => WriteSource::ExecutionStatus,
other => return Err(internal(format!("a compute binding {other:?}"))),
},
BindingSource::Texture(slot) => {
resources.texture(set.set, b.binding, b.ty, slot)?
}
BindingSource::Sampler(slot) => resources.sampler(slot)?,
BindingSource::CombinedTextureSampler { texture, sampler } => {
resources.combined(texture, sampler, b.immutable_sampler.as_ref())?
}
BindingSource::SeparateTexture { texture, sampler } => {
let immutable = separate.get(&(texture.stage, sampler)).ok_or_else(|| {
internal(format!(
"separate texture {texture:?} without its sampler {sampler:?}"
))
})?;
resources.separate_texture(texture, sampler, *immutable)?
}
// The consumer builds the structures.
BindingSource::AccelerationStructure { slot, level } => {
WriteSource::AccelerationStructure { slot, level }
}
// A sparse texture's tile map.
BindingSource::TileMap(slot) => resources.tile_map(slot),
// A two-plane YCbCr texture's planes image, through the device's conversion.
BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?,
// A tile function's attachment.
BindingSource::TileAttachment(color_index) => WriteSource::TileAttachment {
color_index,
format: tile_view_format(p, color_index)?,
},
other => return Err(internal(format!("a compute binding {other:?}"))),
};
descriptors.push(DescriptorWrite {
set: set.set,
binding: b.binding,
array_element: 0,
ty: b.ty,
source,
});
}
}
// Specialization the shape decides.
let layout = &p.stage.specialization.constants;
let imageblock = imageblock_bytes(p, shape)?;
check_tile_pass(p, shape)?;
check_sparse_textures(&p.dependencies, device.profile(), shape)?;
let mut fixed = Vec::new();
// A tile function's tile threadgroup memory starts its arena.
let mut regions_total: Option<u64> = match (&tile_memory, imageblock) {
(Some(memory), imageblock) => Some(memory.tile_bytes + imageblock.unwrap_or(0)),
(None, imageblock) => imageblock,
};
for c in layout {
if let Some(v) = bound_value(c.key, shape, &resources)? {
fixed.push((c.key, v));
continue;
}
let v = match c.key {
// Each region decides these (`dispatch::region_specialization_into`).
SpecKey::LocalSize(_)
| SpecKey::FlatLocalSize
| SpecKey::MultiRegion
| SpecKey::StageInReach
| SpecKey::DeepThreadgroup => continue,
SpecKey::TgLength(n) => {
let len = u64::from(ks.threadgroup_lengths.get(&n).copied().unwrap_or(0));
let len = len.next_multiple_of(TG_ALIGN);
regions_total = Some(regions_total.unwrap_or(0) + len);
len
}
SpecKey::ImageblockWidth if imageblock.is_some() => {
u64::from(shape.imageblock_size.width)
}
SpecKey::ImageblockHeight if imageblock.is_some() => {
u64::from(shape.imageblock_size.height)
}
// A tile dispatch's render area.
SpecKey::RenderAreaWidth => u64::from(shape.render_area[0]),
SpecKey::RenderAreaHeight => u64::from(shape.render_area[1]),
// A tile function's tile threadgroup memory.
SpecKey::TgOffset(_) | SpecKey::TileThreadgroupLength | SpecKey::TileGridWidth => {
tile_memory
.as_ref()
.and_then(|m| m.spec(c.key))
.ok_or_else(|| internal(format!("{:?} without its facts", c.key)))?
}
// What the kernel's handles can name: its raw arms drop where it names no texture
// held by its raw texels.
SpecKey::HeapRawTextures(stage) => {
u64::from(heap_raw(shape, stage, &|_| vec![Stage::Kernel]))
}
other => return Err(internal(format!("a compute specialization {other:?}"))),
};
fixed.push((c.key, v));
}
record_noted([&p.stage], shape, &mut resources, &|_| vec![Stage::Kernel])?;
// Emulated simdgroups: the arena's own static part comes from the fact (the reported static
// length is Metal's layout's, without the arena's minimum).
let emulation = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::SimdgroupEmulation {
bytes_per_simdgroup,
arena,
} => Some((bytes_per_simdgroup, arena)),
_ => None,
});
// A predicated walk's vote word sits beside the arena, counted in the total beside the static
// part, which the reported static length is.
let vote = if p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::PredicationVote)
{
u64::from(VOTE_BYTES)
} else {
0
};
let static_bytes = match emulation {
Some((_, arena)) => arena.map_or(0, u64::from),
None => u64::from(p.metal_info.static_threadgroup_memory_length),
};
// The imageblock, the arena's last region, starts 16-byte aligned.
let static_bytes = if imageblock.is_some() {
static_bytes.next_multiple_of(TG_ALIGN)
} else {
static_bytes
};
if let Some(regions) = regions_total {
let required = static_bytes + regions + vote;
let available = u64::from(limits.max_compute_shared_memory_size);
if required > available {
return Err(BindError::Unsupported(Unsupported::needs(
Feature::ThreadgroupMemorySize,
Capability::Limit {
limit: VkLimit::MaxComputeSharedMemorySize,
required,
available,
},
)));
}
}
let specialization = spec_key(layout, |k| {
fixed.iter().find(|(key, _)| *key == k).map(|(_, v)| *v)
});
// Local-size rules.
let multiples = p
.dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::LocalSizeConstraint { multiple } => Some(multiple),
_ => None,
})
.collect();
// The unit axes a pipeline compiled as its unit-axes variant states, or the masks whose variant
// relieves its predicated walk (`RuntimeFact::UnitAxes`).
let unit_axes = (p.dependencies.iter())
.find_map(|d| match d.fact {
RuntimeFact::UnitAxes { axes, relief } => Some((axes, relief)),
_ => None,
})
.unwrap_or((0, 0));
let local = LocalRules {
flat: layout.iter().any(|c| c.key == SpecKey::FlatLocalSize),
deep: layout.iter().any(|c| c.key == SpecKey::DeepThreadgroup),
multiples,
max_size: limits.max_compute_work_group_size,
max_invocations: limits.max_compute_work_group_invocations,
max_subgroups: f.subgroup.max_compute_workgroup_subgroups,
max_count: limits.max_compute_work_group_count,
required_subgroup_size: p.stage.required_subgroup_size,
stage_flags: p.stage.stage_flags,
scratch: emulation.map(|(per_simdgroup, arena)| ScratchRule {
per_simdgroup,
fixed: arena_bytes(arena, regions_total.unwrap_or(0)),
available: limits.max_compute_shared_memory_size,
}),
rows: p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::RowLockstep),
unit_relief: unit_axes.1,
tile: is_tile_function(p),
tile_threadgroup: tile_threadgroup(p, shape)?,
grid_tiles: p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::GridTiles),
};
// Uses: every bound buffer slot, with its proven access and window, and the used resources
// the function can reach.
let compute_stage = vk::PipelineStageFlags2::COMPUTE_SHADER;
let mut uses: Vec<ResourceUse> = buffers
.iter()
.filter(|b| matches!(b.bound, BoundKind::Buffer { .. }))
.map(|b| buffer_use(b, compute_stage))
.collect();
uses.extend(used_uses(
&shape.used,
p.interface.needs_pointer_translation,
p.interface.needs_handle_translation,
|_| compute_stage,
compute_stage,
));
uses.append(&mut resources.uses);
let mut diagnostics = resources.diagnostics;
let mut template = resources.template;
template.biased_slot_words = crate::lower::access::identity(device.profile());
if let Some(h) = heap {
h.finish(
&mut descriptors,
&mut uses,
|_| compute_stage,
&mut template,
&mut diagnostics,
);
}
let mut variant = resources.variant;
variant.psb_slots = psb_variant(&p.dependencies, &buffers, device.profile());
variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape);
variant.srgb_textures = srgb_variant(
device.profile(),
&p.dependencies,
shape,
&variant.cross_class,
);
variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape);
variant.ycbcr_planes_sampled =
ycbcr_planes_sampled_variant(&p.dependencies, shape, &variant.ycbcr_in_place);
variant.texel_buffer_parts = texel_buffer_parts_variant(&p.dependencies, shape);
variant.address_maps = address_map_variant(&p.dependencies, shape);
variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?;
variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape);
variant.open_cl_lines = open_cl_line_variant(&p.dependencies, &p.interface.slots, shape);
// A pipeline compiled for emulated simdgroups states its variant; a dispatch asks for it where
// the flattened tiers cannot run its threadgroups (`dispatch_variant`).
variant.emulated_simdgroups = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::EmulatedSimdgroups);
// A pipeline compiled as its one-row variant states it; a dispatch asks for it where every
// region is one row of a kernel with `RowLockstep` (`dispatch_variant`).
variant.one_row = p.dependencies.iter().any(|d| d.fact == RuntimeFact::OneRow);
// A pipeline compiled as its unit-axes variant states its axes; a consumer asks for it where a
// dispatch's threadgroups have one thread along axes that relieve the walk
// (`VariantKey::unit_axes`).
variant.unit_axes = unit_axes.0;
// A pipeline compiled for a flat grid states its variant, and one of the call's threadgroups
// states that too.
variant.flat_grid = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::FlatGrid);
variant.call_threadgroups = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::CallThreadgroups);
// And one compiled to fold its group counts, or to run a ragged grid's partial threadgroups.
variant.folded_groups = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::FoldedGroups);
variant.partial_threadgroups = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::PartialThreadgroups);
// A tile function's explicit imageblock standing alone in a pass that keeps fewer of its
// cells' bytes: the variant that reads the others as zero and drops their writes.
variant.kept_imageblock_bytes = kept_imageblock_bytes(p, shape);
// Tables that may pass `maxStorageBufferRange`: the variant that reads them at their
// addresses (and a pipeline compiled so states it).
variant.addressed_function_tables = crate::bind::heap::addressed_function_tables(
device.profile(),
&p.dependencies,
&shape.function_tables,
);
Ok(BindingPlan {
variant,
specialization,
descriptors,
vertex_buffers: Vec::new(),
uses,
push,
diagnostics,
graphics: None,
compute: Some(ComputeTemplate {
buffers,
spec: layout.clone(),
fixed,
local,
fields,
push_range: placement.and_then(|pl| pl.push_range),
table,
root_first,
resources: template,
stage_in_region: p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::StageInRegion),
stage_in_grid: match layout.iter().any(|c| c.key == SpecKey::StageInReach) {
true => (p.interface.stage_in.iter().copied())
.filter(|f| crate::bind::dispatch::grid_axis(f).is_some())
.collect(),
false => Vec::new(),
},
}),
views: Default::default(),
})
}
#[cfg(test)]
mod tests;
@@ -1,60 +0,0 @@
//! Specialization encoding of compute plans. Plans of compiled pipelines are
//! tested end to end in `src/tests/engine_binder.rs`.
use super::*;
use crate::pipeline::sym::Axis;
#[test]
fn specialization_data_packs_each_value_at_its_size_in_id_order() {
let c = |id, key, size| SpecConstant {
id,
key,
size,
default: 0,
unread_bits: 0,
};
let layout = [
c(0, SpecKey::LocalSize(Axis::X), 4),
c(1, SpecKey::MultiRegion, 4),
c(2, SpecKey::TgLength(3), 4),
];
let key = spec_key(&layout, |k| match k {
SpecKey::LocalSize(_) => Some(0x0102_0304),
SpecKey::TgLength(3) => Some(48),
_ => None,
});
assert_eq!(key.data, vec![4, 3, 2, 1, 48, 0, 0, 0]);
let ids: Vec<(u32, u32, u32)> = key
.entries
.iter()
.map(|e| (e.constant_id, e.offset, e.size))
.collect();
assert_eq!(ids, vec![(0, 0, 4), (2, 4, 4)]);
}
/// A key's lists are made at once at the size every constant of the layout takes, not grown a
/// push at a time: where each constant has a value, each list's capacity is its length. A key of
/// no value makes no list at all.
#[test]
fn specialization_lists_are_made_whole_at_once() {
let c = |id, key, size| SpecConstant {
id,
key,
size,
default: 0,
unread_bits: 0,
};
let layout = [
c(0, SpecKey::LocalSize(Axis::X), 4),
c(1, SpecKey::LocalSize(Axis::Y), 4),
c(2, SpecKey::LocalSize(Axis::Z), 4),
c(3, SpecKey::FlatLocalSize, 4),
c(4, SpecKey::MultiRegion, 1),
];
let key = spec_key(&layout, |_| Some(1));
assert_eq!((key.entries.len(), key.data.len()), (5, 17));
assert_eq!(key.entries.capacity(), key.entries.len());
assert_eq!(key.data.capacity(), key.data.len());
let none = spec_key(&layout, |_| None);
assert_eq!((none.entries.capacity(), none.data.capacity()), (0, 0));
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-856
View File
@@ -1,856 +0,0 @@
//! Buffer-slot planning shared by compute and render plans: the Metal table bounds, one
//! [`PlannedBuffer`] per statically used buffer slot, the `BufferRangeLimit` variant a shape's
//! length classes require, and the `uses` of bound buffers and used resources.
use std::collections::BTreeMap;
use super::{AccessClass, BoundKind, ByteRange, PlannedBuffer, ResourceUse, UseTarget};
use crate::bind::state::{
BindShape, BoundBuffer, BufferRanges, BufferShape, TextureShape, UsedClass, UsedShape,
};
use crate::device::profile::Limits;
use crate::device::requirements::VkFeature;
use crate::device::{mechanism, DeviceProfile};
use crate::error::{BindError, Capability, Feature, Unsupported};
use crate::metal;
use crate::pipeline::artifact::RuntimeDependency;
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::interface::SlotInterface;
use crate::pipeline::interface::{AccessSet, BufferForm, BufferSlot, Window};
use crate::pipeline::layout::{BindingSource, PipelineLayout};
use crate::pipeline::sym::{SampledType, SlotClass, SlotRef, SpecKey, Stage};
use crate::vk;
use super::compute::internal;
use super::resources::ResourcePlanner;
/// Metal's argument-table sizes: `buffers[31]` (and `threadgroup_lengths[31]`), `textures[128]`,
/// `samplers[16]`.
pub(crate) const MAX_BUFFERS: u32 = 31;
pub(crate) const MAX_TEXTURES: u32 = 128;
pub(crate) const MAX_SAMPLERS: u32 = 16;
/// Every slot index of `shape` inside Metal's argument tables.
pub(crate) fn check_slots(shape: &BindShape) -> Result<(), BindError> {
for (&stage, s) in &shape.stages {
let tables = [
(SlotClass::Buffer, MAX_BUFFERS, s.buffers.keys().max()),
(SlotClass::Texture, MAX_TEXTURES, s.textures.keys().max()),
(SlotClass::Sampler, MAX_SAMPLERS, s.samplers.keys().max()),
// A threadgroup-memory index names no argument slot; it is reported with the buffer
// table's class, whose size it shares.
(
SlotClass::Buffer,
MAX_BUFFERS,
s.threadgroup_lengths.keys().max(),
),
];
for (class, max, top) in tables {
if let Some(&index) = top.filter(|&&i| i >= max) {
return Err(BindError::SlotOutOfRange {
slot: SlotRef {
stage,
class,
index,
},
});
}
}
}
Ok(())
}
/// Where each layout binding sits, by source.
pub(crate) fn bindings(layout: &PipelineLayout) -> BTreeMap<BindingSource, (u32, u32)> {
let mut out = BTreeMap::new();
for set in &layout.sets {
for b in &set.bindings {
out.insert(b.source, (set.set, b.binding));
}
}
out
}
impl BoundKind {
/// What `shape` binds at a buffer slot.
pub(crate) fn of(shape: Option<&BufferShape>) -> BoundKind {
match shape {
None => BoundKind::Unbound,
Some(&BufferShape::Buffer {
device_address,
length_class,
..
}) => BoundKind::Buffer {
device_address,
length_class,
},
Some(BufferShape::Bytes { .. }) => BoundKind::Bytes,
}
}
/// What `bound` binds at a buffer slot of a table of buffer range limits `ranges`: [`of`](Self::of)
/// its shape, which no offset class changes, read without making the shape.
pub(crate) fn of_bound(bound: Option<&BoundBuffer>, ranges: BufferRanges) -> BoundKind {
match bound {
None => BoundKind::Unbound,
Some(&BoundBuffer::Buffer {
length,
device_address,
..
}) => BoundKind::Buffer {
device_address: device_address.is_some(),
length_class: ranges.length_class(length),
},
Some(BoundBuffer::Bytes { .. }) => BoundKind::Bytes,
}
}
}
/// The plan of buffer slot `slot` with interface `b` and what the shape binds there: its descriptor
/// binding (the descriptor form), the storage view's descriptor base alignment and range limit, and a
/// `MissingDeviceAddress` refusal for a device-address slot bound without an address: a buffer
/// without one, or inline bytes, but in a pipeline compiled for a replay's bindings (`replayed`,
/// `RuntimeFact::ReplayBindings`), which reads every buffer through the slot table the replay's
/// preprocess writes, inline bytes the encoder bound at the consumer's upload of them. The base
/// alignment is
/// `max(minStorageBufferOffsetAlignment, 16)` (`views::base_alignment`): a descriptor byte is then
/// congruent to its Metal address modulo 16, which a `uvec4` view of the slot relies on.
pub(crate) fn plan_buffer(
(slot, b, shape): (SlotRef, &BufferSlot, Option<&BufferShape>),
replayed: bool,
limits: &Limits,
bindings: &BTreeMap<BindingSource, (u32, u32)>,
) -> Result<PlannedBuffer, BindError> {
let bound = BoundKind::of(shape);
let alignment =
crate::memory::views::base_alignment(limits.min_storage_buffer_offset_alignment);
let max_range = u64::from(limits.max_storage_buffer_range);
let binding = match b.form {
BufferForm::Descriptor => Some(
bindings
.get(&BindingSource::Buffer(slot))
.copied()
.ok_or_else(|| internal(format!("descriptor slot {slot:?} has no binding")))?,
),
BufferForm::Psb => {
let unaddressed = match bound {
BoundKind::Bytes => !replayed,
BoundKind::Buffer { device_address, .. } => !device_address,
BoundKind::Unbound => false,
};
if unaddressed {
return Err(BindError::MissingDeviceAddress { slot });
}
None
}
};
Ok(PlannedBuffer {
slot,
window: b.window,
form: b.form,
access: b.access,
binding,
alignment,
max_range,
bound,
})
}
/// The value of `key` for a draw or dispatch of `shape`, whose resources `resources` plans, where
/// the bound resources decide it: a slot's presence, a bound sampler's words, a bound texture's
/// class, swizzle, sparseness and view axes. It is what a specialization constant of `key` is set
/// to, the one place a plan computes it, and the bound sampler's whole word a specialized note's
/// test alone reads (`SpecKey::BoundSamplerWord`). `None` for a key the bound resources do not
/// decide (a threadgroup's, a tile's, a pass's).
pub(crate) fn bound_value(
key: SpecKey,
shape: &BindShape,
resources: &ResourcePlanner<'_>,
) -> Result<Option<u64>, BindError> {
Ok(Some(match key {
SpecKey::Presence(slot) => u64::from(present(shape, slot)),
SpecKey::SamplerState { slot, fields } => resources.sampler_state(slot, fields),
SpecKey::SamplerMinLevel(slot) => resources.sampler_min_level(slot),
SpecKey::SamplerAnisotropy(slot) => resources.sampler_anisotropy(slot),
SpecKey::NearestPixelSampler(slot) => resources.nearest_pixel_sampler(slot),
SpecKey::BoundSamplerWord(slot) => {
resources.sampler_state(slot, metal::sampler::SamplerWord::FIELDS)
}
// An unbound slot, or one bound to a placeholder format, reads its neutral: its
// out-of-bounds texel is all zero.
SpecKey::OutOfBoundsAlpha(slot) => bound_texture(shape, slot)
.and_then(TextureShape::out_of_bounds_alpha)
.unwrap_or(0),
SpecKey::BorderTexels(slot) => bound_texture(shape, slot)
.and_then(TextureShape::border_texels)
.unwrap_or(u64::from(metal::sampler::NEUTRAL_BORDER_TEXELS)),
SpecKey::BicubicTexels(slot) => resources.bicubic_texels(slot)?,
SpecKey::TextureSwizzle(slot) => resources.texture_swizzle(slot),
SpecKey::SparseTexture(slot) => sparse_texture(shape, slot),
SpecKey::ConstantLanes(slot) => constant_lanes(shape, slot),
SpecKey::OffsetBaseAxes(slot) => offset_base_axes(shape, slot),
_ => return Ok(None),
}))
}
/// Record in `resources`' template the value of each key a specialized note of `stages` tests that
/// no push carries but the bound resources decide (`SpecKey::BoundSamplerWord`), or what the
/// command's handles can name (`SpecKey::HeapRawTextures` and `SpecKey::HeapNanFamilies`, through
/// `reach`, the stages a used resource's render stages reach, as for the heap's members), which
/// `BindingPlan::specialized_value` gives the runtime at
/// each draw or dispatch, where it reads such a note (`StageModule::precision_notes_bound`). Nothing
/// pushes it: instantiation writes only the keys its push fields name.
pub(crate) fn record_noted<'a>(
stages: impl IntoIterator<Item = &'a crate::pipeline::StageModule>,
shape: &BindShape,
resources: &mut ResourcePlanner<'_>,
reach: &dyn Fn(metal::RenderStages) -> Vec<Stage>,
) -> Result<(), BindError> {
let tested: Vec<SpecKey> = stages
.into_iter()
.flat_map(|stage| &stage.specialized_notes)
.flat_map(|note| &note.when)
.flat_map(|clause| &clause.all)
.map(|test| test.key)
.filter(|key| {
matches!(
key,
SpecKey::BoundSamplerWord(_)
| SpecKey::HeapRawTextures(_)
| SpecKey::HeapNanFamilies(_)
)
})
.collect();
for key in tested {
if resources
.template
.specialized
.iter()
.any(|(k, _)| *k == key)
{
continue;
}
let value = match key {
SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, reach)),
SpecKey::HeapNanFamilies(stage) => u64::from(heap_nan_families(shape, stage, reach)),
key => bound_value(key, shape, resources)?.ok_or_else(|| {
internal(format!("a noted {key:?}, which no bound resource decides"))
})?,
};
let value = u32::try_from(value)
.map_err(|_| internal(format!("a noted {key:?} of {value}, past a word")))?;
resources.template.specialized.push((key, value));
}
Ok(())
}
/// The `SpecKey::HeapRawTextures` of `stage` for `shape`: of the heap members of `shape` that reach
/// `stage` (`bind::heap`'s members: a texture the command makes resident, its render stages through
/// `reach`, or binds at a texture slot of the stage), the bit `bind::heap::HELD` where one is a
/// texture a heap holds by its raw texels alone (`lower::texture::heap_raw_form`), which the stage's
/// `float` read, sample or gather decodes by the device's arithmetic, and the bit
/// `bind::heap::FILTERED` where one such is of a form whose sample the function filters (not a
/// bfloat one). Both the notes' value and the stage's constant, whose `HELD` bit gates its raw arms
/// (`lower::texture::heap_raw_form`).
pub(crate) fn heap_raw(
shape: &BindShape,
stage: Stage,
reach: &dyn Fn(metal::RenderStages) -> Vec<Stage>,
) -> u32 {
use crate::bind::heap::{FILTERED, HELD};
let mut bits = 0;
for m in crate::bind::heap::members(shape, &[stage], reach) {
let TextureShape::Texture { pixel_format, .. } = m.shape else {
continue;
};
if !crate::bind::heap::raw_held(&m.shape) {
continue;
}
bits |= HELD;
if crate::metal::format::ExtendedRange::of(pixel_format).is_some_and(|f| !f.bfloat()) {
bits |= FILTERED;
}
}
bits
}
/// The `SpecKey::HeapNanFamilies` of `stage` for `shape`: the bit of each family
/// (`bind::heap::nan_family`) of the heap members of `shape` that reach `stage` (as for
/// [`heap_raw`]), whose texels a stage's `half` or `float` write may store a NaN in.
fn heap_nan_families(
shape: &BindShape,
stage: Stage,
reach: &dyn Fn(metal::RenderStages) -> Vec<Stage>,
) -> u32 {
crate::bind::heap::members(shape, &[stage], reach)
.iter()
.map(|m| match m.shape {
TextureShape::Texture { pixel_format, .. } => {
crate::bind::heap::nan_family(pixel_format)
}
TextureShape::Buffer { .. } => 0,
})
.fold(0, |bits, family| bits | family)
}
/// Whether `shape` binds anything at `slot`.
fn present(shape: &BindShape, slot: SlotRef) -> bool {
shape
.stages
.get(&slot.stage)
.is_some_and(|s| match slot.class {
SlotClass::Buffer => s.buffers.contains_key(&slot.index),
SlotClass::Texture => s.textures.contains_key(&slot.index),
SlotClass::Sampler => s.samplers.contains_key(&slot.index),
})
}
/// The `SpecKey::SparseTexture` of `slot` for `shape`: 1 where the slot binds a sparse texture
/// (`TextureFacts::sparse`), 0 where it binds one that is not sparse or nothing.
fn sparse_texture(shape: &BindShape, slot: SlotRef) -> u64 {
u64::from(bound_texture(shape, slot).is_some_and(TextureShape::sparse))
}
/// The `SpecKey::ConstantLanes` of `slot` for `shape`: the lanes the bound sparse texture's format
/// and swizzle make constants (`TextureShape::constant_lanes`), 0 where the slot binds a texture
/// that is not sparse or nothing.
fn constant_lanes(shape: &BindShape, slot: SlotRef) -> u64 {
bound_texture(shape, slot).map_or(0, TextureShape::constant_lanes)
}
/// The `SpecKey::OffsetBaseAxes` of `slot` for `shape`: the plane axes on which the bound view's
/// parent's base-level size, which Metal's texel-offset rule reads, is not a power of two where
/// the view's own is (`TextureShape::offset_base_axes`); 0 where the slot binds any other texture
/// or nothing.
fn offset_base_axes(shape: &BindShape, slot: SlotRef) -> u64 {
bound_texture(shape, slot).map_or(0, TextureShape::offset_base_axes)
}
/// The texture slots whose function decodes an 8-bit sRGB texel (`RuntimeFact::SrgbTexture`) at
/// which `shape` binds a texture of such a format that `profile`'s device holds as its UNORM twin
/// (`metal::texel_format::srgb_twin_on`: a format it cannot sample), whose views read the codes:
/// the plan's `VariantKey::srgb_textures`. So is each slot of `cross` that the variant reads in
/// the float class (an integer slot), whose accesses there take `float` results, which the codes
/// serve as a float slot's: the variant's compile states `SrgbTexture` there. A slot bound in an
/// sRGB format the device samples reads the device's decode and joins nothing. Derived from the
/// device's format features alone, as the runtime's image plan holds the twin; the variant's
/// compile states the same facts, so its plan for the same shape states the same key.
pub(crate) fn srgb_variant(
profile: &DeviceProfile,
dependencies: &[RuntimeDependency],
shape: &BindShape,
cross: &BTreeMap<SlotRef, SampledType>,
) -> std::collections::BTreeSet<SlotRef> {
let read_float = cross
.iter()
.filter(|(_, ty)| **ty == SampledType::Float)
.map(|(slot, _)| *slot);
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::SrgbTexture { slot } => Some(slot),
_ => None,
})
.chain(read_float)
.filter(|slot| {
matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { pixel_format, .. })
if metal::texel_format::srgb_twin_on(*pixel_format, profile))
})
.collect()
}
/// The sampled texture slots whose function reads their texels in any numeric class
/// (`RuntimeFact::CrossClassReads`) at which `shape` binds a texture whose format's class is not
/// the slot's declared one and which the variant reads in that class
/// (`resources::cross_class`), each with that class: the plan's `VariantKey::cross_class`. The
/// variant's compile states the same facts, and its interface the same declared types, so its
/// plan for the same shape states the same key.
pub(crate) fn cross_variant(
dependencies: &[RuntimeDependency],
slots: &BTreeMap<SlotRef, SlotInterface>,
shape: &BindShape,
) -> BTreeMap<SlotRef, SampledType> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::CrossClassReads { slot } => Some(slot),
_ => None,
})
.filter_map(|slot| {
let Some(SlotInterface::Texture(t)) = slots.get(&slot) else {
return None;
};
let bound = bound_texture(shape, slot)?;
// A storage slot whose integer texels take the bound format's signedness reads an
// integer texture of either signedness in its own class: only a float one crosses, as
// the binding sees it (`resources::plain_texture`).
let numeric = dependencies
.iter()
.any(|d| d.fact == RuntimeFact::StorageTextureNumericType { slot });
let t = match numeric {
true => super::resources::bound_integer_type(*t, Some(bound)),
false => *t,
};
let class = super::resources::cross_class(&t, bound)?;
Some((slot, class))
})
.collect()
}
/// The texture slots of a kernel of OpenCL mode's 1D images (`RuntimeFact::OpenClLineTexture`),
/// read by the kernel, at which `shape` binds a 1D texture for a 1D image or a 1D array texture
/// for a 1D array image, where Apple's OpenCL binds a 2D texture of height 1: the plan's
/// `VariantKey::open_cl_lines`, under which the kernel declares each as that 1D texture. Any
/// other texture bound there (the 2D one Apple's OpenCL binds among them) binds as the slot
/// declares it. The base declares a 1D image's slot 2D (`TextureType::Type2D`, `Type2DArray`),
/// the variant 1D, of the same arrayness, so the variant's plan for the same shape states the
/// same key.
pub(crate) fn open_cl_line_variant(
dependencies: &[RuntimeDependency],
slots: &BTreeMap<SlotRef, SlotInterface>,
shape: &BindShape,
) -> std::collections::BTreeSet<SlotRef> {
use metal::TextureType as T;
let arrayed = |t: T| matches!(t, T::Type1DArray | T::Type2DArray);
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::OpenClLineTexture { slot } => Some(slot),
_ => None,
})
.filter(|slot| {
let Some(SlotInterface::Texture(t)) = slots.get(slot) else {
return false;
};
matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { texture_type, .. })
if matches!(texture_type, T::Type1D | T::Type1DArray)
&& arrayed(*texture_type) == arrayed(t.texture_type))
})
.collect()
}
/// The texture slots whose function reads a two-plane YCbCr texture only as its in-place form
/// reads it (`RuntimeFact::YCbCrInPlace`) at which `shape` binds a texture whose planes are read
/// in place (`TextureShape::Texture::ycbcr_in_place`), and each runtime sampler the function
/// samples the slot through states a filter the form reads ([`in_place_word`]): the plan's
/// `VariantKey::ycbcr_in_place`. Any other slot binds the texture's image. The variant's compile
/// states the same facts, so its plan for the same shape states the same key.
pub(crate) fn ycbcr_in_place_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
) -> std::collections::BTreeSet<SlotRef> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::YCbCrInPlace { slot, samplers, .. } => Some((slot, samplers)),
_ => None,
})
.filter(|&(slot, samplers)| {
let in_place = matches!(
bound_texture(shape, slot),
Some(TextureShape::Texture {
ycbcr_in_place: true,
..
})
);
let stage = shape.stages.get(&slot.stage);
let words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| {
stage
.and_then(|s| s.samplers.get(&n))
.map_or(0, |s| s.word.0)
});
in_place && words.into_iter().all(in_place_word)
})
.map(|(slot, _)| slot)
.collect()
}
/// The texture-buffer slots whose function reads the texture buffer bound there through its parts
/// (`RuntimeFact::TexelBufferParts`) at which `shape` binds a texture buffer of more texels than
/// one view holds (`TextureShape::Buffer::parts` past 1), each with those parts: the plan's
/// `VariantKey::texel_buffer_parts` (`bind::texel_parts`). A texture buffer one view holds adds
/// nothing, so its draws keep their key; any other slot binds one view, which
/// `maxTexelBufferElements` bounds. The variant's compile states the same facts, so its plan for
/// the same shape states the same key.
pub(crate) fn texel_buffer_parts_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
) -> BTreeMap<SlotRef, u32> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::TexelBufferParts { slot } => Some(slot),
_ => None,
})
.filter_map(|slot| match bound_texture(shape, slot) {
Some(&TextureShape::Buffer { parts, .. }) if parts > 1 => Some((slot, parts)),
_ => None,
})
.collect()
}
/// The slots of `in_place` (the plan's `VariantKey::ycbcr_in_place`) whose function's every sample
/// the device's own sampler Y′CbCr conversion takes (`RuntimeFact::YCbCrInPlace`'s `device`), at
/// which `shape` binds a texture whose planes are also held as an image it samples
/// (`TextureShape::Texture::ycbcr_planes_sampler`), and each runtime sampler the function samples
/// the slot through addresses no border on either plane axis ([`planes_word`]), each with that
/// conversion: the plan's `VariantKey::ycbcr_planes_sampled`. The variant's compile states the
/// same facts, so its plan for the same shape states the same key.
pub(crate) fn ycbcr_planes_sampled_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
in_place: &std::collections::BTreeSet<SlotRef>,
) -> BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler> {
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::YCbCrInPlace {
slot,
samplers,
device: true,
} if in_place.contains(&slot) => Some((slot, samplers)),
_ => None,
})
.filter_map(|(slot, samplers)| {
let sampler = match bound_texture(shape, slot) {
Some(&TextureShape::Texture {
ycbcr_planes_sampler: Some(sampler),
..
}) => sampler,
_ => return None,
};
let stage = shape.stages.get(&slot.stage);
let mut words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| {
stage
.and_then(|s| s.samplers.get(&n))
.map_or(0, |s| s.word.0)
});
words.all(planes_word).then_some((slot, sampler))
})
.collect()
}
/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way the device's
/// own sampler Y′CbCr conversion of its planes' image takes: no clamp-to-zero or border color on
/// the `s` or `t` axis, which a 4:2:0 texture reads as the border where that sampler clamps to the
/// edge (every other mode a 4:2:0 texture samples as clamp-to-edge). Its filter and coordinate
/// space are the function's to apply.
pub(crate) fn planes_word(word: u32) -> bool {
use crate::metal::sampler::SamplerWord;
use crate::metal::SamplerAddressMode as M;
let border = [M::ClampToZero.as_raw(), M::ClampToBorderColor.as_raw()];
(0..2).all(|axis| {
let mode = (word & SamplerWord::ADDRESS[axis]) >> SamplerWord::ADDRESS_SHIFT[axis];
!border.contains(&mode)
})
}
/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way its
/// in-place form reads: one filter for minification and magnification (nearest or linear), no
/// anisotropy, no cubic filter, no comparison and the weighted-average reduction. Its mip filter
/// and level clamps read the texture's one level, as Metal's sample of it reads it whatever its
/// mip filter (`lower::sampler::in_place`); every address mode, border color and coordinate
/// space is the form's to address. An unbound slot's word is 0, a nearest sampler's.
pub(crate) fn in_place_word(word: u32) -> bool {
use crate::metal::sampler::SamplerWord;
let filter = word & (SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR);
let one_filter = filter == 0 || filter == SamplerWord::LINEAR;
let other = SamplerWord::CUBIC
| SamplerWord::ANISOTROPIC
| SamplerWord::COMPARE
| SamplerWord::REDUCTION;
one_filter && word & other == 0
}
/// The texture slots a constexpr sampler samples (`RuntimeFact::ConstexprSampled`) at which
/// `shape` binds a texture whose address-mode map changes a mode the slot's constexpr samplers
/// state, each with that map restricted to those modes (every other mode to itself): the plan's
/// `VariantKey::address_maps`. A texture whose map keeps them, every ordinary texture's among
/// them, adds nothing, so its draws keep their key; textures whose maps agree on them share a
/// variant. The variant's compile states the same facts, so its plan for the same shape states
/// the same key.
pub(crate) fn address_map_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
) -> BTreeMap<SlotRef, metal::sampler::AddressModeMap> {
let mut out = BTreeMap::new();
for d in dependencies {
let RuntimeFact::ConstexprSampled { slot, modes } = d.fact else {
continue;
};
let Some(&TextureShape::Texture { address_modes, .. }) = bound_texture(shape, slot) else {
continue;
};
let stated = out
.entry(slot)
.or_insert(metal::sampler::AddressModeMap::IDENTITY);
for mode in modes {
*stated = stated.with(mode, address_modes.mode(mode));
}
}
out.retain(|_, map| !map.is_identity());
out
}
/// The runtime sampler slots whose function samples through them (`RuntimeFact::CubicSampler`)
/// at which `shape` binds a sampler whose min or mag filter is `Cubic`, each with the bound word
/// masked by `SamplerWord::CUBIC_STATE`: the plan's `VariantKey::cubic_samplers`. Metal samples
/// through such a sampler with its bicubic filter of that state. The variant's
/// compile states the same facts, so its plan for the same shape states the same key. A bound
/// word whose state the bicubic filter is not measured under, whatever the function samples
/// (`metal::bicubic::runtime_cubic_measured`: a mip filter, anisotropy, another reduction), is
/// `NotImplemented(SamplerBicubicFilter)` here, as the variant's compile would refuse it: the
/// draw is refused before any variant is compiled for it.
pub(crate) fn cubic_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
) -> Result<std::collections::BTreeMap<SlotRef, u32>, BindError> {
use crate::metal::sampler::SamplerWord;
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::CubicSampler { slot } => Some(slot),
_ => None,
})
.filter_map(|slot| {
let bound = shape
.stages
.get(&slot.stage)
.and_then(|s| s.samplers.get(&slot.index))?;
let word = bound.word.0 & SamplerWord::CUBIC_STATE;
bound.shape.cubic.then(
|| match crate::metal::bicubic::runtime_cubic_measured(word) {
true => Ok((slot, word)),
false => Err(BindError::Unsupported(Unsupported::not_implemented(
Feature::SamplerBicubicFilter,
))),
},
)
})
.collect()
}
/// The runtime sampler slots whose samples Metal's anisotropic filter, emulated, reaches
/// (`RuntimeFact::AnisotropicSampler`) at which `shape` binds a sampler whose word states
/// anisotropy (`SamplerWord::ANISOTROPIC`, `maxAnisotropy` above 1): the plan's
/// `VariantKey::anisotropic_samplers`. A function compiled without a slot named there takes the
/// plain sample at it, which is Metal's only where the bound word states no anisotropy, so the
/// variant names every such slot the word of whose bound sampler states it. The variant's compile
/// states the same facts, so its plan for the same shape states the same key.
pub(crate) fn anisotropic_variant(
dependencies: &[RuntimeDependency],
shape: &BindShape,
) -> std::collections::BTreeSet<SlotRef> {
use crate::metal::sampler::SamplerWord;
dependencies
.iter()
.filter_map(|d| match d.fact {
RuntimeFact::AnisotropicSampler { slot } => Some(slot),
_ => None,
})
.filter(|slot| {
shape
.stages
.get(&slot.stage)
.and_then(|s| s.samplers.get(&slot.index))
.is_some_and(|bound| bound.word.0 & SamplerWord::ANISOTROPIC != 0)
})
.collect()
}
/// The texture `shape` binds at `slot`.
fn bound_texture(shape: &BindShape, slot: SlotRef) -> Option<&TextureShape> {
shape
.stages
.get(&slot.stage)
.and_then(|s| s.textures.get(&slot.index))
}
/// Check every slot whose function observes the residency of its accesses
/// (`RuntimeFact::SparseTexture`). A texture that is not sparse is resident everywhere, so its word
/// is answered on every device. A sparse one needs the module's tile-map arm (`tile_map`, on every
/// profile where the slot has one) or its sparse arm (`sparse_arm`, compiled only where the profile
/// enables `shaderResourceResidency` and the slot has no tile map). A slot the function writes
/// drops its writes to a sparse texture under the same specialization, as Metal does
/// (`RuntimeFact::SparseTextureWrites`). A sparse texture is refused, `Unsupported{SparseTexture {
/// slot }}`:
/// - `NotRepresentable` at a slot the function updates by a texture atomic, whose answer on Metal
/// is not deterministic;
/// - at a slot of observed residency without either arm, naming `shaderResourceResidency` where
/// the device lacks it (an access the tile map does not answer, which the device's residency
/// would), and `NotImplemented` where the device has it but the slot's accesses have no sparse
/// form (a bicubic sample).
///
/// This is the shader's side only: the sparse arm reports the residency of the Vulkan image
/// bound and the tile-map arm that of the tile map bound, and that they mirror Metal's tile
/// mappings is the consumer's contract (`docs/API.md`; the profile does not describe sparse
/// binding).
pub(crate) fn check_sparse_textures(
dependencies: &[RuntimeDependency],
profile: &DeviceProfile,
shape: &BindShape,
) -> Result<(), BindError> {
for d in dependencies {
if let RuntimeFact::SparseTextureWrites { slot, atomic: true } = d.fact {
if sparse_texture(shape, slot) != 0 {
let feature = Feature::SparseTexture { slot };
return Err(BindError::Unsupported(Unsupported::not_representable(
feature,
)));
}
}
}
for d in dependencies {
let RuntimeFact::SparseTexture {
slot,
sparse_arm,
tile_map,
} = d.fact
else {
continue;
};
if sparse_arm || tile_map || sparse_texture(shape, slot) == 0 {
continue;
}
let residency = profile
.fields()
.enabled
.features
.contains(&VkFeature::ShaderResourceResidency);
let feature = Feature::SparseTexture { slot };
return Err(BindError::Unsupported(if residency {
Unsupported::not_implemented(feature)
} else {
Unsupported::needs(
feature,
Capability::Feature(VkFeature::ShaderResourceResidency),
)
}));
}
Ok(())
}
/// Whether every range of an allocation of length class `class` fits `max_range`: its padded
/// length is below `2^class` (`BindShape` length class).
pub(crate) fn class_fits(class: u8, max_range: u64) -> bool {
(1u128 << class.min(127)) - 1 <= u128::from(max_range)
}
/// The slots a `BufferRangeLimit` variant must move to device addresses for this shape: every slot
/// whose fact the profile honors by `Variant` and whose bound buffer's length class does not prove
/// that its range fits the view's limit. A slot already in device-address form (the variant's own
/// pipeline) is listed as well, so planning the variant's pipeline with the same shape gives the
/// same key (a fixed point). Profile F honors the fact at instantiation (`DescriptorRangeExceeded`,
/// exact) and needs no variant.
pub(crate) fn psb_variant(
dependencies: &[RuntimeDependency],
buffers: &[PlannedBuffer],
profile: &DeviceProfile,
) -> std::collections::BTreeSet<SlotRef> {
let mut out = std::collections::BTreeSet::new();
for d in dependencies {
let RuntimeFact::BufferRangeLimit { slot } = d.fact else {
continue;
};
let large = buffers
.iter()
.any(|b| b.slot == slot && range_variant(slot, b.bound, profile));
if large {
out.insert(slot);
}
}
out
}
/// Whether a slot with the `BufferRangeLimit` fact bound as `bound` joins the variant's
/// device-address slots: the profile honors the fact by `Variant` and the bound buffer's length
/// class does not prove that its range fits `maxStorageBufferRange`.
pub(crate) fn range_variant(slot: SlotRef, bound: BoundKind, profile: &DeviceProfile) -> bool {
let storage = u64::from(profile.fields().limits.max_storage_buffer_range);
mechanism(&RuntimeFact::BufferRangeLimit { slot }, profile) == Mechanism::Variant
&& matches!(bound, BoundKind::Buffer { length_class, .. } if !class_fits(length_class, storage))
}
/// The `uses` entry of a bound buffer slot: its proven access, `Storage`, `stages`, and the window
/// as a range when it starts at or after the bind offset.
pub(crate) fn buffer_use(b: &PlannedBuffer, stages: vk::PipelineStageFlags2) -> ResourceUse {
ResourceUse {
resource: UseTarget::Slot(b.slot),
access: b.access,
class: AccessClass::Storage,
stages,
range: match b.window {
Window::Bounded { start, len } if start >= 0 => Some(ByteRange {
offset: start as u64,
len,
}),
_ => None,
},
}
}
/// The `uses` of the used resources a pipeline can reach (the handback): buffers and heaps when a
/// function reads the resident root table (`pointer`), textures and heaps when one resolves handles
/// (`handle`). The access is the guest's declared `MTLResourceUsage` (`Read` and `Sample` read,
/// `Write` writes; no usage is `READ_WRITE`), since nothing proves a narrower one, but in the
/// stages whose function writes no memory: there a resource the usage lets the function write is
/// read, in a use of its own, as such a function stores to no buffer or texture and updates none
/// atomically (`StageInterface::writes_memory`). `writers` holds the pipeline stages whose function
/// may write memory. `stages` maps a used resource's render stages to the pipeline stages that
/// reach it (a compute plan maps every resource to `COMPUTE_SHADER`), and a resource reaching none
/// is not listed.
pub(crate) fn used_uses(
used: &BTreeMap<u32, UsedShape>,
pointer: bool,
handle: bool,
stages: impl Fn(metal::RenderStages) -> vk::PipelineStageFlags2,
writers: vk::PipelineStageFlags2,
) -> Vec<ResourceUse> {
let mut out = Vec::new();
for (&token, u) in used {
let reachable = match u.class {
UsedClass::Buffer => pointer,
UsedClass::Texture(_) => handle,
UsedClass::Heap => pointer || handle,
};
let stages = stages(u.stages);
if !reachable || stages.is_empty() {
continue;
}
let read = u
.usage
.intersects(metal::ResourceUsage::READ | metal::ResourceUsage::SAMPLE);
let write = u.usage.contains(metal::ResourceUsage::WRITE);
let access = match (read, write) {
(false, false) => AccessSet::READ_WRITE,
(read, write) => AccessSet { read, write },
};
let class = match u.class {
UsedClass::Texture(_) if write => AccessClass::StorageImage,
UsedClass::Texture(_) => AccessClass::Sampled,
UsedClass::Buffer | UsedClass::Heap => AccessClass::Storage,
};
let (writing, reading) = match access.write {
true => (
stages.intersection(writers),
vk::PipelineStageFlags2::from_raw(stages.as_raw() & !writers.as_raw()),
),
false => (stages, vk::PipelineStageFlags2::empty()),
};
for (stages, access) in [(writing, access), (reading, AccessSet::READ)] {
if !stages.is_empty() {
out.push(ResourceUse {
resource: UseTarget::Used(token),
access,
class,
stages,
range: None,
});
}
}
}
out
}
#[cfg(test)]
mod tests;
@@ -1,872 +0,0 @@
//! Length classes, the `BufferRangeLimit` variant, and the uses of used resources.
use super::*;
use crate::bind::state::{
length_class, BindState, BoundBuffer, BufferRanges, ResourceClass, StageShape, StageTable,
UsedResource,
};
use crate::device::profile::BufferAccess;
use crate::pipeline::facts::Mechanism;
use crate::pipeline::interface::BufferKind;
use crate::pipeline::sym::Stage;
use crate::spirv::testing::committed_profiles;
fn slot(index: u32) -> SlotRef {
SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index,
}
}
/// The class bounds the padded length from above and is the smallest such power of two.
#[test]
fn a_length_class_bounds_the_padded_length() {
for length in [
0u64,
1,
15,
16,
17,
255,
256,
1 << 27,
(1 << 27) + 1,
u64::MAX,
] {
let c = length_class(length);
let padded = u128::from(length).next_multiple_of(16);
assert!(padded < 1u128 << c, "{length}: class {c}");
if padded > 0 {
assert!(
padded >= 1u128 << (c - 1),
"{length}: class {c} is not the smallest"
);
}
}
assert_eq!(length_class(0), 0);
// A class proves a range fits exactly when every padded length below `2^class` does.
let limit = (1u64 << 27) - 1;
assert!(class_fits(length_class((1 << 27) - 16), limit));
assert!(!class_fits(length_class(1 << 27), limit));
assert!(class_fits(
length_class(u64::from(u32::MAX) - 15),
u64::from(u32::MAX)
));
}
fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer {
PlannedBuffer {
slot: slot(index),
window: Window::Whole,
form,
access: AccessSet::READ,
binding: None,
alignment: 16,
max_range: 0,
bound,
}
}
/// On Profile A a large bound buffer under a `BufferRangeLimit` fact needs the variant, in either
/// form (a fixed point); a small one, an unbound slot, or a slot without the fact does not.
/// Profile F (below the runtime's floor, [`PROFILE_F`](crate::pipeline::testing::PROFILE_F))
/// honors the fact at instantiation and never asks for a variant.
#[test]
fn a_large_buffer_needs_the_device_address_variant_on_profile_a_only() {
let deps = [0, 1, 2, 3].map(|n| RuntimeDependency {
fact: RuntimeFact::BufferRangeLimit { slot: slot(n) },
mechanism: Mechanism::Variant,
});
let storage = BufferForm::Descriptor;
let mut seen = [false; 2];
let mut profiles = committed_profiles().expect("profiles");
let f = crate::pipeline::testing::device_f(crate::device::DevicePolicy::RESIDENT_TABLES)
.expect("Profile F");
profiles.push((
crate::pipeline::testing::PROFILE_F.to_string(),
f.profile().clone(),
));
for (stem, p) in profiles {
let max = u64::from(p.fields().limits.max_storage_buffer_range);
let big = length_class(max.saturating_add(1));
let small = length_class(max / 4);
let buffers = [
planned(
0,
BoundKind::Buffer {
device_address: true,
length_class: big,
},
storage,
),
planned(
1,
BoundKind::Buffer {
device_address: true,
length_class: big,
},
BufferForm::Psb,
),
planned(
2,
BoundKind::Buffer {
device_address: true,
length_class: small,
},
storage,
),
planned(3, BoundKind::Unbound, storage),
planned(
4,
BoundKind::Buffer {
device_address: true,
length_class: big,
},
storage,
),
];
let got = psb_variant(&deps, &buffers, &p);
match p.fields().buffer_access {
BufferAccess::Addressed => {
seen[0] = true;
assert_eq!(got, [slot(0), slot(1)].into(), "{stem}");
}
BufferAccess::Floor => {
seen[1] = true;
assert!(got.is_empty(), "{stem}");
}
}
}
assert_eq!(seen, [true, true], "both profile kinds are checked");
}
/// Used resources reach a plan's `uses` exactly when a function can reach them, with the guest's
/// declared usage, and the shape unions a token listed twice.
#[test]
fn used_resources_are_listed_when_the_pipeline_reaches_them() {
let mut state = BindState::default();
let mut buffer = UsedResource::new(ResourceClass::Buffer, 1);
buffer.usage = metal::ResourceUsage::READ;
let mut again = buffer;
again.usage = metal::ResourceUsage::WRITE;
again.stages = metal::RenderStages::FRAGMENT;
let mut heap = UsedResource::new(ResourceClass::Heap, 2);
heap.stages = metal::RenderStages::VERTEX;
let mut texture = UsedResource::new(
ResourceClass::Texture(crate::bind::state::TextureFacts::new(
metal::TextureType::Type2D,
metal::PixelFormat::RGBA8Unorm,
)),
3,
);
texture.usage = metal::ResourceUsage::SAMPLE;
state.used_resources = vec![buffer, heap, texture, again];
let shape = state.shape();
assert_eq!(
shape.used[&1].usage,
metal::ResourceUsage::READ | metal::ResourceUsage::WRITE
);
let compute = |_| vk::PipelineStageFlags2::COMPUTE_SHADER;
// The kernel may write memory.
let all = vk::PipelineStageFlags2::COMPUTE_SHADER;
let tokens = |uses: &[ResourceUse]| -> Vec<(UseTarget, AccessSet, AccessClass)> {
uses.iter()
.map(|u| (u.resource, u.access, u.class))
.collect()
};
assert!(used_uses(&shape.used, false, false, compute, all).is_empty());
assert_eq!(
tokens(&used_uses(&shape.used, true, false, compute, all)),
vec![
(
UseTarget::Used(1),
AccessSet::READ_WRITE,
AccessClass::Storage
),
(
UseTarget::Used(2),
AccessSet::READ_WRITE,
AccessClass::Storage
),
]
);
assert_eq!(
tokens(&used_uses(&shape.used, false, true, compute, all)),
vec![
(
UseTarget::Used(2),
AccessSet::READ_WRITE,
AccessClass::Storage
),
(UseTarget::Used(3), AccessSet::READ, AccessClass::Sampled),
]
);
// A render plan lists a resource only in the stages it is used in.
let vertex = vk::PipelineStageFlags2::VERTEX_SHADER;
let vertex_only = |s: metal::RenderStages| {
if s.contains(metal::RenderStages::VERTEX) {
vk::PipelineStageFlags2::VERTEX_SHADER
} else {
vk::PipelineStageFlags2::empty()
}
};
assert_eq!(
tokens(&used_uses(&shape.used, true, true, vertex_only, vertex)),
vec![(
UseTarget::Used(2),
AccessSet::READ_WRITE,
AccessClass::Storage
)]
);
}
/// A used resource the usage lets a function write is written only in the stages whose function
/// may write memory, and read in the others: a draw whose vertex function stores nothing reads a
/// buffer an earlier compute encoder made resident for writing, as its fragment function, which
/// stores, writes it. One only read keeps a single use; one no stage writes is read everywhere.
#[test]
fn used_resources_are_written_only_by_stages_that_write_memory() {
let mut state = BindState::default();
let mut written = UsedResource::new(ResourceClass::Buffer, 1);
written.usage = metal::ResourceUsage::WRITE;
written.stages = metal::RenderStages::VERTEX.union(metal::RenderStages::FRAGMENT);
let mut read = UsedResource::new(ResourceClass::Buffer, 2);
read.usage = metal::ResourceUsage::READ;
read.stages = written.stages;
state.used_resources = vec![written, read];
let shape = state.shape();
let vertex = vk::PipelineStageFlags2::VERTEX_SHADER;
let fragment = vk::PipelineStageFlags2::FRAGMENT_SHADER;
let reach = |s: metal::RenderStages| {
let mut f = vk::PipelineStageFlags2::empty();
if s.contains(metal::RenderStages::VERTEX) {
f |= vertex;
}
if s.contains(metal::RenderStages::FRAGMENT) {
f |= fragment;
}
f
};
let listed = |writers| -> Vec<(UseTarget, AccessSet, vk::PipelineStageFlags2)> {
used_uses(&shape.used, true, false, reach, writers)
.iter()
.map(|u| (u.resource, u.access, u.stages))
.collect()
};
let write = AccessSet {
read: false,
write: true,
};
assert_eq!(
listed(fragment),
vec![
(UseTarget::Used(1), write, fragment),
(UseTarget::Used(1), AccessSet::READ, vertex),
(UseTarget::Used(2), AccessSet::READ, vertex | fragment),
]
);
assert_eq!(
listed(vk::PipelineStageFlags2::empty()),
vec![
(UseTarget::Used(1), AccessSet::READ, vertex | fragment),
(UseTarget::Used(2), AccessSet::READ, vertex | fragment),
]
);
assert_eq!(
listed(vertex | fragment),
vec![
(UseTarget::Used(1), write, vertex | fragment),
(UseTarget::Used(2), AccessSet::READ, vertex | fragment),
]
);
}
/// A buffer range limit tells a buffer's length class apart as far as a plan reads it
/// (`BufferRanges::length_class`), under a 4 GiB limit (an RX 7900 XTX's), limits of 128 MiB,
/// 64 KiB and 16 KiB, and none (the default, every class its own): the class a buffer's shape
/// states of each length answers `class_fits` against the limit as the exact class does (all a
/// plan reads of it: `range_variant`), still bounds the padded length from above, and is the exact
/// one under none; and instantiation's kind check (`instantiate::bound_buffer`) takes a binding of
/// each length for the kind a plan of another length stored exactly where the two classes are
/// one, which is only where their exact classes answer the limit alike.
#[test]
fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() {
let mut lengths = vec![0u64, 1, 15, 16, 17, u64::MAX];
for bit in 4..64 {
lengths.extend([(1u64 << bit) - 1, 1 << bit, (1 << bit) + 1]);
}
let limits = [
BufferRanges::default(),
BufferRanges { storage: u32::MAX },
BufferRanges { storage: 1 << 27 },
BufferRanges { storage: 1 << 16 },
BufferRanges { storage: 1 << 14 },
];
for ranges in limits {
let fits = |class| class_fits(class, u64::from(ranges.storage));
let states: Vec<BindState> = (lengths.iter())
.map(|&length| {
let mut table = StageTable {
buffer_ranges: ranges,
..StageTable::default()
};
let bound = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length,
offset: 0,
device_address: Some(0x2_0000),
attribute_stride: None,
};
table.buffers.insert(0, bound);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
state
})
.collect();
for (&a, state) in lengths.iter().zip(&states) {
let (exact, class) = (length_class(a), ranges.length_class(a));
let what = format!("{ranges:?}, {a} bytes");
assert_eq!(
fits(class),
fits(exact),
"{what}: class {class}, exact {exact}"
);
let padded = u128::from(a).next_multiple_of(16);
assert!(padded < 1u128 << class, "{what}: class {class}");
if ranges == BufferRanges::default() {
assert_eq!(class, exact, "{what}");
}
let shape = state.shape();
let expected = BoundKind::of(shape.stages[&Stage::Kernel].buffers.get(&0));
for (&b, other) in lengths.iter().zip(&states) {
let took = crate::bind::instantiate::bound_buffer(other, slot(0), expected).is_ok();
assert_eq!(
took,
ranges.length_class(b) == class,
"{what}: a binding of {b} bytes for its kind"
);
if took {
assert_eq!(
fits(length_class(b)),
fits(exact),
"{what}: {b} bytes alike"
);
}
}
}
}
// Under a 4 GiB limit every length up to 4 GiB is one class, past it each its own.
let ranges = limits[1];
assert_eq!(ranges.length_class(1), ranges.length_class((1 << 32) - 16));
assert_ne!(ranges.length_class(1), ranges.length_class(1 << 32));
assert_ne!(ranges.length_class(1 << 32), ranges.length_class(1 << 33));
}
/// A buffer bound by shape and state agree on the bound kind, including the length class.
#[test]
fn the_bound_kind_carries_the_length_class() {
let b = BoundBuffer::Buffer {
length: 100,
offset: 4,
gpu_address: 0,
device_address: Some(8),
attribute_stride: None,
};
assert_eq!(
BoundKind::of(Some(&b.shape(BufferRanges::default()))),
BoundKind::Buffer {
device_address: true,
length_class: 7
}
);
assert_eq!(BoundKind::of(None), BoundKind::Unbound);
}
#[test]
fn slots_beyond_the_metal_tables_are_refused() {
let mut shape = BindShape::default();
let mut s = StageShape::default();
s.buffers.insert(
30,
BufferShape::Bytes {
attribute_stride: None,
},
);
shape.stages.insert(Stage::Kernel, s.clone());
assert_eq!(check_slots(&shape), Ok(()));
s.buffers.insert(
31,
BufferShape::Bytes {
attribute_stride: None,
},
);
shape.stages.insert(Stage::Kernel, s);
assert_eq!(
check_slots(&shape),
Err(BindError::SlotOutOfRange {
slot: SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index: 31
}
})
);
let mut s = StageShape::default();
s.threadgroup_lengths.insert(31, 16);
shape.stages.insert(Stage::Kernel, s);
assert!(check_slots(&shape).is_err());
}
/// On every committed profile a storage view's descriptor base is aligned to
/// `max(minStorageBufferOffsetAlignment, 16)`, so whatever the bind offset and window, every byte
/// of the range sits at a descriptor offset congruent to its allocation offset modulo 16: a 16-byte
/// leaf whose Metal address is a multiple of 16 is one `uvec4` element of the view.
#[test]
fn descriptor_bases_are_sixteen_aligned_on_every_profile() {
let bindings: BTreeMap<_, _> = [(BindingSource::Buffer(slot(0)), (0, 0))].into();
let shape = BufferShape::Buffer {
device_address: false,
length_class: length_class(4096),
attribute_stride: None,
offset_alignment: 4,
};
for (stem, p) in committed_profiles().expect("profiles") {
let limits = &p.fields().limits;
let min = limits.min_storage_buffer_offset_alignment;
let b = BufferSlot {
access: AccessSet::READ,
window: Window::Whole,
form: BufferForm::Descriptor,
kind: BufferKind::Buffer,
};
let pb = plan_buffer((slot(0), &b, Some(&shape)), false, limits, &bindings)
.unwrap_or_else(|e| panic!("{stem}: {e:?}"));
assert_eq!(pb.alignment, min.max(16), "{stem}");
for bind_offset in (0..64).step_by(4) {
for window in [
Window::Whole,
Window::Bounded { start: 0, len: 64 },
Window::Bounded { start: 4, len: 28 },
Window::Bounded { start: 52, len: 16 },
Window::Bounded { start: -8, len: 40 },
] {
let (range, residual) = crate::bind::instantiate::descriptor_range(
bind_offset,
4096,
window,
pb.alignment,
u64::MAX,
)
.unwrap_or_else(|e| panic!("{stem}: {e:?}"));
assert_eq!(range.offset % 16, 0, "{stem} {bind_offset}");
// Byte `m` from the bind offset is byte `residual + m` of the range.
assert_eq!(
u64::from(residual) % 16,
bind_offset % 16,
"{stem} {bind_offset} {window:?}"
);
}
}
}
}
/// A slot whose function observes residency (`RuntimeFact::SparseTexture`) binds a texture that is
/// not sparse (or nothing) on every profile, and a sparse one where the module has the sparse arm
/// or the tile-map arm; without either a sparse texture is refused, naming
/// `shaderResourceResidency` where the profile lacks it and `NotImplemented` where it has it (an
/// access without a sparse form). A slot the function writes binds a sparse texture (its writes
/// dropped under the specialization), and one it updates atomically refuses it as
/// `NotRepresentable` on every profile.
#[test]
fn a_sparse_texture_needs_the_slots_sparse_arm() {
use crate::bind::state::TextureFacts;
let at = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 2,
};
let shape = |sparse: Option<bool>| {
let mut s = BindShape::default();
let mut stage = StageShape::default();
if let Some(sparse) = sparse {
let mut facts =
TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm);
facts.sparse = sparse;
stage.textures.insert(2, facts.shape());
}
s.stages.insert(Stage::Kernel, stage);
s
};
let arms = |sparse_arm: bool, tile_map: bool| {
vec![RuntimeDependency {
fact: RuntimeFact::SparseTexture {
slot: at,
sparse_arm,
tile_map,
},
mechanism: if sparse_arm || tile_map {
Mechanism::Specialization
} else {
Mechanism::PlanTimeCheck
},
}]
};
let deps = |sparse_arm: bool| arms(sparse_arm, false);
let writes = |atomic: bool| {
vec![RuntimeDependency {
fact: RuntimeFact::SparseTextureWrites { slot: at, atomic },
mechanism: if atomic {
Mechanism::PlanTimeCheck
} else {
Mechanism::Specialization
},
}]
};
assert_eq!(sparse_texture(&shape(Some(true)), at), 1);
assert_eq!(sparse_texture(&shape(Some(false)), at), 0);
assert_eq!(sparse_texture(&shape(None), at), 0);
let mut seen = [0; 2];
for (stem, p) in committed_profiles().expect("profiles") {
for bound in [None, Some(false)] {
for arm in [false, true] {
check_sparse_textures(&deps(arm), &p, &shape(bound))
.unwrap_or_else(|e| panic!("{stem}: {bound:?} {arm}: {e}"));
}
}
check_sparse_textures(&deps(true), &p, &shape(Some(true)))
.unwrap_or_else(|e| panic!("{stem}: sparse arm: {e}"));
// A tile-map arm answers a sparse texture too.
check_sparse_textures(&arms(false, true), &p, &shape(Some(true)))
.unwrap_or_else(|e| panic!("{stem}: tile-map arm: {e}"));
let residency = p
.fields()
.enabled
.features
.contains(&VkFeature::ShaderResourceResidency);
let feature = Feature::SparseTexture { slot: at };
let want = if residency {
Unsupported::not_implemented(feature)
} else {
Unsupported::needs(
feature,
Capability::Feature(VkFeature::ShaderResourceResidency),
)
};
match check_sparse_textures(&deps(false), &p, &shape(Some(true))) {
Err(BindError::Unsupported(u)) => assert_eq!(u, want, "{stem}"),
other => panic!("{stem}: {other:?}"),
}
// A written slot binds a sparse texture, its writes dropped; one updated atomically refuses
// it, since Metal's answer there is not deterministic.
for bound in [None, Some(false), Some(true)] {
check_sparse_textures(&writes(false), &p, &shape(bound))
.unwrap_or_else(|e| panic!("{stem}: written, {bound:?}: {e}"));
}
for bound in [None, Some(false)] {
check_sparse_textures(&writes(true), &p, &shape(bound))
.unwrap_or_else(|e| panic!("{stem}: atomic, {bound:?}: {e}"));
}
let mut atomic = deps(false);
atomic.extend(writes(true));
for deps in [writes(true), atomic] {
match check_sparse_textures(&deps, &p, &shape(Some(true))) {
Err(BindError::Unsupported(u)) => {
let feature = Feature::SparseTexture { slot: at };
assert_eq!(u, Unsupported::not_representable(feature), "{stem}")
}
other => panic!("{stem}: atomic: {other:?}"),
}
}
seen[usize::from(residency)] += 1;
}
assert!(seen[0] > 0 && seen[1] > 0, "{seen:?}");
}
/// A constexpr-sampled slot enters `VariantKey::address_maps` only where the bound texture's
/// address-mode map changes a mode the slot's constexpr samplers state, with the map restricted
/// to those modes: a draw of an ordinary texture, or of a mapped one whose map keeps those modes,
/// keeps its key, and textures whose maps agree on them share a variant. A slot no constexpr
/// sampler samples takes no map, whatever its texture's.
#[test]
fn only_a_map_that_moves_a_constexpr_mode_enters_the_variant() {
use crate::bind::state::TextureFacts;
use crate::metal::sampler::AddressModeMap;
use crate::metal::SamplerAddressMode as M;
let texture = |index| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
};
let identity = AddressModeMap::IDENTITY;
let edges = identity.with(M::Repeat, M::ClampToEdge);
// Every mode to the edge, as a two-plane 4:2:0 texture reads.
let all_edges = [
M::MirrorClampToEdge,
M::Repeat,
M::MirrorRepeat,
M::ClampToZero,
M::ClampToBorderColor,
]
.into_iter()
.fold(identity, |map, mode| map.with(mode, M::ClampToEdge));
let shape = |maps: [AddressModeMap; 2]| {
let mut s = BindShape::default();
let mut stage = StageShape::default();
for (index, map) in (0..).zip(maps) {
let mut facts =
TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm);
facts.address_modes = map;
stage.textures.insert(index, facts.shape());
}
s.stages.insert(Stage::Kernel, stage);
s
};
// Slot 0 is constexpr-sampled, by a repeat sampler and by one of `other` modes; slot 1 is
// not.
let deps = |other: Option<M>| {
let sampled = |mode| RuntimeDependency {
fact: RuntimeFact::ConstexprSampled {
slot: texture(0),
modes: [mode; 3],
},
mechanism: Mechanism::Variant,
};
let mut deps = vec![sampled(M::Repeat)];
deps.extend(other.map(sampled));
deps
};
let repeat = deps(None);
assert!(address_map_variant(&repeat, &shape([identity, identity])).is_empty());
assert!(address_map_variant(&repeat, &shape([identity, edges])).is_empty());
assert!(address_map_variant(&[], &shape([edges, edges])).is_empty());
assert_eq!(
address_map_variant(&repeat, &shape([edges, identity])),
BTreeMap::from([(texture(0), edges)])
);
// The map restricted to the stated modes: one that sends every mode to the edge states the
// same variant as one that sends repeat there alone.
assert_eq!(
address_map_variant(&repeat, &shape([all_edges, identity])),
BTreeMap::from([(texture(0), edges)])
);
// A map that keeps every stated mode adds nothing: a clamp-to-edge sampler of a texture whose
// every mode reads the edge samples it as before.
let edge = vec![RuntimeDependency {
fact: RuntimeFact::ConstexprSampled {
slot: texture(0),
modes: [M::ClampToEdge; 3],
},
mechanism: Mechanism::Variant,
}];
assert!(address_map_variant(&edge, &shape([all_edges, identity])).is_empty());
// Two samplers of the slot: the map on the modes of both.
assert_eq!(
address_map_variant(&deps(Some(M::ClampToZero)), &shape([all_edges, identity])),
BTreeMap::from([(texture(0), edges.with(M::ClampToZero, M::ClampToEdge))])
);
// A slot with no texture bound takes no map.
assert!(address_map_variant(&repeat, &BindShape::default()).is_empty());
}
/// A slot that states the in-place form enters `VariantKey::ycbcr_in_place` only where the bound
/// texture's planes are read in place and each runtime sampler the slot samples through states a
/// filter the form reads: one filter, no anisotropy, cubic filter, comparison or other reduction.
#[test]
fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() {
use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts};
use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
use crate::bind::YCbCrInPlace;
use metal::{CompareFunction, SamplerMinMagFilter as F, SamplerReductionMode};
let texture = |index| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
};
let pf = metal::PixelFormat::YCBCR84202P;
let codes = metal::format::ycbcr_format(pf)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Video, YCbCrMatrix::Bt709),
codes,
);
// Slot 0 and 1 bind textures whose planes are read in place, slot 2 one whose are not.
let shape = |sampler: SamplerDescriptor| {
let mut stage = StageShape::default();
for (index, in_place) in [(0, true), (1, true), (2, false)] {
let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf);
if in_place {
facts.ycbcr_in_place = YCbCrInPlace::of(&planes);
}
stage.textures.insert(index, facts.shape());
}
stage.samplers.insert(3, BoundSampler::new(sampler).shape());
let mut s = BindShape::default();
s.stages.insert(Stage::Kernel, stage);
s
};
let fact = |slot, samplers| RuntimeDependency {
fact: RuntimeFact::YCbCrInPlace {
slot,
samplers,
device: true,
},
mechanism: Mechanism::Variant,
};
// Slot 0 samples through constexpr samplers alone, slot 1 also through `[[sampler(3)]]`.
let deps = [
fact(texture(0), 0),
fact(texture(1), 1 << 3),
fact(texture(2), 0),
];
let linear = SamplerDescriptor {
min_filter: F::Linear,
mag_filter: F::Linear,
..SamplerDescriptor::new()
};
let both = std::collections::BTreeSet::from([texture(0), texture(1)]);
let s = shape(linear);
let in_place = ycbcr_in_place_variant(&deps, &s);
assert_eq!(in_place, both);
assert_eq!(
ycbcr_in_place_variant(&deps, &shape(SamplerDescriptor::new())),
both
);
// A sampler the form does not read keeps slot 1 from it, not slot 0.
let unread = [
SamplerDescriptor {
min_filter: F::Linear,
..SamplerDescriptor::new()
},
SamplerDescriptor {
max_anisotropy: 4,
..linear
},
SamplerDescriptor {
min_filter: F::Cubic,
mag_filter: F::Cubic,
..SamplerDescriptor::new()
},
SamplerDescriptor {
compare_function: CompareFunction::Less,
..linear
},
SamplerDescriptor {
reduction_mode: SamplerReductionMode::Minimum,
..linear
},
];
for sampler in unread {
assert_eq!(
ycbcr_in_place_variant(&deps, &shape(sampler)),
std::collections::BTreeSet::from([texture(0)]),
"{sampler:?}"
);
}
// A stage that states no form takes none, whatever its textures.
assert!(ycbcr_in_place_variant(&[], &s).is_empty());
// No texture's planes are held as an image the device samples: no slot samples one.
assert!(ycbcr_planes_sampled_variant(&deps, &s, &in_place).is_empty());
}
/// An in-place slot enters `VariantKey::ycbcr_planes_sampled` only where the bound texture's
/// planes are held as an image the device's conversion samples, the function's every sample is one
/// that sampler takes (the fact's `device`), and each runtime sampler it samples through addresses
/// no border on the plane axes.
#[test]
fn the_planes_image_variant_takes_a_slot_the_device_s_sampler_reads() {
use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts};
use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
use crate::bind::YCbCrInPlace;
use metal::SamplerAddressMode as M;
let texture = |index| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
};
let pf = metal::PixelFormat::YCBCR84202P;
let codes = metal::format::ycbcr_format(pf)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Full, YCbCrMatrix::Bt601),
codes,
);
let words = YCbCrInPlace::of(&planes).expect("in place");
// Slots 0 to 2 bind textures whose planes are held as an image, slot 3 one whose are not.
let shape = |sampler: SamplerDescriptor| {
let mut stage = StageShape::default();
for index in 0..4 {
let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf);
facts.ycbcr_in_place = Some(match index {
3 => words,
_ => words.with_planes_image(),
});
stage.textures.insert(index, facts.shape());
}
stage.samplers.insert(3, BoundSampler::new(sampler).shape());
let mut s = BindShape::default();
s.stages.insert(Stage::Kernel, stage);
s
};
let fact = |slot, samplers, device| RuntimeDependency {
fact: RuntimeFact::YCbCrInPlace {
slot,
samplers,
device,
},
mechanism: Mechanism::Variant,
};
// Slot 0 samples through constexpr samplers the device takes, slot 1 also through
// `[[sampler(3)]]`, slot 2 through a constexpr sampler it does not take.
let deps = [
fact(texture(0), 0, true),
fact(texture(1), 1 << 3, true),
fact(texture(2), 0, false),
fact(texture(3), 0, true),
];
let edge = SamplerDescriptor::new();
let s = shape(edge);
let in_place = ycbcr_in_place_variant(&deps, &s);
assert_eq!(in_place.len(), 4);
let sampler = words.sampler();
assert_eq!(
ycbcr_planes_sampled_variant(&deps, &s, &in_place),
BTreeMap::from([(texture(0), sampler), (texture(1), sampler)])
);
// A runtime sampler that addresses a border on a plane axis keeps slot 1 from it; one on `r`
// does not.
for (mode, axis, taken) in [
(M::ClampToZero, 0, false),
(M::ClampToBorderColor, 1, false),
(M::Repeat, 0, true),
(M::MirrorClampToEdge, 1, true),
(M::ClampToBorderColor, 2, true),
] {
let mut sampler_state = edge;
match axis {
0 => sampler_state.s_address_mode = mode,
1 => sampler_state.t_address_mode = mode,
_ => sampler_state.r_address_mode = mode,
}
let s = shape(sampler_state);
let in_place = ycbcr_in_place_variant(&deps, &s);
let got = ycbcr_planes_sampled_variant(&deps, &s, &in_place);
assert_eq!(
got.contains_key(&texture(1)),
taken,
"{mode:?} on axis {axis}"
);
assert!(got.contains_key(&texture(0)), "{mode:?} on axis {axis}");
}
// A slot outside the in-place variant takes no image.
let none = std::collections::BTreeSet::new();
assert!(ycbcr_planes_sampled_variant(&deps, &s, &none).is_empty());
}
+1 -3
View File
@@ -21,7 +21,7 @@
//! `float` arithmetic is the device's: it computes the shader's
//! answers bit for bit on a device that reads `float` denormals as Metal does, and with the
//! device's own denormals elsewhere (`PrecisionNote::DeviceDenormals`), as the SPIR-V interpreter
//! keeps them. The buffer is then bound like any other ([`BoundBuffer::Buffer`]).
//! keeps them. The buffer is then bound like any other.
//!
//! **Compiling a descriptor.** Metal leaves the compiled map to the device: a layer's quality
//! samples "may be rounded up ... depending on hardware support". [`RasterizationRateMap::new`]
@@ -59,8 +59,6 @@
//!
//! **Rendering a rate-mapped pass** (`MTLRenderPassDescriptor.rasterizationRateMap`) is the
//! consumer's.
//!
//! [`BoundBuffer::Buffer`]: crate::bind::BoundBuffer::Buffer
use std::fmt;
+2 -3
View File
@@ -1,6 +1,6 @@
//! What a merged draw's vertex and fragment variants read (`merged`): the header of a merged draw,
//! its commands' `VkDrawIndirectCommand`s ([`DRAW_ARGUMENT_BYTES`]) and index entries
//! ([`DRAW_INDEX_ENTRY_BYTES`]), and the SPIR-V helpers its reads are built from, reaching memory
//! its commands' `VkDrawIndirectCommand`s (`merged::DRAW_ARGUMENT_BYTES`) and index entries
//! (`merged::DRAW_INDEX_ENTRY_BYTES`), and the SPIR-V helpers its reads are built from, reaching memory
//! by device address (`bufferDeviceAddress`, `shaderInt64`).
use crate::memory::roots;
@@ -11,7 +11,6 @@ use crate::spirv::ir::{BinOp, ConvOp, MemAccess};
mod merged;
pub(crate) use merged::{merged_fragment_table, merged_vertex, MergedVertex};
pub use merged::{DRAW_ARGUMENT_BYTES, DRAW_INDEX_ENTRY_BYTES, MERGED_REST_FIRST};
// ---- The module ----
-174
View File
@@ -1,174 +0,0 @@
//! The resident set and root tables.
//!
//! The resident set of a draw or dispatch is every bound buffer with a device address and every
//! `Buffer`/`Heap` used resource with both addresses, coalesced (`resident_set`): sorted by
//! guest address, an allocation inside another dropped (the outermost wins: a heap over its
//! sub-buffers), a partially overlapping one trimmed of its overlapping head (host and guest
//! advancing together), and empty ones dropped, of any count (At most 2¹⁶ entries before, else
//! `ResidentSetTooLarge`). Indirect command buffers' records (from `RECORDS_ADDRESS_BASE`) are
//! kept whole however they overlap, one a start: a kernel finds an ID's records only where they
//! start (`indirect_commands::records_address`). Each stage that reads a root table gets its own (`stage_root_table`):
//! its `Psb` entries are that stage's slots; the resident set is shared.
use crate::bind::instantiate::{padded, RootTable};
use crate::bind::state::{BindState, BoundBuffer, ResourceClass};
use crate::indirect_commands::RECORDS_ADDRESS_BASE;
use std::cmp::Ordering;
/// One root-table entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) struct RootEntry {
/// The allocation's device address.
pub host: u64,
/// The allocation's Metal address.
pub guest: u64,
/// The allocation's size, padded to 16 bytes.
pub size: u64,
/// The Metal bind offset (parameter entries only; 0 in the resident set).
pub bind_offset: u64,
}
/// The resident set of `all` allocations: sorted by guest address; an allocation inside another one
/// is dropped (the outermost wins: a heap over its sub-buffers); a partially overlapping one loses
/// its overlapping head (its host and guest addresses advance together, which is exact when both
/// ranges view one mapping); empty allocations are dropped. Records of indirect command buffers
/// (from `RECORDS_ADDRESS_BASE`, where no Metal allocation lies) are kept whole, one for each
/// start (the largest): an ID's records may run past later IDs' starts, and a kernel searches
/// them only at their start, so each start must stay an entry's.
pub(crate) fn resident_set(all: Vec<RootEntry>) -> Vec<RootEntry> {
coalesced_of_sorted(&sorted(all))
}
/// `all` as a resident set takes its allocations: the empty ones dropped, the rest sorted by guest
/// address, the larger first at one address, else in their order (a stable sort).
pub(crate) fn sorted(mut all: Vec<RootEntry>) -> Vec<RootEntry> {
all.retain(|e| e.size > 0);
all.sort_by(order);
all
}
/// The order [`sorted`] takes allocations in.
fn order(a: &RootEntry, b: &RootEntry) -> Ordering {
a.guest.cmp(&b.guest).then(b.size.cmp(&a.size))
}
/// The resident set of `sorted`, allocations in [`sorted`]'s order.
pub(crate) fn coalesced_of_sorted(sorted: &[RootEntry]) -> Vec<RootEntry> {
let mut out: Vec<RootEntry> = Vec::with_capacity(sorted.len());
for &e in sorted {
coalesce(&mut out, e);
}
out
}
/// Add `e`, an allocation at or after every one `out` was made of in [`sorted`]'s order, to `out`,
/// the resident set of those: dropped where it lies inside the last entry, or a record's at the
/// last entry's start; trimmed of its head where it overlaps the last entry; else whole. Whether
/// it went in whole.
fn coalesce(out: &mut Vec<RootEntry>, mut e: RootEntry) -> bool {
let end = |e: &RootEntry| u128::from(e.guest) + u128::from(e.size);
e.bind_offset = 0;
let Some(last) = out.last() else {
out.push(e);
return true;
};
if e.guest >= RECORDS_ADDRESS_BASE {
if e.guest == last.guest {
return false;
}
out.push(e);
return true;
}
let last_end = end(last);
if end(&e) <= last_end {
return false;
}
if u128::from(e.guest) >= last_end {
out.push(e);
return true;
}
// `last_end - e.guest < e.size`, so the cut fits in `u64`.
let cut = (last_end - u128::from(e.guest)) as u64;
e.guest += cut;
e.host = e.host.wrapping_add(cut);
e.size -= cut;
out.push(e);
false
}
/// The coalesced resident set of `state`: every bound buffer with a device address (every stage)
/// and every `Buffer`/`Heap` used resource with both addresses, at their padded sizes.
pub(crate) fn resident_entries(state: &BindState) -> Vec<RootEntry> {
coalesced(resident_allocations(state))
}
/// The coalesced resident set a root table of `state` holds: [`resident_entries`], or, where the
/// consumer points its root tables at a set holding the used resources and the listed ranges
/// (`BindState::resident_apart`), the bound buffers' alone.
pub(crate) fn table_entries(state: &BindState) -> Vec<RootEntry> {
match state.resident_apart {
true => coalesced(bound_allocations(state)),
false => resident_entries(state),
}
}
/// The resident set of `allocations`, each `(host, guest, length)`, at their padded sizes.
fn coalesced(allocations: impl Iterator<Item = (u64, u64, u64)>) -> Vec<RootEntry> {
let all = allocations
.map(|(host, guest, length)| RootEntry {
host,
guest,
size: padded(length),
bind_offset: 0,
})
.collect();
resident_set(all)
}
/// Every allocation of `state`'s resident set before coalescing, as `(host, guest, length)` at
/// its own length (before the padding): the bound buffers, the used buffers and heaps, and the
/// ranges listed apart (`BindState::resident_ranges`).
fn resident_allocations(state: &BindState) -> impl Iterator<Item = (u64, u64, u64)> + '_ {
let used = state.used_resources.iter().filter_map(|u| {
match (u.class, u.gpu_address, u.device_address) {
(ResourceClass::Buffer | ResourceClass::Heap, Some(guest), Some(host)) => {
Some((host, guest, u.length))
}
_ => None,
}
});
let listed = state
.resident_ranges
.iter()
.map(|range| (range.host, range.guest, range.length));
bound_allocations(state).chain(used).chain(listed)
}
/// The bound buffers of `state` with a device address (every stage), as `(host, guest, length)`
/// at their own lengths.
fn bound_allocations(state: &BindState) -> impl Iterator<Item = (u64, u64, u64)> + '_ {
state.stages.values().flat_map(|stage_table| {
stage_table.buffers.values().filter_map(|b| match *b {
BoundBuffer::Buffer {
length,
gpu_address,
device_address: Some(host),
..
} => Some((host, gpu_address, length)),
_ => None,
})
})
}
/// The root table of one stage: its `Psb` entries (`(n, entry)` for `[[buffer(n)]]`) and the
/// coalesced `resident` set from root `first`.
pub(crate) fn stage_root_table(
statics: &[(u32, RootEntry)],
first: u32,
resident: &[RootEntry],
) -> RootTable {
RootTable::build(statics, u64::from(first), resident)
}
#[cfg(test)]
mod tests;
@@ -1,362 +0,0 @@
//! Resident-set coalescing properties over deterministic pseudo-random sets.
use super::*;
/// A small deterministic generator (xorshift64*), so the properties need no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
/// Allocations that view one mapping (`host = guest + delta`), as heap sub-allocations do, placed
/// so that nesting, partial overlap, adjacency, and gaps all occur.
fn one_mapping(rng: &mut Rng, delta: u64) -> Vec<RootEntry> {
let n = 1 + rng.below(24) as usize;
(0..n)
.map(|_| {
let guest = 0x1_0000 + 16 * rng.below(256);
let size = 16 * rng.below(40);
RootEntry {
host: guest.wrapping_add(delta),
guest,
size,
bind_offset: rng.below(64),
}
})
.collect()
}
fn covers(set: &[RootEntry], byte: u64) -> Option<&RootEntry> {
set.iter()
.find(|e| e.guest <= byte && u128::from(byte) < u128::from(e.guest) + u128::from(e.size))
}
/// The coalesced set is sorted, disjoint, and non-empty per entry; it covers exactly the bytes of
/// the input (every input byte in one entry, no other byte); every entry translates as the
/// mapping does; bind offsets are cleared; and coalescing is idempotent and independent of the
/// input order.
#[test]
fn coalescing_is_sorted_disjoint_exact_and_idempotent() {
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
for case in 0..500 {
let delta = rng.next() & !15;
let input = one_mapping(&mut rng, delta);
let out = resident_set(input.clone());
for pair in out.windows(2) {
let end = u128::from(pair[0].guest) + u128::from(pair[0].size);
assert!(end <= u128::from(pair[1].guest), "case {case}: {pair:?}");
}
for e in &out {
assert!(e.size > 0, "case {case}");
assert_eq!(e.bind_offset, 0, "case {case}");
assert_eq!(e.host, e.guest.wrapping_add(delta), "case {case}");
}
let lo = input.iter().map(|e| e.guest).min().unwrap_or(0);
let hi = input.iter().map(|e| e.guest + e.size).max().unwrap_or(0);
for byte in (lo.saturating_sub(16)..hi + 16).step_by(8) {
let inside = input
.iter()
.any(|e| e.guest <= byte && byte < e.guest + e.size);
assert_eq!(
covers(&out, byte).is_some(),
inside,
"case {case}: byte {byte:#x}"
);
}
assert_eq!(resident_set(out.clone()), out.clone(), "case {case}");
let mut reversed = input;
reversed.reverse();
assert_eq!(resident_set(reversed), out, "case {case}");
}
}
/// A heap and the buffers sub-allocated inside it coalesce to the heap alone (the outermost
/// wins); a partial overlap keeps the earlier allocation whole and trims the later one's head.
#[test]
fn the_outermost_allocation_wins_and_overlaps_are_trimmed() {
let e = |guest: u64, size: u64| RootEntry {
host: guest + 0x1000_0000,
guest,
size,
bind_offset: 3,
};
let heap = e(0x1000, 0x1000);
let out = resident_set(vec![
e(0x1100, 0x40),
heap,
e(0x1000, 0x10),
e(0x1FF0, 0x10),
]);
assert_eq!(
out,
vec![RootEntry {
bind_offset: 0,
..heap
}]
);
let out = resident_set(vec![e(0x2000, 0x100), e(0x1F00, 0x180)]);
assert_eq!(out.len(), 2);
assert_eq!((out[0].guest, out[0].size), (0x1F00, 0x180));
assert_eq!((out[1].guest, out[1].size), (0x2080, 0x80));
assert_eq!(out[1].host, 0x2080 + 0x1000_0000);
assert_eq!(resident_set(vec![e(0x10, 0)]), Vec::new());
}
/// Coalescing counts entries after merging, duplicates of one allocation once; a set of more
/// than 2¹⁷ disjoint allocations is made whole.
#[test]
fn a_large_set_is_made_whole() {
let past = (1u64 << 17) + 3;
let e = |i: u64| RootEntry {
host: i * 32,
guest: i * 32,
size: 16,
bind_offset: 0,
};
let all: Vec<RootEntry> = (0..past).map(e).collect();
assert_eq!(resident_set(all.clone()).len() as u64, past);
let mut dup = all.clone();
dup.extend(all.iter().copied());
assert_eq!(resident_set(dup), all);
}
/// A state's resident set lists bound buffers of every stage and used buffers and heaps with both
/// addresses; textures, bytes, and buffers without a device address stay out.
#[test]
fn a_states_resident_set_comes_from_every_stage_and_the_used_resources() {
use crate::bind::state::{StageTable, TextureFacts, UsedResource};
use crate::metal;
use crate::pipeline::sym::Stage;
let buffer = |gpu: u64, host: Option<u64>| BoundBuffer::Buffer {
length: 100,
offset: 8,
gpu_address: gpu,
device_address: host,
attribute_stride: None,
};
let mut state = BindState::default();
let mut v = StageTable::default();
v.buffers.insert(0, buffer(0x1000, Some(0x9000)));
v.buffers.insert(1, buffer(0x2000, None));
v.buffers.insert(
2,
BoundBuffer::Bytes {
len: 64,
attribute_stride: None,
},
);
let mut f = StageTable::default();
f.buffers.insert(0, buffer(0x3000, Some(0xA000)));
state.stages.insert(Stage::Vertex, v);
state.stages.insert(Stage::Fragment, f);
let mut heap = UsedResource::new(ResourceClass::Heap, 1);
heap.gpu_address = Some(0x4000);
heap.device_address = Some(0xB000);
heap.length = 0x100;
let mut tex = UsedResource::new(
ResourceClass::Texture(TextureFacts::new(
metal::TextureType::Type2D,
metal::PixelFormat::RGBA8Unorm,
)),
2,
);
tex.gpu_address = Some(0x5000);
tex.device_address = Some(0xC000);
tex.length = 0x100;
state.used_resources = vec![heap, tex];
let got: Vec<(u64, u64, u64)> = resident_entries(&state)
.iter()
.map(|e| (e.guest, e.host, e.size))
.collect();
assert_eq!(
got,
vec![
(0x1000, 0x9000, 112),
(0x3000, 0xA000, 112),
(0x4000, 0xB000, 0x100)
]
);
}
fn entry(host: u64, guest: u64, size: u64) -> RootEntry {
RootEntry {
host,
guest,
size,
bind_offset: 0,
}
}
#[test]
fn the_resident_set_is_sorted_disjoint_and_outermost() {
let heap = entry(0x9000, 0x1000, 0x1000);
let inner = entry(0x9100, 0x1100, 0x100);
let same_start = entry(0x9000, 0x1000, 0x10);
let after = entry(0x5000, 0x4000, 0x40);
let partial = entry(0x9f00, 0x1f00, 0x200);
let empty = entry(0x7000, 0x3000, 0);
let set = resident_set(vec![after, partial, inner, empty, same_start, heap]);
assert_eq!(
set,
vec![
heap,
// The partially overlapping allocation loses its head, host and guest together.
entry(0xa000, 0x2000, 0x100),
after
]
);
for w in set.windows(2) {
assert!(w[0].guest + w[0].size <= w[1].guest, "disjoint and sorted");
}
assert_eq!(resident_set(Vec::new()), Vec::new());
}
/// Indirect command buffers' records are kept whole however they overlap, one entry a start (the
/// largest of those at one start), past the Metal allocations, which coalesce as before: the
/// records of ID 5, 3 GiB long, run past ID 6's start, and ID 6's own stay an entry, so a search
/// at each ID's start finds that ID's records.
#[test]
fn records_are_kept_whole_one_entry_a_start() {
use crate::indirect_commands::records_address;
let gib = 1u64 << 30;
let metal = entry(0x9000, 0x1000, 0x1000);
let inner = entry(0x9100, 0x1100, 0x100);
let five = entry(0x10_0000_0000, records_address(5), 3 * gib);
let six = entry(0x20_0000_0000, records_address(6), 0x1000);
let six_again = entry(0x30_0000_0000, records_address(6), 0x100);
let seven = entry(0x40_0000_0000, records_address(7), 0x1000);
let set = resident_set(vec![seven, six_again, inner, six, five, metal]);
assert_eq!(set, vec![metal, five, six, seven]);
for id in [5, 6, 7] {
let start = records_address(id);
let found = set.iter().rposition(|e| e.guest <= start).unwrap();
assert_eq!(
set[found].guest, start,
"ID {id}'s start is its own entry's"
);
}
}
/// Ranges listed apart (`BindState::resident_ranges`) join the resident set as used buffers do,
/// and leave the shape as it was.
#[test]
fn ranges_listed_apart_join_the_resident_set_and_not_the_shape() {
use crate::bind::state::UsedResource;
use crate::bind::ResidentRange;
let mut used = UsedResource::new(ResourceClass::Buffer, 0);
used.gpu_address = Some(0x2000);
used.device_address = Some(0x9_2000);
used.length = 100;
let state = BindState {
used_resources: vec![used],
..BindState::default()
};
let listed = BindState {
resident_ranges: vec![
ResidentRange {
host: 0x9_1000,
guest: 0x1000,
length: 60,
},
// Inside the used buffer's window: dropped as one inside another is.
ResidentRange {
host: 0x9_2010,
guest: 0x2010,
length: 16,
},
ResidentRange {
host: 0x9_3000,
guest: 0x3000,
length: 0x20,
},
],
..state.clone()
};
let resident = resident_entries(&listed);
let got: Vec<(u64, u64, u64)> = resident.iter().map(|e| (e.guest, e.host, e.size)).collect();
assert_eq!(
got,
vec![
(0x1000, 0x9_1000, 64),
(0x2000, 0x9_2000, 112),
(0x3000, 0x9_3000, 0x20)
]
);
assert_eq!(listed.shape(), state.shape());
}
/// Under `BindState::resident_apart` a root table's own resident set is the bound buffers' alone,
/// and without it the whole set, over pseudo-random states whose bound buffers, used buffers and
/// heaps and listed ranges nest, overlap, touch and repeat.
#[test]
fn a_state_resident_apart_keeps_the_used_resources_out_of_its_tables() {
use crate::bind::state::{StageTable, UsedResource};
use crate::bind::ResidentRange;
use crate::pipeline::sym::Stage;
let mut rng = Rng(0x5eed_0fa9_a7c3);
for _ in 0..300 {
let delta = 0x10_0000;
let mut state = BindState::default();
let (mut vertex, mut fragment) = (StageTable::default(), StageTable::default());
for (i, e) in one_mapping(&mut rng, delta).into_iter().enumerate() {
let length = e.size.saturating_sub(rng.below(16));
match rng.below(4) {
0 | 1 => {
let table = match rng.below(2) {
0 => &mut vertex,
_ => &mut fragment,
};
let buffer = BoundBuffer::Buffer {
length,
offset: 0,
gpu_address: e.guest,
device_address: Some(e.host),
attribute_stride: None,
};
table.buffers.insert(i as u32, buffer);
}
2 => {
let class = match rng.below(2) {
0 => ResourceClass::Buffer,
_ => ResourceClass::Heap,
};
let mut used = UsedResource::new(class, i as u32);
used.gpu_address = Some(e.guest);
used.device_address = Some(e.host);
used.length = length;
state.used_resources.push(used);
}
_ => {
let range = ResidentRange {
host: e.host,
guest: e.guest,
length,
};
state.resident_ranges.push(range);
}
}
}
state.stages.insert(Stage::Vertex, vertex);
state.stages.insert(Stage::Fragment, fragment);
let mut apart = state.clone();
apart.resident_apart = true;
assert_eq!(table_entries(&state), resident_entries(&state));
let bound_only = BindState {
used_resources: Vec::new(),
resident_ranges: Vec::new(),
..state.clone()
};
assert_eq!(table_entries(&apart), resident_entries(&bound_only));
assert_eq!(apart.shape(), state.shape());
}
}
File diff suppressed because it is too large. Load diff
+4 -148
View File
@@ -1,65 +1,9 @@
//! `ExecutionStatus` buffer layout: word indices and status bits.
//!
//! One 16-byte buffer per command buffer, shared by every plan in it. The consumer initializes it
//! with [`ExecutionStatus::initial`] before the command buffer's first use and reads it back with
//! [`ExecutionStatus::decode`] after the last one (a `SHADER_WRITE -> HOST_READ` barrier first);
//! the resident-set miss counter, the index
//! bounds pass, an absent argument's read, a mesh draw's arguments pass, a sample
//! through a cubic argument sampler, and a sequentially consistent fence write the
//! words named here.
/// The `ExecutionStatus` buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ExecutionStatus;
impl ExecutionStatus {
/// Size of the buffer in bytes.
pub const BYTES: usize = 16;
/// The buffer's initial bytes: every word 0.
pub const fn initial() -> [u8; ExecutionStatus::BYTES] {
[0; ExecutionStatus::BYTES]
}
/// What the buffer's bytes report after the command buffer ran. The consumer maps a mesh grid
/// Metal's GPU discards or the device cannot launch, and a cubic argument sampler's sample, to a
/// command-buffer execution error, and treats resident-set misses by its own policy.
pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport {
let word = |w: StatusWord| {
let at = w.byte_offset() as usize;
u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]])
};
let bits = StatusBits(word(StatusWord::Status));
StatusReport {
resident_miss: bits.contains(StatusBits::RESIDENT_MISS),
resident_misses: word(StatusWord::ResidentMisses),
cubic_argument_sampler: bits.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER),
mesh_grid_discarded: bits.contains(StatusBits::MESH_GRID_DISCARDED),
mesh_grid_past_limits: bits.contains(StatusBits::MESH_GRID_PAST_LIMITS),
}
}
}
/// What an `ExecutionStatus` buffer reports.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct StatusReport {
/// An access missed the resident set.
pub resident_miss: bool,
/// The number of resident-set misses counted (a `u32` the device increments, wrapping after
/// `2^32` misses).
pub resident_misses: u32,
/// A function sampled through an argument buffer's sampler whose min or mag filter is
/// `Cubic`, whose bicubic filter it does not emulate there
/// (`RuntimeFact::CubicArgumentSampler`): no result of the command buffer is then Metal's.
pub cubic_argument_sampler: bool,
/// An indirect mesh draw's arguments pass met an object grid that Metal's GPU discards (`StatusBits::MESH_GRID_DISCARDED`): that draw drew
/// nothing, and the command buffer fails as Metal's does (`MTLCommandBufferErrorInternal`).
pub mesh_grid_discarded: bool,
/// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot launch (`StatusBits::MESH_GRID_PAST_LIMITS`):
/// that draw drew nothing, and the command buffer fails (not Metal's failure).
pub mesh_grid_past_limits: bool,
}
//! One 16-byte buffer per command buffer, shared by every pipeline in it, which the consumer
//! zeroes before the command buffer's first use; the resident-set miss counter, an absent
//! argument's read, a sample through a cubic argument sampler, and a sequentially consistent
//! fence write the words named here.
/// A word of the `ExecutionStatus` buffer.
#[non_exhaustive]
@@ -105,92 +49,4 @@ impl StatusBits {
/// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest
/// placeholder, not Metal's.
pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 3);
/// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot
/// launch: a mesh grid past the mesh stage's limits, an unfolded object grid past the task
/// stage's, or a folded one of more pieces than `MeshArguments::OBJECT_PIECES` (only under task
/// limits below Vulkan's required least); the draw drew nothing (`bind::MeshArguments`).
pub const MESH_GRID_PAST_LIMITS: StatusBits = StatusBits(1 << 4);
/// An indirect mesh draw's arguments pass met an object grid of more threadgroups than
/// `bind::METAL_OBJECT_GRID_TOTAL`, which Metal's GPU discards; the draw drew nothing
/// (`bind::MeshArguments`).
pub const MESH_GRID_DISCARDED: StatusBits = StatusBits(1 << 5);
/// Every bit in `other` is set in `self`.
pub const fn contains(self, other: StatusBits) -> bool {
self.0 & other.0 == other.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn words_are_distinct_and_inside_the_buffer() {
let words = [
StatusWord::Status,
StatusWord::ResidentMisses,
StatusWord::SeqCstFences,
];
for (i, w) in words.iter().enumerate() {
assert!(
words[..i].iter().all(|other| other.index() != w.index()),
"{w:?}"
);
assert_eq!(w.byte_offset(), 4 * w.index(), "{w:?}");
assert!(
w.byte_offset() as usize + 4 <= ExecutionStatus::BYTES,
"{w:?}"
);
}
assert_eq!(
StatusWord::SeqCstFences.byte_offset() as usize + 4,
ExecutionStatus::BYTES
);
}
#[test]
fn status_bits_are_distinct() {
let bits = [
StatusBits::RESIDENT_MISS,
StatusBits::CUBIC_ARGUMENT_SAMPLER,
StatusBits::MESH_GRID_PAST_LIMITS,
StatusBits::MESH_GRID_DISCARDED,
];
let mut all = 0u32;
for b in bits {
assert_eq!(b.0.count_ones(), 1);
assert_eq!(all & b.0, 0);
all |= b.0;
}
assert!(StatusBits(all).contains(StatusBits::CUBIC_ARGUMENT_SAMPLER));
assert!(!StatusBits::RESIDENT_MISS.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER));
}
/// The initial bytes are all zero, and `decode` of them reports nothing.
#[test]
fn initial_bytes_are_zero_and_decode_clean() {
let bytes = ExecutionStatus::initial();
assert!(bytes.iter().all(|&b| b == 0));
assert_eq!(ExecutionStatus::decode(&bytes), StatusReport::default());
}
#[test]
fn decode_reports_every_bit_and_counter() {
let mut bytes = [0u8; ExecutionStatus::BYTES];
let bits = StatusBits::CUBIC_ARGUMENT_SAMPLER.0 | StatusBits::RESIDENT_MISS.0;
bytes[0..4].copy_from_slice(&bits.to_le_bytes());
bytes[4..8].copy_from_slice(&7u32.to_le_bytes());
let r = ExecutionStatus::decode(&bytes);
assert!(r.cubic_argument_sampler && r.resident_miss);
assert_eq!(r.resident_misses, 7);
bytes = [0u8; ExecutionStatus::BYTES];
bytes[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes());
let r = ExecutionStatus::decode(&bytes);
assert!(r.cubic_argument_sampler && !r.resident_miss);
assert_eq!(r.resident_misses, 0);
let mut cubic = [0u8; ExecutionStatus::BYTES];
cubic[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes());
let c = ExecutionStatus::decode(&cubic);
assert!(c.cubic_argument_sampler && !c.resident_miss);
}
}
+9 -124
View File
@@ -1,97 +1,19 @@
//! The buffer a visible-function table is bound as.
//! The words of a visible-function table's buffer, as the tests build them.
//!
//! A `visible_function_table` argument compiles to a read-only buffer at its Metal buffer index
//! (`pipeline::table` has the word layout), so the binder binds a table like any other buffer:
//! `setVisibleFunctionTable:atBufferIndex:` is a [`BoundBuffer::Buffer`] at that index of the
//! stage's table ([`StageTable::buffers`]), over a buffer the consumer owns for the
//! `MTLVisibleFunctionTable` and fills with the table's words. The shader reads its words
//! through the buffer slot only, never through the guest address, so the bound buffer's
//! `gpu_address` is not read for it. `setVisibleFunctionTable:nil` binds nothing: the slot gets
//! the plan's zero-filled neutral, whose word 0 makes `is_null_visible_function_table` true.
//! `setFunction:atIndex:` writes one entry: the word of the function's
//! [`FunctionHandle`] (`LinkedFunctions::function_handle` of the stage the table belongs to), or
//! [`FunctionHandle::NULL_WORD`] for a null entry.
//!
//! [`BoundBuffer::Buffer`]: crate::bind::BoundBuffer::Buffer
//! [`StageTable::buffers`]: crate::bind::StageTable::buffers
//! (`pipeline::table` has the word layout): `setVisibleFunctionTable:atBufferIndex:` binds a
//! buffer the consumer owns for the `MTLVisibleFunctionTable` and fills with the table's words.
//! The shader reads its words through the buffer slot only, never through the guest address, so
//! the bound buffer's `gpu_address` is not read for it. A slot bound to no table reads zeros,
//! whose word 0 makes `is_null_visible_function_table` true. `setFunction:atIndex:` writes one
//! entry: the word of the function's `FunctionHandle` (`LinkedFunctions::function_handle` of the
//! stage the table belongs to), or `FunctionHandle::NULL_WORD` for a null entry.
use crate::air::canon::function_table::FIRST_ENTRY_WORD;
#[cfg(test)]
use crate::air::canon::function_table::{PRESENT_WORD, SIZE_WORD};
use crate::air::canon::function_table::{FIRST_ENTRY_WORD, PRESENT_WORD, SIZE_WORD};
#[cfg(test)]
use crate::pipeline::table::FunctionHandle;
/// The function-table snapshot: the words of a command's listed tables
/// (`BindState::function_tables`) in one read-only storage buffer, which the consumer writes as the
/// command's command buffer commits
/// ([`WriteSource::FunctionTableSnapshot`](crate::bind::WriteSource::FunctionTableSnapshot)).
///
/// Word 0 is the null table's record: a word count of 0. Listed table `i`'s record follows the
/// records before it: its word count (its buffer's words: the table's header words and one
/// entry word for each of its size), then those words. The stage's function-table directory gives each listed
/// nonzero id the offset of its record's first word, and the null id and every id the directory
/// misses the null table's, 0: a read of word `w` of a table reads its record's word `1 + w`
/// below the record's count, and 0 at or past it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FunctionTableSnapshot {
/// The word offset of each listed table's record, in the list's order.
offsets: Vec<u32>,
/// The snapshot's length in words.
words: u32,
}
impl FunctionTableSnapshot {
/// The snapshot of tables of `sizes` entries, in the list's order; `None` when it would pass
/// `u32::MAX` words.
pub fn of(sizes: impl IntoIterator<Item = u32>) -> Option<FunctionTableSnapshot> {
let mut offsets = Vec::new();
let mut words: u32 = 1;
for size in sizes {
offsets.push(words);
let record = FIRST_ENTRY_WORD.checked_add(size)?.checked_add(1)?;
words = words.checked_add(record)?;
}
Some(FunctionTableSnapshot { offsets, words })
}
/// The word offset of each listed table's record, in the list's order: what the directory
/// gives its id.
pub fn offsets(&self) -> &[u32] {
&self.offsets
}
/// The snapshot's length in bytes.
#[cfg(test)]
pub(crate) fn byte_len(&self) -> u64 {
u64::from(self.words) * 4
}
/// The snapshot's bytes (little-endian words), of the listed tables' buffers `tables` in the
/// list's order, each as [`FunctionTableWords::to_bytes`] gives it. `None` when `tables` is
/// not one buffer of its size's length for each listed table.
#[cfg(test)]
pub(crate) fn bytes<'a>(&self, tables: impl IntoIterator<Item = &'a [u8]>) -> Option<Vec<u8>> {
let len = usize::try_from(self.byte_len()).ok()?;
let mut out = Vec::with_capacity(len);
out.extend(0u32.to_le_bytes());
let mut tables = tables.into_iter();
for (i, &offset) in self.offsets.iter().enumerate() {
let end = self.offsets.get(i + 1).copied().unwrap_or(self.words);
let count = end - offset - 1;
let table = tables.next()?;
if table.len() as u64 != u64::from(count) * 4 {
return None;
}
out.extend(count.to_le_bytes());
out.extend_from_slice(table);
}
match tables.next() {
Some(_) => None,
None => Some(out),
}
}
}
/// The words of one visible-function table's buffer: bound, its size, and its entries.
#[cfg(test)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -212,43 +134,6 @@ mod tests {
assert_eq!(empty.size(), 0);
}
/// A snapshot is the null table's record, then each table's word count and words; the
/// offsets are where each record starts, and buffers of other lengths than the sizes' make
/// none.
#[test]
fn a_snapshot_holds_each_table_after_its_word_count() {
let snapshot = FunctionTableSnapshot::of([3, 0]).expect("snapshot");
assert_eq!(snapshot.offsets(), [1, 7]);
assert_eq!(snapshot.byte_len(), 4 * 10);
let mut t = FunctionTableWords::new(3);
assert!(t.set_opaque_triangle(1));
let empty = FunctionTableWords::new(0);
let (t, empty) = (t.to_bytes(), empty.to_bytes());
let bytes = snapshot
.bytes([t.as_slice(), empty.as_slice()])
.expect("bytes");
let words: Vec<u32> = bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| u32::from_le_bytes(*w))
.collect();
let entry = FunctionHandle::RESERVED_WORD;
assert_eq!(words, [0, 5, 1, 3, 0, entry, 0, 2, 1, 0]);
assert_eq!(snapshot.bytes([t.as_slice()]), None, "a table missing");
assert_eq!(
snapshot.bytes([empty.as_slice(), t.as_slice()]),
None,
"the sizes out of order"
);
assert_eq!(
FunctionTableSnapshot::of([]).expect("empty").byte_len(),
4,
"the null table's record alone"
);
assert_eq!(FunctionTableSnapshot::of([u32::MAX]), None);
}
/// An intersection function table's opaque triangle entry is the reserved word 1.
#[test]
fn the_opaque_triangle_entry_is_the_reserved_word() {
+5 -6
View File
@@ -5,9 +5,8 @@
//! view holds at most the device's `maxTexelBufferElements` texels
//! (`VUID-VkBufferViewCreateInfo-range-00930`): 2^27 on ANV and lavapipe, 2^26 on MoltenVK. The
//! consumer states with a texture buffer's binding how many parts its texels take
//! (`BoundTexture::Buffer::parts`: its texels over [`part_texels`], rounded up), which its shape carries
//! (`TextureShape::Buffer::parts`): one for every texture buffer within the limit, which binds one
//! view as it always has.
//! (its texels over [`part_texels`], rounded up): one for every texture buffer within the limit,
//! which binds one view.
//!
//! **The views.** Part `k` views the texels from `k · P`, `P` the device's [`part_texels`] (its
//! `maxTexelBufferElements` rounded down to a multiple of its `minTexelBufferOffsetAlignment`, so
@@ -19,13 +18,13 @@
//! **What a function reads.** A slot whose function reads, writes, updates by an atomic or asks
//! the width of the texture buffer bound there, and does nothing else with it
//! (`RuntimeFact::TexelBufferParts`), on a device that indexes arrays of its kind of texel buffer
//! by a `NonUniform` value, takes the parts variant where the shape binds more than one part
//! there (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its
//! by a `NonUniform` value, takes the parts variant where the bound texture buffer takes more than
//! one part (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its
//! parts, and texel `i` is texel `i − k · P` of part `k = min(⌊i / P⌋, parts − 1)`. A texel past
//! the last lies past the last part's end, so its read is Metal's out-of-bounds texel and its
//! write is dropped, by the device's robustness or the function's own check as through one view.
//! The width is `(parts − 1) · P` plus the last part's. Any other slot binds one view, which
//! `maxTexelBufferElements` bounds (`BindError::TexelBufferTooLarge`).
//! `maxTexelBufferElements` bounds.
use crate::device::Limits;
@@ -1,66 +0,0 @@
//! A 2D texture over a buffer's rows whose image is a shadow, read and written in place through a
//! texel buffer view of the rows' bytes.
//!
//! **Where.** A texture over a buffer's bytes lies in an image over them where the device makes
//! one; where it makes none (the runtime's image refusals), the texture is a shadow, an image of
//! the runtime's own memory its commands' encoders copy the texels into and back. The buffer
//! itself is still in place. A texture in such a shadow states its rows in its facts
//! (`TextureFacts::texel_rows`), and a texture slot whose function only reads, writes or asks the
//! size of it (`RuntimeFact::TexelRows`: no sample, gather, atomic, read through a sampler or
//! level past the first) takes the slot's rows variant (`VariantKey::texel_rows`).
//!
//! **The binding.** Under the variant the slot's one descriptor is a texel buffer over the rows'
//! bytes (`WriteSource::TexelRows`), uniform where the function only reads the texture and storage
//! where it writes it, in the format a texture buffer of the texture's pixel format takes
//! (`bind::plan`'s texel formats: the format's own, an alias, or `R8_UNORM` for `A8Unorm`). Vulkan
//! states a texel buffer's texels "going through format conversion when read in a shader in the
//! same way as they are for an image" (Uniform Texel Buffer, Storage Texel Buffer), so a read
//! answers the device's conversion of the texel, as the shadow's image does. The view starts at
//! the texture's first texel, or before it where the device's texel buffer offset alignment asks:
//! the texture's size, its rows in texels and its first texel in the view are the slot's push
//! field (`PushField::TexelRows`, [`TexelRows::words`]).
//!
//! **What a function reads.** Texel `(x, y)` is the view's texel `first + y · row + x`. A read of
//! a texel outside the texture, or at a level past its one, is Metal's out-of-bounds texel, and a
//! write there is dropped, by the function's own test of the coordinate against the texture's
//! size: a coordinate past the width names a texel of the next row in the view, which the
//! device's robustness, bounding the view alone, would read. A size query answers the field's
//! size, at a level as at any texture, and the level count 1.
//!
//! **Ordering.** The slot's use is a use of the rows' bytes (`AccessClass::TexelRows`), as a
//! texture buffer's is: the consumer orders it against every use of the buffer, its shadow's
//! copies among them. A store to a texel buffer writes its texel's bytes alone (Vulkan's memory
//! model: "A memory operation must not affect memory at a memory location not within its set of
//! memory locations"), and a buffer view has no layout moves or load and store operations, so the
//! bytes between the rows keep whatever the CPU or another command writes there.
/// A 2D texture's rows in a texel buffer view of its buffer's bytes, where its image is a shadow
/// (the module docs): the words of its slot's push field (`PushField::TexelRows`). A texture states
/// one in its facts
/// (`TextureFacts::texel_rows`), and a slot whose function only reads, writes or asks the size of
/// it (`RuntimeFact::TexelRows`) takes the rows variant (`VariantKey::texel_rows`), which binds
/// the view (`WriteSource::TexelRows`) and addresses texel `(x, y)` at `first + y · row + x`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TexelRows {
words: [u32; TexelRows::WORDS],
}
impl TexelRows {
/// The words of the slot's push field ([`words`](Self::words)), one `uvec4`.
pub const WORDS: usize = 4;
/// Word: the texture's width in texels.
pub const WIDTH: usize = 0;
/// Word: the texture's height in texels.
pub const HEIGHT: usize = 1;
/// Word: the texels from one row's first to the next's in the view.
pub const ROW: usize = 2;
/// Word: the view's texel that is the texture's first.
pub const FIRST: usize = 3;
/// The words of the slot's push field.
pub fn words(&self) -> [u32; Self::WORDS] {
self.words
}
}
+20 -2
View File
@@ -61,9 +61,10 @@
use crate::metal::format::ChromaSubsampling;
/// The range of a YCbCr surface's codes, which its pixel format names.
#[cfg(test)]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum YCbCrRange {
pub(crate) enum YCbCrRange {
/// Video range: luma codes 16 to 235 span black to white (CoreVideo's `420v`).
Video,
/// Full range: luma codes 0 to 255 (CoreVideo's `420f`).
@@ -72,9 +73,10 @@ pub enum YCbCrRange {
/// The YCbCr matrix of a conversion: the surface's `IOSurfaceYCbCrMatrix` as Metal reads it when
/// it makes the texture (none reads as BT.601).
#[cfg(test)]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum YCbCrMatrix {
pub(crate) enum YCbCrMatrix {
/// ITU-R BT.601 (`ITU_R_601_4`, or no matrix).
Bt601,
/// ITU-R BT.709 (`ITU_R_709_2`).
@@ -165,6 +167,7 @@ impl YCbCrCodes {
/// The `(kb, kr)` of red, green and blue for `range` and `matrix`, in the units of the module
/// docs' conversion (measured, the module docs).
#[cfg(test)]
pub(crate) fn coefficients(range: YCbCrRange, matrix: YCbCrMatrix) -> [(i32, i32); 3] {
match (range, matrix) {
(YCbCrRange::Video, YCbCrMatrix::Bt601) => [(-9, 13123), (-3218, -6686), (16591, 9)],
@@ -329,5 +332,20 @@ pub(crate) fn ycbcr_read(
}
}
/// The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes held as an
/// image of the multi-planar 4:2:0 format over their bytes: the codes' bits, the surface's range
/// and matrix, Metal's reconstruction (the chroma at the midpoint through a linear chroma filter)
/// and a linear filter. A slot that samples such a texture through it is a combined image sampler
/// whose immutable sampler is the device's conversion of this (`ResourceKind::YCbCrPlanes`,
/// `vk::SamplerDesc::ycbcr`); the consumer makes the image's view with the same conversion.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct YCbCrPlanesSampler {
/// The conversion: the codes' bits in bits 0 to 7, full range in bit 8, and the matrix in bits
/// 9 and 10 (0 BT.601, 1 BT.709, 2 BT.2020).
pub(crate) conversion: u32,
}
#[cfg(test)]
mod tests;
@@ -1,392 +0,0 @@
//! A two-plane YCbCr texture's planes read in place: a function reads the codes from the planes'
//! own bytes and converts each texel as Metal does, where the texture's image of converted texels
//! (`ycbcr_convert`) would otherwise stand between them.
//!
//! **What it covers.** `YCBCR8_420_2P` and `YCBCR10_420_2P` (500 and 505) over a surface's two
//! planes, read converted ([`YCbCrOutput::Converted`]): the 4:2:0 layouts of unpacked codes, a
//! byte or the high 10 bits of a little-endian 16-bit word. A texture whose planes are those
//! states it in its facts (`TextureFacts::ycbcr_in_place`), and a texture
//! slot whose function reads it only as the in-place form reads
//! (`RuntimeFact::YCbCrInPlace`) takes the slot's in-place variant (`VariantKey::ycbcr_in_place`).
//!
//! **The binding.** The slot's one descriptor is a uniform texel buffer over the planes' bytes,
//! from the first byte of the first plane in memory, in `R8G8_UINT`
//! for 8-bit codes and `R16G16_UINT` for 10-bit ones, so one element holds two luma codes or one
//! chroma pair. Vulkan requires `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on
//! every device (the specification's "Required Format Support": `R8G8_UINT` in "1-3 Byte-Sized
//! Components", `R16G16_UINT` in "16-bit Components"). The texture's size, its planes' places
//! and rows in elements, and its conversion are the slot's push field
//! (`PushField::YCbCrInPlace`, [`YCbCrInPlace::words`]).
//!
//! **What a function reads** is Metal's texel (`ycbcr_convert`'s module docs): the luma code at
//! the texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, and
//! the conversion of the surface's range and matrix, each channel a step of `1 / 2048`, alpha 1.
//! A sample is Metal's filter of those texels on that grid (`lower::sampler::in_place`), exact,
//! as the image's emulated filter is.
//!
//! **Through the device's sampler.** Where the consumer also holds the planes as an image of the
//! multi-planar 4:2:0 format over their own bytes, which the device's sampler Y′CbCr conversion
//! reads with Metal's reconstruction (the chroma at the midpoint through a linear chroma filter),
//! the texture states it, and a slot whose every sample the
//! device's sampler takes (`RuntimeFact::YCbCrInPlace`'s `device`: no border address mode, no
//! texel offset placed by a parent's size) samples that image instead
//! (`VariantKey::ycbcr_planes_sampled`): its binding a combined image sampler whose immutable
//! sampler bakes the conversion ([`YCbCrPlanesSampler`], `ResourceKind::YCbCrPlanes`), each sample
//! the device's at level 0, a nearest one at the centre of the luma texel Metal reads. Its answer
//! is the device's conversion and filter of the codes, not Metal's.
#[cfg(test)]
use super::ycbcr_convert::{YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange};
#[cfg(test)]
use crate::metal::format::ChromaSubsampling;
#[cfg(test)]
use crate::vk;
/// A two-plane YCbCr texture's planes as a function reads them in place, where the texture's image
/// of converted texels would otherwise stand between them: the words of its slot's push field
/// (`PushField::YCbCrInPlace`), and the uniform texel buffer the slot binds over the planes' bytes
/// (`R8G8_UINT` of 8-bit codes, `R16G16_UINT` of 10-bit ones, from the first byte of the first
/// plane through the last row of codes either plane holds). A texture states one in its facts
/// (`TextureFacts::ycbcr_in_place`), and a slot whose function reads the texture only as this form
/// does (`RuntimeFact::YCbCrInPlace`) takes the in-place variant (`VariantKey::ycbcr_in_place`),
/// which fetches the codes and converts and filters them as Metal does: the luma code at the
/// texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, the
/// surface's range and matrix, each channel a step of `1 / 2048`, alpha 1. Vulkan requires
/// `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on every device.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct YCbCrInPlace {
words: [u32; YCbCrInPlace::WORDS],
/// The bytes the texel buffer views, from the planes' first byte: the end of the last row of
/// codes either plane holds, rounded up to a whole element.
bytes: u64,
/// The consumer holds the planes as an image the device's conversion samples.
#[cfg_attr(feature = "serde", serde(default))]
planes_image: bool,
}
impl YCbCrInPlace {
/// The words of the slot's push field ([`words`](Self::words)), two `uvec4`s.
pub const WORDS: usize = 8;
/// Word: the texture's width in texels.
pub const WIDTH: usize = 0;
/// Word: the texture's height in texels.
pub const HEIGHT: usize = 1;
/// Word: the luma plane's first element in the texel buffer.
pub const LUMA_AT: usize = 2;
/// Word: the elements from one luma row to the next.
pub const LUMA_ROW: usize = 3;
/// Word: the chroma plane's first element in the texel buffer.
pub const CHROMA_AT: usize = 4;
/// Word: the elements from one chroma row to the next.
pub const CHROMA_ROW: usize = 5;
/// Word: the conversion: the codes' bits in bits 0 to 7, full range in bit 8, and the matrix
/// in bits 9 and 10 (0 BT.601, 1 BT.709, 2 BT.2020).
pub const CONVERSION: usize = 6;
/// The device's conversion of the planes as an image ([`YCbCrPlanesSampler`]): their codes'
/// bits, range and matrix.
pub fn sampler(&self) -> YCbCrPlanesSampler {
YCbCrPlanesSampler {
conversion: self.words[Self::CONVERSION],
}
}
/// [`sampler`](Self::sampler), where the consumer holds the planes as an image it samples;
/// `None` where it does not.
pub fn planes_sampler(&self) -> Option<YCbCrPlanesSampler> {
self.planes_image.then(|| self.sampler())
}
/// The words of the slot's push field.
pub fn words(&self) -> [u32; Self::WORDS] {
self.words
}
/// The in-place form of `planes`, where a function reads them so: a
/// converted 4:2:0 layout of unpacked 8- or 10-bit codes, both planes in the bytes (a chroma
/// plane of rows; not the conversion's row of zeros), each plane's first byte and rows a
/// multiple of an element. `None` for any other: such a texture keeps its image of converted
/// texels alone.
#[cfg(test)]
pub(crate) fn of(planes: &YCbCrPlanes) -> Option<YCbCrInPlace> {
let codes = planes.codes;
if codes.output != YCbCrOutput::Converted
|| codes.subsampling != ChromaSubsampling::Chroma420
|| codes.packed
|| !matches!((codes.bits, codes.bytes), (8, 1) | (10, 2))
|| planes.chroma[1] == 0
{
return None;
}
let element = 2 * codes.bytes;
let [luma_at, luma_row] = planes.luma;
let [chroma_at, chroma_row] = planes.chroma;
if [luma_at, luma_row, chroma_at, chroma_row]
.iter()
.any(|v| v % element != 0)
{
return None;
}
let [w, h] = planes.size;
if w == 0 || h == 0 {
return None;
}
let [cw, ch] = planes.chroma_size().map(u64::from);
let unit = u64::from(codes.bytes);
let end = |at: u32, row: u32, rows: u64, bytes: u64| {
u64::from(at) + u64::from(row) * (rows - 1) + bytes
};
let reach = end(luma_at, luma_row, u64::from(h), unit * u64::from(w)).max(end(
chroma_at,
chroma_row,
ch,
unit * 2 * cw,
));
let bytes = reach.next_multiple_of(u64::from(element));
let mut words = [0; Self::WORDS];
words[Self::WIDTH] = w;
words[Self::HEIGHT] = h;
words[Self::LUMA_AT] = luma_at / element;
words[Self::LUMA_ROW] = luma_row / element;
words[Self::CHROMA_AT] = chroma_at / element;
words[Self::CHROMA_ROW] = chroma_row / element;
words[Self::CONVERSION] = conversion_word(codes.bits, planes.range, planes.matrix);
Some(YCbCrInPlace {
words,
bytes,
planes_image: false,
})
}
/// The form of the same planes where the consumer also holds them as an image of
/// [`sampler`](Self::sampler)'s format over their bytes, which the device's sampler Y′CbCr
/// conversion of it reads (the module docs): a slot whose every sample the device's sampler
/// takes samples that image (`VariantKey::ycbcr_planes_sampled`).
#[cfg(test)]
pub(crate) fn with_planes_image(self) -> YCbCrInPlace {
YCbCrInPlace {
planes_image: true,
..self
}
}
/// The codes' bits: 8 or 10.
#[cfg(test)]
pub(crate) fn bits(&self) -> u32 {
self.words[Self::CONVERSION] & 0xff
}
/// The texel buffer's format: `R8G8_UINT` of 8-bit codes, `R16G16_UINT` of 10-bit ones.
#[cfg(test)]
pub(crate) fn format(&self) -> vk::Format {
match self.bits() {
8 => vk::Format::R8G8_UINT,
_ => vk::Format::R16G16_UINT,
}
}
/// The bytes of one element of the texel buffer: 2 of 8-bit codes, 4 of 10-bit ones.
#[cfg(test)]
pub(crate) fn element_bytes(&self) -> u64 {
match self.bits() {
8 => 2,
_ => 4,
}
}
/// The bytes the texel buffer views from the planes' first byte: through the last row of
/// codes either plane holds, a whole number of elements.
#[cfg(test)]
pub(crate) fn view_bytes(&self) -> u64 {
self.bytes
}
/// The elements the texel buffer holds (`maxTexelBufferElements` bounds them).
#[cfg(test)]
pub(crate) fn elements(&self) -> u64 {
self.bytes / self.element_bytes()
}
}
/// The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes held as an
/// image of the multi-planar 4:2:0 format over their bytes (the module docs, **Through the
/// device's sampler**): the codes' bits, the surface's range and matrix, Metal's reconstruction
/// (the chroma at the midpoint through a linear chroma filter) and a linear filter. A slot that
/// samples such a texture through it is a combined image sampler whose immutable sampler is the
/// device's conversion of this (`ResourceKind::YCbCrPlanes`, `vk::SamplerDesc::ycbcr`); the
/// consumer makes the image's view with the same conversion.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct YCbCrPlanesSampler {
/// The conversion word ([`YCbCrInPlace::CONVERSION`]).
pub(crate) conversion: u32,
}
impl YCbCrPlanesSampler {
/// The codes' bits: 8 or 10.
#[cfg(test)]
pub(crate) fn bits(self) -> u32 {
self.conversion & 0xff
}
/// The surface's range.
#[cfg(test)]
pub(crate) fn range(self) -> YCbCrRange {
match self.conversion >> 8 & 1 {
1 => YCbCrRange::Full,
_ => YCbCrRange::Video,
}
}
/// The surface's matrix.
#[cfg(test)]
pub(crate) fn matrix(self) -> YCbCrMatrix {
match self.conversion >> 9 & 3 {
1 => YCbCrMatrix::Bt709,
2 => YCbCrMatrix::Bt2020,
_ => YCbCrMatrix::Bt601,
}
}
/// The multi-planar format of the planes' image: `G8_B8R8_2PLANE_420_UNORM` of 8-bit codes,
/// `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` of 10-bit ones (the high 10 bits of each
/// little-endian 16-bit word, as the planes hold them).
#[cfg(test)]
pub(crate) fn format(self) -> vk::Format {
match self.bits() {
8 => vk::Format::G8_B8R8_2PLANE_420_UNORM,
_ => vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
}
}
}
/// The conversion word ([`YCbCrInPlace::CONVERSION`]) of `bits`-bit codes of `range` and
/// `matrix`.
#[cfg(test)]
fn conversion_word(bits: u32, range: YCbCrRange, matrix: YCbCrMatrix) -> u32 {
let full = match range {
YCbCrRange::Video => 0,
YCbCrRange::Full => 1,
};
let m = match matrix {
YCbCrMatrix::Bt601 => 0,
YCbCrMatrix::Bt709 => 1,
YCbCrMatrix::Bt2020 => 2,
};
bits | full << 8 | m << 9
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bind::ycbcr_convert::YCbCrCodes;
use crate::metal::format::ycbcr_format;
use crate::metal::PixelFormat;
fn planes(pf: PixelFormat, luma: [u32; 2], chroma: [u32; 2]) -> YCbCrPlanes {
let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).expect("codes");
YCbCrPlanes::new(
[7, 5],
luma,
chroma,
(YCbCrRange::Full, YCbCrMatrix::Bt709),
codes,
)
}
/// The two converted 4:2:0 formats take the form, in elements of their own width; every
/// other layout keeps its image.
#[test]
fn only_converted_four_two_zero_codes_read_in_place() {
let p8 =
YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit");
assert_eq!(p8.format(), vk::Format::R8G8_UINT);
assert_eq!(
p8.words(),
[
7,
5,
0,
8,
48,
8,
conversion_word(8, YCbCrRange::Full, YCbCrMatrix::Bt709),
0
]
);
// The chroma plane's last row (3 rows of 4 pairs) ends at 96 + 32 + 8.
assert_eq!(p8.view_bytes(), 136);
assert_eq!(p8.elements(), 68);
let p10 = YCbCrInPlace::of(&planes(PixelFormat::YCBCR104202P, [0, 16], [96, 32]))
.expect("10-bit");
assert_eq!(p10.format(), vk::Format::R16G16_UINT);
assert_eq!(p10.words()[YCbCrInPlace::LUMA_ROW], 4);
assert_eq!(p10.words()[YCbCrInPlace::CHROMA_AT], 24);
assert_eq!(p10.bits(), 10);
// The luma plane ends the bytes: its last row's seven codes round up to a whole element.
let tail = YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [64, 16], [0, 16]))
.expect("chroma first");
assert_eq!(tail.view_bytes(), 64 + 4 * 16 + 8);
for pf in [
PixelFormat::YCBCR84222P,
PixelFormat::YCBCR84442P,
PixelFormat::YCBCR84202PSRGB,
PixelFormat::RGB84202P,
PixelFormat::YCBCR104202PPACKED,
] {
assert_eq!(
YCbCrInPlace::of(&planes(pf, [0, 16], [96, 16])),
None,
"{pf:?}"
);
}
// The conversion's row of zeros is no chroma plane.
let zero = planes(PixelFormat::YCBCR84202P, [0, 16], [96, 0]);
assert_eq!(YCbCrInPlace::of(&zero), None);
}
/// The planes' image's conversion is the codes' bits, range and matrix, of the format of
/// their bits; a texture states it only once the consumer holds the image.
#[test]
fn the_planes_sampler_is_the_conversion_word() {
let p8 =
YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit");
assert_eq!(p8.planes_sampler(), None);
let held = p8.with_planes_image();
assert_eq!(held.words(), p8.words());
let s = held.planes_sampler().expect("held");
assert_eq!(s, p8.sampler());
assert_eq!(
(s.bits(), s.range(), s.matrix(), s.format()),
(
8,
YCbCrRange::Full,
YCbCrMatrix::Bt709,
vk::Format::G8_B8R8_2PLANE_420_UNORM
)
);
let codes = ycbcr_format(PixelFormat::YCBCR104202P)
.and_then(YCbCrCodes::of)
.expect("codes");
let p10 = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Video, YCbCrMatrix::Bt2020),
codes,
);
let s = YCbCrInPlace::of(&p10).expect("10-bit").sampler();
assert_eq!(
(s.bits(), s.range(), s.matrix(), s.format()),
(
10,
YCbCrRange::Video,
YCbCrMatrix::Bt2020,
vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16
)
);
}
}
-6
View File
@@ -885,9 +885,7 @@ codec_enum! {
VerticesPerPrimitive,
MergedDrawAddress,
AlphaTestReference,
YCbCrInPlace(f0),
LineBand,
TexelRows(f0),
ArgumentTableAddress,
ConstexprSampler(f0),
TessellationFactorAddress,
@@ -1257,12 +1255,10 @@ codec_enum! {
MergedDraws,
QuadPrimitiveIds,
PrivateList,
YCbCrInPlace { slot, samplers, device },
PartialObjectThreadgroups,
BorderTexels { slot },
RegionViewports,
PartialThreadgroups,
TexelRows { slot },
UnitAxes { axes, relief },
TexelBufferParts { slot },
AddressAlignment { slot, align },
@@ -1390,9 +1386,7 @@ codec_enum! {
RestrictedDepthRange,
CubeGradientFootprint,
HalfTexelConversion,
HalfSampleFilter,
SrgbTexelDecode,
FloatSampleFilter,
FunctionStorageAssumed,
QuadsCountedBeforeDiscard,
ViewBaseTexelOffset,
-355
View File
@@ -185,360 +185,5 @@ impl Node {
}
}
#[cfg(feature = "serde")]
pub(crate) use serialized::node_of;
/// The same nodes for a value through its `serde` serialization, for the types the cache does not
/// encode (a [`BindingPlan`](crate::bind::BindingPlan)). Struct and variant fields are named by
/// their serialized names, tuple fields by their positions; a map is the sequence of its entries
/// as pairs; a unit or unit struct is zero. Primitives are leaves over their little-endian bytes
/// (floats by their bits), strings and byte strings over their length and bytes, as the codec
/// writes them.
#[cfg(feature = "serde")]
mod serialized {
use serde::ser::{self, Serialize};
use super::Node;
/// A serialization that refused: a `Serialize` impl reported an error of its own.
#[derive(Debug)]
pub(crate) struct NotDigested(pub(crate) String);
impl std::fmt::Display for NotDigested {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "the value did not serialize: {}", self.0)
}
}
impl std::error::Error for NotDigested {}
impl ser::Error for NotDigested {
fn custom<T: std::fmt::Display>(msg: T) -> Self {
NotDigested(msg.to_string())
}
}
/// `value`'s node.
pub(crate) fn node_of<T: Serialize + ?Sized>(value: &T) -> Result<Node, NotDigested> {
value.serialize(Nodes)
}
fn leaf(bytes: &[u8]) -> Node {
Node::leaf(|sink| sink(bytes))
}
fn counted(bytes: &[u8]) -> Node {
Node::leaf(|sink| {
sink(&u32::try_from(bytes.len()).unwrap_or(u32::MAX).to_le_bytes());
sink(bytes);
})
}
/// The serializer whose output is a value's node.
struct Nodes;
/// Positional field names, for tuple variants.
const POSITIONS: [&str; 16] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
];
fn position(index: usize) -> Result<&'static str, NotDigested> {
POSITIONS
.get(index)
.copied()
.ok_or_else(|| NotDigested(format!("a tuple variant of more than {index} fields")))
}
/// The items of a sequence, a tuple, or a map's entries.
struct Items {
nodes: Vec<Node>,
tuple: bool,
key: Option<Node>,
}
impl Items {
fn finish(self) -> Node {
if self.tuple {
Node::tuple(self.nodes)
} else {
Node::sequence(self.nodes)
}
}
}
/// The named fields of a struct or a variant (`variant` names it).
struct Fields {
variant: Option<&'static str>,
fields: Vec<(&'static str, Node)>,
}
impl Fields {
fn finish(mut self) -> Node {
match self.variant {
Some(name) => Node::variant(name, &mut self.fields),
None => Node::fields(&mut self.fields),
}
}
}
impl ser::Serializer for Nodes {
type Ok = Node;
type Error = NotDigested;
type SerializeSeq = Items;
type SerializeTuple = Items;
type SerializeTupleStruct = Items;
type SerializeTupleVariant = Fields;
type SerializeMap = Items;
type SerializeStruct = Fields;
type SerializeStructVariant = Fields;
fn serialize_bool(self, v: bool) -> Result<Node, NotDigested> {
Ok(leaf(&[u8::from(v)]))
}
fn serialize_i8(self, v: i8) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_i16(self, v: i16) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_i32(self, v: i32) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_i64(self, v: i64) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_i128(self, v: i128) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_u8(self, v: u8) -> Result<Node, NotDigested> {
Ok(leaf(&[v]))
}
fn serialize_u16(self, v: u16) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_u32(self, v: u32) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_u64(self, v: u64) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_u128(self, v: u128) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_le_bytes()))
}
fn serialize_f32(self, v: f32) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_bits().to_le_bytes()))
}
fn serialize_f64(self, v: f64) -> Result<Node, NotDigested> {
Ok(leaf(&v.to_bits().to_le_bytes()))
}
fn serialize_char(self, v: char) -> Result<Node, NotDigested> {
Ok(leaf(&u32::from(v).to_le_bytes()))
}
fn serialize_str(self, v: &str) -> Result<Node, NotDigested> {
Ok(counted(v.as_bytes()))
}
fn serialize_bytes(self, v: &[u8]) -> Result<Node, NotDigested> {
Ok(counted(v))
}
fn serialize_none(self) -> Result<Node, NotDigested> {
Ok(Node::ZERO)
}
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<Node, NotDigested> {
Ok(Node::some(node_of(value)?))
}
fn serialize_unit(self) -> Result<Node, NotDigested> {
Ok(Node::ZERO)
}
fn serialize_unit_struct(self, _: &'static str) -> Result<Node, NotDigested> {
Ok(Node::ZERO)
}
fn serialize_unit_variant(
self,
_: &'static str,
_: u32,
variant: &'static str,
) -> Result<Node, NotDigested> {
Ok(Node::variant(variant, &mut []))
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(
self,
_: &'static str,
value: &T,
) -> Result<Node, NotDigested> {
node_of(value)
}
fn serialize_newtype_variant<T: Serialize + ?Sized>(
self,
_: &'static str,
_: u32,
variant: &'static str,
value: &T,
) -> Result<Node, NotDigested> {
Ok(Node::variant(
variant,
&mut [(POSITIONS[0], node_of(value)?)],
))
}
fn serialize_seq(self, len: Option<usize>) -> Result<Items, NotDigested> {
Ok(Items {
nodes: Vec::with_capacity(len.unwrap_or(0)),
tuple: false,
key: None,
})
}
fn serialize_tuple(self, len: usize) -> Result<Items, NotDigested> {
Ok(Items {
nodes: Vec::with_capacity(len),
tuple: true,
key: None,
})
}
fn serialize_tuple_struct(self, _: &'static str, len: usize) -> Result<Items, NotDigested> {
self.serialize_tuple(len)
}
fn serialize_tuple_variant(
self,
_: &'static str,
_: u32,
variant: &'static str,
len: usize,
) -> Result<Fields, NotDigested> {
Ok(Fields {
variant: Some(variant),
fields: Vec::with_capacity(len),
})
}
fn serialize_map(self, len: Option<usize>) -> Result<Items, NotDigested> {
self.serialize_seq(len)
}
fn serialize_struct(self, _: &'static str, len: usize) -> Result<Fields, NotDigested> {
Ok(Fields {
variant: None,
fields: Vec::with_capacity(len),
})
}
fn serialize_struct_variant(
self,
_: &'static str,
_: u32,
variant: &'static str,
len: usize,
) -> Result<Fields, NotDigested> {
Ok(Fields {
variant: Some(variant),
fields: Vec::with_capacity(len),
})
}
}
impl ser::SerializeSeq for Items {
type Ok = Node;
type Error = NotDigested;
fn serialize_element<T: Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), NotDigested> {
self.nodes.push(node_of(value)?);
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
impl ser::SerializeTuple for Items {
type Ok = Node;
type Error = NotDigested;
fn serialize_element<T: Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), NotDigested> {
self.nodes.push(node_of(value)?);
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
impl ser::SerializeTupleStruct for Items {
type Ok = Node;
type Error = NotDigested;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), NotDigested> {
self.nodes.push(node_of(value)?);
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
/// A map is the sequence of its entries, each the pair of its key's and value's nodes.
impl ser::SerializeMap for Items {
type Ok = Node;
type Error = NotDigested;
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), NotDigested> {
self.key = Some(node_of(key)?);
Ok(())
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), NotDigested> {
let key = self
.key
.take()
.ok_or_else(|| NotDigested("a map value without its key".into()))?;
self.nodes.push(Node::tuple([key, node_of(value)?]));
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
impl ser::SerializeTupleVariant for Fields {
type Ok = Node;
type Error = NotDigested;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), NotDigested> {
let name = position(self.fields.len())?;
self.fields.push((name, node_of(value)?));
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
impl ser::SerializeStruct for Fields {
type Ok = Node;
type Error = NotDigested;
fn serialize_field<T: Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), NotDigested> {
self.fields.push((key, node_of(value)?));
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
impl ser::SerializeStructVariant for Fields {
type Ok = Node;
type Error = NotDigested;
fn serialize_field<T: Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), NotDigested> {
self.fields.push((key, node_of(value)?));
Ok(())
}
fn end(self) -> Result<Node, NotDigested> {
Ok(self.finish())
}
}
}
#[cfg(test)]
mod tests;
-169
View File
@@ -68,172 +68,3 @@ fn nodes_omit_only_struct_fields() {
assert_ne!(node(1).root("a"), node(1).root("b"));
assert_ne!(Node::ZERO.root("a"), node(1).root("a"));
}
#[cfg(feature = "serde")]
mod serialized {
use std::collections::BTreeMap;
use serde::Serialize;
use super::super::node_of;
use super::*;
#[derive(Serialize)]
struct Before {
count: u32,
items: Vec<Item>,
mode: Mode,
}
#[derive(Serialize)]
struct After {
added: Option<u32>,
mode: Mode,
count: u32,
items: Vec<ItemAfter>,
flag: bool,
pairs: Vec<(u32, u32)>,
}
#[derive(Serialize)]
struct Item {
word: u64,
}
#[derive(Serialize)]
struct ItemAfter {
word: u64,
view: Option<Item>,
}
#[derive(Serialize)]
enum Mode {
Off,
Level(u32),
Pair(u32, u32),
Window { start: u32, len: u32 },
}
#[derive(Serialize)]
enum ModeInserted {
Window { start: u32, len: u32 },
Auto,
Pair(u32, u32),
Level(u32),
Off,
}
fn digest<T: Serialize>(value: &T) -> Node {
node_of(value).unwrap()
}
/// The serde path follows the codec path's rules: an added field at zero moves nothing, and
/// its non-zero values do.
#[test]
fn an_added_field_at_zero_keeps_the_digest() {
let before = Before {
count: 2,
items: vec![Item { word: 5 }, Item { word: 0 }],
mode: Mode::Level(3),
};
let after = After {
added: None,
mode: Mode::Level(3),
count: 2,
items: vec![
ItemAfter {
word: 5,
view: None,
},
ItemAfter {
word: 0,
view: None,
},
],
flag: false,
pairs: Vec::new(),
};
assert_eq!(digest(&before), digest(&after));
let moved = After {
added: Some(0),
..after
};
assert_ne!(digest(&before), digest(&moved));
let moved = After {
added: None,
flag: true,
..moved
};
assert_ne!(digest(&before), digest(&moved));
let moved = After {
flag: false,
pairs: vec![(0, 0)],
..moved
};
assert_ne!(digest(&before), digest(&moved));
}
/// Variants are named: reordering or inserting variants moves nothing, and switching a value
/// to another variant does.
#[test]
fn variants_are_named_not_numbered() {
let pairs = [
(Mode::Off, ModeInserted::Off),
(Mode::Level(4), ModeInserted::Level(4)),
(Mode::Pair(1, 2), ModeInserted::Pair(1, 2)),
(
Mode::Window { start: 1, len: 0 },
ModeInserted::Window { start: 1, len: 0 },
),
];
for (mode, inserted) in &pairs {
assert_eq!(digest(mode), digest(inserted));
}
let digests = [
digest(&Mode::Off),
digest(&Mode::Level(0)),
digest(&Mode::Level(4)),
digest(&Mode::Pair(1, 2)),
digest(&Mode::Pair(2, 1)),
digest(&Mode::Window { start: 0, len: 0 }),
digest(&ModeInserted::Auto),
];
for (i, a) in digests.iter().enumerate() {
for b in &digests[i + 1..] {
assert_ne!(a, b);
}
}
}
/// A map is the sequence of its entries as pairs, so it digests as a sequence of pairs does
/// (the plan's `serde_pairs` maps).
#[test]
fn a_map_is_its_entries() {
let map: BTreeMap<u32, u64> = [(1, 5), (2, 0)].into();
let pairs: Vec<(u32, u64)> = map.clone().into_iter().collect();
assert_eq!(digest(&map), digest(&pairs));
assert!(digest(&BTreeMap::<u32, u64>::new()).is_zero());
}
/// A plan's digest is its serialization's, covers what the plan says, and is pinned.
#[test]
fn a_plan_digest_follows_the_plan() {
use crate::bind::BindingPlan;
let plan = BindingPlan::default();
let digest = plan.content_digest().unwrap();
assert_eq!(digest, node_of(&plan).unwrap().root("binding plan"));
let mut viewed = plan.clone();
viewed.views.view_mask = 3;
assert_ne!(viewed.content_digest().unwrap(), digest);
let hex = viewed
.content_digest()
.unwrap()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
assert_eq!(
hex, "a7fb58b1d327f235fb690324f99969bccd238a3488178ac0cacb8cac19e2ebe0",
"the plan digest's definition changed"
);
}
}
+85 -216
View File
@@ -15,9 +15,9 @@
//! checks the format and semantics versions, the key, the device's profile fingerprint, and a
//! checksum, then scans the modules; it does not re-run the verifier. Every [`ArtifactError`]
//! is a cache miss: compile again and replace the entry.
//! - A [`BindingPlan`](crate::bind::BindingPlan) memoizes in memory on `(PipelineKey, BindShape)`.
//!
//! [`VariantKey`] names the variant of a pipeline a bind shape or a dispatch asks for, and
//! [`VariantKey`] names a variant of a pipeline, the lowering inputs each of its functions
//! compiles under ([`VariantKey::lowering_inputs`]), and
//! [`SpecializationKey`] is the data of one `VkSpecializationInfo`.
//!
//! Three versions move independently: the crate's (the API), [`SEMANTICS_VERSION`] (the output:
@@ -42,8 +42,7 @@ use crate::vk;
mod artifacts;
mod checksum;
mod codec;
// Content digests: `ComputePipeline::content_digest`, `RenderPipeline::content_digest` and
// `BindingPlan::content_digest`.
// Content digests: `ComputePipeline::content_digest` and `RenderPipeline::content_digest`.
pub(crate) mod digest;
mod envelope;
mod scan;
@@ -73,20 +72,20 @@ pub const SEMANTICS_VERSION: u32 = 2273;
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 591;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
/// tables, dispatch regions and draws), the device replay and its preprocess, resident sets, status
/// decoding, and the other run-time data the binder computes. Independent of
/// [`SEMANTICS_VERSION`] (what is compiled) and [`ARTIFACT_FORMAT_VERSION`] (how it is encoded):
/// two runs of byte-identical artifacts and plans under one runtime version do the same thing. A
/// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the
/// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime
/// maps, the record and table formats it writes (indirect commands, rate and tile maps, function
/// tables, argument-buffer layouts), the texel decoders, and the other run-time data `bind` holds.
/// Independent of [`SEMANTICS_VERSION`] (what is compiled) and [`ARTIFACT_FORMAT_VERSION`] (how it
/// is encoded): two runs of byte-identical artifacts under one runtime version do the same thing. A
/// consumer that keeps records of what runs of an artifact did (its own regression records, or what
/// a run refused) keys them on it beside the artifact, as it keys cached artifacts on
/// [`SEMANTICS_VERSION`].
///
/// Bump it whenever a run of an unchanged artifact and plan may do something else: an answer, a
/// refusal or its class, an announcement, or what the run records and submits. A field added to an
/// encoded artifact or a plan whose zero value would change what existing pipelines do needs the
/// same bump (or the executor's), since their digests omit it.
/// Bump it whenever a run of an unchanged artifact may do something else: an answer, a refusal or
/// its class, an announcement, or what the run records and submits. A field added to an encoded
/// artifact whose zero value would change what existing pipelines do needs the same bump (or the
/// executor's), since its digest omits it.
///
/// This workspace's validation holds every recorded run to it beside the run's artifact content
/// digest (`cache::digest`), and its runtime guard fails when the runtime's sources no longer hash
@@ -131,13 +130,10 @@ impl fmt::Debug for PipelineKey {
}
}
/// The per-function variant choices a bind shape or a dispatch can require: storage-image choices
/// for slots whose `StorageTextureFormat` fact maps to `Variant`, slots that a `BufferRangeLimit`
/// variant moves to `BufferForm::Psb`, vertex buffers the shape binds where fixed-function vertex
/// input cannot fetch them, a kernel's emulated simdgroups for a dispatch whose threadgroup has a
/// partial simdgroup, a vertex function's dropped `Layer` output in a pass of one layer, and the
/// read-only slots Profile F's per-stage storage-buffer fallback keeps as storage views. Canonical
/// (ordered maps) and empty on the common path.
/// The per-function variant choices of a pipeline: storage-image choices for slots whose
/// `StorageTextureFormat` fact maps to `Variant`, slots that a `BufferRangeLimit` variant moves to
/// `BufferForm::Psb`, vertex buffers fetched in the shader, a kernel's emulated simdgroups, and the
/// other forms each field names. Canonical (ordered maps) and empty on the common path.
///
/// [`VariantKey::lowering_inputs`] is each function's `LoweringInputs` under the key, so the
/// choice reaches `select` and the `FunctionCompileKey`; a render pipeline's keys under one are
@@ -156,80 +152,46 @@ pub struct VariantKey {
pub pulled_vertex_buffers: BTreeSet<u32>,
/// The kernel's simdgroups run in the emulated tier, which is exact for every threadgroup size:
/// a dispatch whose threadgroup has a partial simdgroup asks for it where the kernel's own tier
/// runs simdgroups on whole subgroups (`BindingPlan::dispatch_variant`,
/// `BindError::NeedsVariant`), and the plan of a pipeline compiled under it states it.
/// runs simdgroups on whole subgroups.
#[cfg_attr(feature = "serde", serde(default))]
pub emulated_simdgroups: bool,
/// Every threadgroup of the dispatch is one row, so each of its simdgroups lies within the
/// row: a kernel whose lockstep simdgroup barriers order only pairs that meet where a
/// simdgroup spans two rows (`RuntimeFact::RowLockstep`) runs without them, keeping its
/// threadgroup ones, and without the subgroup size they pinned (`LoweringInputs::one_row`).
/// A dispatch whose every region is one row asks for it (`BindingPlan::dispatch_variant`),
/// and the plan of a pipeline compiled under it states it and asks another dispatch for the
/// variant without it.
/// Every threadgroup of the dispatch is one row, so each of its simdgroups lies within the row:
/// a kernel whose lockstep simdgroup barriers order only pairs that meet where a simdgroup
/// spans two rows (`RuntimeFact::RowLockstep`) runs without them, keeping its threadgroup ones,
/// and without the subgroup size they pinned (`LoweringInputs::one_row`). A dispatch whose
/// every region is one row asks for it.
#[cfg_attr(feature = "serde", serde(default))]
pub one_row: bool,
/// The axes along which every threadgroup of the dispatch has one thread (bit 0 `x`, bit 1
/// `y`, bit 2 `z`): a kernel whose walk is predicated, where those axes' thread positions
/// alone make some of its synchronizations' blocks divergent (`RuntimeFact::UnitAxes`'s
/// `relief`), compiles with them uniform (`LoweringInputs::unit_axes`). The plan of a pipeline
/// compiled under it states it and asks a dispatch of more threads along such an axis for the
/// variant without it.
/// The axes along which every threadgroup of the dispatch has one thread (bit 0 `x`, bit 1 `y`,
/// bit 2 `z`): a kernel whose walk is predicated, where those axes' thread positions alone make
/// some of its synchronizations' blocks divergent (`RuntimeFact::UnitAxes`'s `relief`),
/// compiles with them uniform (`LoweringInputs::unit_axes`).
#[cfg_attr(feature = "serde", serde(default))]
pub unit_axes: u8,
/// Texture slots bound to an 8-bit sRGB texture the device cannot sample, which the runtime
/// holds as the format's UNORM twin (`metal::format::srgb_raw_twin`), whose views read the
/// codes (`c / 255`): every slot of a `RuntimeFact::SrgbTexture` the shape binds in such a
/// format (`metal::texel_format::srgb_twin_on`). The function decodes what it reads there
/// by the MSL transfer through the device's `Pow`, as the device would through an sRGB view
/// it lacks
/// (`LoweringInputs::srgb_textures`); a slot bound in an sRGB format the device samples reads
/// the device's decode and is no slot of this. The plan of a pipeline compiled under it
/// states it.
/// format (`metal::texel_format::srgb_twin_on`). The function decodes what it reads there by
/// the MSL transfer through the device's `Pow`, as the device would through an sRGB view it
/// lacks (`LoweringInputs::srgb_textures`); a slot bound in an sRGB format the device samples
/// reads the device's decode and is no slot of this.
#[cfg_attr(feature = "serde", serde(default))]
pub srgb_textures: BTreeSet<SlotRef>,
/// Texture slots whose function reads the two-plane YCbCr texture the shape binds there in
/// place: every slot of a `RuntimeFact::YCbCrInPlace` the shape binds a texture whose planes
/// are read so (`TextureShape::Texture::ycbcr_in_place`). Each such slot binds the planes'
/// texel buffer alone, and its accesses read the codes and convert them as Metal does
/// (`bind::YCbCrInPlace`). The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub ycbcr_in_place: BTreeSet<SlotRef>,
/// Slots of [`ycbcr_in_place`](Self::ycbcr_in_place) whose function's every sample the
/// device's own sampler Y′CbCr conversion takes, at which the shape binds a texture whose
/// planes are also held as an image it samples, each with that conversion
/// (`TextureShape::Texture::ycbcr_planes_sampler`, `RuntimeFact::YCbCrInPlace`'s `device`):
/// each such slot binds that image through an immutable sampler of the conversion, and its
/// samples are the device's (`bind::YCbCrPlanesSampler`). The plan of a pipeline compiled
/// under it states it.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub ycbcr_planes_sampled: BTreeMap<SlotRef, crate::bind::YCbCrPlanesSampler>,
/// Texture slots whose function only reads, writes or asks the size of the 2D texture the
/// shape binds there, whose rows are read and written in place: every slot of a
/// `RuntimeFact::TexelRows` the shape binds such a texture at
/// (`TextureShape::Texture::texel_rows`). Each such slot binds a texel buffer over the rows'
/// bytes alone (`bind::TexelRows`). The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub texel_rows: BTreeSet<SlotRef>,
/// Texture-buffer slots whose function reads it through its parts, each with the parts of the
/// texture buffer the shape binds there: every slot of a `RuntimeFact::TexelBufferParts` the
/// shape binds a texture buffer of more texels than one view holds at
/// (`TextureShape::Buffer::parts`). Each such slot binds an array of that many texel buffer
/// shape binds a texture buffer of more texels than one view holds at. Each such slot binds an array of that many texel buffer
/// views (`bind::texel_parts`). A texture buffer one view holds adds nothing, so its draws
/// keep their key. The plan of a pipeline compiled under it states it.
/// keep their key.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub texel_buffer_parts: BTreeMap<SlotRef, u32>,
/// Texture slots a constexpr sampler samples, each with the address-mode map of the texture
/// the shape binds there where it is not the identity: every slot of a
/// Texture slots a constexpr sampler samples, each with the address-mode map of the texture the
/// shape binds there where it is not the identity: every slot of a
/// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr
/// samplers sample the slot with their modes mapped; the plan of a pipeline compiled under it
/// states it. A texture of the identity map adds nothing, so ordinary draws keep their key.
/// samplers sample the slot with their modes mapped. A texture of the identity map adds
/// nothing, so ordinary draws keep their key.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
@@ -238,20 +200,18 @@ pub struct VariantKey {
/// The kernel runs its grid flat (`LoweringInputs::flat_grid`): one variant runs every grid
/// and threadgroup size of a kernel that does not observe its threadgroup partition
/// (`KernelFacts::partition_oblivious`), reading the grid from the region record at its
/// `PushField::ReplayRegionAddress`. The plan of a pipeline compiled under it states it.
/// `PushField::ReplayRegionAddress`.
#[cfg_attr(feature = "serde", serde(default))]
pub flat_grid: bool,
/// With [`flat_grid`](Self::flat_grid), its dispatch's threadgroups are the call's
/// (`LoweringInputs::call_threadgroups`): a one-row grid in threadgroups of one row, so a
/// kernel that observes its partition through its simdgroups alone
/// (`KernelFacts::partition_simdgroups`) runs flat too. The plan of a pipeline compiled under
/// it states it.
/// (`KernelFacts::partition_simdgroups`) runs flat too.
#[cfg_attr(feature = "serde", serde(default))]
pub call_threadgroups: bool,
/// The kernel, or the render pipeline's vertex and fragment functions, are a device-replay
/// variant (`LoweringInputs::replay_bindings`): every buffer they read is at its device
/// address in the slot table a replay's preprocess writes for its command; a compute plan of
/// it does not state the key. The runtime compiles a kernel's with `flat_grid` per pipeline state an execution of
/// address in the slot table a replay's preprocess writes for its command. The runtime compiles a kernel's with `flat_grid` per pipeline state an execution of
/// commands a kernel writes may name, to run it on the GPU alone; and a render pipeline's for
/// the state an execution of GPU-written draws inherits, its draws' buffers the records'.
#[cfg_attr(feature = "serde", serde(default))]
@@ -259,78 +219,73 @@ pub struct VariantKey {
/// With `replay_bindings`, the render pipeline's vertex and fragment functions run a draw
/// replay merged into one draw (`LoweringInputs::merged_draws`): the variant the runtime
/// compiles where an execution of GPU-written draws of one list type or points draws as one
/// draw. The plan of a pipeline compiled under it states it.
/// draw.
#[cfg_attr(feature = "serde", serde(default))]
pub merged_draws: bool,
/// The render pipeline draws each vertex amplification as a draw of its own
/// (`LoweringInputs::amplification_draws` for its vertex and fragment functions): the
/// variant a shape whose amplification Vulkan multiview cannot draw as Metal renders it asks
/// for (a `nil` mapping above a count of 1, layers out of order, apart or repeated, a
/// viewport offset, a stage that chooses or reads its slice, or more amplifications than
/// the device has views; `bind::graphics`). The plan of a pipeline compiled under it states
/// it.
/// (`LoweringInputs::amplification_draws` for its vertex and fragment functions): the variant a
/// shape whose amplification Vulkan multiview cannot draw as Metal renders it asks for (a `nil`
/// mapping above a count of 1, layers out of order, apart or repeated, a viewport offset, a
/// stage that chooses or reads its slice, or more amplifications than the device has views;
/// `bind::graphics`).
#[cfg_attr(feature = "serde", serde(default))]
pub amplification_draws: Option<crate::pipeline::AmplificationDraws>,
/// The kernel folds Metal's group counts into one dispatch within the device's limits
/// (`LoweringInputs::folded_groups`): the variant a threadgroup dispatch whose group counts
/// are GPU data runs on, for a kernel that observes its threadgroup partition, reading its
/// group counts and every grid builtin's region from the region record at its
/// `PushField::ReplayRegionAddress`. The plan of a pipeline compiled under it states it.
/// `PushField::ReplayRegionAddress`.
#[cfg_attr(feature = "serde", serde(default))]
pub folded_groups: bool,
/// The kernel runs a ragged `dispatchThreads` grid in the threadgroups its threads fill, at
/// the call's threadgroup size, the last along an axis Metal's partial threadgroup
/// The kernel runs a ragged `dispatchThreads` grid in the threadgroups its threads fill, at the
/// call's threadgroup size, the last along an axis Metal's partial threadgroup
/// (`LoweringInputs::partial_threadgroups`): the variant such a dispatch of a kernel that
/// observes its threadgroup partition runs on, one `VkPipeline` of the call's size in place of
/// an edge region's of each remainder. The plan of a pipeline compiled under it states it,
/// and plans such a dispatch so (`BindingPlan::instantiate_dispatch`).
/// an edge region's of each remainder.
#[cfg_attr(feature = "serde", serde(default))]
pub partial_threadgroups: bool,
/// Texture slots bound in one of Apple's extended-range formats, by the format
/// (`LoweringInputs::extended_range`): the function reads and writes the bound texture's raw
/// texels there, decoding and encoding Metal's values. The plan of a pipeline compiled under
/// it states it.
/// texels there, decoding and encoding Metal's values.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub extended_range: BTreeMap<SlotRef, crate::metal::format::ExtendedRange>,
/// Color attachments of the pass the render pipeline has no pixel format for, the pass's
/// pixel format of each by color index (`BindShape::zeroed_colors`): plain Metal stores zero
/// pixel format of each by color index: plain Metal stores zero
/// bytes into each at every sample a draw covers. The variant's pipeline has each attachment
/// in that format, written whole and unblended, and its fragment function writes zero to it
/// (`LoweringInputs::zeroed_colors`). The plan of a pipeline compiled under it states it.
/// (`LoweringInputs::zeroed_colors`).
#[cfg_attr(feature = "serde", serde(default))]
pub zeroed_colors: BTreeMap<u32, crate::metal::PixelFormat>,
/// Color attachments the render pipeline has a pixel format for and the pass has none, by
/// color index (`BindShape::dropped_colors`): plain Metal drops the fragment function's
/// color index: plain Metal drops the fragment function's
/// writes there. The variant's fragment function keeps no output at each
/// (`LoweringInputs::dropped_colors`). The plan of a pipeline compiled under it states it.
/// (`LoweringInputs::dropped_colors`).
#[cfg_attr(feature = "serde", serde(default))]
pub dropped_colors: BTreeSet<u32>,
/// The bytes of each cell of a tile function's explicit imageblock standing alone that the
/// render pass keeps, fewer than the cell holds (`BindShape::kept_imageblock_bytes`): plain
/// render pass keeps, fewer than the cell holds: plain
/// Metal reads the block's other words as zero and drops their writes. The variant's
/// function does (`LoweringInputs::kept_imageblock_bytes`). The plan of a tile function with
/// such an imageblock states it.
/// function does (`LoweringInputs::kept_imageblock_bytes`).
#[cfg_attr(feature = "serde", serde(default))]
pub kept_imageblock_bytes: Option<u32>,
/// The fragment function clamps the depth it writes to the draw's depth clamp range itself
/// (`BindShape::depth_clamp_range`, `LoweringInputs::depth_clamp_range`): the variant a draw
/// (`LoweringInputs::depth_clamp_range`): the variant a draw
/// in depth clamp mode through a range above 0 runs, where Metal stores a negative NaN as 0.
/// The plan of a pipeline compiled under it states it.
///
#[cfg_attr(feature = "serde", serde(default))]
pub depth_clamp_range: bool,
/// The fragment function's triangles are drawn with Metal's last vertex first
/// (`BindShape::rotated_weights`, `LoweringInputs::rotated_weights`): the variant a listed
/// (`LoweringInputs::rotated_weights`): the variant a listed
/// triangle draw under Apple's last provoking vertex runs, whose `[[barycentric_coord]]` reads
/// take Metal's weights back from the drawn triangle's. The plan of a pipeline compiled under
/// it states it.
/// take Metal's weights back from the drawn triangle's.
#[cfg_attr(feature = "serde", serde(default))]
pub rotated_weights: bool,
/// The pipeline draws its lines, or its triangles' edges, as bands of triangles through
/// synthesized tessellation stages, each patch one primitive of this kind
/// (`BindShape::line_band`, `pipeline::link::band`): the variant a draw of lines, or of
/// (`pipeline::link::band`): the variant a draw of lines, or of
/// triangles in fill mode `Lines`, at an Apple `setLineWidth:` width the device's own lines do
/// not draw runs. Its graphics state states it (`GraphicsState::line_band`).
#[cfg_attr(feature = "serde", serde(default))]
@@ -340,60 +295,55 @@ pub struct VariantKey {
/// (`LoweringInputs::swizzled_storage`): a Vulkan storage view takes no swizzle, so the
/// function applies the bound texture's swizzle to its reads and undoes it on its writes, as
/// plain Metal does, under the slot's `SpecKey::TextureSwizzle`, and the slot's storage view
/// takes none (`ImageViewDesc::shader_swizzle`). The plan of a pipeline compiled under it
/// states it. It holds too each sampled slot of `extended_range` bound to such a texture whose
/// texels the function reads or samples: its view holds raw codes, so the function swizzles the
/// decoded texels and the view takes none. So does, on a device without Metal's own sampler,
/// each sampled slot bound to a swizzled packed normalized texture, whose texels the function
/// converts by each channel's own scale before it swizzles them.
/// takes none. It holds too each sampled slot of
/// `extended_range` bound to such a texture whose texels the function reads or samples: its
/// view holds raw codes, so the function swizzles the decoded texels and the view takes none.
/// So does, on a device without Metal's own sampler, each sampled slot bound to a swizzled
/// packed normalized texture, whose texels the function converts by each channel's own scale
/// before it swizzles them.
#[cfg_attr(feature = "serde", serde(default))]
pub swizzled_storage: BTreeSet<SlotRef>,
/// Every function that reads visible-function tables by their resource ids reads their
/// words through their device addresses (`LoweringInputs::addressed_function_tables`): the
/// variant a shape whose listed tables may pass `maxStorageBufferRange` asks for
/// (`FunctionTablesShape::bytes_class`). The plan of a pipeline compiled under it states it.
/// (`FunctionTablesShape::bytes_class`).
#[cfg_attr(feature = "serde", serde(default))]
pub addressed_function_tables: bool,
/// The runtime sampler slots of a `RuntimeFact::CubicSampler` that the shape binds to a
/// sampler whose min or mag filter is `Cubic`, each with the bound word masked by
/// The runtime sampler slots of a `RuntimeFact::CubicSampler` that the shape binds to a sampler
/// whose min or mag filter is `Cubic`, each with the bound word masked by
/// `SamplerWord::CUBIC_STATE` (`LoweringInputs::cubic_samplers`): the variant whose function
/// samples through each with Metal's bicubic filter of that state. The plan of a pipeline
/// compiled under it states it.
/// samples through each with Metal's bicubic filter of that state.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub cubic_samplers: BTreeMap<SlotRef, u32>,
/// The de-indexed form of a pipeline whose vertex function writes the primitive ID's varying
/// (`LoweringInputs::primitive_id_indices`, `BindShape::primitive_id_indices`): the vertex
/// (`LoweringInputs::primitive_id_indices`): the vertex
/// function of an indexed draw of this index type runs the draw's indices as `index count`
/// vertices from 0, read at the draw's index address, so each primitive's stream position
/// names it. The runtime asks for it for an indexed draw of such a pipeline, and the plan of
/// a pipeline compiled under it states it.
/// vertices from 0, read at the draw's index address, so each primitive's stream position names
/// it. The runtime asks for it for an indexed draw of such a pipeline.
#[cfg_attr(feature = "serde", serde(default))]
pub primitive_id_indices: Option<crate::metal::IndexType>,
/// A draw of Metal's private quads or quad strip, listed as two triangles a quad, of a
/// pipeline whose fragment function reads Vulkan's `PrimitiveId` (`BindShape::
/// quad_primitive_ids`): the variant's fragment function reads `[[primitive_id]]` as that
/// pipeline whose fragment function reads Vulkan's `PrimitiveId`: the variant's fragment function reads `[[primitive_id]]` as that
/// value shifted right by one, the quad's (`LoweringInputs::quad_primitive_ids`). The runtime
/// asks for it for such a draw, and the plan of a pipeline compiled under it states it
/// (`RuntimeFact::QuadPrimitiveIds`).
/// asks for it for such a draw (`RuntimeFact::QuadPrimitiveIds`).
#[cfg_attr(feature = "serde", serde(default))]
pub quad_primitive_ids: bool,
/// A draw of one of Metal's private primitive types drawn in the pulled list form
/// (`BindShape::private_list`): the variant's vertex function runs each position of the
///: the variant's vertex function runs each position of the
/// consumer's list once, without indices, reading its index and Metal's base vertex at the
/// list's address (`LoweringInputs::private_list`). The runtime asks for it for such a draw
/// whose vertex function writes memory or the primitive ID's varying, or whose vertex start
/// a list's base vertex cannot carry, and the plan of a pipeline compiled under it states it
/// (`RuntimeFact::PrivateList`).
/// a list's base vertex cannot carry (`RuntimeFact::PrivateList`).
#[cfg_attr(feature = "serde", serde(default))]
pub private_list: bool,
/// Sampled texture slots whose compile states `RuntimeFact::CrossClassReads` bound to a
/// texture of a color format whose numeric class is not the slot's declared one, by the
/// bound format's class (`LoweringInputs::cross_class`): the variant's function reads,
/// samples and gathers the texture in its own class and hands back its words as the declared
/// type, as plain Metal does. The plan of a pipeline compiled under it states it.
/// type, as plain Metal does.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
@@ -402,21 +352,19 @@ pub struct VariantKey {
/// The runtime sampler slots of a `RuntimeFact::AnisotropicSampler` that the shape binds to a
/// sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`,
/// `LoweringInputs::anisotropic_samplers`): the variant whose function takes Metal's
/// anisotropic filter, emulated, at each one's samples. The plan of a pipeline compiled under
/// it states it.
/// anisotropic filter, emulated, at each one's samples.
#[cfg_attr(feature = "serde", serde(default))]
pub anisotropic_samplers: BTreeSet<SlotRef>,
/// The texture slots of a kernel of OpenCL mode whose `RuntimeFact::OpenClLineTexture` (a 1D
/// image it reads as the 2D texture of height 1 Apple's OpenCL binds) the shape binds a 1D or
/// 1D array texture at (`LoweringInputs::open_cl_lines`): the variant's kernel declares each
/// as that 1D texture and reads it. The plan of a pipeline compiled under it states it.
/// as that 1D texture and reads it.
#[cfg_attr(feature = "serde", serde(default))]
pub open_cl_lines: BTreeSet<SlotRef>,
/// The render pipeline draws a rasterization-rate-mapped pass's regions several at a time,
/// each one draw of a multi-draw whose index selects its viewport and scissor
/// (`BindShape::region_viewports`): its vertex function stores `ViewportIndex` as `DrawIndex`
/// (`LoweringInputs::region_viewports`). The plan of a pipeline compiled under it states it
/// (`RuntimeFact::RegionViewports`).
/// each one draw of a multi-draw whose index selects its viewport and scissor: its vertex
/// function stores `ViewportIndex` as `DrawIndex`
/// (`LoweringInputs::region_viewports`, `RuntimeFact::RegionViewports`).
#[cfg_attr(feature = "serde", serde(default))]
pub region_viewports: bool,
}
@@ -427,64 +375,6 @@ impl VariantKey {
VariantKey::default()
}
/// This key in the large-buffer form, for a pipeline of `dependencies` bound as `shape`: with
/// every slot a large buffer would move to its device address ([`psb_slots`](Self::psb_slots):
/// a `RuntimeFact::BufferRangeLimit` the pipeline honours by a variant) at its device address
/// whatever buffer is bound there, but those `shape` binds without one (inline bytes, or a
/// buffer without a device address). A pipeline of this key runs a dispatch or draw of any
/// buffer lengths at those slots ([`covers`](Self::covers)), so one compiled before the buffers
/// are known (an indirect command the GPU may write) is the one that runs. Every access inside
/// a slot's window reads and writes as in the form the bound buffers ask for; outside it, the
/// slot has a large buffer's containment. On a device without device addresses the fact is a
/// plan-time check, and the key is unchanged.
pub fn large_buffer_form(
&self,
dependencies: &[crate::pipeline::RuntimeDependency],
shape: &crate::bind::BindShape,
) -> VariantKey {
use crate::bind::BufferShape;
use crate::pipeline::{Mechanism, RuntimeFact};
let addressless = |slot: &SlotRef| {
let bound = shape
.stages
.get(&slot.stage)
.and_then(|stage| stage.buffers.get(&slot.index));
matches!(
bound,
Some(
BufferShape::Bytes { .. }
| BufferShape::Buffer {
device_address: false,
..
}
)
)
};
let mut out = self.clone();
out.psb_slots.extend(
dependencies
.iter()
.filter_map(|dependency| match dependency.fact {
RuntimeFact::BufferRangeLimit { slot }
if dependency.mechanism == Mechanism::Variant && !addressless(&slot) =>
{
Some(slot)
}
_ => None,
}),
);
out
}
/// Whether a pipeline compiled under this key runs a dispatch or draw whose plan settles on
/// `settled`: the same key but for device-address slots this one adds, as
/// [`large_buffer_form`](Self::large_buffer_form) adds them.
pub fn covers(&self, settled: &VariantKey) -> bool {
let mut widened = settled.clone();
widened.psb_slots.extend(self.psb_slots.iter().copied());
widened == *self
}
/// Whether nothing needs a variant (the common path).
pub fn is_empty(&self) -> bool {
self.storage_images.is_empty()
@@ -494,9 +384,6 @@ impl VariantKey {
&& !self.one_row
&& self.unit_axes == 0
&& self.srgb_textures.is_empty()
&& self.ycbcr_in_place.is_empty()
&& self.ycbcr_planes_sampled.is_empty()
&& self.texel_rows.is_empty()
&& self.texel_buffer_parts.is_empty()
&& self.address_maps.is_empty()
&& !self.flat_grid
@@ -593,24 +480,6 @@ impl VariantKey {
.filter(|s| s.stage == stage)
.copied()
.collect();
out.ycbcr_in_place = self
.ycbcr_in_place
.iter()
.filter(|s| s.stage == stage)
.copied()
.collect();
out.ycbcr_planes_sampled = self
.ycbcr_planes_sampled
.iter()
.filter(|(s, _)| s.stage == stage)
.map(|(s, sampler)| (*s, *sampler))
.collect();
out.texel_rows = self
.texel_rows
.iter()
.filter(|s| s.stage == stage)
.copied()
.collect();
out.texel_buffer_parts = self
.texel_buffer_parts
.iter()
+1 -521
View File
@@ -708,8 +708,7 @@ fn the_version_535_member_round_trips() {
/// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and
/// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and
/// `CombinedSampler`, `RuntimeFact::SrgbTexture` and
/// `SrgbTexture`, and `PrecisionNote::HalfTexelConversion`,
/// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`,
/// `SrgbTexture`, `PrecisionNote::HalfTexelConversion` and `SrgbTexelDecode`,
/// `HandleClass::Sampler { compare, integer }` and
/// `SyntheticBinding::SamplerTable`, each beside the others rather than only on its own side's
/// fixtures.
@@ -733,9 +732,7 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
let notes = [
PrecisionNote::CubeGradientFootprint,
PrecisionNote::HalfTexelConversion,
PrecisionNote::HalfSampleFilter,
PrecisionNote::SrgbTexelDecode,
PrecisionNote::FloatSampleFilter,
];
let dev = device("moltenvk-m3");
let Some(bc) = fixture("stage_io") else {
@@ -872,298 +869,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
);
}
/// The emulated-simdgroups variant of a kernel moltenvk-m3 runs on whole subgroups round trips as a
/// function and as a pipeline, and the decoded pipeline's plan states the variant, so a cached
/// variant settles as the compiled one does.
#[test]
fn the_emulated_simdgroups_variant_round_trips() {
use crate::bind::BindShape;
use crate::cache::VariantKey;
use crate::pipeline::facts::RuntimeFact;
let dev = device("moltenvk-m3");
let Some(bc) = fixture("simd_ops") else {
return;
};
let f = Library::from_air(&bc)
.and_then(|lib| lib.function("simd_sum_k"))
.expect("kernel");
let mut key = VariantKey::new();
key.emulated_simdgroups = true;
let compiled = dev
.compile_function(
&FunctionDescriptor::new(f),
&key.lowering_inputs(Stage::Kernel),
&Budget::standard(),
)
.expect("variant");
assert!(compiled
.artifact()
.facts
.contains(&RuntimeFact::EmulatedSimdgroups));
assert_eq!(
CompiledFunction::from_bytes(&compiled.to_bytes(), &dev),
Ok(compiled.clone())
);
let pipeline = dev
.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
&Budget::standard(),
)
.expect("pipeline");
let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, pipeline);
let plan = decoded.plan(&dev, &BindShape::default()).expect("plan");
assert_eq!(plan.variant, key);
}
/// The `SrgbTexture` fact round trips, and a kernel compiled under the `SrgbTexture` variant (a
/// slot bound to an 8-bit sRGB format the device holds as its UNORM twin) round trips as a
/// function and as a pipeline, whose decoded plan for a shape binding such a texture at the slot
/// states the variant, so a cached variant settles as the compiled one does; a shape binding an
/// sRGB format the device samples states none.
#[test]
fn the_srgb_texture_variant_round_trips() {
use crate::bind::{BindState, BoundTexture, StageTable, TextureFacts};
use crate::cache::VariantKey;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::facts::RuntimeFact;
let slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 2,
};
let fact = RuntimeFact::SrgbTexture { slot };
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
let note = PrecisionNote::SrgbTexelDecode;
assert_eq!(decode::<PrecisionNote>(&encode(&note)), Ok(note));
let dev = device("lavapipe");
let Some(bc) = fixture("texture_ops") else {
return;
};
let f = Library::from_air(&bc)
.and_then(|lib| lib.function("short_texels"))
.expect("kernel");
let mut key = VariantKey::new();
key.srgb_textures.insert(slot);
let compiled = dev
.compile_function(
&FunctionDescriptor::new(f),
&key.lowering_inputs(Stage::Kernel),
&Budget::standard(),
)
.expect("variant");
assert!(compiled
.artifact()
.facts
.contains(&RuntimeFact::SrgbTexture { slot }));
assert_eq!(
CompiledFunction::from_bytes(&compiled.to_bytes(), &dev),
Ok(compiled.clone())
);
let pipeline = dev
.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
&Budget::standard(),
)
.expect("pipeline");
let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, pipeline);
let mut table = StageTable::default();
// lavapipe samples no `RG8Unorm_sRGB`, which the runtime holds as `RG8Unorm`, and samples
// `RGBA8Unorm_sRGB` itself.
for (pf, twin) in [
(metal::PixelFormat::RG8UnormSRGB, true),
(metal::PixelFormat::RGBA8UnormSRGB, false),
] {
let mut facts = TextureFacts::new(metal::TextureType::Type3D, pf);
facts.usage = metal::TextureUsage::SHADER_READ;
table.textures.insert(
2,
BoundTexture::Texture {
facts,
resource_id: None,
},
);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table.clone());
let plan = decoded.plan(&dev, &state.shape()).expect("plan");
match twin {
true => assert_eq!(plan.variant.srgb_textures, key.srgb_textures, "{pf:?}"),
false => assert!(plan.variant.srgb_textures.is_empty(), "{pf:?}"),
}
}
}
/// The `CubicSampler` fact round trips, and a kernel compiled under the cubic-sampler variant round
/// trips as a function and as a pipeline, whose decoded plan for a shape binding a sampler with a
/// `Cubic` filter at the slot states the variant (the bound word's `SamplerWord::CUBIC_STATE`
/// bits), so a cached variant settles as the compiled one does. A nearest sampler at the slot
/// states none; every sample through the slot states the fact, with the variant or without it.
#[test]
fn the_cubic_sampler_variant_round_trips() {
use crate::bind::{
BindState, BoundSampler, BoundTexture, SamplerDescriptor, StageTable, TextureFacts,
};
use crate::cache::VariantKey;
use crate::metal::sampler::SamplerWord;
use crate::pipeline::facts::RuntimeFact;
let slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Sampler,
index: 0,
};
let fact = RuntimeFact::CubicSampler { slot };
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
let dev = device("lavapipe");
let Some(bc) = fixture("gsm2_cubic_samplers") else {
return;
};
let function = || {
Library::from_air(&bc)
.and_then(|lib| lib.function("gsm2_cubic_samples"))
.expect("kernel")
};
let plain = dev
.compile_function(
&FunctionDescriptor::new(function()),
&LoweringInputs::new(),
&Budget::standard(),
)
.expect("plain");
assert!(plain.artifact().facts.contains(&fact));
let mut cubic = SamplerDescriptor::new();
cubic.min_filter = metal::SamplerMinMagFilter::Cubic;
cubic.mag_filter = metal::SamplerMinMagFilter::Linear;
cubic.s_address_mode = metal::SamplerAddressMode::Repeat;
cubic.t_address_mode = metal::SamplerAddressMode::ClampToBorderColor;
cubic.border_color = metal::SamplerBorderColor::OpaqueWhite;
let mut key = VariantKey::new();
key.cubic_samplers
.insert(slot, SamplerWord::of(&cubic).0 & SamplerWord::CUBIC_STATE);
let compiled = dev
.compile_function(
&FunctionDescriptor::new(function()),
&key.lowering_inputs(Stage::Kernel),
&Budget::standard(),
)
.expect("variant");
assert!(compiled.artifact().facts.contains(&fact));
assert_eq!(
CompiledFunction::from_bytes(&compiled.to_bytes(), &dev),
Ok(compiled.clone())
);
let pipeline = dev
.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
&Budget::standard(),
)
.expect("pipeline");
let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, pipeline);
let shape = |desc: SamplerDescriptor| {
let mut table = StageTable::default();
let mut facts =
TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm);
facts.usage = metal::TextureUsage::SHADER_READ;
table.textures.insert(
0,
BoundTexture::Texture {
facts,
resource_id: None,
},
);
table.samplers.insert(
0,
BoundSampler {
desc,
resource_id: None,
},
);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
state.shape()
};
let plan = decoded.plan(&dev, &shape(cubic)).expect("plan");
assert_eq!(plan.variant.cubic_samplers, key.cubic_samplers);
let plan = decoded
.plan(&dev, &shape(SamplerDescriptor::new()))
.expect("plan");
assert!(plan.variant.cubic_samplers.is_empty());
}
/// A render pipeline compiled under the amplification draws variant round trips with its fact and
/// its amplification push fields, and the decoded pipeline's plan for a state whose amplification
/// multiview cannot express states the variant, so a cached variant settles as the compiled one
/// does.
#[test]
fn the_amplification_draws_variant_round_trips() {
use crate::bind::{BindState, VertexAmplification, ViewMapping};
use crate::cache::VariantKey;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::PushField;
use crate::pipeline::AmplificationDraws;
let dev = device("nvidia-rtx50-linux");
let Some(bc) = fixture("vertex_amplification") else {
return;
};
let lib = Library::from_air(&bc).expect("library");
let stage = |name: &str| {
StageSource::Function(FunctionDescriptor::new(
lib.function(name).expect("function"),
))
};
let mut d = RenderPipelineDescriptor::new(stage("amp_vertex"));
d.fragment = Some(stage("amp_fragment"));
d.max_vertex_amplification_count = 2;
let mut key = VariantKey::new();
key.amplification_draws = Some(AmplificationDraws::new(true, true));
let pipeline = dev
.compile_render_variant(&d, &key, &Budget::standard())
.expect("pipeline");
let decoded = RenderPipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, pipeline);
assert!(decoded.dependencies.iter().any(|d| d.fact
== RuntimeFact::AmplificationDraws {
layered: true,
viewports: true
}));
for field in [
PushField::AmplificationId,
PushField::AmplificationLayerOffset,
PushField::AmplificationViewportOffset,
] {
assert!(
decoded
.interface
.push
.iter()
.any(|p| p.fields.iter().any(|f| f.field == field)),
"{field:?}"
);
}
let state = BindState {
render_target_array_length: 2,
vertex_amplification: VertexAmplification::new(
2,
vec![
ViewMapping {
viewport_array_index_offset: 1,
render_target_array_index_offset: 1,
},
ViewMapping {
viewport_array_index_offset: 0,
render_target_array_index_offset: 0,
},
],
),
..Default::default()
};
let plan = decoded.plan(&dev, &state.shape()).expect("plan");
assert_eq!(plan.variant, key);
}
/// A kernel compiled under the storage-view variant round trips with its uniform-view facts (kept,
/// viewed, spare, and the alias check), and the decoded pipeline's plan for a shape that binds a
/// large buffer at the kept slot states the variant, so a cached variant settles as the compiled
@@ -1571,231 +1276,6 @@ fn a_content_digest_is_the_content_not_the_key() {
assert_ne!(edited.content_digest(), digest);
}
/// A pipeline state's creation compile on a device that reads storage textures only with a declared
/// format takes stand-ins (`runtime::pipeline::stand_in`: the first of `R32Float`, `R32Uint` and
/// `R32Sint` each slot's texels take). On ANV on Iris Xe (RPL-P), the compile of
/// `a2_storage_read_formats` (a float, a uint and an int `read_write` texture, read) under those
/// stand-ins is the compile of the bind of those formats: its plan for that bind names its own key,
/// and the bind's compile has the same function and pipeline cache keys (what the disk cache stores
/// and loads them under) and byte-identical artifacts, so the compile carries nothing of the
/// stand-in beyond its key. Every bind of another format at any of the slots plans another key,
/// except where the plan does not bind that texture at all: a texture the slot cannot take is
/// replaced by the slot's neutral (`IncompatibleBinding`, `CrossClassNeutral` for a storage read
/// of another numeric class, or `AstcStorageNeutral` for an ASTC texture), an `R32` texture of the
/// slot's texel type, whose compile is the stand-in's.
#[test]
fn a_stand_in_compile_is_the_compile_of_its_formats_bind_and_no_other() {
use crate::bind::{BindState, BoundTexture, PlanDiagnostic, StageTable, TextureFacts};
use crate::cache::VariantKey;
use crate::error::{Error, RuntimeInput};
use crate::metal::format::storage_image_choice;
use crate::metal::{PixelFormat, TextureType, TextureUsage};
let Some(bc) = fixture("a2_storage_read_formats") else {
return;
};
let dev = device("intel-irisxe-rplp-anv");
let profile = dev.profile();
assert!(!profile.fields().images.storage_read_without_format);
let descriptor = FunctionDescriptor::new(
Library::from_air(&bc)
.and_then(|lib| lib.function("a2_storage_read_formats"))
.expect("kernel"),
);
let budget = Budget::standard();
// The runtime's compile of a variant (`Variant::compiled`, without the cache).
let compile = |key: &VariantKey| -> Result<(CompiledFunction, ComputePipeline), Error> {
let inputs = key.lowering_inputs(Stage::Kernel);
let function = dev.compile_function(&descriptor, &inputs, &budget)?;
assert_eq!(
*function.key(),
dev.function_compile_key(&descriptor, &inputs)
);
let pipeline = dev.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(function.clone())),
&budget,
)?;
Ok((function, pipeline))
};
let slot = |index: u32| SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
};
assert!(matches!(
compile(&VariantKey::new()),
Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat { .. }))
));
let formats = [
(0, PixelFormat::R32Float),
(1, PixelFormat::R32Uint),
(2, PixelFormat::R32Sint),
];
let mut stand_in_key = VariantKey::new();
for (index, pf) in formats {
let choice = storage_image_choice(pf, profile).expect("a stand-in's choice");
stand_in_key.storage_images.insert(slot(index), choice);
}
let (stand_in_function, stand_in) = compile(&stand_in_key).expect("the stand-in compile");
// The plan of a bind of `bound`, as the runtime's `settle` reads it off the creation compile.
let planned = |bound: &[(u32, PixelFormat)]| {
let mut table = StageTable::default();
for &(index, pf) in bound {
let mut facts = TextureFacts::new(TextureType::Type2D, pf);
facts.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
let texture = BoundTexture::Texture {
facts,
resource_id: None,
};
table.textures.insert(index, texture);
}
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
stand_in.plan(&dev, &state.shape())
};
let own = planned(&formats).expect("the stand-ins' bind plans");
assert!(own.diagnostics.is_empty(), "{:?}", own.diagnostics);
assert_eq!(own.variant, stand_in_key);
let (own_function, own_pipeline) = compile(&own.variant).expect("the bind's compile");
assert_eq!(own_function.key(), stand_in_function.key());
assert_eq!(own_pipeline.key(), stand_in.key());
assert_eq!(own_function.to_bytes(), stand_in_function.to_bytes());
assert_eq!(own_pipeline.to_bytes(), stand_in.to_bytes());
// Any other format a texture can have, at any slot: another key, or the slot's neutral.
let (mut other_keys, mut replaced) = (0, 0);
let mut same = Vec::new();
for at in 0..formats.len() {
for &pf in metal::PixelFormat::ALL {
if pf == formats[at].1 || pf == PixelFormat::Invalid {
continue;
}
let mut bound = formats;
bound[at].1 = pf;
let Ok(plan) = planned(&bound) else {
continue;
};
let neutral = plan.diagnostics.iter().any(|d| match d {
PlanDiagnostic::IncompatibleBinding { slot: s, .. }
| PlanDiagnostic::CrossClassNeutral { slot: s, .. }
| PlanDiagnostic::AstcStorageNeutral { slot: s, .. } => *s == slot(bound[at].0),
_ => false,
});
if neutral {
replaced += 1;
} else if plan.variant == stand_in_key {
same.push((at, pf));
} else {
other_keys += 1;
}
}
}
assert!(
same.is_empty(),
"binds that plan the stand-ins' key: {same:?}"
);
// An ASTC texture, of every profile and footprint, at a storage slot: the slot's neutral, and
// the plan says why (`PlanDiagnostic::AstcStorageNeutral`), which the runtime announces.
let astc = metal::PixelFormat::ALL
.iter()
.filter(|&&pf| crate::bind::AstcDecode::of(pf).is_some());
for &pf in astc {
let mut bound = formats;
bound[0].1 = pf;
let plan = planned(&bound).unwrap_or_else(|e| panic!("{pf:?}: {e}"));
let said = plan.diagnostics.iter().any(
|d| matches!(d, PlanDiagnostic::AstcStorageNeutral { slot: s, .. } if *s == slot(0)),
);
assert!(said, "{pf:?}: {:?}", plan.diagnostics);
}
assert!(other_keys > 0, "no other format plans");
eprintln!(
"{other_keys} binds of other formats plan other keys; {replaced} are replaced by the \
slot's neutral"
);
}
/// Kernel buffer slot `index`.
fn kernel_buffer(index: u32) -> SlotRef {
SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index,
}
}
/// A variant key with device-address kernel buffer slots `slots`.
fn addressed(slots: &[u32]) -> super::VariantKey {
let mut key = super::VariantKey::new();
key.psb_slots = slots.iter().copied().map(kernel_buffer).collect();
key
}
/// The large-buffer form's variant runs every dispatch or draw whose plan asks for fewer
/// device-address slots, and no other variant's.
#[test]
fn the_large_buffer_variant_covers_plans_of_fewer_device_address_slots() {
let large = addressed(&[0, 3]);
assert!(large.covers(&large));
assert!(large.covers(&addressed(&[3])));
assert!(large.covers(&super::VariantKey::new()));
assert!(!large.covers(&addressed(&[1])));
assert!(!addressed(&[3]).covers(&large));
let mut emulated = addressed(&[3]);
emulated.emulated_simdgroups = true;
assert!(!large.covers(&emulated));
}
/// The large-buffer form moves every slot whose range a large buffer exceeds to its device address,
/// unless the shape binds it without one (bytes), keeping what the key held; on a device without
/// device addresses (the fact a plan-time check) it moves none, so a variant still follows the
/// bound buffers there.
#[test]
fn the_large_buffer_form_moves_the_range_limited_slots_to_device_addresses() {
use crate::bind::{BindShape, BufferShape, StageShape};
use crate::pipeline::{Mechanism, RuntimeDependency, RuntimeFact};
let limited = |index, mechanism| {
let slot = kernel_buffer(index);
RuntimeDependency::new(RuntimeFact::BufferRangeLimit { slot }, mechanism)
};
let addressed_device = [
limited(0, Mechanism::Variant),
limited(2, Mechanism::Variant),
RuntimeDependency::new(
RuntimeFact::ThreadsPerThreadgroup,
Mechanism::Specialization,
),
];
let unbound = BindShape::default();
let empty = super::VariantKey::new();
assert_eq!(
empty.large_buffer_form(&addressed_device, &unbound),
addressed(&[0, 2])
);
let mut stage = StageShape::default();
stage.buffers.insert(
2,
BufferShape::Bytes {
attribute_stride: None,
},
);
let mut bytes = BindShape::default();
bytes.stages.insert(Stage::Kernel, stage);
assert_eq!(
empty.large_buffer_form(&addressed_device, &bytes),
addressed(&[0])
);
let mut emulated = addressed(&[5]);
emulated.emulated_simdgroups = true;
let mut widened = addressed(&[0, 5]);
widened.emulated_simdgroups = true;
assert_eq!(
emulated.large_buffer_form(&addressed_device, &bytes),
widened
);
let floor_device = [limited(0, Mechanism::PlanTimeCheck)];
assert_eq!(empty.large_buffer_form(&floor_device, &unbound), empty);
}
/// A render descriptor's linked-use answers and reflection decode as they were encoded, under
/// their descriptor key on the device they were encoded for; another key or profile is
/// `WrongDevice`, another kind of frame `Corrupt`, a changed byte `Corrupt`.
+1 -2
View File
@@ -71,8 +71,7 @@ impl Device {
/// coverage and the tessellator orders triangles as the device does (each module records its
/// static note, `PrecisionNote::ClippedCoverageSplit` and
/// `PrecisionNote::TessellationTriangleOrder`), `InterpolateAtOffset` reads from the pixel's center as GLSL.std.450 states, and a thread's
/// Function storage is the 16 KiB floor. A two-plane YCbCr texture's planes are read in place
/// on every device, whatever its type. Every stage output is 32-bit: a `half` color output
/// Function storage is the 16 KiB floor. Every stage output is 32-bit: a `half` color output
/// reaches the device widened to `float`, whatever `storageInputOutput16` says.
pub fn from_queries(desc: DeviceDescription, policy: DevicePolicy) -> Result<Device, Error> {
if desc.api_version < ApiVersion::V1_2 {
@@ -166,11 +166,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
// The runtime pushes its arena's address, and sizes and orders the arena's slots by the
// slot's bytes.
RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant,
// Keyed by the slots bound to a texture whose planes are read in place, on a profile that
// reads them so (`ProfileFields::ycbcr_in_place`).
RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant,
// Keyed by the slots bound to a texture whose rows are read and written in place.
RuntimeFact::TexelRows { .. } => Mechanism::Variant,
// Keyed by the slots bound to a texture buffer of more texels than one view holds.
RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant,
// The runtime refuses a dispatch whose slot address is not a multiple of the alignment.
+4 -31
View File
@@ -359,14 +359,9 @@ pub struct ProfileFields {
pub dynamic_vertex_stride: bool,
/// The enabled capability sets `Requirements` are checked against.
pub enabled: EnabledCaps,
/// Whether a two-plane YCbCr texture's planes may be read in place
/// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between
/// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a
/// texture only as the in-place form reads records `RuntimeFact::YCbCrInPlace`, and the
/// consumer states the planes of each texture it holds so. A discrete, virtual or other
/// device, or one of no stated type, keeps every such texture's image of converted texels,
/// which its refresh reads across the bus once per encoder where the in-place form would read
/// the planes there at every pass. Both forms read Metal's texels exactly.
/// Whether a two-plane YCbCr texture's planes may be read in place: true on every device
/// (`device::derive`). No lowering reads it; it is part of the profile's fingerprint, the
/// `Debug` text of these fields, which stored observations name.
pub ycbcr_in_place: bool,
/// The Function storage a thread holds correctly (`device::function_storage`): a stage's
/// private memory, its call stacks included, may take this much a thread
@@ -855,26 +850,4 @@ pub struct FormatTable {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::device::requirements::Requirements;
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::spirv::ids::{BlockId, DemoteTy, Value, VarId};
/// Vocabulary shared across threads by the consumer's worker pool.
#[test]
fn vocabulary_is_send_and_sync() {
fn send_sync<T: Send + Sync>() {}
send_sync::<DeviceProfile>();
send_sync::<ProfileFields>();
send_sync::<Requirements>();
send_sync::<RuntimeFact>();
send_sync::<Mechanism>();
send_sync::<DemoteTy>();
send_sync::<Value>();
send_sync::<VarId>();
send_sync::<BlockId>();
send_sync::<crate::air::ir::value::ValueId>();
send_sync::<crate::bind::status::ExecutionStatus>();
}
}
mod tests {}
@@ -128,12 +128,6 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::RegionViewports,
RuntimeFact::PartialThreadgroups,
RuntimeFact::GridTiles,
RuntimeFact::YCbCrInPlace {
slot,
samplers: 1,
device: true,
},
RuntimeFact::TexelRows { slot },
RuntimeFact::ZeroedColor {
color: 1,
format: crate::metal::PixelFormat::RGBA8Unorm,
@@ -287,15 +281,13 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::QuadPrimitiveIds => 54,
RuntimeFact::RotatedWeights => 77,
RuntimeFact::PrivateList => 80,
RuntimeFact::YCbCrInPlace { .. } => 60,
RuntimeFact::PartialObjectThreadgroups => 83,
RuntimeFact::OpenClMode => 85,
RuntimeFact::RowLockstep => 86,
RuntimeFact::BorderTexels { .. } => 87,
RuntimeFact::HeapResidency { .. } => 88,
RuntimeFact::BorderTexels { .. } => 60,
RuntimeFact::HeapResidency { .. } => 78,
RuntimeFact::CallThreadgroups => 84,
RuntimeFact::PartialThreadgroups => 81,
RuntimeFact::TexelRows { .. } => 78,
RuntimeFact::UnitAxes { .. } => 53,
RuntimeFact::TexelBufferParts { .. } => 65,
RuntimeFact::OpenClLineTexture { .. } => 69,
@@ -309,7 +301,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..89).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..87).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -384,8 +376,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::QuadPrimitiveIds
| RuntimeFact::PrivateList
| RuntimeFact::RegionViewports
| RuntimeFact::YCbCrInPlace { .. }
| RuntimeFact::TexelRows { .. }
| RuntimeFact::TexelBufferParts { .. }
| RuntimeFact::OpenClLineTexture { .. }
| RuntimeFact::ZeroedColor { .. }
+9 -133
View File
@@ -1,8 +1,8 @@
//! Errors: every way compiling or binding can fail, as typed values to match on.
//! Errors: every way compiling can fail, as typed values to match on.
//!
//! Compiling returns [`Error`]: `Device::from_queries`, `Library::parse`, every `Device::compile_*`
//! call, `Device::render_pipeline_key`, and the [`metal`](crate::metal) mappings. Planning and
//! instantiating a binding returns [`BindError`]. Decoding cached bytes returns
//! call, `Device::render_pipeline_key`, and the [`metal`](crate::metal) mappings. Decoding cached
//! bytes returns
//! [`ArtifactError`](crate::cache::ArtifactError), which is always a cache miss. Match variants,
//! not messages: `Display` is for logs.
//!
@@ -29,14 +29,7 @@
//! - [`Error::Internal`]: a translator bug ([`InternalError`]). A panic inside a compile entry
//! point is caught and returned as one.
//!
//! **Caching failures.** [`Error::retry`] says whether the same request can succeed later. A
//! [`BindError`] from a pipeline's `plan` depends only on the pipeline, the
//! device, and the [`BindShape`](crate::bind::BindShape), so it memoizes beside the plan on
//! `(PipelineKey, BindShape)`. One from `instantiate_dispatch` or `instantiate_draw` can also
//! depend on that dispatch or draw and on the bind state's per-draw values (offsets, lengths,
//! addresses, the stage-in region, the tessellation factor buffer), so it does not memoize on the
//! shape. [`BindError::NeedsVariant`] names the pipeline variant to plan or instantiate on
//! instead.
//! **Caching failures.** [`Error::retry`] says whether the same request can succeed later.
//!
//! Every enum here is `#[non_exhaustive]`, and so are [`Unsupported`], [`InputError`], and
//! [`InternalError`]: new refusals and variants arrive additively, so match with a wildcard arm.
@@ -1356,135 +1349,18 @@ pub enum DynamicLibraryProblem {
FunctionConstants,
}
/// A binder planning or instantiation error. A pipeline's `plan` sees only the pipeline, the
/// device, and the `BindShape`, so a planning error is permanent for its `(PipelineKey,
/// BindShape)` pair. An instantiation error can also depend on the dispatch or draw and on the
/// bind state's per-draw values (`MissingStageInRegion`, the patch-draw
/// errors, a descriptor range or texel buffer beyond its limit, ...), so it is not permanent for
/// the pair. `NeedsVariant` names the pipeline a dispatch or draw runs on instead.
/// Why the view of a texture a heap array may hold cannot be made (`bind::heap`): the storage-read
/// check of `lower::texture::slot` skips such a member.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BindError {
/// A slot index beyond the Metal maximum for its table.
SlotOutOfRange { slot: SlotRef },
/// The bind shape needs something the device cannot do (local size limits, formats,
/// sampler reduction, GPU-encoded ICBs, …).
pub(crate) enum BindError {
/// The view needs something the device cannot do (a format, a view type).
Unsupported(Unsupported),
/// A device-address slot received a buffer without a device address.
MissingDeviceAddress { slot: SlotRef },
/// A descriptor-form slot's window exceeds the descriptor range limit (Profile F).
DescriptorRangeExceeded {
slot: SlotRef,
needed: u64,
limit: u64,
},
/// A texture buffer bound through one texel buffer view exceeds `maxTexelBufferElements`:
/// one wider than that view binds through views of its parts (`bind::texel_parts`) except at
/// a slot whose function reads it through a sampler, on a device that indexes no array of
/// the slot's kind of texel buffer by a `NonUniform` value, or in a format whose block holds
/// several texels.
TexelBufferTooLarge {
slot: SlotRef,
elements: u64,
limit: u64,
},
/// The pipeline and the binder disagree (a pipeline built by another device, or a binder
/// bug); always a bug, never the guest's.
/// A view the derivation cannot state; always a bug, never the guest's.
Internal(InternalError),
/// A bound resource's descriptor is invalid (e.g. a sampler whose LOD clamps are NaN or
/// inverted).
InvalidDescriptor(DescriptorError),
/// A render pipeline fetches a fixed-function vertex buffer that nothing is bound to.
UnboundVertexBuffer { slot: SlotRef },
/// The set-1 heap's elements (one per resident texture a handle can name, plus the null
/// element) exceed the pipeline's heap capacity: the heap arrays' count, at most the handle
/// table's reach.
HeapTooLarge { count: u64, limit: u64 },
/// A pipeline reads the Metal address of a buffer slot (`SlotGuestBase`: a pointer compare,
/// `ptrtoint`, or stored pointer) that is bound with `set*Bytes`, which gives the binder no
/// Metal address to write.
MissingGuestAddress { slot: SlotRef },
/// The encoder's vertex amplification (`setVertexAmplificationCount:viewMappings:`) is not
/// one Metal draws this pipeline with: a count of 0, one above 1 for a pipeline whose
/// `maxVertexAmplificationCount` (`max`) is 1, or view mappings given for fewer
/// amplifications than the count.
InvalidVertexAmplification {
count: u32,
max: u32,
view_mappings: u32,
},
/// The dispatch runs on another variant of the pipeline than the one planned: a threadgroup
/// with a partial simdgroup, which the kernel's flattened simd tier cannot run, runs on its
/// emulated-simdgroups variant (`VariantKey::emulated_simdgroups`). The consumer compiles the
/// pipeline under `variant` (the plan's key and what the dispatch adds, also
/// `BindingPlan::dispatch_variant`), plans it for the same shape, whose plan states `variant`,
/// and instantiates the dispatch there. Nothing is dispatched on the plan asked. A draw answers
/// it when the pipeline planned is not the variant the shape asks for (its amplification
/// draws, its colors, its depth clamp range, its rotated weights, its band, its tests, its
/// primitive IDs, its list or its regions); `variant` is then the plan's own. Boxed: a key holds a set per kind of variant, and the
/// error stays small.
NeedsVariant {
variant: Box<crate::cache::VariantKey>,
},
/// The compute encoder's imageblock size (`setImageblockWidth:height:`) is not one a kernel
/// with an imageblock dispatches with: a width or height of 0 (the encoder never set it) or
/// above 65535, which `get_imageblock_width` and `get_imageblock_height` cannot answer.
InvalidImageblockSize { width: u32, height: u32 },
/// The kernel reads the compute encoder's stage-in region (a `[[stage_in]]` attribute
/// stepping by thread position, or `[[grid_origin]]` or `[[grid_size]]`) and the encoder
/// never set one (`setStageInRegion:`): what Metal reads then is not established.
MissingStageInRegion,
/// A draw Metal does not make with this pipeline: patches (`patches`) with a pipeline whose
/// vertex function is not post-tessellation, or primitives with one whose vertex function is.
InvalidDrawKind { patches: bool },
/// A patch draw's `numberOfPatchControlPoints` (`given`) differs from the `N` the
/// post-tessellation vertex function's `[[patch(_, N)]]` states (`expected`).
PatchControlPoints { given: u32, expected: u32 },
/// The tessellation factors a draw reads span more bytes (`needed`) than one storage-buffer
/// descriptor can bind (`limit`, `maxStorageBufferRange`), or an instance stride does.
TessellationFactorRange { needed: u64, limit: u64 },
/// The encoder's tessellation factor scale (`bits`, the `float`'s) rounded to `half` is not a
/// positive `half` (it is negative, zero, or NaN). Metal's validation stops
/// `setTessellationFactorScale:` for a scale that is not a positive normal `float`, and
/// culls every patch for one that is 0 as a `half` (2^-30), which
/// a consumer draws as nothing.
InvalidTessellationFactorScale { bits: u32 },
/// A tile function's render area (`BindState::render_area`) has a width or height of 0: the
/// encoder's render pass was never set, so the dispatch has no tile to run.
InvalidRenderArea { width: u32, height: u32 },
/// A patch draw's patch index buffer is bound at an offset that is not a multiple of 4, which
/// Metal requires (a Metal probe on an M4: "patchIndexBufferOffset(2) must be a multiple of 4
/// bytes").
InvalidPatchIndexBuffer { offset: u64 },
/// The patch indices a draw reads span more bytes (`needed`) than one storage-buffer
/// descriptor can bind (`limit`, `maxStorageBufferRange`).
PatchIndexRange { needed: u64, limit: u64 },
/// A patch draw with a control-point index buffer (`indexed`, `drawIndexedPatches`) for a
/// pipeline whose `tessellationControlPointIndexType` is `None`, or one without it for a
/// pipeline whose type is not, which Metal's validation stops (a Metal probe on an M4:
/// "tessellationControlPointIndexType of MTLTessellationControlPointIndexTypeNone not valid for
/// drawIndexedPatches", and of `UInt32` for `drawPatches`).
ControlPointIndexing { indexed: bool },
/// A patch draw's control-point index buffer is bound at an offset that is not a multiple of
/// its pipeline's index size, which Metal requires (a Metal probe on an M4:
/// "controlPointIndexBufferOffset(1) must be a multiple of 2 bytes").
InvalidControlPointIndexBuffer { offset: u64 },
/// The control-point indices a draw reads span more bytes (`needed`) than one storage-buffer
/// descriptor can bind (`limit`, `maxStorageBufferRange`).
ControlPointIndexRange { needed: u64, limit: u64 },
/// A tile function reads its threadgroup argument `index`, which the encoder never set
/// (`BindState::tile_threadgroup`, `setThreadgroupMemoryLength:offset:atIndex:`): Metal's
/// validation stops the dispatch ("missing Threadgroup Memory binding").
MissingThreadgroupMemory { index: u32 },
/// A draw Metal does not make with this pipeline: a mesh draw (`mesh`) with a pipeline that is
/// not a mesh render pipeline, or a draw of primitives or patches with one (Metal ends the
/// process on `drawPrimitives` with a mesh pipeline state).
InvalidMeshDraw { mesh: bool },
/// A draw of a pipeline whose vertex function writes the primitive ID
/// (`LoweringInputs::primitive_id_varying`) whose bind state names no primitive type
/// (`BindState::primitive_type`): its vertices per primitive, and whether an indexed draw
/// runs de-indexed (a strip's does not), depend on it.
MissingPrimitiveType,
}
impl fmt::Display for BindError {
@@ -245,8 +245,8 @@ pub enum Side {
Null,
}
/// SPIR-V words of the module's resident-set search ([`roots::resolve`], once per module): the
/// table's and the set's conversions, the hit test, and a function's frame (216); its two loops,
/// SPIR-V words of the module's resident-set search ([`roots::define_resolve`], once per module):
/// the table's and the set's conversions, the hit test, and a function's frame (216); its two loops,
/// each with its two variables' stores and loads and the loop's and its exit's blocks (96 each);
/// three steps (the halving, the entry's access chain and load, a compare, and a select, about 40
/// words each: one in the 64-bit narrowing, two in the 32-bit loop); and the window between them,
+2 -5
View File
@@ -20,8 +20,8 @@
//! (`lower::dispatch`, measured for the threadgroups the binder alone runs, up to 32x32).
//!
//! **Tile staging.** The tile's cells are the threadgroup arena's imageblock region: its extent is
//! the tile size (`SpecKey::ImageblockWidth`/`Height`, which the binder specializes from
//! `BindState::imageblock_size`), and a cell holds each attachment's texel at its layout's offset
//! the tile size (`SpecKey::ImageblockWidth`/`Height`, which the consumer specializes from the
//! pass's tile size), and a cell holds each attachment's texel at its layout's offset
//! (`memory::plan`: the aliased layout's, or the implicit layout's). The entry is a new function
//! ([`wrap_entry`]) that loads the tile's pixels of every attachment the function reaches into the
//! cells (a cell past the render area, `SpecKey::RenderAreaWidth`/`Height`, is zeroed: Metal leaves
@@ -1013,9 +1013,6 @@ fn image_decl(s: &TileSlot) -> ImageDecl {
level_views: None,
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
rows: false,
parts: None,
}
}
@@ -184,16 +184,8 @@ fn bicubic_routines_words_bound_their_emission() {
routines::define_line(fb.module())?;
Ok(x[0])
}) - without;
let quad = size(&|fb, x| {
routines::define_quad(fb.module())?;
Ok(x[0])
}) - without;
eprintln!("bicubic routines: plane {plane} words, line {line} words, quad {quad} words");
for (routine, words) in [
(Routine::Plane, plane),
(Routine::Line, line),
(Routine::Quad, quad),
] {
eprintln!("bicubic routines: plane {plane} words, line {line} words");
for (routine, words) in [(Routine::Plane, plane), (Routine::Line, line)] {
assert!(
words <= routine.words() as usize,
"{routine:?} is {words} words, bound {}",
@@ -24,7 +24,6 @@ pub(super) fn half_of(x: f32, mode: HalfRounding) -> u32 {
let q = a / ulp;
let r = match mode {
HalfRounding::NearestEven => q.round_ties_even(),
HalfRounding::NearestAway => q.round(),
HalfRounding::TowardZeroSaturating => q.trunc(),
} * ulp;
let r = if r > 65504.0 {
@@ -91,7 +90,6 @@ fn f32_to_half_rounds_exactly_in_every_mode() {
.collect();
for mode in [
HalfRounding::NearestEven,
HalfRounding::NearestAway,
HalfRounding::TowardZeroSaturating,
] {
check(
@@ -110,69 +108,3 @@ fn f32_to_half_rounds_exactly_in_every_mode() {
);
}
}
/// The normalized grids the bicubic filter's exact sums land on: `16 · 255`, `16 · 127`, `65535`,
/// `32767`, and the sRGB step scale 4095. The grids: the bicubic sums', the sRGB table's, and the
/// normalized formats' fields' that a tile function's `half` member reads, down to a 2-bit alpha's
/// 3 and 1, where `3 · 2^24 / d` reaches `2^24`.
const GRIDS: [u32; 10] = [4080, 2032, 65535, 32767, 4095, 1023, 255, 127, 3, 1];
fn ratio_cases(d: u32) -> Vec<Case> {
let step = if d > 4095 { 13 } else { 1 };
(0..=u64::from(d))
.step_by(step)
.chain([1, 2, 3, 4, u64::from(d) - 1, u64::from(d)])
// The quotients that round differently through `f32` (module docs).
.chain([65455, 65519, 32759])
.filter(|k| *k <= u64::from(d))
.map(|k| vec![vec![k], vec![u64::from(d)]])
.collect()
}
/// `ratio_to_f32` is correctly rounded with a run-time divisor on every grid.
#[test]
fn ratio_to_f32_is_correctly_rounded() {
let u = int(32);
for d in GRIDS {
check(
&format!("k / {d} to f32"),
&[u, u],
float(32),
&|fb, a| texel_round::ratio_to_f32(fb, u, a[0], a[1]),
&ratio_cases(d),
&|c| {
Some(vec![u64::from(
((arg(c, 0) as f64 / d as f64) as f32).to_bits(),
)])
},
false,
);
}
}
/// `ratio_to_half` rounds `k / d` to `half` once, half denormals included, where rounding the
/// `f32` quotient would round twice.
#[test]
fn ratio_to_half_rounds_once() {
let u = int(32);
for d in GRIDS {
check(
&format!("k / {d} to half"),
&[u, u],
float(32),
&|fb, a| texel_round::ratio_to_half(fb, u, a[0], a[1]),
&ratio_cases(d),
&|c| {
let h = f64_to_f16(arg(c, 0) as f64 / d as f64);
Some(vec![u64::from((f16_to_f64(h) as f32).to_bits())])
},
false,
);
}
// The quotients where the f32 detour differs exist: the test above covers them.
let twice = |k: u32, d: u32| {
let f = (f64::from(k) / f64::from(d)) as f32;
f64_to_f16(f64::from(f)) != f64_to_f16(f64::from(k) / f64::from(d))
};
assert!(twice(65455, 65535) && twice(65519, 65535) && twice(32759, 32767));
}
@@ -1,18 +1,11 @@
//! Exact conversions of texel values, shared by the sampling lowerings: integer sequences only, so
//! every device and every fast-math mode answers alike.
//!
//! - [`f32_to_half`]: an `f32` rounded to `half` to nearest even, to nearest with ties away from
//! zero, or toward zero saturating at the largest finite `half`; half denormals are kept.
//! - [`f32_to_half`]: an `f32` rounded to `half` to nearest even, or toward zero saturating at the
//! largest finite `half`; half denormals are kept.
//! Metal converts a 32-bit float texel to a `half` result to nearest even when a shader reads
//! it and toward zero, saturating at `±65504`, when it samples it (authored case
//! `half-conversion-of-wider-texels-by-read-and-sample`).
//! - [`ratio_to_f32`] and [`ratio_to_half`]: `k / d` correctly rounded to `f32` or to `half`
//! (nearest even) for a divisor known only at run time, as a normalized channel's value `n / D`
//! on a format's grid is (the 8- and 16-bit normalized formats' bicubic sums). [`ratio_to_half`]
//! rounds once: rounding the `f32` quotient to `half` instead differs from it at `±65455 /
//! 65535`, `±65519 / 65535`, and `±32759 / 32767`.
//! - [`grid_value`]: a signed step's value `n / D` on a normalized format's grid exactly, the
//! bicubic sums'.
//!
//! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as its
//! `air.unpack` does: the step `k` of [`srgb`](crate::lower::arith::srgb), then `k / 4095`
@@ -34,8 +27,6 @@ use crate::spirv::ir::{BinOp, ConvOp, GlslOp};
pub enum HalfRounding {
/// To nearest, ties to even; past the largest finite `half` to the infinity of the sign.
NearestEven,
/// To nearest, ties away from zero; past the largest finite `half` to the infinity.
NearestAway,
/// Toward zero; a finite value past the largest finite `half` becomes `±65504`.
TowardZeroSaturating,
}
@@ -125,10 +116,6 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding)
let bias = even_bias(fb)?;
bin(fb, BinOp::IAdd, mag, bias)?
}
HalfRounding::NearestAway => {
let half = c(fb, 0x1000)?;
bin(fb, BinOp::IAdd, mag, half)?
}
HalfRounding::TowardZeroSaturating => mag,
};
let normal = bin(fb, BinOp::BitwiseAnd, biased, keep)?;
@@ -136,7 +123,7 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding)
let over = bin(fb, BinOp::UGreaterThan, normal, max)?;
let past = match rule {
HalfRounding::TowardZeroSaturating => max,
HalfRounding::NearestEven | HalfRounding::NearestAway => inf,
HalfRounding::NearestEven => inf,
};
let normal = fb.select(over, past, normal)?;
// A denormal half (or zero): round on the grid 2^-24.
@@ -171,7 +158,6 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding)
};
let up = match rule {
HalfRounding::NearestEven => Some(even_up(fb)?),
HalfRounding::NearestAway => Some(bin(fb, BinOp::UGreaterThanEqual, rem, tie)?),
HalfRounding::TowardZeroSaturating => None,
};
let h = match up {
@@ -190,144 +176,3 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding)
let ft = ty(fb, floats(f))?;
fb.convert(ConvOp::Bitcast, r, ft)
}
/// The leading part of [`ratio_to_f32`] and [`ratio_to_half`]: for `1 <= k <= d < 2^16`, the
/// shift `e >= 0` that puts `a = k · 2^e` in `[d, 2d)`, and `a`.
fn normalize(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult<(Value, Value)> {
let one = splat(fb, u, 1)?;
let m = fb.glsl(GlslOp::FindUMsb, &[k])?;
let top = fb.glsl(GlslOp::FindUMsb, &[d])?;
let e = bin(fb, BinOp::ISub, top, m)?;
let a = bin(fb, BinOp::ShiftLeftLogical, k, e)?;
let short = bin(fb, BinOp::ULessThan, a, d)?;
let a2 = bin(fb, BinOp::ShiftLeftLogical, a, one)?;
let a = fb.select(short, a2, a)?;
let e1 = bin(fb, BinOp::IAdd, e, one)?;
let e = fb.select(short, e1, e)?;
Ok((e, a))
}
/// Whether quotient `q` with remainder `r` of a division by `d` rounds up to nearest even.
fn round_up(fb: &mut FunctionBuilder<'_>, u: Form, q: Value, r: Value, d: Value) -> BResult<Value> {
let (z, one) = (splat(fb, u, 0)?, splat(fb, u, 1)?);
let twice = bin(fb, BinOp::ShiftLeftLogical, r, one)?;
let above = bin(fb, BinOp::UGreaterThan, twice, d)?;
let tie = bin(fb, BinOp::IEqual, twice, d)?;
let lsb = bin(fb, BinOp::BitwiseAnd, q, one)?;
let odd = bin(fb, BinOp::INotEqual, lsb, z)?;
let tie_up = bin(fb, BinOp::LogicalAnd, tie, odd)?;
bin(fb, BinOp::LogicalOr, above, tie_up)
}
/// `k / d` correctly rounded to `f32` (nearest even), for `u32` lanes (form `u`) with
/// `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value, with integer operations only:
/// `k` shifted into `[d, 2d)`, two exact integer divisions for the significand and the last
/// remainder's rounding to nearest even, the divisor's leading bit found at run time. `k = 0` is
/// `+0`.
pub fn ratio_to_f32(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult<Value> {
let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v);
let (z, one) = (c(fb, 0)?, c(fb, 1)?);
let zero = bin(fb, BinOp::IEqual, k, z)?;
let k = fb.glsl(GlslOp::UMax, &[k, one])?;
let (e, a) = normalize(fb, u, k, d)?;
// q = floor(a · 2^23 / d) in two exact divisions (a · 2^12 < 2^29).
let (k11, k12) = (c(fb, 11)?, c(fb, 12)?);
let hi = bin(fb, BinOp::ShiftLeftLogical, a, k12)?;
let q1 = bin(fb, BinOp::UDiv, hi, d)?;
let t = bin(fb, BinOp::IMul, q1, d)?;
let r1 = bin(fb, BinOp::ISub, hi, t)?;
let lo = bin(fb, BinOp::ShiftLeftLogical, r1, k11)?;
let q2 = bin(fb, BinOp::UDiv, lo, d)?;
let t = bin(fb, BinOp::IMul, q2, d)?;
let r2 = bin(fb, BinOp::ISub, lo, t)?;
let q = bin(fb, BinOp::ShiftLeftLogical, q1, k11)?;
let q = bin(fb, BinOp::BitwiseOr, q, q2)?;
let up = round_up(fb, u, q, r2, d)?;
let inc = fb.select(up, one, z)?;
let k126 = c(fb, 126)?;
let be = bin(fb, BinOp::ISub, k126, e)?;
let k23 = c(fb, 23)?;
let be = bin(fb, BinOp::ShiftLeftLogical, be, k23)?;
let bits = bin(fb, BinOp::IAdd, be, q)?;
let bits = bin(fb, BinOp::IAdd, bits, inc)?;
let bits = fb.select(zero, z, bits)?;
let ft = ty(fb, floats(u))?;
fb.convert(ConvOp::Bitcast, bits, ft)
}
/// `k / d` correctly rounded to `half` (nearest even), held as its `f32`, for `u32` lanes (form
/// `u`) with `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value. `k = 0` is `+0`.
///
/// A quotient of at least `2^-14` takes the 11-bit significand `floor(a · 2^10 / d)` of the
/// normalized `a` (`normalize`, one exact division: `a · 2^10 < 2^27`) and rounds it on the
/// remainder; the rounding carries into the exponent. A smaller one (then `k <= 3`) is
/// `k · 2^24 / d` rounded to an integer, its value on the denormal grid `2^-24`: at most `2^10`,
/// to which the step is clamped, so a lane that takes the normal quotient keeps the denormal
/// one's shifts in range (a grid `d <= 3` puts `3 · 2^24 / d` at `2^24` or more).
pub fn ratio_to_half(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult<Value> {
let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v);
let (z, one) = (c(fb, 0)?, c(fb, 1)?);
let zero = bin(fb, BinOp::IEqual, k, z)?;
let kk = fb.glsl(GlslOp::UMax, &[k, one])?;
let (e, a) = normalize(fb, u, kk, d)?;
let k10 = c(fb, 10)?;
let hi = bin(fb, BinOp::ShiftLeftLogical, a, k10)?;
let q = bin(fb, BinOp::UDiv, hi, d)?;
let t = bin(fb, BinOp::IMul, q, d)?;
let r = bin(fb, BinOp::ISub, hi, t)?;
let up = round_up(fb, u, q, r, d)?;
let inc = fb.select(up, one, z)?;
// Bits: exponent 127 - e, significand (q - 2^10) << 13, the rounding added below it.
let k126 = c(fb, 126)?;
let be = bin(fb, BinOp::ISub, k126, e)?;
let k23 = c(fb, 23)?;
let be = bin(fb, BinOp::ShiftLeftLogical, be, k23)?;
let sig = bin(fb, BinOp::IAdd, q, inc)?;
let k13 = c(fb, 13)?;
let sig = bin(fb, BinOp::ShiftLeftLogical, sig, k13)?;
let normal = bin(fb, BinOp::IAdd, be, sig)?;
// Below 2^-14 (e >= 15): k <= 3, so k · 2^24 < 2^26.
let k3 = c(fb, 3)?;
let small_k = fb.glsl(GlslOp::UMin, &[kk, k3])?;
let k24 = c(fb, 24)?;
let n = bin(fb, BinOp::ShiftLeftLogical, small_k, k24)?;
let g = bin(fb, BinOp::UDiv, n, d)?;
let t = bin(fb, BinOp::IMul, g, d)?;
let gr = bin(fb, BinOp::ISub, n, t)?;
let gup = round_up(fb, u, g, gr, d)?;
let ginc = fb.select(gup, one, z)?;
let g = bin(fb, BinOp::IAdd, g, ginc)?;
let k1024 = c(fb, 1024)?;
let g = fb.glsl(GlslOp::UMin, &[g, k1024])?;
let denormal = grid_bits(fb, u, g)?;
let k15 = c(fb, 15)?;
let small = bin(fb, BinOp::UGreaterThanEqual, e, k15)?;
let bits = fb.select(small, denormal, normal)?;
let bits = fb.select(zero, z, bits)?;
let ft = ty(fb, floats(u))?;
fb.convert(ConvOp::Bitcast, bits, ft)
}
/// The value `n / D` of signed grid step `n` (`i32` bits in `u32` lanes of form `u`, within
/// `[-D, D]`; `d` the grid `D` in `u32` lanes, `1 <= D < 2^16`): `+0` for zero, else the
/// magnitude `|n| / D` correctly rounded by `round` ([`ratio_to_f32`], [`ratio_to_half`], or a
/// choice of the two) with the sign of `n`.
pub fn grid_value(
fb: &mut FunctionBuilder<'_>,
u: Form,
n: Value,
d: Value,
round: impl FnOnce(&mut FunctionBuilder<'_>, Value, Value) -> BResult<Value>,
) -> BResult<Value> {
let z = splat(fb, u, 0)?;
let neg = bin(fb, BinOp::SLessThan, n, z)?;
let m = fb.glsl(GlslOp::SAbs, &[n])?;
let r = round(fb, m, d)?;
let ut = ty(fb, u)?;
let bits = fb.convert(ConvOp::Bitcast, r, ut)?;
let sign = splat(fb, u, 0x8000_0000)?;
let sign = fb.select(neg, sign, z)?;
let bits = bin(fb, BinOp::BitwiseOr, bits, sign)?;
let ft = ty(fb, floats(u))?;
fb.convert(ConvOp::Bitcast, bits, ft)
}
+1 -7
View File
@@ -63,7 +63,7 @@
//! partial object threadgroup's draw or a kernel's ragged grid on its partial-threadgroups
//! variant (below).
//!
//! With `MultiRegion = 0` (single-region `Threadgroups` and every `ThreadgroupsIndirect`) the push
//! With `MultiRegion = 0` (a single-region `dispatchThreadgroups:` and every indirect one) the push
//! field is not read: the region base is 0, `L = (sx, sy, sz)`, `threadgroups_per_grid =
//! NumWorkgroups`, and `threads_per_grid = NumWorkgroups · L`, so GPU-written indirect arguments
//! work. With `MultiRegion = 1` (the edge regions of `dispatchThreads` and group-count splits,
@@ -1203,12 +1203,6 @@ pub fn region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u
Some(out)
}
/// The `DispatchRegion` bytes of a draw of the object threadgroups `threads` fill at nominal
/// size `l`, the last along an axis running only the threads left ([`NONUNIFORM`]).
pub fn partial_region_bytes(threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> {
nonuniform_region_bytes([0; 3], threads, l)
}
/// [`region_bytes`] of a region flagged [`NONUNIFORM`]: its threadgroups the ones `threads` fill
/// at nominal size `l` from `base`, the last along an axis running only the threads left.
pub fn nonuniform_region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> {
@@ -548,7 +548,7 @@ fn group_count_splits_match_the_single_dispatch() {
/// A partial object threadgroups module's run of a draw of `threads` threads in threadgroups of
/// `l` (one dispatch of the threadgroups the threads fill, rounded up, each of `l` invocations,
/// `MultiRegion` 1), its region flagged where `flagged` ([`partial_region_bytes`]): each
/// `MultiRegion` 1), its region flagged where `flagged` ([`nonuniform_region_bytes`]): each
/// invocation's live word and builtins.
fn run_partial(
m: &TypedModule,
@@ -571,7 +571,7 @@ fn run_partial(
}
spec.insert(SpecKey::MultiRegion, 1);
let push = match flagged {
true => partial_region_bytes(threads, l),
true => nonuniform_region_bytes([0; 3], threads, l),
false => region_bytes([0; 3], threads, l),
};
let res = Resources {
@@ -307,9 +307,6 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl {
level_views: None,
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
rows: false,
parts: None,
}
}
-4
View File
@@ -195,10 +195,6 @@ pub const fn shape(f: PushField) -> FieldShape {
// A constexpr sampler's index in its use's sampler array, and the sampled-texture array's
// element a fetched color attachment is read through.
PushField::ConstexprSampler(_) | PushField::FetchedColor { .. } => FieldShape::U32,
// An in-place YCbCr texture's size, planes and conversion.
PushField::YCbCrInPlace(_) => FieldShape::UVec4Array(2),
// A texture's size, rows and first texel in its texel buffer view.
PushField::TexelRows(_) => FieldShape::UVec4Array(1),
// The residual is below `min{Storage,Uniform}BufferOffsetAlignment`.
PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32,
// The bytes of a slot's buffer before its bind offset, and its length: each at most 2 GiB
@@ -319,126 +319,6 @@ fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() {
assert!(!a.facts.contains(&fact));
}
/// The binder names a slot of the `AnisotropicSampler` fact in the plan's variant where the shape
/// binds a sampler whose word states anisotropy (`maxAnisotropy` above 1), whatever its filters,
/// and nowhere else; the variant's own plan for that shape states the same key, so a draw or
/// dispatch settles on it. Its compiled pipeline round trips as the cached form. On lavapipe
/// without `samplerAnisotropy`, where the emulation runs.
#[test]
fn a_bound_anisotropic_sampler_asks_for_the_variant() {
use crate::bind::{
BindState, BoundSampler, BoundTexture, SamplerDescriptor, StageTable, TextureFacts,
};
use crate::budget::Budget;
use crate::cache::{PipelineArtifact, VariantKey};
use crate::device::DeviceDescription;
use crate::library::Library;
use crate::metal;
use crate::pipeline::artifact::ComputePipeline;
use crate::pipeline::descriptor::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
let Some(bc) = assemble("binder", RUNTIME_KERNEL) else {
return;
};
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles/lavapipe.json");
let text = std::fs::read_to_string(&path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
assert!(desc.features.remove(&VkFeature::SamplerAnisotropy));
let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device");
let pipeline = |inputs: &LoweringInputs| {
let function = Library::from_air(&bc)
.and_then(|lib| lib.function("k"))
.expect("kernel");
let compiled = dev
.compile_function(
&FunctionDescriptor::new(function),
inputs,
&Budget::standard(),
)
.expect("function");
dev.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
&Budget::standard(),
)
.expect("pipeline")
};
let shape = |desc: SamplerDescriptor| {
let mut table = StageTable::default();
let mut facts =
TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm);
facts.usage = metal::TextureUsage::SHADER_READ;
facts.mipmap_level_count = 4;
table.textures.insert(
0,
BoundTexture::Texture {
facts,
resource_id: None,
},
);
table.samplers.insert(
0,
BoundSampler {
desc,
resource_id: None,
},
);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);
state.shape()
};
let sampler = |filter, mip, anisotropy| {
let mut desc = SamplerDescriptor::new();
desc.min_filter = filter;
desc.mag_filter = filter;
desc.mip_filter = mip;
desc.max_anisotropy = anisotropy;
desc
};
let mut key = VariantKey::new();
key.anisotropic_samplers.insert(SLOT);
let base = pipeline(&LoweringInputs::new());
let named = pipeline(&key.lowering_inputs(Stage::Kernel));
let decoded = ComputePipeline::from_bytes(&named.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, named);
let linear = metal::SamplerMinMagFilter::Linear;
let nearest = metal::SamplerMinMagFilter::Nearest;
let (none, near) = (
metal::SamplerMipFilter::NotMipmapped,
metal::SamplerMipFilter::Nearest,
);
// Anisotropic samplers, the consumer's (linear filters, a nearest mip filter) among them.
for desc in [
sampler(linear, near, 16),
sampler(linear, near, 2),
sampler(nearest, none, 4),
] {
let shape = shape(desc);
let plan = base.plan(&dev, &shape).expect("plan");
assert_eq!(
plan.variant.anisotropic_samplers, key.anisotropic_samplers,
"{desc:?}"
);
let plan = decoded.plan(&dev, &shape).expect("variant's plan");
assert_eq!(
plan.variant.anisotropic_samplers, key.anisotropic_samplers,
"{desc:?}"
);
}
// Isotropic samplers and none: the base.
for desc in [
sampler(linear, none, 1),
sampler(linear, near, 1),
SamplerDescriptor::new(),
] {
let plan = base.plan(&dev, &shape(desc)).expect("plan");
assert!(plan.variant.anisotropic_samplers.is_empty(), "{desc:?}");
}
let plan = base
.plan(&dev, &crate::bind::BindShape::default())
.expect("plan");
assert!(plan.variant.anisotropic_samplers.is_empty());
}
/// A fragment function sampling slot 0, a texture of AIR type `tex_ty`, at its implicit level
/// through the constexpr sampler of first state word `words`: `call` makes `%v` (a `float4`) of
/// `%uv` (the position over 16) or `%uvw` (`%uv` and 0.5); `decl` is the intrinsic's declaration.
@@ -30,8 +30,9 @@
//! linear filter under the sampler's address modes: its sample equals a linear sampler's with
//! the same modes on all 4,096 lanes of each run, under `clamp_to_edge`, `repeat`,
//! `mirrored_repeat`, `clamp_to_zero`, and one mirrored axis beside a clamped one. The
//! emulation takes the linear 2D sample there ([`routines::Quad`]) over the footprint's inner
//! taps, which are the linear filter's (the bicubic and linear footprints share `q`).
//! emulation takes the linear 2D sample there ([`routines::Plane`]'s `bilinear` form) over the
//! footprint's inner taps, which are the linear filter's (the bicubic and linear footprints
//! share `q`).
//! - On a level of at least four texels each way, a mirrored axis of a format Metal filters
//! bicubically reads texel 1 at fraction 0 whatever the coordinate: with both axes mirrored
//! every lane is texel `(1, 1)` exactly, and with one the sample varies with the other axis
@@ -354,7 +355,6 @@ pub(super) struct Tys {
pub(super) f32_: TypeId,
i32_: TypeId,
pub(super) u32_: TypeId,
pub(super) bool_: TypeId,
pub(super) vec4: TypeId,
}
@@ -370,13 +370,13 @@ impl Tys {
width: 32,
signed: false,
})?;
let bool_ = m.ty(SType::Bool)?;
// Declared here, so the module keeps the order of its type declarations.
m.ty(SType::Bool)?;
let vec4 = m.ty(SType::Vector { elem: f32_, len: 4 })?;
Ok(Tys {
f32_,
i32_,
u32_,
bool_,
vec4,
})
}
@@ -1098,25 +1098,6 @@ pub(super) fn footprint_of_image(
footprint_at(fb, t, &at, (size, base, image), bits, taps)
}
/// [`footprint_of_image`] of an image whose base-level size `size` (a `uvec2`) the caller states:
/// an in-place texture's (`super::in_place`), whose taps read the base level of its one level.
pub(super) fn footprint_sized(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
(coord, layer, offset): (SValue, Option<SValue>, Option<(SValue, u8)>),
(size, image): (SValue, CombinedImage),
bits: Bits,
(taps, parent): (&Taps<'_>, Option<OffsetBase>),
) -> BResult<Footprint> {
let at = At {
coord,
layer,
parent,
offset,
};
footprint_at(fb, t, &at, (size, None, image), bits, taps)
}
/// The footprint of sample `s` over `taps` on an image of level-0 size `size` (image facts
/// `image`), the border color seen through the channels of the bound format's treatment `bits`.
pub(super) fn footprint_on(
@@ -3,9 +3,8 @@
//!
//! Each routine takes the bound format's `BicubicTexels` bits (or its `TexelFormat` class) as an
//! argument, the texture slot's specialization constant at every call, so once a device
//! specializes the module and inlines a call, the paths of the other formats fold away. The
//! texel routine (the in-place linear quad's sum) is a kept routine (`ModuleBuilder::kept_routine`),
//! declared `DontInline`; the others are plain functions.
//! specializes the module and inlines a call, the paths of the other formats fold away. They are
//! plain functions.
//!
//! - [`Plane`] (a 2D bicubic sample): the Catmull-Rom weights (`a = -1/2`) of each axis's fraction
//! `k / 256` in `f32`, the footprint's sixteen taps summed row by row and then the rows, in the
@@ -15,28 +14,14 @@
//! datapath (`PrecisionNote::BicubicFilterArithmetic`).
//! - [`Line`] (a 1D bicubic sample, bilinear over taps `i` and `i + 1` whatever the format): the
//! device's `FMix` of the two taps, then the normalized formats' clamps.
//! - [`Quad`] (a two-plane YCbCr texture's linear sample read in place, `super::super::in_place`,
//! bilinear over the footprint's taps `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, and `(i + 1, j + 1)`).
//! `exact` weighs each tap `wx · wy` in units of `2^-16`, the integer weights `256 - k` and `k`
//! per axis (a merged axis's fraction arrives as 0), and truncates each code's term before the
//! half-up step, as Metal's 2D sums do: a packed field's by its own `s`
//! (`PackedTexels::filter_truncation`: 7 on YCbCr's grid `2048`).
//!
//! The codes are recovered exactly: a YCbCr field's channels (`PackedTexels::YCbCr2048`,
//! `YCbCr8192`, `YCbCrExtended8192`) arrive as their steps `k / D`, exact, and sum on the grid
//! `2048` or `8192` (`S = D`), each 2D term `k · w` truncated by `2^7`; the extended-range field's
//! steps are signed and reach `2D`, so its quotient divides by `2D` and doubles, exactly, and a
//! YCbCr field's `half` result rounds the exact `f32` with ties away from zero.
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::splat;
use crate::lower::arith::texel_round::{self, HalfRounding};
use crate::metal::bicubic::BicubicTexels;
use crate::metal::texel_format::{PackedTexels, TexelFormat};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, TypeId, Value};
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type, UnOp};
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type};
/// The routines a module defines for its emulated samples, by the samples' dimension.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -45,8 +30,6 @@ pub enum Routine {
Plane,
/// A 1D (or 1D array) texture's bicubic sample: [`Line`].
Line,
/// A two-plane YCbCr texture's linear sample read in place: [`Quad`].
Quad,
}
impl Routine {
@@ -56,7 +39,6 @@ impl Routine {
match self {
Routine::Plane => PLANE_WORDS,
Routine::Line => LINE_WORDS,
Routine::Quad => 5440,
}
}
@@ -65,7 +47,6 @@ impl Routine {
match self {
Routine::Plane => "sampler.bicubic.plane",
Routine::Line => "sampler.bicubic.line",
Routine::Quad => "sampler.linear.quad",
}
}
}
@@ -221,23 +202,6 @@ fn clamped(fb: &mut FunctionBuilder<'_>, flags: Value, r: Value) -> BResult<Valu
fb.select(is_snorm, snorm, r)
}
/// A two-plane YCbCr texture's in-place linear sample's routine (module docs). The taps are the
/// footprint's row `j`, then row `j + 1`, each from column `i`; `kx` and `ky` are the fractions'
/// 1/256 steps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Quad {
/// `fn(t00: vec4, t01: vec4, t10: vec4, t11: vec4, kx: u32, ky: u32, flags: u32, half: bool)
/// -> vec4`: the exact sum on the field's grid, taking a merged axis's fraction as 0.
pub exact: FuncId,
}
/// Define the in-place linear sample's routine in `mb`.
pub fn define_quad(mb: &mut ModuleBuilder) -> BResult<Quad> {
Ok(Quad {
exact: define_exact_quad(mb)?,
})
}
// ---- Types and constants ----
/// The four lanes of a texel.
@@ -260,13 +224,6 @@ fn fform(lanes: u8) -> Form {
}
}
fn bform(lanes: u8) -> Form {
Form {
held: Held::Bool,
lanes,
}
}
/// The routines' types.
#[derive(Clone, Copy)]
struct Tys {
@@ -274,7 +231,6 @@ struct Tys {
u: TypeId,
b: TypeId,
vf: TypeId,
vu: TypeId,
}
fn types(mb: &mut ModuleBuilder) -> BResult<Tys> {
@@ -288,32 +244,23 @@ fn types(mb: &mut ModuleBuilder) -> BResult<Tys> {
elem: f,
len: LANES,
})?;
let vu = mb.ty(Type::Vector {
// Declared here, so the module keeps the order of its type declarations.
mb.ty(Type::Vector {
elem: u,
len: LANES,
})?;
Ok(Tys { f, u, b, vf, vu })
Ok(Tys { f, u, b, vf })
}
fn bin(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult<Value> {
fb.binary(op, a, b)
}
/// A float operation no device may contract or regroup.
fn exact_op(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult<Value> {
fb.binary_no_contraction(op, a, b)
}
/// The `u32` scalar `v`.
fn u1(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
splat(fb, uform(1), u64::from(v))
}
/// The `uvec4` of `v` in every lane.
fn u4(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
splat(fb, uform(LANES), u64::from(v))
}
/// The `f32` scalar `x`.
fn f1(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult<Value> {
splat(fb, fform(1), u64::from(x.to_bits()))
@@ -342,396 +289,3 @@ fn finish(mut fb: FunctionBuilder<'_>, r: Value) -> BResult<FuncId> {
fb.ret(Some(r))?;
fb.finish()
}
// ---- The exact sums ----
/// The grid of an `EXACT` format: `D` (`16 · 255`, `16 · 127`, `65535`,
/// or `32767`; with `SRGB` `4095` for the color lanes and `16 · 255` for
/// alpha; with `EXTENDED` `16 · 510` for the color lanes, `8192` an `_sRGB` twin's, and `8 · 510`
/// for alpha) as `u32` lanes, the bounds of a tap's code (`±D`, `±2D` for `EXTENDED`) as `f32`
/// lanes, the bounds of a sum's step (`[0, D]`, `[-D, D]` for a signed format,
/// `[-2D, 2D]` for `EXTENDED`) as `i32` bits, and what the result's quotient reads: the grid it
/// divides by (`D`, or `2D` for `EXTENDED`, whose steps reach past `D`), the factor that restores
/// it (1 or 2, exact), and the lanes whose `half` result rounds ties away from zero (an
/// `EXTENDED` `_sRGB` twin's color lanes, a YCbCr field's). A tap's code is recovered on `scale`
/// (`f32` lanes) and
/// multiplied by `per` (`u32` lanes): `D` and 1 (no `per`), but on a packed normalized format's
/// lanes (its `TexelFormat::PACKED` field with `PackedTexels::filter_grids`, where the routine
/// reads such a class: [`Packed`]), which take the field's grid `D` each, their channel's code
/// scale `S` (also the code's bound) and `D / S`. Such a routine's grid also states whether the
/// field names its grids and the field's truncation `s` per lane
/// (`PackedTexels::filter_truncation`), which [`Truncation::of`] takes there. A field whose steps
/// reach `±2D` (`PackedTexels::filter_extended`) bounds its codes by `±2S` and divides by `2D`.
struct Grid {
scale: Value,
per: Option<Value>,
cap: Value,
neg_cap: Value,
lo: Value,
hi: Value,
divisor: Value,
factor: Value,
away: Value,
packed: Option<(Value, Value)>,
}
/// Whether a routine's treatment may name a packed normalized format's grids: a `TexelFormat`
/// class's routine (the linear filter's), not a `BicubicTexels` one's.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Packed {
Field,
No,
}
fn grid(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, packed: Packed) -> BResult<Grid> {
let wide16 = flag(fb, flags, BicubicTexels::WIDE16)?;
let snorm = flag(fb, flags, BicubicTexels::SNORM)?;
let (d16s, d16u) = (u1(fb, 32767)?, u1(fb, 65535)?);
let (d8s, d8u) = (u1(fb, 16 * 127)?, u1(fb, 16 * 255)?);
let d16 = fb.select(snorm, d16s, d16u)?;
let d8 = fb.select(snorm, d8s, d8u)?;
let d = fb.select(wide16, d16, d8)?;
let d = broadcast(fb, t.vu, d)?;
let srgb = flag(fb, flags, BicubicTexels::SRGB)?;
let (color, alpha) = (u1(fb, 4095)?, u1(fb, 16 * 255)?);
let srgb_d = fb.composite_construct(t.vu, &[color, color, color, alpha])?;
let d = fb.select(srgb, srgb_d, d)?;
let extended = flag(fb, flags, BicubicTexels::EXTENDED)?;
let (linear, steps, alpha) = (u1(fb, 16 * 510)?, u1(fb, 8192)?, u1(fb, 8 * 510)?);
let color = fb.select(srgb, steps, linear)?;
let extended_d = fb.composite_construct(t.vu, &[color, color, color, alpha])?;
let d = fb.select(extended, extended_d, d)?;
let (one, two) = (u1(fb, 1)?, u1(fb, 2)?);
let factor_u = fb.select(extended, two, one)?;
let factor_u = broadcast(fb, t.vu, factor_u)?;
let divisor = bin(fb, BinOp::IMul, d, factor_u)?;
let factor = fb.convert(ConvOp::ConvertUToF, factor_u, t.vf)?;
let lo = |fb: &mut FunctionBuilder<'_>, divisor: Value| -> BResult<Value> {
let neg = fb.unary(UnOp::SNegate, divisor)?;
let z = u4(fb, 0)?;
let signed = bin(fb, BinOp::LogicalOr, snorm, extended)?;
fb.select(signed, neg, z)
};
let srgb_steps = bin(fb, BinOp::LogicalAnd, extended, srgb)?;
let (yes, no) = (splat(fb, bform(1), 1)?, splat(fb, bform(1), 0)?);
let lanes = crate::lower::arith::ops::ty(fb, bform(LANES))?;
let color_lanes = fb.composite_construct(lanes, &[yes, yes, yes, no])?;
let none = splat(fb, bform(LANES), 0)?;
let away = fb.select(srgb_steps, color_lanes, none)?;
let Some(p) = packed_grids(fb, t, flags, packed)? else {
let cap = fb.convert(ConvOp::ConvertUToF, divisor, t.vf)?;
return Ok(Grid {
scale: fb.convert(ConvOp::ConvertUToF, d, t.vf)?,
per: None,
cap,
neg_cap: fb.unary(UnOp::FNegate, cap)?,
lo: lo(fb, divisor)?,
hi: divisor,
divisor,
factor,
away,
packed: None,
});
};
let packed = p.named;
// A packed field's lanes: its grids, each tap's code recovered on its channel's scale
// (clamped there, within `±2S` where the field's steps reach `±2D`) and moved onto the grid;
// such a field's step divided by `2D` and doubled, and a YCbCr field's `half` rounded with
// ties away from zero.
let scale = fb.select(packed, p.scales, d)?;
let scale = fb.convert(ConvOp::ConvertUToF, scale, t.vf)?;
let wide = bin(fb, BinOp::LogicalAnd, packed, p.wide)?;
let span = fb.select(wide, two, one)?;
let span = broadcast(fb, t.vu, span)?;
let field_cap = bin(fb, BinOp::IMul, p.scales, span)?;
let cap = fb.select(packed, field_cap, divisor)?;
let cap = fb.convert(ConvOp::ConvertUToF, cap, t.vf)?;
let neg_cap = fb.unary(UnOp::FNegate, cap)?;
let ones = u4(fb, 1)?;
let per = Some(fb.select(packed, p.per, ones)?);
let field_divisor = bin(fb, BinOp::IMul, p.d, span)?;
let divisor = fb.select(packed, field_divisor, divisor)?;
let span = fb.convert(ConvOp::ConvertUToF, span, t.vf)?;
let factor = fb.select(packed, span, factor)?;
let rounds_away = bin(fb, BinOp::LogicalAnd, packed, p.away)?;
let away = fb.select(rounds_away, color_lanes, away)?;
Ok(Grid {
scale,
per,
cap,
neg_cap,
lo: lo(fb, divisor)?,
hi: divisor,
divisor,
factor,
away,
packed: Some((packed, p.truncation)),
})
}
/// The code of normalized texel `x` on grid `g`, as `i32` bits: `RoundEven(x · D)` (module docs),
/// or on a packed normalized format's lane `RoundEven(x · S) · (D / S)`, its code on its channel's
/// scale `S` moved onto the grid (the device's value may miss `c / S` by more than half a grid
/// step, never by half a code). The product is clamped into the code bounds first (`[-D, D]`,
/// `[-2D, 2D]` for an extended-range lane, `[-S, S]` on a packed lane), which changes no texel's of
/// the format, so that a texel of a format this routine does not serve (its result is selected
/// away) still converts and shifts within range.
fn code(fb: &mut FunctionBuilder<'_>, g: &Grid, x: Value) -> BResult<Value> {
let y = fb.binary_no_contraction(BinOp::FMul, x, g.scale)?;
let y = fb.glsl(GlslOp::NClamp, &[y, g.neg_cap, g.cap])?;
let y = fb.glsl(GlslOp::RoundEven, &[y])?;
let it = crate::lower::arith::ops::ty(fb, uform(LANES))?;
let c = fb.convert(ConvOp::ConvertFToS, y, it)?;
match g.per {
Some(per) => bin(fb, BinOp::IMul, c, per),
None => Ok(c),
}
}
/// The value `n / D` of grid step `n` (`i32` bits, within the grid's step bounds): `+0` for
/// zero, the magnitude divided exactly, rounded to `f32`, or to `half` when `half`, and the sign
/// set. An extended-range lane divides by `2D` and doubles, exactly; its `_sRGB` color lanes'
/// `half` is the exact `f32` rounded with ties away from zero.
fn ratio(fb: &mut FunctionBuilder<'_>, g: &Grid, n: Value, half: Value) -> BResult<Value> {
let rf = texel_round::grid_value(fb, uform(LANES), n, g.divisor, |fb, m, d| {
texel_round::ratio_to_f32(fb, uform(LANES), m, d)
})?;
let rh = texel_round::grid_value(fb, uform(LANES), n, g.divisor, |fb, m, d| {
texel_round::ratio_to_half(fb, uform(LANES), m, d)
})?;
let rf = exact_op(fb, BinOp::FMul, rf, g.factor)?;
let rh = exact_op(fb, BinOp::FMul, rh, g.factor)?;
let ra = texel_round::f32_to_half(fb, fform(LANES), rf, HalfRounding::NearestAway)?;
let rh = fb.select(g.away, ra, rh)?;
fb.select(half, rh, rf)
}
/// The parameters of a [`Quad`] routine, in order.
struct QuadParams {
t00: Value,
t01: Value,
t10: Value,
t11: Value,
kx: Value,
ky: Value,
flags: Value,
half: Value,
}
fn quad_params(fb: &mut FunctionBuilder<'_>, t: Tys) -> BResult<QuadParams> {
Ok(QuadParams {
t00: fb.param(t.vf)?,
t01: fb.param(t.vf)?,
t10: fb.param(t.vf)?,
t11: fb.param(t.vf)?,
kx: fb.param(t.u)?,
ky: fb.param(t.u)?,
flags: fb.param(t.u)?,
half: fb.param(t.b)?,
})
}
/// `fn(t00, t01, t10, t11, kx, ky, flags, half) -> vec4` (module docs, [`Quad::exact`]): Metal's
/// sum over the four taps under the weights `w = wx · wy` in units of `2^-16`, the axes' weights
/// `256 - k` and `k` (a merged axis's fraction arrives as 0), each term truncated: `T = Σ ⌊c · w /
/// 2^s⌋` for the codes `c` on the format's grid, then the step `⌊(T + 2^(15 - s)) / 2^(16 -
/// s)⌋`, clamped and divided by the grid exactly. `s` is 8 for a 16-bit format's codes and 4 for
/// every 12-bit grid: an sRGB color lane's step is truncated, and an 8-bit lane's `16 ·
/// code` term is a multiple of 16, so its sum is the exact one, rounded half up. An extended-range
/// format's `s`
/// is 7 on a color lane and 4 on alpha (every lane of random 2D footprints of the
/// four formats). An unsigned format's product `c · w` is below `2^32` (codes below `2^16`, weights
/// at most `2^16`), a `u32` word shifted logically; a signed format's codes (at most `2^15 - 1` in
/// magnitude) keep it below `2^31`, an `i32` shifted arithmetically (toward negative infinity), as
/// an extended-range format's do (below `2^14`). The terms' sum is below `2^24` in magnitude (the
/// weights sum to `2^16`, and the codes are below `2^12` where `s` is 4, below `2^14` where it is
/// 7, and below `2^16` where it is 8), and so is the biased one.
fn define_exact_quad(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let t = types(mb)?;
let mut fb = mb.kept_routine(t.vf)?;
let q = quad_params(&mut fb, t)?;
let fb_ = &mut fb;
let g = grid(fb_, t, q.flags, Packed::Field)?;
let n = quad_sum(fb_, t, &g, &q, |fb, x| code(fb, &g, x))?;
let r = ratio(fb_, &g, n, q.half)?;
finish(fb, r)
}
/// The exact quad's step ([`define_exact_quad`]) over grid `g` of `q`'s taps (`(i, j)`, `(i + 1,
/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`), each tap's code `code_of` it (taken where its term is),
/// under `q`'s fractions and flags: the terms' step rounded half up and clamped into the grid's
/// step bounds, which the caller divides.
fn quad_sum(
fb_: &mut FunctionBuilder<'_>,
t: Tys,
g: &Grid,
q: &QuadParams,
mut code_of: impl FnMut(&mut FunctionBuilder<'_>, Value) -> BResult<Value>,
) -> BResult<Value> {
let (kx, ky, flags) = (q.kx, q.ky, q.flags);
let k256 = u1(fb_, 256)?;
let wx = [bin(fb_, BinOp::ISub, k256, kx)?, kx];
let wy = [bin(fb_, BinOp::ISub, k256, ky)?, ky];
let tr = Truncation::of(fb_, t, flags, g)?;
let rows = [[q.t00, q.t01], [q.t10, q.t11]];
let mut total = u4(fb_, 0)?;
for (row, b) in rows.into_iter().zip(wy) {
for (x, a) in row.into_iter().zip(wx) {
let c = code_of(fb_, x)?;
let w = bin(fb_, BinOp::IMul, a, b)?;
let w = broadcast(fb_, t.vu, w)?;
let term = tr.term(fb_, c, w)?;
total = bin(fb_, BinOp::IAdd, total, term)?;
}
}
let n = tr.step(fb_, total)?;
fb_.glsl(GlslOp::SClamp, &[n, g.lo, g.hi])
}
/// How a 2D or 3D exact sum truncates its terms: `s` per lane (8 for a 16-bit format's codes, 4 for
/// every 12-bit grid, for an extended-range format 7 on a color lane and 4 on alpha, and on a
/// packed field's grids the field's own, `PackedTexels::filter_truncation`: 7 on YCbCr's grid
/// `2048`), the bias `2^(15 - s)` and shift `16 - s` of the step, and whether the codes are signed
/// (a signed normalized or an extended-range format's), whose terms and sum shift arithmetically
/// (toward negative infinity).
struct Truncation {
s: Value,
bias: Value,
shift: Value,
signed: Value,
}
impl Truncation {
fn of(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, g: &Grid) -> BResult<Truncation> {
let wide16 = flag(fb, flags, BicubicTexels::WIDE16)?;
let snorm = flag(fb, flags, BicubicTexels::SNORM)?;
let extended = flag(fb, flags, BicubicTexels::EXTENDED)?;
let (a, b) = (u1(fb, 8)?, u1(fb, 4)?);
let plain = fb.select(wide16, a, b)?;
let plain = broadcast(fb, t.vu, plain)?;
let seven = u1(fb, 7)?;
let lanes = fb.composite_construct(t.vu, &[seven, seven, seven, b])?;
let s = fb.select(extended, lanes, plain)?;
let s = match g.packed {
Some((named, own)) => fb.select(named, own, s)?,
None => s,
};
let (k15, k16, one) = (u4(fb, 15)?, u4(fb, 16)?, u4(fb, 1)?);
let up = bin(fb, BinOp::ISub, k15, s)?;
let bias = bin(fb, BinOp::ShiftLeftLogical, one, up)?;
let shift = bin(fb, BinOp::ISub, k16, s)?;
let signed = bin(fb, BinOp::LogicalOr, snorm, extended)?;
Ok(Truncation {
s,
bias,
shift,
signed,
})
}
/// The term `⌊c · w / 2^s⌋` of code `c` under weight `w` (`uvec4` lanes).
fn term(&self, fb: &mut FunctionBuilder<'_>, c: Value, w: Value) -> BResult<Value> {
let prod = bin(fb, BinOp::IMul, c, w)?;
let unsigned = bin(fb, BinOp::ShiftRightLogical, prod, self.s)?;
let signed = bin(fb, BinOp::ShiftRightArithmetic, prod, self.s)?;
fb.select(self.signed, signed, unsigned)
}
/// The grid step `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋` of the terms' sum `T`.
fn step(&self, fb: &mut FunctionBuilder<'_>, total: Value) -> BResult<Value> {
let total = bin(fb, BinOp::IAdd, total, self.bias)?;
let unsigned = bin(fb, BinOp::ShiftRightLogical, total, self.shift)?;
let signed = bin(fb, BinOp::ShiftRightArithmetic, total, self.shift)?;
fb.select(self.signed, signed, unsigned)
}
}
/// A packed field's grids ([`packed_grids`]), each `uvec4` lanes.
struct PackedGrids {
/// Whether the treatment names the field's grids.
named: Value,
/// The grids `D`.
d: Value,
/// The channels' code scales `S`.
scales: Value,
/// `D / S`.
per: Value,
/// The 2D and 3D sums' truncation `s` (`PackedTexels::filter_truncation`).
truncation: Value,
/// Whether the field's codes and steps reach `±2D` (`PackedTexels::filter_extended`), a
/// `bool`.
wide: Value,
/// Whether a `half` result rounds the step's value with ties away from zero
/// (`PackedTexels::ycbcr`), a `bool`.
away: Value,
}
/// Whether treatment `flags` names a packed field's grids (its `TexelFormat::PACKED` field with
/// `PackedTexels::filter_grids`, under `BicubicTexels::EXACT`: `TexelFormat::packed_exact`), and
/// per lane that field's grids (each lane 1 for any other field); `None` for a routine whose
/// treatment names none.
fn packed_grids(
fb: &mut FunctionBuilder<'_>,
t: Tys,
flags: Value,
packed: Packed,
) -> BResult<Option<PackedGrids>> {
if packed == Packed::No {
return Ok(None);
}
let shift = u1(fb, TexelFormat::PACKED)?;
let field = bin(fb, BinOp::ShiftRightLogical, flags, shift)?;
let four_bits = u1(fb, 0xF)?;
let field = bin(fb, BinOp::BitwiseAnd, field, four_bits)?;
let no = splat(fb, bform(1), 0)?;
let (mut named, mut wide, mut away) = (no, no, no);
let ones = u4(fb, 1)?;
let (mut d, mut s, mut per, mut truncation) = (ones, ones, ones, ones);
for p in PackedTexels::ALL {
let (Some(grids), Some(cut)) = (p.filter_grids(), p.filter_truncation()) else {
continue;
};
// A field without code scales (a YCbCr field's exact steps) recovers its codes on the
// grids.
let scales = p.scales().unwrap_or(grids);
let k = u1(fb, p as u32)?;
let is = bin(fb, BinOp::IEqual, field, k)?;
let lanes = |fb: &mut FunctionBuilder<'_>, v: [u32; 4]| -> BResult<Value> {
let mut l = Vec::with_capacity(4);
for x in v {
l.push(u1(fb, x)?);
}
fb.composite_construct(t.vu, &l)
};
let mut steps = grids;
for (g, s) in steps.iter_mut().zip(scales) {
*g /= s.max(1);
}
let these_d = lanes(fb, grids)?;
let these_s = lanes(fb, scales)?;
let these_per = lanes(fb, steps)?;
let these_cut = lanes(fb, cut)?;
d = fb.select(is, these_d, d)?;
s = fb.select(is, these_s, s)?;
per = fb.select(is, these_per, per)?;
truncation = fb.select(is, these_cut, truncation)?;
named = bin(fb, BinOp::LogicalOr, named, is)?;
if p.filter_extended() {
wide = bin(fb, BinOp::LogicalOr, wide, is)?;
}
if p.ties_away() {
away = bin(fb, BinOp::LogicalOr, away, is)?;
}
}
let exact = flag(fb, flags, BicubicTexels::EXACT)?;
let named = bin(fb, BinOp::LogicalAnd, named, exact)?;
Ok(Some(PackedGrids {
named,
d,
scales: s,
per,
truncation,
wide,
away,
}))
}
@@ -483,9 +483,6 @@ pub(super) struct Texture {
/// The slot's `SpecKey::OffsetBaseAxes` tests, by which a texel offset is placed
/// (`position::offset_dropped`), where the sample reads them ([`Sample::offset_base`]).
pub parent: Option<crate::lower::texture::OffsetBase>,
/// The base level's size (a `uvec2`) where the image's own query does not state it: an
/// in-place texture's, whose image is its planes' texel buffer (`super::in_place`).
pub size: Option<SValue>,
}
/// How a sample's raw texels decode: by one form, a slot's variant's; or by the form a heap handle's class index names (`sampler::heap_raw`), through the
@@ -503,9 +500,6 @@ pub(super) enum Decode {
/// The routine of a `float` result, and of a `half` one where the access rounds to it.
routines: (FuncId, Option<FuncId>),
},
/// The planes of a two-plane YCbCr texture read in place, each tap converted as Metal reads
/// it (`super::in_place::texel`).
InPlace(super::in_place::Planes),
}
/// Where a sample reads: its plane coordinate (two floats), a 2D array's layer (an integer), the
@@ -688,7 +682,6 @@ fn sampled(
flags: value(fb, flags)?,
swizzle,
parent,
size: None,
};
let at = At {
coord,
@@ -787,7 +780,7 @@ fn sampled(
}
/// The footprint over `taps` of the sample at `at` of `tex`, the border color seen through the
/// channels `bits` state: its size the image's query of the taps' level, or `tex`'s stated size.
/// channels `bits` state: its size the image's query of the taps' level.
fn footprint_of(
fb: &mut FunctionBuilder<'_>,
t: &Tys,
@@ -796,24 +789,14 @@ fn footprint_of(
bits: Bits,
taps: &Taps<'_>,
) -> BResult<Footprint> {
match tex.size {
Some(size) => super::bicubic::footprint_sized(
fb,
t,
(at.coord, at.layer, at.passed),
(size, tex.image),
bits,
(taps, tex.parent),
),
None => footprint_of_image(
fb,
t,
(at.coord, at.layer, at.passed),
(tex.img, tex.image),
bits,
(taps, tex.parent),
),
}
footprint_of_image(
fb,
t,
(at.coord, at.layer, at.passed),
(tex.img, tex.image),
bits,
(taps, tex.parent),
)
}
/// The filtered texel at `at` of `tex` (unswizzled) by `state`: a constexpr sampler's linear or
@@ -1043,9 +1026,7 @@ fn swizzled(fb: &mut FunctionBuilder<'_>, tex: &Texture, x: SValue) -> BResult<S
/// The linear sample at `at` of `tex` under `addressing`: the device's `FMix` of the four taps'
/// decoded values by the fractions `k / 256`, a merged axis's fraction taken as 0, or a 3D
/// texture's of the eight ([`block_taps`]); its `half` result the device's narrowing. An in-place
/// two-plane YCbCr texture's is Metal's exact sum of its taps on its grid (`super::in_place`,
/// `bicubic::routines::Quad`).
/// texture's of the eight ([`block_taps`]); its `half` result the device's narrowing.
pub(super) fn filtered(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -1054,19 +1035,6 @@ pub(super) fn filtered(
tex: &Texture,
addressing: Addressing<'_>,
) -> BResult<SValue> {
if let Decode::InPlace(_) = tex.decode {
let Some(quad) = cx.decl.families.sampler.linear_quad else {
return Err(cx.fail("an in-place linear sample without its routines"));
};
let mut args = quad_taps(cx, fb, t, at, tex, addressing)?.to_vec();
args.push(tex.flags);
let half = fb.module().constant(Constant::Scalar {
ty: t.bool_,
bits: ConstBits(u64::from(at.half)),
})?;
args.push(value(fb, half)?);
return fb.call(quad.exact, &args)?.ok_or_else(missing_routine);
}
let x = match tex.image.plane {
3 => {
let (taps, [kx, ky, kz]) = block_taps(cx, fb, t, at, tex, addressing)?;
@@ -1290,7 +1258,7 @@ pub(super) fn nearest(
let v = texel(cx, fb, &fp, tex, &site, false)?;
crate::lower::arith::extended_range::bfloat_sample_half(fb, v)
}
(true, Decode::Form { .. } | Decode::InPlace(_)) => texel(cx, fb, &fp, tex, &site, true),
(true, Decode::Form { .. }) => texel(cx, fb, &fp, tex, &site, true),
// A heap handle's form: both roundings of the one raw texel, chosen by the form.
(true, Decode::Heap { bfloat, .. }) => {
let (raw, inside) = tap(fb, &fp, tex, &site)?;
@@ -1352,11 +1320,6 @@ pub(super) fn texel(
site: &[Tap],
half: bool,
) -> BResult<SValue> {
if let Decode::InPlace(planes) = tex.decode {
let (at, inside) = fp.site(fb, site)?;
let v = super::in_place::texel(fb, &planes, tex.img, at, half)?;
return fp.border(fb, v, inside);
}
let (raw, inside) = tap(fb, fp, tex, site)?;
let v = decoded(cx, fb, tex, raw, half)?;
fp.border(fb, v, inside)
@@ -1400,7 +1363,6 @@ fn decoded(
fb.call(routine, &[raw, form, inside])?
.ok_or_else(missing_routine)
}
Decode::InPlace(_) => Err(cx.fail("an in-place tap decoded as a raw texel")),
}
}
@@ -1,5 +1,5 @@
//! The sampling routines are routines: the in-place linear quad's exact sum states `DontInline`,
//! every other function none, and the entry states none.
//! The bicubic filters' sums are plain routines: each states no function control, as the entry
//! does.
use super::kernel_on;
use crate::lower::sampler::bicubic::routines;
@@ -21,21 +21,16 @@ fn controls(words: &[u32]) -> Vec<u32> {
out
}
/// The linear and bicubic filters' sums beside a kernel entry: the in-place linear quad's exact
/// sum, a kept routine, states `DontInline` (0x2) and every other function `None`.
/// The bicubic filters' sums beside a kernel entry: each routine and the entry state `None`.
#[test]
fn the_texel_routine_alone_is_declared_dont_inline() {
fn the_bicubic_routines_state_no_function_control() {
let mut b = ModuleBuilder::new();
routines::define_plane(&mut b).expect("plane");
routines::define_line(&mut b).expect("line");
routines::define_quad(&mut b).expect("quad");
let m = kernel_on(b, 3, &|_, p, _| Ok(p)).expect("kernel");
let words = serialize(m).expect("serialized").words;
let mut got = controls(&words);
got.sort_unstable();
// 3 routines (the plane's, the line's and the quad's) and the entry.
assert!(got.len() >= 4, "{} functions", got.len());
let mut want = vec![0; got.len() - 1];
want.push(0x2);
assert_eq!(got, want, "each routine's control, and none on the entry");
let got = controls(&words);
// 2 routines (the plane's and the line's) and the entry.
assert!(got.len() >= 3, "{} functions", got.len());
assert_eq!(got, vec![0; got.len()], "each function's control");
}
@@ -214,7 +214,6 @@ pub(crate) fn emit(
swizzle: None,
// A heap element's access reads no slot's `OffsetBaseAxes`.
parent: None,
size: None,
};
let at = At {
coord: super::emit::plane_coord(cx, fb, s)?,
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
//! What the device-sampled filters share with the emulated ones the device has no form for
//! (`extended`, `heap_raw`, `in_place`, `bicubic`): the census words of a filter's footprint and
//! (`extended`, `heap_raw`, `bicubic`): the census words of a filter's footprint and
//! of a runtime sampler's word, the rule of an axis whose two taps read one texel ([`merged`]), and
//! the samplers that read one texel of one level ([`unfiltered`]).
//!
@@ -11,8 +11,7 @@
//! (`PackedTexels::YCbCr2048`), `8192` (`PackedTexels::YCbCr8192`), or `8192` signed within
//! `[-2, 2]` (`PackedTexels::YCbCrExtended8192`). Metal's 2D linear sample sums the steps on the
//! grid, each term truncated; the device's sampler filters the view's texels its own way
//! (`PrecisionNote::DeviceSampling`). A device whose memory is the host's reads a slot's planes in
//! place, Metal's filter exactly (`in_place`).
//! (`PrecisionNote::DeviceSampling`).
use crate::air::abi::{Filter, MipFilter, SamplerState};
use crate::lower::select::{NoteOn, NoteTest};
@@ -166,7 +166,6 @@ pub mod extended;
pub mod face;
pub mod footprint;
pub mod heap_raw;
pub mod in_place;
pub mod level;
pub mod linear;
pub mod position;
@@ -1312,8 +1311,6 @@ pub struct Declared {
pub bicubic_plane: Option<bicubic::routines::Plane>,
/// The 1D bicubic samples' routine, when the module has one.
pub bicubic_line: Option<bicubic::routines::Line>,
/// The in-place two-plane YCbCr linear samples' routines, when the module has one.
pub linear_quad: Option<bicubic::routines::Quad>,
/// Under the identity domains, the set-1 sampler array of each use ([`IdentitySampling`]).
pub identity: BTreeMap<SamplerUse, GlobalId>,
}
@@ -1364,9 +1361,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
level_views: None,
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
rows: false,
parts: None,
};
if crate::lower::access::identity(cx.profile) {
@@ -1857,9 +1851,6 @@ pub fn declare(
bicubic::routines::Routine::Line => {
d.bicubic_line = Some(bicubic::routines::define_line(mb)?);
}
bicubic::routines::Routine::Quad => {
d.linear_quad = Some(bicubic::routines::define_quad(mb)?);
}
}
}
Ok(d)
@@ -1,6 +1,6 @@
//! Metal's texel-space position of a normalized coordinate, which the filters the device has no
//! form for read their footprints from (`bicubic`, `extended`, `heap_raw`, `in_place`, and the
//! residency `footprint`), and Metal's placement of a texel offset on a repeating or mirrored axis.
//! form for read their footprints from (`bicubic`, `extended`, `heap_raw`, and the residency
//! `footprint`), and Metal's placement of a texel offset on a repeating or mirrored axis.
//!
//! **The position** (Apple M3 Max, macOS 26.7, and Apple M4, macOS 27.0.1, byte-identical; the
//! tie, gather, and bicubic probes). Per axis of size `N` and normalized coordinate `u`, Apple's
@@ -665,7 +665,7 @@ fn the_offset_rule_is_metals_by_level_and_base() {
/// view's own, as before.
#[test]
fn the_offset_rule_reads_the_parent_s_base_through_the_view_bit() {
use crate::bind::TextureFacts;
use crate::bind::state::TextureFacts;
use crate::metal::{PixelFormat, TextureType};
let rule = |n: u32, base: u32| (2..=7).contains(&n) && !base.is_power_of_two();
let mut lanes = Vec::new();
@@ -1300,9 +1300,6 @@ fn select_slot(
}
_ => sampler,
};
if let Some(sample) = select_in_place(cx, call, index, &sampler, arm, m)? {
return Ok(TextureStrategy::InPlaceSample(Box::new(sample)));
}
match crate::lower::texture::extended_range(cx, ImageRef::Slot(index))? {
Some(form) => select_extended(cx, call, (index, form), sampler, m),
None => select_one(cx, call, ImageRef::Slot(index), sampler, arm, m)
@@ -1310,263 +1307,6 @@ fn select_slot(
}
}
/// Observe sampling call `call` of texture slot `index` through `sampler` for the slot's in-place
/// form (`slot::InPlaceReads`), and where the slot's variant reads a two-plane YCbCr texture's
/// planes in place (`LoweringInputs::ycbcr_in_place`) select the form's sample
/// ([`in_place_sample`]); else `None`, and the slot's other forms sample it. A call the form does
/// not read keeps the slot from it, so its variant never meets one.
fn select_in_place(
cx: &mut SelectCx<'_>,
call: Call<'_>,
index: u32,
sampler: &SamplerArg,
arm: Option<bool>,
m: &mut Meter,
) -> Result<Option<super::in_place::Sample>, Error> {
let variant = crate::lower::texture::ycbcr_in_place(cx, index)?;
let Some((sample, samplers)) = in_place_sample(cx, call, index, sampler, arm)? else {
crate::lower::texture::not_in_place(cx, index);
return Ok(None);
};
let Some(s) = cx.families.texture.slots.get_mut(&index) else {
return Err(cx.invariant("an unplanned texture slot"));
};
s.in_place.samplers |= samplers;
s.in_place.device_blocked |= !device_takes(&sample);
if !variant {
return Ok(None);
}
// The slot's planes are fetched, as a read fetches texels.
s.observe(call.t.image, Some(TexelClass::Float))?;
s.uses.read = true;
s.offset_base |= sample.offset_base;
// The device's own conversion samples a planes image's slot (`in_place`'s **The device's
// sampler**), whose answers the runtime announces where it binds one: the model is the
// texel buffer's.
let mut sample = sample;
sample.model &= !cx.inputs.ycbcr_planes_sampled.contains_key(&s.slot);
// A runtime sampler's word states the filter, the coordinates, the address modes and the
// border color.
if let super::extended::State::Slot { sampler: n } = sample.state {
let Some(r) = cx.families.sampler.slots.get_mut(&n) else {
return Err(cx.invariant("an unplanned sampler slot"));
};
r.linear = true;
}
// A linear filter's exact sum (a gather sums nothing, and the model's linear sample blends the
// codes; a runtime sampler's word may still take Metal's).
let sums = match sample.state {
super::extended::State::Constant { linear, .. } => linear && !sample.model,
super::extended::State::Slot { .. } => true,
};
if sample.gather.is_none() && sums {
cx.families
.sampler
.bicubic_routines
.insert(super::bicubic::routines::Routine::Quad);
}
if sample.model {
model_note(cx, &sample, m)?;
}
Ok(Some(sample))
}
/// The note of the model's sample `s` (`super::in_place`'s **The model**): the codes' blend, not
/// Metal's exact filter of the format, `PrecisionNote::HalfSampleFilter` for a `half` result and
/// `FloatSampleFilter` for a `float` one, under the clause that the slot binds a converted 4:2:0
/// format (`SpecKey::BoundTexelFormat`, which a consumer reads at each draw or dispatch,
/// `StageModule::precision_notes_bound`), and through a runtime sampler slot that the word bound
/// there filters linearly and addresses no border on either plane axis
/// (`SpecKey::BoundSamplerWord`), where the sample takes the model.
fn model_note(
cx: &mut SelectCx<'_>,
s: &super::in_place::Sample,
m: &mut Meter,
) -> Result<(), Error> {
use crate::metal::texel_format::{PackedTexels, TexelFormat};
let note = match s.half {
true => PrecisionNote::HalfSampleFilter,
false => PrecisionNote::FloatSampleFilter,
};
let format = NoteTest::equal(
NoteOn::Bound(s.texture),
TexelFormat::PACKED_MASK,
PackedTexels::YCbCr2048.class().0,
);
let mut clause = crate::lower::select::NoteClause::from([format]);
if let super::extended::State::Slot { sampler: n } = s.state {
let on = NoteOn::BoundSampler(n);
let filter = SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR;
clause.insert(NoteTest::equal(on, filter, SamplerWord::LINEAR));
// A mode from 4 on (clamp-to-zero, clamp-to-border) addresses a border.
for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(2) {
clause.insert(NoteTest::equal(on, 4 << shift, 0));
}
}
cx.note_when(note, vec![clause], m)
}
/// Whether the device's own sampler Y′CbCr conversion of a planes image takes in-place sample `s`
/// (`LoweringInputs::ycbcr_planes_sampled`, `super::in_place`'s **The device's sampler**): a
/// constexpr sampler that addresses no border on either plane axis (a 4:2:0 texture samples every
/// other mode as clamp-to-edge, as that sampler does), or a runtime sampler, whose bound word the
/// binder holds to the same (`bind::plan::slots::planes_word`); and no texel offset Metal places
/// by a parent's size; and no gather, which the conversion does not take
/// (`VUID-RuntimeSpirv-OpTypeSampledImage-12206`).
fn device_takes(s: &super::in_place::Sample) -> bool {
use super::bicubic::TapAddress;
let border = match &s.state {
super::extended::State::Constant { address, .. } => {
address.iter().any(|m| matches!(m, TapAddress::Border))
}
super::extended::State::Slot { .. } => false,
};
!border && !s.offset_base && s.gather.is_none()
}
/// Sampling call `call` of texture slot `index` through `sampler` as the in-place form reads it
/// (`in_place`), with the runtime sampler slots it reads (bit `n` `[[sampler(n)]]`); `None` where
/// the form does not: anything but a 2D texture's sample or gradient sample without comparison, or
/// gather of a component without comparison (which follows no filter), with a `float` or `half`
/// result, a constant texel offset or none, no `min_lod_clamp`, and no
/// status word observed, through a constexpr sampler of one filter for minification and
/// magnification (nearest or linear), no anisotropy and the weighted-average reduction, or a
/// runtime sampler slot, whose bound word the binder holds to the same
/// (`bind::plan::slots::in_place_word`); and not an arm of a switch-at-use. Metal's sample reads
/// the texture's one level whatever the mip filter, the level, the bias or the gradients, so the
/// form reads none of them.
fn in_place_sample(
cx: &mut SelectCx<'_>,
call: Call<'_>,
index: u32,
sampler: &SamplerArg,
arm: Option<bool>,
) -> Result<Option<(super::in_place::Sample, u32)>, Error> {
use super::bicubic::TapAddress;
use super::extended::State;
let Call { at, inst, t, args } = call;
let ops = Operands { t, args };
let shape = t.image;
if arm.is_some() || shape.dim != ImageDim::D2 || shape.array || shape.ms || shape.depth {
return Ok(None);
}
let (has_offset, gather) = match t.op {
TexOp::Sample {
compare: false,
offset,
..
}
| TexOp::SampleGrad {
compare: false,
offset,
} => (offset, None),
TexOp::Gather {
component,
compare: false,
offset,
} => {
use crate::air::intrinsics::Component as C;
let component = match component {
None | Some(C::X) => 0,
Some(C::Y) => 1,
Some(C::Z) => 2,
Some(C::W) => 3,
};
(offset, Some(component))
}
_ => return Ok(None),
};
if clamp_value(cx, &ops)?.is_some() || crate::lower::texture::observes_status(cx, at) {
return Ok(None);
}
let offset = match fetch_offset(cx, &ops, has_offset, 2)? {
None => None,
Some(Offset::Const(k)) => Some(k),
Some(Offset::Dynamic(..)) => return Ok(None),
};
let Ok((form, _)) = texel(t, 4) else {
return Ok(None);
};
let half = match form.conv {
TexelConv::F16 => true,
TexelConv::F32 => false,
_ => return Ok(None),
};
let (state, samplers) = match *sampler {
SamplerArg::Static(SamplerRef::Constexpr(words), _) => {
let s = super::state_of(words)?;
let linear = match (s.min_filter, s.mag_filter) {
(Filter::Linear, Filter::Linear) => true,
(Filter::Nearest, Filter::Nearest) => false,
_ => return Ok(None),
};
if s.max_anisotropy > 1 || s.reduction != crate::air::abi::Reduction::WeightedAverage {
return Ok(None);
}
// A gather follows no filter.
let linear = linear && gather.is_none();
let address = [s.address_s, s.address_t]
.into_iter()
.map(|m| match m {
AddressMode::ClampToEdge => TapAddress::Edge,
AddressMode::Repeat => TapAddress::Repeat,
AddressMode::MirroredRepeat => TapAddress::Mirror,
AddressMode::ClampToZero | AddressMode::ClampToBorder => TapAddress::Border,
})
.collect();
let state = State::Constant {
linear,
address,
border: s.border_color,
pixel: s.coordinates == Coordinates::Pixel,
};
(state, 0)
}
SamplerArg::Static(SamplerRef::Slot(n), _) if n < 32 => {
(State::Slot { sampler: n }, 1 << n)
}
_ => return Ok(None),
};
// An offset on an axis that may repeat or mirror is placed by Metal's rule, which reads a
// view's parent's base-level size: the slot's `OffsetBaseAxes` states where it differs.
let offset_base = offset.as_deref().is_some_and(|o| {
o.iter().enumerate().any(|(a, k)| {
*k != 0
&& match &state {
State::Constant { address, .. } => address
.get(a)
.is_some_and(|m| matches!(m, TapAddress::Repeat | TapAddress::Mirror)),
State::Slot { .. } => true,
}
})
});
let coord = ops
.get(TexRole::Coord)
.ok_or_else(|| cx.invariant("a sampling call without a coordinate"))?;
// The model takes a linear sample that addresses no border and whose offset no parent's size
// places: a constexpr sampler's state decides now, a runtime sampler's word as it runs.
let model = gather.is_none()
&& !offset_base
&& match &state {
State::Constant {
linear, address, ..
} => *linear && !address.iter().any(|m| matches!(m, TapAddress::Border)),
State::Slot { .. } => true,
};
let sample = super::in_place::Sample {
texture: index,
state,
offset,
offset_base,
coord: id(cx, coord)?,
half,
gather,
model,
result: cx.lowered_repr(Value::Inst(at), inst.ty)?,
};
Ok(Some((sample, samplers)))
}
/// Select sampling call `call` of texture slot `index`, whose variant binds the extended-range
/// format `form`, through `sampler`: Metal's nearest or linear filter of the decoded texels,
/// emulated by fetches of the raw texels on every device (`extended`). Built: a 2D or 2D array
+1 -6
View File
@@ -1827,8 +1827,6 @@ fn identity_unsourced(f: &RuntimeFact) -> bool {
| RuntimeFact::HeapStorageReads { .. }
| RuntimeFact::AnisotropicSampler { .. }
| RuntimeFact::StorageTextureIntegerChannels { .. }
| RuntimeFact::YCbCrInPlace { .. }
| RuntimeFact::TexelRows { .. }
| RuntimeFact::TexelBufferParts { .. }
)
}
@@ -1976,10 +1974,7 @@ fn identity_refusal(plan: &Plan) -> Option<String> {
// at pixel coordinates, bicubic sample of a 1D texture (`Routine::Line`), or specialization of
// a slot's state. Constexpr samplers a lane chooses among beside an argument buffer's texture
// read the set-1 sampler array at the chosen candidate's pushed index
// (`SamplerPlan::heap_array_identity`) or are a switch over them. A two-plane texture's
// sample read in place (`Routine::Quad`) never reaches here: its slot's
// `PushField::YCbCrInPlace` is refused first, as an encoder value the identity domains do not
// source.
// (`SamplerPlan::heap_array_identity`) or are a switch over them.
use crate::lower::sampler::bicubic::routines::Routine;
let sampled = &plan.families.sampler;
let refused = [
+2 -127
View File
@@ -88,7 +88,6 @@ fn value(
return Ok(None);
}
TextureStrategy::ExtendedSample(e) => crate::lower::sampler::extended::emit(cx, fb, e)?,
TextureStrategy::InPlaceSample(e) => crate::lower::sampler::in_place::emit(cx, fb, e)?,
TextureStrategy::AbsentArgument(a) => {
return Ok(null_value(cx, fb, &a.value)?.first().copied());
}
@@ -2416,20 +2415,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR
// read through a sampler is tested as it accesses, with its addressed coordinate against the
// size at its level, so only its layer or sample index can fail.
let mut in_range = None;
if decl.rows {
// A rows slot's texel (`ImageDecl::rows`): its index in the view, of the coordinate
// clamped into the texture, and in range inside the texture at its one level (the select
// checks every such read).
let words = rows_words(cx, fb, &r.image)?;
let (index, mut inside) = rows_texel(fb, words, coord)?;
if let Some(l) = level.take() {
let zero = u32s(fb, 1, 0)?;
let first = fb.binary(BinOp::IEqual, l, zero)?;
inside = fb.binary(BinOp::LogicalAnd, inside, first)?;
}
coord = index;
in_range = Some(inside);
} else if (r.checked() || spec.is_some()) && !volume {
if (r.checked() || spec.is_some()) && !volume {
let size = match (&through, level) {
// The size at the level the read through a sampler accesses, which is the image's.
(Some((_, a)), _) => a.size,
@@ -2784,7 +2770,7 @@ pub(crate) fn heap_raw_form(
/// Whether a texture `stage`'s handles can name is held by its raw texels alone: the
/// `bind::heap::HELD` bit of `SpecKey::HeapRawTextures`, a `bool` fixed at pipeline creation,
/// which a plan gives from the command's heap members (`bind::plan::slots::heap_raw`). It defaults
/// which a consumer may specialize from the command's heap members. It defaults
/// to every bit set, the module's every arm live, where nothing specializes it.
fn raw_textures_held(fb: &mut FunctionBuilder<'_>, stage: Stage) -> BResult<SValue> {
use crate::bind::heap::{FILTERED, HELD};
@@ -3000,16 +2986,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
true => Some(volume_write(cx, fb, img, coord, w.level)?),
false => None,
};
// A rows slot's write (`ImageDecl::rows`): to its texel's index in the view, stored only
// inside the texture, by the function's own test on every profile, as a two-plane 3D
// texture's is.
let volume = match (volume, decl.rows) {
(None, true) => {
let words = rows_words(cx, fb, &w.image)?;
Some(rows_texel(fb, words, coord)?)
}
(volume, _) => volume,
};
let coord = volume.map_or(coord, |(at, _)| at);
// A texture buffer's parts: the part that holds the texel, at its index there; the check
// below tests the texel against the whole width.
@@ -3401,12 +3377,6 @@ fn query_value(
q: &QueryOp,
(decl, img, storage): (&ImageDecl, SValue, bool),
) -> BResult<SValue> {
if decl.in_place {
return in_place_query(cx, fb, q);
}
if decl.rows {
return rows_query(cx, fb, q);
}
let sampled_mips =
decl.usage == ImageUsage::Sampled && !decl.multisampled && decl.dim != Dim::Buffer;
let n = coord_len(decl);
@@ -3500,101 +3470,6 @@ fn query_value(
})
}
/// The answer of query `q` of a slot under its in-place variant (`sampler::in_place`): its
/// texture's width or height from the slot's push field, at a level as at any texture's
/// ([`level_extent`]), and its one level.
fn in_place_query(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
q: &QueryOp,
) -> BResult<SValue> {
let ImageRef::Slot(index) = q.image else {
return Err(cx.fail("an in-place query of a heap element"));
};
let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else {
return Err(cx.fail(format!("texture slot {index} is not planned")));
};
match q.kind {
QueryKind::Size { component } => {
let e = crate::lower::sampler::in_place::extent(cx, fb, slot, component)?;
match q.level {
Some(l) => {
let l = cx.operand(fb, l)?;
level_extent(fb, e, l)
}
None => Ok(e),
}
}
QueryKind::Levels => u32s(fb, 1, 1),
_ => Err(cx.fail("an in-place query the form does not answer")),
}
}
/// The answer of query `q` of a rows slot (`ImageDecl::rows`): its texture's width or height
/// from the slot's push field, at a level as at any texture's ([`level_extent`]), and its one
/// level.
fn rows_query(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, q: &QueryOp) -> BResult<SValue> {
let words = rows_words(cx, fb, &q.image)?;
match q.kind {
QueryKind::Size {
component: c @ (0 | 1),
} => {
let e = fb.composite_extract(words, &[u32::from(c)])?;
match q.level {
Some(l) => {
let l = cx.operand(fb, l)?;
level_extent(fb, e, l)
}
None => Ok(e),
}
}
QueryKind::Levels => u32s(fb, 1, 1),
_ => Err(cx.fail("a rows query the rows do not answer")),
}
}
/// The words of rows slot `image`'s push field (`PushField::TexelRows`, `bind::TexelRows`), a
/// `uvec4` of the texture's width, height, row and first texel in the view, in the open block.
fn rows_words(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
image: &ImageRef,
) -> BResult<SValue> {
let ImageRef::Slot(index) = *image else {
return Err(cx.fail("the rows of a heap element"));
};
let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else {
return Err(cx.fail(format!("texture slot {index} is not planned")));
};
let field = cx.push_field(fb, crate::pipeline::sym::PushField::TexelRows(slot))?;
fb.composite_extract(field, &[0])
}
/// The texel at `coord` (a `uvec2`) of rows `words` ([`rows_words`]): its index in the view,
/// `first + y · row + x` of the coordinate clamped into the texture (whose width and height are
/// never 0), so the access stays inside the view, which ends at the last row's last texel; and
/// whether `coord` lies in the texture.
fn rows_texel(
fb: &mut FunctionBuilder<'_>,
words: SValue,
coord: SValue,
) -> BResult<(SValue, SValue)> {
use crate::bind::TexelRows as W;
let at = |i: usize| i as u32;
let size = fb.vector_shuffle(words, words, &[at(W::WIDTH), at(W::HEIGHT)])?;
let lt = fb.binary(BinOp::ULessThan, coord, size)?;
let inside = fb.unary(UnOp::All, lt)?;
let clamped = clamp_below(fb, coord, size, 2)?;
let x = fb.composite_extract(clamped, &[0])?;
let y = fb.composite_extract(clamped, &[1])?;
let row = fb.composite_extract(words, &[at(W::ROW)])?;
let first = fb.composite_extract(words, &[at(W::FIRST)])?;
let down = fb.binary(BinOp::IMul, y, row)?;
let start = fb.binary(BinOp::IAdd, first, down)?;
let index = fb.binary(BinOp::IAdd, start, x)?;
Ok((index, inside))
}
/// The extent Metal answers at level `l` of a texture whose first level's extent is `e`:
/// `max(1, e >> (l & 255))`, at every level, past the texture's level count too, a shift of 32 or
/// more answering 1. Measured on an Apple M3 Max under macOS 27.0.1: the width, height, and depth
+1 -82
View File
@@ -665,9 +665,6 @@ pub enum TextureStrategy {
/// A sample of a texture slot bound in an extended-range format, emulated by fetches of its
/// raw texels (`sampler::extended`).
ExtendedSample(Box<crate::lower::sampler::extended::Sample>),
/// A sample of a two-plane YCbCr texture slot whose variant reads its planes in place,
/// computed from their codes (`sampler::in_place`).
InPlaceSample(Box<crate::lower::sampler::in_place::Sample>),
/// An operation on the absent handle: a texture or sampler a function constant removed
/// (`memory::handles::Candidate::Absent`).
AbsentArgument(AbsentArgument),
@@ -901,7 +898,6 @@ impl TextureStrategy {
TextureStrategy::ImageblockSlice(s) if s.guard => "texture.imageblock_slice_guarded",
TextureStrategy::ImageblockSlice(_) => "texture.imageblock_slice",
TextureStrategy::ExtendedSample(e) => e.name(),
TextureStrategy::InPlaceSample(e) => e.name(),
TextureStrategy::AbsentArgument(_) => AbsentArgument::NAME,
})
}
@@ -958,7 +954,6 @@ impl TextureStrategy {
TextureStrategy::Switch(s) => s.words(),
TextureStrategy::ImageblockSlice(s) => s.words(),
TextureStrategy::ExtendedSample(e) => e.words(),
TextureStrategy::InPlaceSample(e) => e.words(),
// The zero, a constant.
TextureStrategy::AbsentArgument(_) => 0,
}
@@ -1242,19 +1237,7 @@ pub fn declare(
}
None => image,
};
// A planes image's slot is the combined image sampler of the device's conversion
// (`ResourceKind::YCbCrPlanes`).
let (ty, symbol) = match decl.planes_sampler {
Some(sampler) => (
mb.ty(SType::SampledImage { image: ty })?,
crate::pipeline::sym::ResourceSlot {
stage: s.slot.stage,
kind: crate::pipeline::sym::ResourceKind::YCbCrPlanes(sampler),
index: s.slot.index,
},
),
None => (ty, crate::pipeline::sym::ResourceSlot::metal(s.slot)),
};
let symbol = crate::pipeline::sym::ResourceSlot::metal(s.slot);
let g = mb.resource(symbol, crate::spirv::ir::StorageClass::UniformConstant, ty)?;
if s.volatile && volatile_decorated(plan) {
mb.volatile(g)?;
@@ -1805,8 +1788,6 @@ pub fn select(
_ => Vec::new(),
};
for index in slots {
not_in_place(cx, index);
not_rows(cx, index);
if extended_range(cx, ImageRef::Slot(index))?.is_some() {
return Err(Unsupported::not_implemented(Feature::Format).into());
}
@@ -1850,8 +1831,6 @@ pub fn select(
let arm = match c {
// A switch-at-use's arm reads its slot's image.
Candidate::Texture(index) => {
not_in_place(cx, index);
not_rows(cx, index);
select_image(cx, (at, inst), t, &ops, ImageRef::Slot(index), m)?
}
Candidate::Absent => AbsentArgument::select(cx, at, inst)?,
@@ -2454,29 +2433,6 @@ pub(crate) fn extended_range(
Ok(cx.inputs.extended_range.get(&slot).copied())
}
/// Whether texture slot `index`'s variant reads a two-plane YCbCr texture's planes in place
/// (`LoweringInputs::ycbcr_in_place`, `sampler::in_place`).
pub(crate) fn ycbcr_in_place(cx: &SelectCx<'_>, index: u32) -> Result<bool, Error> {
let slot = slot_of(cx, index)?.slot;
Ok(cx.inputs.ycbcr_in_place.contains(&slot))
}
/// Record an access of texture slot `index` that its in-place form does not read
/// (`slot::InPlaceReads::blocked`): no texture is read in place there.
pub(crate) fn not_in_place(cx: &mut SelectCx<'_>, index: u32) {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.in_place.blocked = true;
}
}
/// Record an access of texture slot `index` that its texture's rows read in place do not answer
/// (`slot::SlotPlan::not_rows`): the slot takes no rows variant.
pub(crate) fn not_rows(cx: &mut SelectCx<'_>, index: u32) {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.not_rows = true;
}
}
/// Mark texture slot `index` as accessed in a way a texture buffer's parts do not answer
/// (`slot::SlotPlan::not_parts`): the slot takes no parts variant.
pub(crate) fn not_parts(cx: &mut SelectCx<'_>, index: u32) {
@@ -2485,11 +2441,6 @@ pub(crate) fn not_parts(cx: &mut SelectCx<'_>, index: u32) {
}
}
/// Whether the function observes any of texture call `at`'s status word.
pub(crate) fn observes_status(cx: &mut SelectCx<'_>, at: InstId) -> bool {
status_use(cx, at).is_some()
}
/// The numeric class of the texture texture slot `image`'s variant binds where it is not the
/// class the function declares there (`LoweringInputs::cross_class`), else `None`: the slot's
/// image is declared of that class (`slot::image_class`), and its reads, samples and gathers take
@@ -2582,16 +2533,6 @@ pub(crate) fn swizzled_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result<boo
Ok(cx.inputs.swizzled_storage.contains(&slot))
}
/// Whether texture slot `image`'s variant reads and writes its texture's rows in place
/// (`LoweringInputs::texel_rows`, `bind::texel_rows`). A heap element never does.
pub(crate) fn texel_rows(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
let ImageRef::Slot(index) = image else {
return Ok(false);
};
let slot = slot_of(cx, index)?.slot;
Ok(cx.inputs.texel_rows.contains(&slot))
}
/// Record that texture slot `index`'s function applies its bound texture's swizzle: the slot's
/// `TextureSwizzle` specialization (`RuntimeFact::TextureSwizzle`).
pub(crate) fn swizzles(cx: &mut SelectCx<'_>, index: u32) -> Result<(), Error> {
@@ -2669,25 +2610,7 @@ fn select_image(
m: &mut Meter,
) -> Result<TextureStrategy, Error> {
let shape = t.image;
// The in-place form reads a slot's width, height and level count, and nothing else here.
if let ImageRef::Slot(index) = image {
if !matches!(
t.op,
TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels)
) {
not_in_place(cx, index);
}
// The rows read and write a texel by its coordinate, and answer the size, the level
// count and the presence; nothing else.
if !matches!(
t.op,
TexOp::Read
| TexOp::Write
| TexOp::IsNull
| TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels)
) {
not_rows(cx, index);
}
// A texture buffer's parts read, write and update a texel by its index, and answer the
// width, the presence and a fence; nothing else.
if !matches!(
@@ -2912,7 +2835,6 @@ fn select_read_as(
if let Some(t) = through {
select_through(cx, image, texel, t)?;
if let ImageRef::Slot(index) = image {
not_rows(cx, index);
not_parts(cx, index);
}
}
@@ -2946,9 +2868,6 @@ fn select_read_as(
}
let check = match slot::read_check(cx, shape.dim == ImageDim::Buffer) {
ReadCheck::Device if extended.is_some() => ReadCheck::Shader,
// A rows slot's coordinate past the width names the next row's texel in the view
// (`bind::texel_rows`): the shader selects Metal's out-of-bounds texel on every profile.
_ if texel_rows(cx, image)? => ReadCheck::Shader,
c => c,
};
// A storage read at a level reads the slot's level views, and past the bound level count
+6 -219
View File
@@ -91,22 +91,6 @@ pub struct Uses {
pub narrow_result: bool,
}
/// How a slot's accesses read a two-plane YCbCr texture bound there, for its planes read in
/// place (`sampler::in_place`, `RuntimeFact::YCbCrInPlace`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct InPlaceReads {
/// An access the form does not read: anything but a sample or gather it builds
/// (`sampler::select`'s `in_place_sample`) and a query of the width, the height or the level
/// count.
pub blocked: bool,
/// The runtime sampler slots the slot's samples and gathers read, bit `n` `[[sampler(n)]]`.
pub samplers: u32,
/// A sample the device's own sampler Y′CbCr conversion does not take
/// (`LoweringInputs::ycbcr_planes_sampled`): one through a constexpr sampler that addresses a
/// border, one that places a texel offset by a parent's size, or a gather.
pub device_blocked: bool,
}
/// The `OpTypeImage` a slot is declared as, and the conversion a storage image's class needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageDecl {
@@ -132,20 +116,6 @@ pub struct ImageDecl {
/// after the class's conversion, its reads take alpha 1 and its writes store green in the
/// fourth channel.
pub x_channel: bool,
/// The slot's variant reads a two-plane YCbCr texture's planes in place
/// (`LoweringInputs::ycbcr_in_place`): the image is the planes' uniform texel buffer of
/// unsigned codes (`sampler::in_place`), the texture's size its push field's.
pub in_place: bool,
/// The slot's variant samples those planes as an image through the device's own sampler
/// Y′CbCr conversion (`LoweringInputs::ycbcr_planes_sampled`): the slot is a combined image
/// sampler of a sampled 2D `float` image (`ResourceKind::YCbCrPlanes`), whose immutable
/// sampler bakes the conversion; `in_place` holds, so its size is still the push field's.
pub planes_sampler: Option<crate::bind::YCbCrPlanesSampler>,
/// The slot's variant reads and writes a 2D texture's rows in place
/// (`LoweringInputs::texel_rows`, `bind::texel_rows`): the image is the rows' texel buffer,
/// uniform for a sampled slot and storage for a storage one, texel `(x, y)` its texel
/// `first + y · row + x` and the texture's size the push field's.
pub rows: bool,
/// A texture-buffer slot under its parts variant (`LoweringInputs::texel_buffer_parts`,
/// `bind::texel_parts`), declared as an array of its parts' texel buffers.
pub parts: Option<Parts>,
@@ -247,12 +217,6 @@ pub struct SlotPlan {
/// specialization, which states the axes on which the base-level size the rule reads, a
/// view's parent's, is not a power of two where the bound view's is.
pub offset_base: bool,
/// How its accesses read a two-plane YCbCr texture's planes in place.
pub in_place: InPlaceReads,
/// An access its texture's rows read in place do not answer (`bind::texel_rows`): anything
/// but a read or write of a texel by its coordinate, a query of the width, the height or the
/// level count, and a presence test. The uses rule out the rest ([`rows_reads`]).
pub not_rows: bool,
/// An access a texture buffer's parts do not answer (`bind::texel_parts`): anything but a
/// read of a texel by its index (not through a sampler), a write, an atomic, a width query, a
/// presence test and a fence. The uses rule out the rest ([`parts_reads`]).
@@ -281,8 +245,6 @@ impl SlotPlan {
swizzle: false,
constant_lanes: false,
offset_base: false,
in_place: InPlaceReads::default(),
not_rows: false,
not_parts: false,
decl: None,
}
@@ -607,9 +569,6 @@ fn declare_heap(
level_views: None,
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
rows: false,
parts: None,
};
Ok((class, decl))
@@ -1096,107 +1055,6 @@ fn declare_slot(
) -> Result<ImageDecl, Error> {
let images = &cx.profile.fields().images;
let storage = s.storage();
// A slot that samples its texture's planes as an image through the device's own sampler
// Y′CbCr conversion is a combined image sampler of a 2D `float` image, with the field of the
// planes' words for its size (`sampler::in_place`).
if let Some(&sampler) = cx.inputs.ycbcr_planes_sampled.get(&s.slot) {
if !cx.inputs.ycbcr_in_place.contains(&s.slot) {
return Err(cx.invariant("a planes image's slot outside its in-place variant"));
}
push.push(PushField::YCbCrInPlace(s.slot));
counts.sampled_images = counts.sampled_images.saturating_add(1);
counts.samplers = counts.samplers.saturating_add(1);
return Ok(ImageDecl {
dim: Dim::D2,
arrayed: false,
multisampled: false,
depth: false,
usage: ImageUsage::Sampled,
format: crate::spv::ImageFormat::Unknown,
texel: TexelClass::Float,
cube_as_array: false,
class: StorageImageClass::Identity,
level_views: None,
extended: None,
x_channel: false,
in_place: true,
planes_sampler: Some(sampler),
rows: false,
parts: None,
});
}
// A slot under its in-place variant is the uniform texel buffer of its texture's planes, of
// unsigned codes, with the field of their words (`sampler::in_place`).
if cx.inputs.ycbcr_in_place.contains(&s.slot) {
push.push(PushField::YCbCrInPlace(s.slot));
counts.sampled_images = counts.sampled_images.saturating_add(1);
return Ok(ImageDecl {
dim: Dim::Buffer,
arrayed: false,
multisampled: false,
depth: false,
usage: ImageUsage::Sampled,
format: crate::spv::ImageFormat::Unknown,
texel: TexelClass::Uint,
cube_as_array: false,
class: StorageImageClass::Identity,
level_views: None,
extended: None,
x_channel: false,
in_place: true,
planes_sampler: None,
rows: false,
parts: None,
});
}
// A slot under its rows variant is the texel buffer of its texture's rows, with the field of
// their words (`bind::texel_rows`): a uniform one for a sampled slot, a storage one, declared
// as the slot's storage image would be, for a storage slot.
if cx.inputs.texel_rows.contains(&s.slot) {
if !rows_reads(s) {
return Err(cx.invariant("a rows slot whose accesses the rows do not answer"));
}
push.push(PushField::TexelRows(s.slot));
let texel = image_class(cx.inputs, s);
let (format, class) = match storage {
true => {
facts.push(RuntimeFact::StorageTextureFormat { slot: s.slot });
storage_format(cx, s, texel)?
}
false => (
crate::spv::ImageFormat::Unknown,
StorageImageClass::Identity,
),
};
if class != StorageImageClass::Identity {
return Err(cx.invariant("a rows slot whose storage image converts its texels"));
}
match storage {
true => counts.storage_images = counts.storage_images.saturating_add(1),
false => counts.sampled_images = counts.sampled_images.saturating_add(1),
}
return Ok(ImageDecl {
dim: Dim::Buffer,
arrayed: false,
multisampled: false,
depth: false,
usage: match storage {
true => ImageUsage::Storage,
false => ImageUsage::Sampled,
},
format,
texel,
cube_as_array: false,
class,
level_views: None,
extended: None,
x_channel: false,
in_place: false,
planes_sampler: None,
rows: true,
parts: None,
});
}
// A slot bound in an extended-range format holds its raw texels in an unsigned integer
// image.
let extended = cx.inputs.extended_range.get(&s.slot).copied();
@@ -1325,47 +1183,10 @@ fn declare_slot(
level_views: views,
extended,
x_channel,
in_place: false,
planes_sampler: None,
rows: false,
parts,
})
}
/// Whether every access of slot `s` is one its texture's planes read in place answer
/// (`sampler::in_place`), on a profile that takes the form (`ProfileFields::ycbcr_in_place`): a
/// sampled 2D texture's (not an array, multisampled or depth one), of a `float` class or only
/// queried, used, and no access blocked ([`InPlaceReads::blocked`]).
fn in_place_reads(cx: &SelectCx<'_>, s: &SlotPlan) -> bool {
let used = s.uses.read || s.uses.query || s.uses.sample;
cx.profile.fields().ycbcr_in_place
&& used
&& !s.in_place.blocked
&& !s.storage()
&& s.shape
.is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth)
&& matches!(s.texel, None | Some(TexelClass::Float))
}
/// Whether every access of slot `s` is one its texture's rows read in place answer
/// (`bind::texel_rows`): a single-sample 2D color texture's (not an array, multisampled or depth
/// one) of a 32-bit class, read, written or asked its size, every access of a texel at the first
/// level of a storage slot (no level views), and nothing sampled, gathered, updated by an atomic,
/// read through a sampler or a switch, its residency observed or its integer channels read; no
/// access blocked ([`SlotPlan::not_rows`]).
fn rows_reads(s: &SlotPlan) -> bool {
let u = &s.uses;
(u.read || u.write || u.query)
&& !(u.sample || u.compare || u.atomic || u.level_views || u.residency || u.faces)
&& !(u.int_channels || u.narrow_result || s.not_rows)
&& s.shape
.is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth)
&& matches!(
s.texel,
None | Some(TexelClass::Float | TexelClass::Sint | TexelClass::Uint)
)
}
/// Whether every access of texture-buffer slot `s` is one its parts answer (`bind::texel_parts`),
/// on a profile that indexes an array of its kind of texel buffer (storage where the function
/// writes or updates it, else uniform) by a `NonUniform` value: read, written, updated by an
@@ -1435,13 +1256,12 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
}
Err(error) => return Err(error),
};
// A rows slot's every load and store is the function's own test's, inside the view.
let volatile = !d.rows && forwards(cx, &s.uses, shape.dim == ImageDim::Buffer);
let volatile = forwards(cx, &s.uses, shape.dim == ImageDim::Buffer);
decls.push((*index, d, volatile));
}
// The variants a slot may take by its bound texture (cross-class reads, planes read in place,
// a texture's rows, a texture buffer's parts): under the identity domains no binder chooses a
// variant, and the slot reads whatever texture its resource ID names through the plain form.
// The variants a slot may take by its bound texture (cross-class reads, a texture buffer's
// parts): under the identity domains no variant is chosen, and the slot reads whatever
// texture its resource ID names through the plain form.
if !crate::lower::access::identity(cx.profile) {
// The slots read, sampled or gathered in any class (a slot only sampled is declared by its
// combined bindings, `sampler::finish`).
@@ -1450,35 +1270,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
facts.push(RuntimeFact::CrossClassReads { slot: s.slot });
}
}
// The slots whose every access the in-place form reads, on a profile that takes it: their
// compile under the form states the same, which its plan holds to.
for s in cx.families.texture.slots.values() {
let reads = in_place_reads(cx, s);
if !reads && cx.inputs.ycbcr_in_place.contains(&s.slot) {
return Err(
cx.invariant("an in-place texture slot whose accesses the form does not read")
);
}
if s.in_place.device_blocked && cx.inputs.ycbcr_planes_sampled.contains_key(&s.slot) {
return Err(cx.invariant(
"a planes image's texture slot with a sample the device's sampler does not take",
));
}
if reads {
facts.push(RuntimeFact::YCbCrInPlace {
slot: s.slot,
samplers: s.in_place.samplers,
device: !s.in_place.device_blocked,
});
}
}
// The slots whose every access the rows answer: their compile under the rows variant states
// the same, which its plan holds to.
for s in cx.families.texture.slots.values() {
if rows_reads(s) {
facts.push(RuntimeFact::TexelRows { slot: s.slot });
}
}
// The texture-buffer slots whose every access their parts answer: their compile under the
// parts variant states the same, which its plan holds to.
for s in cx.families.texture.slots.values() {
@@ -1747,17 +1538,13 @@ impl SlotPlan {
/// shader joins and splits, so its class is the unsigned integer one of its shape. A texture
/// buffer's is a texel buffer's, uniform where the slot reads and storage where it writes, the
/// element its resource ID holds in the texel-buffer arrays. `None` for a declaration the identity
/// arrays hold no element of yet: a cube viewed as an array, level views, a texture buffer's parts
/// or rows, planes, an extended-range or RGBX form, or a storage image with another format or a
/// conversion.
/// arrays hold no element of yet: a cube viewed as an array, level views, a texture buffer's parts,
/// an extended-range or RGBX form, or a storage image with another format or a conversion.
pub(crate) fn identity_class(decl: &ImageDecl) -> Option<ImageHandleClass> {
let plain = !decl.cube_as_array
&& decl.level_views.is_none()
&& decl.extended.is_none()
&& !decl.x_channel
&& !decl.in_place
&& decl.planes_sampler.is_none()
&& !decl.rows
&& decl.parts.is_none()
&& decl.class == StorageImageClass::Identity;
let dim = match decl.dim {
+3 -35
View File
@@ -1687,25 +1687,6 @@ pub fn define_lookup(mb: &mut ModuleBuilder, t: Table, form: Lookup) -> BResult<
fb.finish()
}
/// The search [`lookup`] emits, on the host: the element of `id` in `table`, a slice of
/// `(resource_id, element)` entries sorted by id whose first entry is the null entry. The
/// emitter's reference model, which every table a binder builds must satisfy.
pub fn lookup_host(table: &[(u64, u32)], id: u64) -> u32 {
let (mut base, mut len) = (0usize, table.len());
for _ in 0..SEARCH_STEPS {
let half = len >> 1;
let mid = base + half;
if table.get(mid).is_some_and(|(k, _)| *k <= id) {
base = mid;
}
len -= half;
}
match table.get(base) {
Some((k, e)) if *k == id => *e,
_ => NEUTRAL_ELEMENT,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1876,19 +1857,6 @@ mod tests {
.map_or(NEUTRAL_ELEMENT, |i| t[i].1)
}
/// The host model finds every entry of sorted tables up to [`TABLE_CAPACITY`] entries in
/// [`SEARCH_STEPS`] steps, and maps every absent id (and the null id) to the neutral element.
#[test]
fn the_search_finds_every_entry_up_to_the_capacity() {
assert_eq!(1u64 << SEARCH_STEPS, u64::from(TABLE_CAPACITY));
for n in [1, 2, 3, 4, 5, 16, 17, 100, 4097, TABLE_CAPACITY as usize] {
let t = table(n);
for id in keys(&t) {
assert_eq!(lookup_host(&t, id), reference(&t, id), "n {n} id {id:#x}");
}
}
}
const KEYS: u32 = 8;
/// A kernel that looks up the [`KEYS`] ids (low, high word pairs) at the start of the
@@ -1948,7 +1916,7 @@ mod tests {
/// The emitted search is the host model: over the CPU interpreter, every key of tables of
/// several sizes up to [`TABLE_CAPACITY`] entries (the null id, present ids, absent ids between
/// and beyond them) gets [`lookup_host`]'s element, through an entry array (`u64` ids) and a
/// and beyond them) gets [`reference`]'s element, through an entry array (`u64` ids) and a
/// word view. [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`]
/// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, its texel class where it carries that,
/// and its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`] where it carries that, carrying no other
@@ -2149,7 +2117,7 @@ mod tests {
u32::from_le_bytes(io[at..at + 4].try_into().expect("word"))
};
for (i, id) in chunk.iter().enumerate() {
let e = lookup_host(&t, *id);
let e = reference(&t, *id);
let carried = |on: bool, flag: u32, bit: u32| match on {
true if flags(e) & flag != 0 => bit,
_ => 0,
@@ -2227,7 +2195,7 @@ mod tests {
for (i, id) in chunk.iter().enumerate() {
let at = 4 * (2 * KEYS as usize + i);
let got = u32::from_le_bytes(io[at..at + 4].try_into().expect("word"));
let e = lookup_host(&t, *id);
let e = reference(&t, *id);
let carried = |on: bool, flag: u32, bit: u32| match on {
true if flags(e) & flag != 0 => bit,
_ => 0,
+8 -8
View File
@@ -16,17 +16,17 @@
//! entries `{host, guest, size, bind_offset}: u64`. Entry 0 is the null root (all fields 0:
//! `guest = 0` makes a miss round-trip through a later `ptrtoint`, `size = 0` puts every access
//! through it out of bounds). Entry 1 is the write-only sink (`host` its device address). Entry
//! `2 + n` is `[[buffer(n)]]`. The **resident set** (the bound arguments and
//! `BindState.used_resources`, overlaps coalesced into the outermost range) is the entries `R0 ..
//! `2 + n` is `[[buffer(n)]]`. The **resident set** (the bound arguments and the resources the
//! encoder makes resident, `useResource:`, overlaps coalesced into the outermost range) is the
//! entries `R0 ..
//! R0 + N`, sorted by `guest` and disjoint but for indirect command buffers' records, which may
//! overlap (each found only at its start, `lower::access::dynamic::search_start`), each with
//! `bind_offset = 0`. The binder states `R0` and
//! `bind_offset = 0`. The consumer states `R0` and
//! `N` in the sink entry's otherwise unread `guest` and `size` fields ([`RESIDENT_FIRST`],
//! [`RESIDENT_COUNT`]); `N` is any count (At most 2¹⁶ before, a larger set
//! `BindError::ResidentSetTooLarge`). `R0` counts entries from the table's address modulo 2⁶⁴, so
//! [`RESIDENT_COUNT`]); `N` is any count. `R0` counts entries from the table's address modulo 2⁶⁴, so
//! the set may lie apart from the table, below it too (a consumer's set shared by many tables).
//!
//! **The search** ([`resolve`]) turns a guest address `i` into a wide pointer: a binary search for
//! **The search** ([`define_resolve`]) turns a guest address `i` into a wide pointer: a binary search for
//! the last resident entry whose `guest ≤ i`, whose step halves the candidates whatever its
//! compare gives (one entry load and a select, no branch on the address), so its trip count
//! follows `N` alone and every invocation that searches one table takes the same branches. A set
@@ -250,7 +250,7 @@ fn field_of(fb: &mut FunctionBuilder<'_>, e: Value, root: Value, field: u64) ->
}
/// The wide pointer `[root, at, host, size]` (four `u64`s) of guest address `guest` (a `u64`)
/// through the resident set of the root table at `table` ([`resolve`]): a hit's `at` is `i −
/// through the resident set of the root table at `table` ([`define_resolve`]): a hit's `at` is `i −
/// guest` (a resident entry's `bind_offset` is 0) and `host` and `size` its entry's, read here
/// once; a miss is `[0, i, 0, 0]`, the null root's fields.
pub fn resolve_wide(
@@ -280,7 +280,7 @@ struct Found {
off: Value,
}
/// The search of [`resolve`].
/// The search of [`define_resolve`].
fn search(fb: &mut FunctionBuilder<'_>, table: Value, guest: Value) -> BResult<Found> {
let e = entries(fb, table)?;
let sink = k64(fb, SINK_ROOT)?;
+6 -26
View File
@@ -136,8 +136,7 @@ pub enum FormatEmulation {
/// `R32G32B32A32_SFLOAT` of an `_sRGB` twin's (a grid of `1/8192`), and
/// `A2B10G10R10_UNORM_PACK32` of the codes. Exact for a sampled image a function reads or
/// fetches from; a linear sample is the device's filter of the texels, noted, off their grid
/// (`metal::texel_format::PackedTexels::YCbCr2048` and `YCbCr8192`), but where the function
/// reads the planes in place (`bind::YCbCrInPlace`), Metal's filter. Admitted for sampling only:
/// (`metal::texel_format::PackedTexels::YCbCr2048` and `YCbCr8192`). Admitted for sampling only:
/// Metal drops a function's writes to a 4:2:0 or 4:2:2 format ([`writes_dropped`]), stores a
/// 4:4:4 one's into both planes (refused here, `storage_choice`), and renders into such a
/// texture by an inverse conversion, for which a pipeline into one of [`ycbcr_renders`] is
@@ -1131,24 +1130,6 @@ pub fn alpha_in_red(pf: PixelFormat, profile: &DeviceProfile) -> bool {
alpha_in_red_format(pf).is_some() && direct_format(pf).is_some_and(|own| !held(own))
}
/// The format a texel buffer view of a texture buffer of `pf` takes for `usage` (a texel buffer
/// usage) on `profile` where the format's own does not serve it and the bytes hold Metal's alpha in
/// red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm` on a device that views no
/// `A8_UNORM` texels for the usage (a Vulkan 1.2 device without `VK_KHR_maintenance5`), where it
/// views `R8_UNORM` ones. A view reads `(r, 0, 0, 1)` where Metal reads `(0, 0, 0, r)`: a storage
/// view's reads and writes convert by its choice's class (`StorageImageClass::AlphaInRed`,
/// [`storage_choice`]), and a uniform view's reads take the alpha from red through the slot's
/// swizzle (`TextureSwizzleChannels::alpha_in_red`). `None` elsewhere.
pub(crate) fn texel_buffer_alpha_in_red(
pf: PixelFormat,
usage: FormatUsage,
profile: &DeviceProfile,
) -> Option<vk::Format> {
let own = direct_format(pf)?;
let held = alpha_in_red_format(pf)?;
(!profile.supports_format(own, usage) && profile.supports_format(held, usage)).then_some(held)
}
/// The format of `pf`'s image where the device holds no image of its direct format and `pf`
/// holds Metal's alpha in red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm`,
/// `None` for every other format.
@@ -1873,10 +1854,10 @@ pub fn ycbcr(pf: PixelFormat) -> bool {
/// kernel's write leaves both planes' bytes as they were, and Metal's validation stops the
/// binding), and the packed ones, `YCBCR10_444_2P_PACKED` and its `_sRGB` twin among them (the
/// M3 Max under macOS 27.0.1, our probe `ycw` over `p444` and `pf44` surfaces: every byte of both
/// planes kept, the command buffer completed; an Apple M4 stores them). A storage slot a function
/// only writes takes its neutral there (`bind::plan`), and so does a heap's storage class
/// (`bind::heap`, an argument buffer's texture, whose writes Metal drops alike: the M3 Max under
/// macOS 27.0.1, `YCBCR8_420_2P`), which the writes leave as Metal leaves the texture.
/// planes kept, the command buffer completed; an Apple M4 stores them). A heap's storage class
/// holds such a texture as its neutral (`bind::heap::fit`, an argument buffer's texture, whose
/// writes Metal drops alike: the M3 Max under macOS 27.0.1, `YCBCR8_420_2P`), which the writes
/// leave as Metal leaves the texture.
///
/// An unpacked 4:4:4 YCbCr format's writes are not dropped: Metal stores each texel's codes into
/// both planes, and a slot that writes one is refused (`storage_choice`).
@@ -2661,8 +2642,7 @@ pub fn storage_image_choice(
/// `SrgbEncode` (`BGRA8Unorm_sRGB`, where its twin is not accessed without a format, through
/// `R8G8B8A8_UNORM` with `SrgbEncodeBgra`), `RGB9E5Float` through `R32_UINT` with
/// `SharedExponentBits`, and `A8Unorm` through `R8_UNORM` with `AlphaInRed` (no alias: such a
/// texture's image is `R8_UNORM` itself, [`FormatEmulation::AlphaInRed`]; a texture buffer's bytes
/// take that view wherever `A8_UNORM` does not serve the use, [`texel_buffer_alpha_in_red`]).
/// texture's image is `R8_UNORM` itself, [`FormatEmulation::AlphaInRed`]).
/// Anything else is `Unsupported{Format}` naming what each route lacks, a format's without-format
/// usage included.
///
-20
View File
@@ -375,26 +375,6 @@ impl TextureSwizzleChannels {
a: channel(3, self.alpha),
}
}
/// This swizzle of the texel `(0, 0, 0, a)` an `A8Unorm` texture buffer reads, as a swizzle
/// of the texel `(a, 0, 0, 1)` its bytes' `R8_UNORM` view reads
/// (`metal::format::texel_buffer_alpha_in_red`): each channel taken from red, green or blue is
/// zero, one taken from alpha the view's red, and `Zero` and `One` stay.
pub(crate) fn alpha_in_red(self) -> TextureSwizzleChannels {
let held = |s: TextureSwizzle| match s {
TextureSwizzle::Red | TextureSwizzle::Green | TextureSwizzle::Blue => {
TextureSwizzle::Zero
}
TextureSwizzle::Alpha => TextureSwizzle::Red,
constant => constant,
};
TextureSwizzleChannels {
red: held(self.red),
green: held(self.green),
blue: held(self.blue),
alpha: held(self.alpha),
}
}
}
impl Default for TextureSwizzleChannels {
+3 -189
View File
@@ -396,42 +396,6 @@ pub fn check_sampler(
Ok(())
}
/// [`check_sampler`] for a sampler an argument buffer lists, which a function reads without
/// knowing its state: anisotropy above 1 without `samplerAnisotropy` is refused too, since such a
/// function neither emulates Metal's anisotropic filter through it nor records the isotropic
/// filter its Vulkan sampler takes there (`lower::sampler::anisotropic`'s reach).
pub(crate) fn check_argument_sampler(
shape: &SamplerShape,
use_: SamplerUse,
profile: &DeviceProfile,
) -> Result<(), Error> {
check_sampler(shape, use_, profile)?;
if shape.anisotropic && !profile.fields().images.sampler_anisotropy {
return Err(Unsupported::needs(
Feature::SamplerAnisotropy,
Capability::Feature(VkFeature::SamplerAnisotropy),
)
.into());
}
Ok(())
}
/// What of the Vulkan sampler [`vk_sampler`] makes for a sampler of `shape` used as `use_` decides
/// the format features it needs of a view it reads (`bind::sampler_desc`): whether some filter is
/// linear (none for an integer use, which [`vk_sampler`] makes nearest), and its reduction, the
/// weighted average ([`vk_sampler`]). A plan reads it where a runtime sampler meets its textures
/// through separate descriptors, so the textures' views are checked against the bound sampler at
/// plan time as a combined write's view is per bind.
pub(crate) fn vk_filtering(
shape: &SamplerShape,
use_: SamplerUse,
) -> (bool, vk::SamplerReductionMode) {
(
shape.linear && !use_.integer_texture,
vk::SamplerReductionMode::WEIGHTED_AVERAGE,
)
}
/// The Vulkan sampler for a Metal sampler descriptor used as `use_` on `profile`.
///
/// An integer texture is never filtered: Metal reads a linear filter on one as nearest (an Apple M3
@@ -926,39 +890,10 @@ pub(crate) fn border_texel(
]
}
/// The first bit of a [`constant_lanes`] word that says a lane is the constant 1: bit
/// The first bit of a `SpecKey::ConstantLanes` word that says a lane is the constant 1: bit
/// `CONSTANT_ONES + lane`, where bit `lane` says it is a constant.
pub(crate) const CONSTANT_ONES: u32 = 4;
/// The lanes Metal reads as constants from every texel of a texture whose format holds the
/// channels `present` (red, green, blue, alpha; [`crate::metal::format::channels`]), made with
/// `swizzle`, as a word: bit `lane` (0 red to 3 alpha) where the lane's source is a channel the
/// format lacks or a `Zero` or `One` swizzle, and bit [`CONSTANT_ONES`]` + lane` where that
/// constant is 1 (a missing alpha, or `One`); a missing red, green or blue, and `Zero`, read 0.
/// Metal reads them so at a mapped texel, an unmapped one, and the border alike, and so after any
/// filter, which weighs constants alone there.
pub(crate) fn constant_lanes(present: [bool; 4], swizzle: TextureSwizzleChannels) -> u32 {
let lanes = [swizzle.red, swizzle.green, swizzle.blue, swizzle.alpha];
let mut word = 0;
for (lane, source) in (0u32..).zip(lanes) {
let constant = match source {
TextureSwizzle::Zero => Some(false),
TextureSwizzle::One => Some(true),
TextureSwizzle::Red => (!present[0]).then_some(false),
TextureSwizzle::Green => (!present[1]).then_some(false),
TextureSwizzle::Blue => (!present[2]).then_some(false),
TextureSwizzle::Alpha => (!present[3]).then_some(true),
};
if let Some(one) = constant {
word |= 1 << lane;
if one {
word |= 1 << (CONSTANT_ONES + lane);
}
}
}
word
}
/// Whether every component of `m` is the identity swizzle (Vulkan's "identity mapping": each
/// component `IDENTITY` or its own channel).
pub(crate) fn is_identity(m: vk::ComponentMapping) -> bool {
@@ -1007,16 +942,6 @@ pub fn compare_op(f: CompareFunction) -> vk::CompareOp {
}
}
/// `log2` of the degree a sampler of `desc` filters with: its `maxAnisotropy` rounded up to a power
/// of two, 0 for an isotropic one; a pixel-coordinate sampler is isotropic. The runtime hands the
/// descriptor Metal samples with (`maxAnisotropy` 32 for 17 to 31), whose degree is then 5.
pub(crate) fn anisotropy_degree(desc: &SamplerDescriptor) -> u32 {
if !desc.normalized_coordinates || desc.max_anisotropy <= 1 {
return 0;
}
desc.max_anisotropy.next_power_of_two().trailing_zeros()
}
/// Metal's discrete sampler state as one `u32` word: what a shader reads of a sampler it learns
/// only at run time. Each field holds its `MTLSamplerDescriptor` value's raw Metal enumeration
/// value, so `MTLSamplerDescriptor`'s defaults are the word 0. The bits:
@@ -1348,55 +1273,6 @@ mod tests {
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap()
}
/// What a plan reads of a bound sampler's shape to check its separate textures' views
/// (`vk_filtering`) is exactly what `vk_sampler` makes of the descriptor for the use: a linear
/// filter or mip mode (none for an integer texture) and the reduction, the weighted average
/// whatever the descriptor's, with or without a comparison.
#[test]
fn the_shape_states_the_filtering_vk_sampler_makes() {
use SamplerMinMagFilter as F;
let dev = device(&[], &[VkFeature::SamplerFilterMinmax]);
let mut checked = 0;
for min in [F::Nearest, F::Linear] {
for mag in [F::Nearest, F::Linear] {
for mip in [
SamplerMipFilter::NotMipmapped,
SamplerMipFilter::Nearest,
SamplerMipFilter::Linear,
] {
for reduction in [
SamplerReductionMode::WeightedAverage,
SamplerReductionMode::Minimum,
SamplerReductionMode::Maximum,
] {
for (compare, integer) in
[(false, false), (true, false), (false, true), (true, true)]
{
let mut d = metal_default();
d.min_filter = min;
d.mag_filter = mag;
d.mip_filter = mip;
d.reduction_mode = reduction;
let use_ = SamplerUse::new(compare, integer);
let s = vk_sampler(&d, use_, dev.profile()).expect("a sampler");
assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE);
let linear = s.mag_filter == vk::Filter::LINEAR
|| s.min_filter == vk::Filter::LINEAR
|| s.mipmap_mode == vk::SamplerMipmapMode::LINEAR;
assert_eq!(
vk_filtering(&d.shape(), use_),
(linear, s.reduction),
"{d:?} {use_:?}"
);
checked += 1;
}
}
}
}
}
assert_eq!(checked, 12 * 3 * 4);
}
#[test]
fn defaults_map_to_a_base_level_sampler() {
let dev = device(&[], &[]);
@@ -1409,16 +1285,14 @@ mod tests {
assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE);
}
/// A descriptor's LOD bias makes, on every committed device and for every use, the binding
/// shape its zero bias makes, and the Vulkan sampler its zero bias makes but for its
/// `mipLodBias`: without `SamplerUse::lod_bias` (an Apple GPU of the families the runtime
/// A descriptor's LOD bias makes, on every committed device and for every use, the Vulkan
/// sampler its zero bias makes but for its `mipLodBias`: without `SamplerUse::lod_bias` (an Apple GPU of the families the runtime
/// claims, which samples every level as with no bias) 0; with it (a Mac with an Intel or AMD
/// GPU) `device_lod_bias`'s, the bias within the device's `maxSamplerLodBias` and none through
/// a portability subset that withholds `samplerMipLodBias`, and 0 for a use of texel
/// coordinates. Refused nowhere: past the limit, NaN or infinite, and withheld.
#[test]
fn a_lod_bias_is_the_device_s_where_the_use_adds_it() {
use crate::bind::state::BoundSampler;
use SamplerMinMagFilter::{Linear, Nearest};
let biases = [
1.0,
@@ -1473,7 +1347,6 @@ mod tests {
descs.push((pixel, SamplerUse::default().with_unnormalized(true)));
for (unbiased, plain) in descs {
let want = vk_sampler(&unbiased, plain, p);
let shape = BoundSampler::new(unbiased).shape();
for bias in biases {
let mut d = unbiased;
d.lod_bias = bias;
@@ -1495,7 +1368,6 @@ mod tests {
assert_eq!(got, want, "{stem}: bias {bias}, {d:?} {use_:?}");
checked += 1;
}
assert_eq!(BoundSampler::new(d).shape(), shape, "{stem}: bias {bias}");
past_limit += usize::from(bias.abs() > limit);
}
}
@@ -1895,64 +1767,6 @@ mod tests {
assert_eq!(s.border_color, vk::BorderColor::FLOAT_TRANSPARENT_BLACK);
}
/// Mirror-clamp needs its feature; anisotropy needs its own only through an argument buffer
/// (`check_argument_sampler`), the Vulkan sampler isotropic without it; a min or max
/// reduction needs none and reads the weighted average, with or without a comparison.
#[test]
fn optional_sampler_features_are_required_or_refused() {
let none = device(
&[],
&[
VkFeature::SamplerMirrorClampToEdge,
VkFeature::SamplerFilterMinmax,
VkFeature::SamplerAnisotropy,
],
);
let all = device(
&[
VkFeature::SamplerMirrorClampToEdge,
VkFeature::SamplerFilterMinmax,
VkFeature::SamplerAnisotropy,
],
&[],
);
let mut mirror = metal_default();
mirror.r_address_mode = SamplerAddressMode::MirrorClampToEdge;
let mut minmax = metal_default();
minmax.reduction_mode = SamplerReductionMode::Maximum;
// Linear filters: off Metal's sampler a nearest one is handed no anisotropy.
let mut aniso = metal_default();
aniso.min_filter = SamplerMinMagFilter::Linear;
aniso.mag_filter = SamplerMinMagFilter::Linear;
aniso.max_anisotropy = 32;
let feature = |err: Error| {
let Error::Unsupported(u) = err else {
panic!("{err:?}")
};
u.needs
};
let needs = |f| crate::error::Needs::AnyOf(vec![vec![Capability::Feature(f)]]);
let err = vk_sampler(&mirror, SamplerUse::default(), none.profile()).unwrap_err();
assert_eq!(feature(err), needs(VkFeature::SamplerMirrorClampToEdge));
assert!(vk_sampler(&mirror, SamplerUse::default(), all.profile()).is_ok());
let s = vk_sampler(&aniso, SamplerUse::default(), none.profile()).unwrap();
assert_eq!(s.max_anisotropy, None, "isotropic without the feature");
let s = vk_sampler(&aniso, SamplerUse::default(), all.profile()).unwrap();
assert_eq!(s.max_anisotropy, Some(16.0), "clamped to the device limit");
// An argument buffer's sampler needs the feature.
let shape = aniso.shape();
let err = check_argument_sampler(&shape, SamplerUse::default(), none.profile());
assert_eq!(
feature(err.unwrap_err()),
needs(VkFeature::SamplerAnisotropy)
);
assert!(check_argument_sampler(&shape, SamplerUse::default(), all.profile()).is_ok());
for (p, compare) in [(&none, false), (&none, true), (&all, false), (&all, true)] {
let s = vk_sampler(&minmax, SamplerUse::new(compare, false), p.profile()).unwrap();
assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE);
}
}
/// An opaque-black border through a non-identity view mapping, the texture's swizzle composed
/// on the format's, needs the device to swizzle borders; a view whose
/// border texel is not Metal's (`A8Unorm` through `A8_UNORM`) refuses; other borders, identity mappings, and samplers
+6 -266
View File
@@ -67,7 +67,7 @@
//! 2D sample, and in 3D the half-float residue (about 0.3% of channels half a `half` ulp off).
//! Its class is the half-float family.
//! - **A cube's linear sample** of a packed format is not measured. A packed normalized format's
//! ([`TexelFormat::packed_exact`]) keeps the device's filter: its made-up corner texel lies off
//! (a [`BicubicTexels::EXACT`] class with a `PACKED` field) keeps the device's filter: its made-up corner texel lies off
//! the code scale its sum recovers the codes on. A small float's takes the half-float family's
//! emulation, an inference from its parts, each measured on the small floats: the face
//! position (format-independent), the 2D sum above, and the corner tap, the `x` face's texel
@@ -118,7 +118,7 @@
//! codes (`bind::AstcDecode`, `bind::PvrtcDecode`, `bind::EtcDecode`), its own decode again.
//!
//! A device that cannot sample an 8-bit sRGB format holds a sampled texture of it as the format's
//! UNORM twin (`metal::format::srgb_raw_twin`, [`srgb_twin_on`]: `R8Unorm_sRGB` and
//! UNORM twin (`metal::format::srgb_raw_twin`: `R8Unorm_sRGB` and
//! `RG8Unorm_sRGB` on lavapipe, `RG8Unorm_sRGB` on ANV and NVIDIA among the committed profiles),
//! whose views read the codes as `c / 255`. Having no sRGB decode there, the slot's
//! `RuntimeFact::SrgbTexture` variant decodes what the view reads (one texel's codes, or the
@@ -194,13 +194,6 @@ impl TexelFormat {
pub fn has_channels(self) -> bool {
self.0 >> BicubicTexels::PRESENT & 0xF != 0
}
/// Whether the class sums its channels on its [`PACKED`](Self::PACKED) field's grids
/// ([`PackedTexels::filter_grids`]): a packed normalized format's [`BicubicTexels::EXACT`]
/// class (module docs).
pub fn packed_exact(self) -> bool {
self.0 & BicubicTexels::EXACT != 0 && self.0 & TexelFormat::PACKED_MASK != 0
}
}
/// How Metal's cube gather reads the tap past both edges of a face of a format outside the
@@ -320,8 +313,7 @@ pub enum PackedTexels {
/// small float's is, so the field has no code scales. Metal's linear filter sums the steps on
/// that grid, each 2D term `k · w` truncated by `2^7` (an Apple M3 Max on macOS 26.7 and an
/// Apple M4 on macOS 27.0.1, byte-identical, every channel of `YCBCR8_420_2P`; every 8- and
/// 10-bit format, packed or not, at each subsampling and range;
/// [`filter_truncation`](Self::filter_truncation)).
/// 10-bit format, packed or not, at each subsampling and range).
YCbCr2048 = 7,
/// The `_sRGB` twins' and the unpacked 12-bit YCbCr formats' channels as their view holds them:
/// steps `k / 8192` of `[0, 1]`, alpha 1, which Metal's linear filter sums as
@@ -344,20 +336,6 @@ pub enum PackedTexels {
}
impl PackedTexels {
/// Every value, in field order.
pub const ALL: [PackedTexels; 10] = [
PackedTexels::Rgb565,
PackedTexels::Rgb5A1,
PackedTexels::Rgba4,
PackedTexels::Rgb10A2,
PackedTexels::SmallFloat,
PackedTexels::Argb8,
PackedTexels::YCbCr2048,
PackedTexels::YCbCr8192,
PackedTexels::YCbCrExtended8192,
PackedTexels::Rgb10A2Srgb,
];
/// The packed channels of `pf`, where Metal's reads of them are measured, a two-plane YCbCr
/// format's by its layout ([`of_ycbcr`](Self::of_ycbcr)).
pub fn of(pf: PixelFormat) -> Option<PackedTexels> {
@@ -403,24 +381,6 @@ impl PackedTexels {
})
}
/// Each channel's code scale `2^b - 1`, red to alpha (an absent alpha's 1, which its value
/// 1 recovers), or `None` where the device's value is Metal's exactly: the small floats, the
/// YCbCr fields and `RGB10A2Unorm_sRGB`'s, whose function decodes Metal's values itself.
pub fn scales(self) -> Option<[u32; 4]> {
Some(match self {
PackedTexels::Rgb565 => [31, 63, 31, 1],
PackedTexels::Rgb5A1 => [31, 31, 31, 1],
PackedTexels::Rgba4 => [15; 4],
PackedTexels::Rgb10A2 => [1023, 1023, 1023, 3],
PackedTexels::Argb8 => [255; 4],
PackedTexels::SmallFloat
| PackedTexels::YCbCr2048
| PackedTexels::YCbCr8192
| PackedTexels::YCbCrExtended8192
| PackedTexels::Rgb10A2Srgb => return None,
})
}
/// This field in place.
pub fn class(self) -> TexelFormat {
TexelFormat((self as u32) << TexelFormat::PACKED)
@@ -431,7 +391,7 @@ impl PackedTexels {
/// 10, or 12 bits, `16 · 255` for a channel of 1, 2, or 4 bits, `4 · 1023` for one of 5 or 10,
/// `4095` for one of 6; the YCbCr fields' `2048` or `8192`, on which their steps are their
/// codes (`S = D` below). Each
/// is a multiple of the channel's code scale ([`scales`](Self::scales)), so a code `c` lies on
/// is a multiple of the channel's code scale, so a code `c` lies on
/// it at `c · D / S`. `None` for the small floats, whose sum is a half-float format's, and for
/// `ARGB8Unorm`, whose filter is not measured.
pub fn filter_grids(self) -> Option<[u32; 4]> {
@@ -448,41 +408,6 @@ impl PackedTexels {
})
}
/// The bits `s` Metal's 2D and 3D linear sums drop from each term where
/// [`filter_grids`](Self::filter_grids) names the grids: the term of a code `c` on its grid
/// under the weight `w` (in units of `2^-16`) is `⌊c · w / 2^s⌋`, and the sum's grid step
/// `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋` (module docs). 4 for a packed normalized format's 12-bit
/// grids, as for an 8-bit format's, and 7 for the YCbCr fields', measured on their 2D samples;
/// `RGB10A2Unorm_sRGB`'s 7 for its color channels and 4 for alpha. Red to alpha.
pub fn filter_truncation(self) -> Option<[u32; 4]> {
self.filter_grids().map(|_| match self {
PackedTexels::Rgb10A2Srgb => [7, 7, 7, 4],
_ if self.ycbcr() => [7; 4],
_ => [4; 4],
})
}
/// Whether a `half` result of the field's one texel or linear filter rounds with ties away
/// from zero: the two-plane YCbCr fields' ([`ycbcr`](Self::ycbcr)) and
/// `RGB10A2Unorm_sRGB`'s, whose color steps lie on the grid `8192` (its alpha's values are
/// never a tie).
pub fn ties_away(self) -> bool {
self.ycbcr() || self == PackedTexels::Rgb10A2Srgb
}
/// Whether the field is a two-plane YCbCr format's: its view holds Metal's reads exactly, and a
/// `half` result of its linear filter is the step's value rounded with ties away from zero (on
/// the grid `8192`, where a step's value may lie between two halves; the grid `2048`'s are
/// halves), as is a `half` read or nearest sample of one texel (every channel of
/// `YCBCR8_420_2P_sRGB`, `YCBCR10_420_2P_sRGB` and three 12-bit and
/// extended-range formats on the grid `8192`).
pub fn ycbcr(self) -> bool {
matches!(
self,
PackedTexels::YCbCr2048 | PackedTexels::YCbCr8192 | PackedTexels::YCbCrExtended8192
)
}
/// Whether the filter's codes and steps are signed and reach `±2D`
/// ([`YCbCrExtended8192`](Self::YCbCrExtended8192)): each step divided by `2D` and doubled,
/// exactly.
@@ -697,7 +622,7 @@ pub fn heap_numeric_base() -> u32 {
/// Whether Metal's read of a texture of `pf` in another numeric class than its format's is
/// measured: a color format of the float, signed or unsigned integer class, not a depth, stencil,
/// extended-range (bfloat included) or two-plane YCbCr one. A slot of another class takes such a
/// texture under its cross-class variant (`bind::plan::resources::cross_class`), and a heap group's
/// texture under its cross-class variant, and a heap group's
/// read of another class reads it in its own class ([`heap_numeric`]).
pub fn crosses_classes(pf: PixelFormat) -> bool {
use crate::metal::format::{is_depth_stencil, sampled_type, ycbcr_format, ExtendedRange};
@@ -731,23 +656,6 @@ pub fn heap_alpha_in_red_index() -> u32 {
heap_class_index(PixelFormat::A8Unorm, TextureSwizzleChannels::DEFAULT)
}
/// Whether a texture of pixel format `pf` holds 16-bit float channels of its own: its class is
/// the half-float family's without a packed field.
pub fn half_channels(pf: PixelFormat) -> bool {
use crate::metal::bicubic::BicubicTexels;
texel_format(pf).0 & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF
}
/// Whether Metal's `textureWriteRoundingMode` 2 stores a fragment function's write to a texture of
/// `pf` otherwise than its default, where the translation builds only the default's rule
/// (`RuntimeFact::StorageTextureWriteRounding`, `RuntimeFact::HeapWriteRounding`): an
/// `RG11B10Float` or `RGB9E5Float` texture's, and where `halves` (a `float` texel) a half-float
/// one's ([`half_channels`]).
pub fn mode_two_rounds(pf: PixelFormat, halves: bool) -> bool {
matches!(pf, PixelFormat::RG11B10Float | PixelFormat::RGB9E5Float)
|| (halves && half_channels(pf))
}
/// The index among the heap's classes of the class a heap texture of pixel format `pf` made with
/// `swizzle` carries ([`heap_class`]); for an unswizzled texture of a form of
/// `ExtendedRange::HEAP_READ`, that form's index past [`heap_extended_base`]; for an integer color
@@ -814,17 +722,6 @@ pub fn srgb_coded(pf: PixelFormat) -> bool {
)
}
/// Whether `profile`'s device holds a sampled texture of `pf` as its 8-bit sRGB format's UNORM twin
/// (`metal::format::srgb_raw_twin`): it samples no format of `pf`'s and samples the twin's, whose
/// views read the codes, so a function decodes them itself (module docs). The runtime's image plan
/// holds the twin by the same format features.
pub fn srgb_twin_on(pf: PixelFormat, profile: &crate::device::profile::DeviceProfile) -> bool {
use crate::device::requirements::FormatUsage;
let usages = [FormatUsage::SampledImage].into();
let samples = |pf| crate::metal::format::vk_format(pf, &usages, profile).is_ok();
!samples(pf) && crate::metal::format::srgb_raw_twin(pf).is_some_and(samples)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -966,8 +863,7 @@ mod tests {
/// A format of a measured cube corner outside the families is its corner's field alone (no
/// family, channel, or border bit, so every other access reads it as `OTHER`), but for a
/// packed format's family and field beside it; each field fits its four bits, and each grid
/// suits `texel_round::grid_value` (`1 <= D < 2^16`).
/// packed format's family and field beside it.
#[test]
fn a_cube_corner_alone_is_its_field() {
let mut seen = std::collections::BTreeSet::new();
@@ -1014,162 +910,6 @@ mod tests {
}
}
/// Each packed format takes its field beside its corner, and nothing else does: the field fits
/// its four bits, each value has a format, each code scale suits `texel_round::grid_value` (`1
/// <= S < 2^16`), and the field touches no other field's bit. `ARGB8Unorm`'s cube gathers and
/// linear filter are not measured: its field stands alone, as the linear PVRTC formats' does;
/// BC1 to BC3's unorm forms and the 8-bit linear ETC2 and EAC formats take it beside their
/// corner. No cube gather of a two-plane YCbCr format is measured: its field has
/// no corner. A packed normalized format's class is its normalized family's with `EXACT`, a
/// small float's the half-float family's, each with its channels and border texels, and a
/// two-plane format's the normalized family's with `EXACT` (signed where its field's steps are)
/// and its format's channels. A field with grids states its sums' truncation, and only it.
#[test]
fn a_packed_format_takes_its_field_beside_its_corner() {
let mut seen = std::collections::BTreeSet::new();
for &pf in PixelFormat::ALL {
let class = texel_format(pf);
let field = class.0 & TexelFormat::PACKED_MASK;
match PackedTexels::of(pf) {
Some(p) => {
assert_eq!(field, p.class().0, "{pf:?}");
let two_plane = crate::metal::format::ycbcr_format(pf).is_some();
let blocks = matches!(
pf,
PixelFormat::BC1RGBA
| PixelFormat::BC2RGBA
| PixelFormat::BC3RGBA
| PixelFormat::ETC2RGB8
| PixelFormat::ETC2RGB8A1
| PixelFormat::EACRGBA8
);
assert_eq!(
CubeCorner::of(pf).is_some(),
(p != PackedTexels::Argb8 || blocks) && !two_plane,
"{pf:?}"
);
assert_eq!(p.ycbcr(), two_plane && p != PackedTexels::Rgb10A2, "{pf:?}");
let family = class.0 & !(TexelFormat::PACKED_MASK | CORNER_MASK);
let want = match p {
PackedTexels::SmallFloat => T::HALF,
PackedTexels::Argb8 => 0,
_ if p.filter_extended() => T::SNORM | T::EXACT,
_ => T::UNORM | T::EXACT,
};
assert_eq!(family & !(0xF << T::PRESENT | 0xfff << T::BORDER), want);
// A two-plane format's channels are its format's, which the bicubic filter's
// treatment does not state: red, green and blue, alpha reading 1 at the border.
let t = match two_plane {
true => {
assert!(texels(pf).is_none(), "{pf:?}");
T(0b0111 << T::PRESENT)
.with_border(pf, TextureSwizzleChannels::DEFAULT)
.0
}
false => texels(pf).map_or(0, |t| t.0),
};
assert_eq!(family, t | want, "{pf:?}");
assert_eq!(class.packed_exact(), p.filter_grids().is_some(), "{pf:?}");
seen.insert(p as u32);
}
None => {
assert_eq!(field, 0, "{pf:?}");
assert!(!class.packed_exact(), "{pf:?}");
}
}
}
// The two-plane YCbCr formats by the grid of Metal's reads: 9 on
// `1/2048`, 12 on `1/8192`, 9 on the signed `1/8192`, 6 of 10-bit codes; the 3 of 8-bit
// codes `RGBA8Unorm`'s family without a field; the 30 others (PQ, HLG, packed 12 bits) no
// class.
use crate::metal::format::YCbCrReads;
let mut by = std::collections::BTreeMap::new();
for &pf in PixelFormat::ALL {
let Some(y) = crate::metal::format::ycbcr_format(pf) else {
continue;
};
let class = texel_format(pf);
let key = match PackedTexels::of(pf) {
Some(p) => format!("{p:?}"),
None if class.0 == 0 => "other".to_owned(),
None => {
let rgb = T(T::UNORM | T::EXACT | 0b0111 << T::PRESENT)
.with_border(pf, TextureSwizzleChannels::DEFAULT);
assert_eq!(class.0, rgb.0, "{pf:?}");
assert_eq!((y.bits, y.reads), (8, YCbCrReads::Codes), "{pf:?}");
"codes8".to_owned()
}
};
*by.entry(key).or_insert(0) += 1;
}
let want = [
("Rgb10A2", 6),
("YCbCr2048", 9),
("YCbCr8192", 12),
("YCbCrExtended8192", 9),
("codes8", 3),
("other", 30),
];
assert_eq!(
by,
want.map(|(k, n)| (k.to_owned(), n)).into_iter().collect()
);
for (pf, p) in [
(
PixelFormat::YCBCR104442PPACKED,
Some(PackedTexels::YCbCr2048),
),
(
PixelFormat::YCBCR104202PPACKEDSRGB,
Some(PackedTexels::YCbCr8192),
),
(PixelFormat::YCBCR124222P, Some(PackedTexels::YCbCr8192)),
(
PixelFormat::YCBCR104202PPACKEDXR,
Some(PackedTexels::YCbCrExtended8192),
),
(
PixelFormat::YCBCR124442PXR,
Some(PackedTexels::YCbCrExtended8192),
),
(PixelFormat::YCBCR124202PPACKED, None),
(PixelFormat::YCBCR124202PPACKEDXR, None),
(PixelFormat::YCBCR104202PPQ, None),
(PixelFormat::YCBCR124442PHLG, None),
(PixelFormat::RGB104202PPACKED, Some(PackedTexels::Rgb10A2)),
] {
assert_eq!(PackedTexels::of(pf), p, "{pf:?}");
}
for (k, p) in PackedTexels::ALL.into_iter().enumerate() {
assert_eq!(p as u32, k as u32 + 1);
assert_eq!(p.class().0 & !TexelFormat::PACKED_MASK, 0);
for s in p.scales().into_iter().flatten() {
assert!((1..1 << 16).contains(&s), "{p:?}");
}
// Each filter grid lies on its channel's code scale, below `2^12`.
if let (Some(s), Some(g)) = (p.scales(), p.filter_grids()) {
for (s, g) in s.into_iter().zip(g) {
assert_eq!(g % s, 0, "{p:?}");
assert!(g < 1 << 12, "{p:?}");
}
}
assert_eq!(
p.filter_truncation().is_some(),
p.filter_grids().is_some(),
"{p:?}"
);
// `RGB10A2Unorm_sRGB`'s field is its extended-range form's class's
// (`lower::sampler::extended`), which no format's own class takes.
let extended = p == PackedTexels::Rgb10A2Srgb;
assert!(
seen.contains(&(p as u32)) || extended,
"{p:?} has no format"
);
}
assert_eq!(TexelFormat::PACKED_MASK & CORNER_MASK, 0);
assert_eq!(TexelFormat::PACKED_MASK & 0xff_ffff, 0);
}
/// The heap classes are few enough for a handle-table entry's class field, `OTHER` first; each
/// unswizzled format's index names its slot class with its border texels, and a swizzled
/// texture's names `OTHER`. An unswizzled texture of a form a heap reads names that form past
-9
View File
@@ -118,15 +118,6 @@ pub(crate) fn vk_scaled_vertex_format(format: VertexFormat) -> Option<vk::Format
})
}
/// The bytes an attribute of `format` takes in its element: its Vulkan format's block, the bytes
/// a fixed-function fetch of it reads and the bytes a pulled one decodes
/// (`lower::stage_io::fetch::Encoding::bytes`, which `tests::stage_in_element_bytes` holds equal
/// to this for every format). `None` for `Invalid`, which no fetch decodes.
pub(crate) fn vertex_bytes(format: VertexFormat) -> Option<u32> {
let f = vk_vertex_format(format).ok()?;
f.block().map(|b| b.size)
}
/// The alignment in bytes Vulkan's fixed-function vertex input requires of an attribute's address
/// in `format` ("Vertex Input Address Calculation", `VUID-vkCmdDraw-format-10389`/`-10390`): the
/// [`vk::FormatBlock::vertex_alignment`] of its Vulkan format, the component size or the whole
+5 -486
View File
@@ -89,7 +89,7 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() {
precision_notes: vec![
PrecisionNote::GradFromBias,
PrecisionNote::PixelSamplerScaling,
PrecisionNote::HalfSampleFilter,
PrecisionNote::SrgbTexelDecode,
],
strategies: StrategyCensus::default(),
constant_blob: None,
@@ -110,7 +110,7 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() {
],
},
SpecializedNote {
note: PrecisionNote::HalfSampleFilter,
note: PrecisionNote::SrgbTexelDecode,
when: vec![SpecClause {
all: vec![SpecTest::equal(texel, 0x109, 0)],
}],
@@ -130,9 +130,9 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() {
}
k
};
use PrecisionNote::{GradFromBias as G, HalfSampleFilter as H, PixelSamplerScaling as P};
use PrecisionNote::{GradFromBias as G, PixelSamplerScaling as P, SrgbTexelDecode as H};
for (values, want) in [
// Every default: the class 0 takes the filter note, the word 0 no scaling.
// Every default: the class 0 takes the sRGB note, the word 0 no scaling.
(vec![], vec![G, H]),
(vec![(3, 0x100)], vec![G]),
(vec![(3, 0x100), (4, 1)], vec![G, P]),
@@ -170,22 +170,6 @@ mod serde_round_trips {
assert_eq!(&back, value, "{json}");
}
/// A planes image's conversion: an 8-bit 4:2:0 surface's, full range, BT.709.
fn planes_sampler() -> crate::bind::YCbCrPlanesSampler {
use crate::bind::{YCbCrCodes, YCbCrInPlace, YCbCrMatrix, YCbCrPlanes, YCbCrRange};
let codes = metal::format::ycbcr_format(metal::PixelFormat::YCBCR84202P)
.and_then(YCbCrCodes::of)
.expect("codes");
let planes = YCbCrPlanes::new(
[8, 4],
[0, 16],
[64, 16],
(YCbCrRange::Full, YCbCrMatrix::Bt709),
codes,
);
YCbCrInPlace::of(&planes).expect("in place").sampler()
}
fn buffer(index: u32) -> SlotRef {
slot(Stage::Fragment, SlotClass::Buffer, index)
}
@@ -216,12 +200,6 @@ mod serde_round_trips {
one_row: true,
unit_axes: 6,
srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]),
ycbcr_planes_sampled: BTreeMap::from([(
slot(Stage::Kernel, SlotClass::Texture, 7),
planes_sampler(),
)]),
texel_rows: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 9)]),
texel_buffer_parts: BTreeMap::from([(slot(Stage::Kernel, SlotClass::Texture, 11), 2)]),
flat_grid: true,
call_threadgroups: true,
@@ -314,12 +292,6 @@ mod serde_round_trips {
replay_bindings: true,
merged_draws: true,
srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]),
ycbcr_planes_sampled: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 9),
planes_sampler(),
)]),
texel_rows: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 10)]),
texel_buffer_parts: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 11),
4,
@@ -773,457 +745,4 @@ fn descriptor_and_library_serde_round_trips() {
}
#[cfg(feature = "serde")]
mod bind_serde_round_trips {
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::bind::*;
use crate::cache::SpecializationKey;
use crate::metal;
use crate::pipeline::sym::{PushField, SampledType};
fn round_trip<T>(value: &T)
where
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
{
let json = serde_json::to_string(value).expect("serializes");
let back: T = serde_json::from_str(&json).expect("deserializes");
assert_eq!(&back, value, "{json}");
}
#[test]
fn bind_state_and_shape() {
let mut table = StageTable::default();
table.buffers.insert(
0,
BoundBuffer::Buffer {
length: 4096,
offset: 256,
gpu_address: 0x1_0000_0000,
device_address: Some(0xdead_0000),
attribute_stride: None,
},
);
table.buffers.insert(
1,
BoundBuffer::Bytes {
len: 16,
attribute_stride: None,
},
);
table.textures.insert(
3,
BoundTexture::Texture {
facts: TextureFacts::new(
metal::TextureType::Type2D,
metal::PixelFormat::RGBA8Unorm,
),
resource_id: Some(9),
},
);
table.samplers.insert(
0,
BoundSampler {
desc: SamplerDescriptor {
min_filter: metal::SamplerMinMagFilter::Linear,
mag_filter: metal::SamplerMinMagFilter::Nearest,
mip_filter: metal::SamplerMipFilter::Linear,
s_address_mode: metal::SamplerAddressMode::ClampToEdge,
t_address_mode: metal::SamplerAddressMode::ClampToEdge,
r_address_mode: metal::SamplerAddressMode::ClampToEdge,
border_color: metal::SamplerBorderColor::TransparentBlack,
normalized_coordinates: false,
lod_min_clamp: 0.0,
lod_max_clamp: 1000.0,
lod_average: false,
max_anisotropy: 1,
compare_function: metal::CompareFunction::Never,
reduction_mode: metal::SamplerReductionMode::WeightedAverage,
lod_bias: 1.5,
},
resource_id: None,
},
);
table.threadgroup_lengths.insert(0, 1024);
let mut stages = BTreeMap::new();
stages.insert(Stage::Kernel, table);
round_trip(&BindState {
stages,
used_resources: vec![UsedResource {
class: ResourceClass::Heap,
gpu_address: Some(0x2_0000_0000),
length: 1 << 20,
device_address: None,
usage: metal::ResourceUsage::READ,
stages: metal::RenderStages::empty(),
token: 7,
resource_id: None,
}],
used_in_token_order: true,
resident_apart: true,
vertex_amplification: VertexAmplification::new(
2,
vec![ViewMapping {
viewport_array_index_offset: 0,
render_target_array_index_offset: 3,
}],
),
imageblock_size: ImageblockSize::new(16, 8),
render_target_array_length: 6,
stage_in_region: Some(StageInRegion::new([1, 2, 3], [4, 5, 6])),
tessellation_factors: TessellationFactors::new(
Some(TessellationFactorBuffer::new(4096, 16, 64)),
0.5,
),
render_area: [40, 24],
argument_samplers: vec![ArgumentSampler::new(
SamplerDescriptor {
normalized_coordinates: false,
..SamplerDescriptor::new()
},
0x5a17_0001,
)],
depth_stencil: metal::state::DepthStencilDescriptor {
front_face_stencil: metal::state::StencilDescriptor {
stencil_compare_function: metal::CompareFunction::LessEqual,
depth_stencil_pass_operation: metal::StencilOperation::IncrementWrap,
write_mask: 0x0F,
..Default::default()
},
depth_write_enabled: true,
..Default::default()
},
heap_placement: HeapPlacement::ResourceId,
viewport_count: 3,
function_tables: vec![crate::bind::ArgumentFunctionTable {
resource_id: 0x7ab1_0001,
size: 9,
address: 0,
}],
tile_threadgroup: tile_threadgroup(),
zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]),
dropped_colors: BTreeSet::from([4]),
kept_imageblock_bytes: Some(4),
depth_clamp_range: Some([0.25, 0.5]),
rotated_weights: true,
line_band: Some((
crate::pipeline::BandPrimitive::Triangles,
[8.0, -8.0, 1.75, -1.0],
)),
resident_ranges: vec![crate::bind::ResidentRange {
host: 0x9_0000,
guest: 0x3_0000,
length: 100,
}],
blend_color: [0.25, -0.5, 1.5, 0.75],
alpha_test_reference: Some(0.375),
primitive_type: Some(metal::PrimitiveType::TriangleStrip),
primitive_id_indices: Some(metal::IndexType::UInt16),
quad_primitive_ids: true,
private_list: true,
far_vertex_buffers: BTreeSet::from([2]),
region_viewports: true,
});
let mut shape = StageShape::default();
shape.buffers.insert(
0,
BufferShape::Buffer {
attribute_stride: Some(24),
device_address: false,
length_class: 20,
offset_alignment: 2,
},
);
shape.samplers.insert(
0,
BoundSamplerShape {
shape: SamplerShape {
reduction: metal::SamplerReductionMode::Minimum,
compare: true,
anisotropic: true,
mirror_clamp_to_edge: false,
valid_lod_clamps: true,
opaque_black_border: true,
linear: true,
cubic: true,
},
word: crate::metal::sampler::SamplerWord(0x0012_3456),
min_level: 160,
degree: 3,
},
);
let mut stages = BTreeMap::new();
stages.insert(Stage::Fragment, shape);
round_trip(&BindShape {
stages,
used: BTreeMap::new(),
vertex_amplification: VertexAmplification::default(),
imageblock_size: ImageblockSize::new(32, 32),
render_target_array_length: 1,
tessellation_factor_buffer: true,
render_area: [1920, 1080],
argument_samplers: ArgumentSamplersShape::of(&[ArgumentSampler::new(
SamplerDescriptor::new(),
3,
)]),
function_tables: crate::bind::FunctionTablesShape::of(&[
crate::bind::ArgumentFunctionTable {
resource_id: 3,
size: 0,
address: 0,
},
]),
tile_threadgroup: tile_threadgroup(),
zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]),
dropped_colors: BTreeSet::from([4]),
kept_imageblock_bytes: Some(4),
depth_clamp_range: true,
rotated_weights: true,
line_band: Some(crate::pipeline::BandPrimitive::Lines),
primitive_id_indices: Some(metal::IndexType::UInt32),
quad_primitive_ids: true,
private_list: true,
far_vertex_buffers: BTreeSet::from([1, 30]),
region_viewports: true,
});
}
/// A tile threadgroup memory of 96 bytes with two arguments.
fn tile_threadgroup() -> crate::bind::TileThreadgroupMemory {
let mut memory = crate::bind::TileThreadgroupMemory {
length: 96,
arguments: BTreeMap::new(),
};
for (index, length, offset) in [(0, 32, 0), (3, 64, 32)] {
memory.arguments.insert(
index,
crate::bind::TileThreadgroupArgument { length, offset },
);
}
memory
}
#[test]
fn plans_and_commands() {
let slot = slot(Stage::Kernel, SlotClass::Buffer, 2);
let neutral = NeutralResource::Image {
view_type: vk::ImageViewType::TYPE_2D_ARRAY,
sampled_type: SampledType::Uint,
depth_compare: false,
samples: 1,
storage_format: Some(vk::Format::R32_UINT),
};
round_trip(&BindingPlan {
variant: VariantKey::new(),
specialization: SpecializationKey::new(),
descriptors: vec![
DescriptorWrite {
set: 0,
binding: 0,
array_element: 0,
ty: vk::DescriptorType::STORAGE_BUFFER,
source: WriteSource::Buffer { slot },
},
DescriptorWrite {
set: 0,
binding: 1,
array_element: 0,
ty: vk::DescriptorType::STORAGE_IMAGE,
source: WriteSource::Neutral(neutral),
},
DescriptorWrite {
set: 1,
binding: 0,
array_element: 5,
ty: vk::DescriptorType::SAMPLER,
source: WriteSource::HeapEntry {
class: crate::pipeline::sym::HandleClass::Sampler {
compare: false,
integer: false,
},
element: 5,
source: HeapSource::Used(3),
view: ImageViewDesc {
view_type: vk::ImageViewType::TYPE_2D,
format: vk::Format::R8G8B8A8_UNORM,
aspect: vk::ImageAspectFlags::COLOR,
layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
components: vk::ComponentMapping::IDENTITY,
level: None,
shader_swizzle: false,
},
},
},
],
vertex_buffers: vec![VertexBufferBind {
binding: 0,
buffer_index: 30,
per_bind_stride: false,
}],
uses: vec![ResourceUse {
resource: UseTarget::Slot(slot),
access: AccessSet::WRITE,
class: AccessClass::Storage,
stages: vk::PipelineStageFlags2::COMPUTE_SHADER,
range: Some(ByteRange { offset: 0, len: 64 }),
}],
push: PushTemplate {
fields: vec![PushFieldPlacement {
stage: Stage::Kernel,
field: PushField::SlotBindOffset(slot),
location: FieldLocation::PushWindow { offset: 0 },
size: 4,
}],
},
diagnostics: vec![PlanDiagnostic::IncompatibleBinding {
slot: crate::pipeline::sym::SlotRef {
class: SlotClass::Texture,
..slot
},
substituted: neutral,
}],
compute: None,
graphics: None,
views: ViewSetup {
view_mask: 0b11,
base_layer: 4,
},
});
round_trip(&DispatchCommands {
regions: vec![DispatchRegion {
specialization: SpecializationKey::new(),
group_count: [4, 1, 1],
push_constants: vec![PushConstantWrite {
stages: vk::ShaderStageFlags::COMPUTE,
offset: 0,
bytes: vec![1, 2, 3, 4],
}],
indirect: None,
stage_flags: vk::PipelineShaderStageCreateFlags::empty(),
required_subgroup_size: Some(32),
}],
descriptor_bytes: vec![DescriptorBytes {
set: 0,
binding: 3,
bytes: vec![0; 8],
}],
extents: vec![BufferExtent {
slot,
window: Window::Whole,
}],
descriptor_ranges: Vec::new(),
push_holes: vec![PushHole::RootTableAddress {
stages: vk::ShaderStageFlags::COMPUTE,
offset: 8,
}],
region_record: Some([7; 32]),
root_table: None,
uses: vec![ResourceUse {
resource: UseTarget::Indirect,
access: AccessSet::READ,
class: AccessClass::Indirect,
stages: vk::PipelineStageFlags2::DRAW_INDIRECT,
range: Some(ByteRange { offset: 0, len: 12 }),
}],
});
round_trip(&Dispatch::ThreadgroupsIndirect {
indirect: IndirectRef {
token: 2,
offset: 0,
},
threads_per_group: [32, 1, 1],
});
round_trip(&DrawCall::Indirect {
indirect: IndirectRef {
token: 4,
offset: 0,
},
indexed: Some((vk::IndexType::UINT16, IndexBufferRef::new(5, 256), 64)),
});
round_trip(&DrawCall::Patches {
control_points: 4,
patch_start: 2,
patch_count: 9,
patch_index: None,
instance_count: 3,
base_instance: 1,
control_point_index: Some((IndexBufferRef::new(7, 96), 2)),
});
round_trip(&DrawCall::PatchesIndirect {
control_points: 3,
patch_index: Some((IndexBufferRef::new(6, 64), 8)),
indirect: IndirectRef {
token: 4,
offset: 16,
},
control_point_index: None,
});
round_trip(&WriteSource::TessellationFactors);
round_trip(&UseTarget::TessellationFactors);
round_trip(&WriteSource::PatchIndices { min_bytes: 16 });
round_trip(&WriteSource::TileMemory { bytes: 480 });
round_trip(&UseTarget::PatchIndices);
round_trip(&WriteSource::ControlPointIndices);
round_trip(&UseTarget::ControlPointIndices);
round_trip(&DrawCommands {
push_constants: Vec::new(),
descriptor_bytes: Vec::new(),
buffer_offsets: vec![(0, 256)],
draw: vk::DrawCommand::DrawIndexed {
index_type: vk::IndexType::UINT32,
index_buffer_offset: 0,
index_count: 36,
instance_count: 1,
first_index: 0,
vertex_offset: -4,
first_instance: 0,
},
indirect_needs_arguments: false,
mesh_arguments: None,
object_fold: None,
discards_command_buffer: false,
extents: Vec::new(),
push_holes: Vec::new(),
descriptor_ranges: Vec::new(),
root_tables: Vec::new(),
vertex_strides: vec![(0, 32)],
uses: vec![ResourceUse {
resource: UseTarget::IndexBuffer,
access: AccessSet::READ,
class: AccessClass::Index,
stages: vk::PipelineStageFlags2::INDEX_INPUT,
range: Some(ByteRange {
offset: 0,
len: 144,
}),
}],
index_overrun: Some(IndexOverrun::Clamped { past_end: 4 }),
amplifications: vec![
Vec::new(),
vec![PushConstantWrite {
stages: vk::ShaderStageFlags::VERTEX,
offset: 16,
bytes: 1u32.to_le_bytes().to_vec(),
}],
],
specialization: None,
});
// A mesh draw's commands.
round_trip(&vk::DrawCommand::DrawMeshTasks {
group_count_x: 2,
group_count_y: 1,
group_count_z: 1,
});
round_trip(&vk::DrawCommand::DrawMeshTasksIndirect {
offset: 12,
draw_count: 1,
stride: 12,
});
round_trip(&vk::DrawCommand::DrawMeshTasksIndirectCount {
offset: 36,
count_offset: 32,
max_draw_count: 128,
stride: 12,
});
}
}
mod bind_serde_round_trips {}
+8 -29
View File
@@ -141,19 +141,14 @@ pub struct StageModule {
pub entry_point: String,
/// SPIR-V 1.5 words, relocated for this pipeline.
pub spirv: Arc<[u32]>,
/// The specialization constants with their defaults. A kernel's defaults are placeholders the
/// binder replaces (a local size of 1): create each compute `VkPipeline` from a planned
/// dispatch's [`DispatchRegion`](crate::bind::DispatchRegion), its `specialization`,
/// `stage_flags`, and `required_subgroup_size`, never from this stage's defaults.
/// The specialization constants with their defaults. A kernel's defaults are placeholders (a
/// local size of 1): create each compute `VkPipeline` with the values its dispatch gives
/// the constants' keys, never from this stage's defaults.
pub specialization: SpecializationLayout,
/// `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo`, when the tier pins a size. For a
/// kernel, each [`DispatchRegion`](crate::bind::DispatchRegion) carries the value to create its
/// pipeline with.
/// `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo`, when the tier pins a size.
pub required_subgroup_size: Option<u32>,
/// Stage create flags (`REQUIRE_FULL_SUBGROUPS`). For a kernel, each
/// [`DispatchRegion`](crate::bind::DispatchRegion) carries the flags to create its pipeline
/// with: a region that is not whole subgroups runs on a variant without them. These flags at
/// the default specialization's local size of 1 are invalid usage
/// Stage create flags (`REQUIRE_FULL_SUBGROUPS`). These flags at the default specialization's
/// local size of 1 are invalid usage
/// (`VUID-VkPipelineShaderStageCreateInfo-flags-02759`, or `-pNext-02757` with a required
/// subgroup size).
pub stage_flags: vk::PipelineShaderStageCreateFlags,
@@ -206,7 +201,7 @@ impl StageModule {
/// or dispatch binds the values `bound` gives, where a test of a key no pipeline's
/// key carries (the bound format's class, `SpecKey::BoundTexelFormat`; a bound sampler's word,
/// `SpecKey::BoundSamplerWord`; what the command's handles can name) reads the value `bound`
/// gives for it (`BindingPlan::specialized_value`); a test of a key neither gives holds.
/// gives for it; a test of a key neither gives holds.
pub fn precision_notes_bound(
&self,
specialization: &SpecializationKey,
@@ -854,7 +849,7 @@ pub enum PrecisionNote {
/// slot bound in an 8-bit sRGB format the device holds as its UNORM twin decodes the code
/// exactly instead, and a bicubic sample sums the codes' steps exactly, under the slot's
/// `SrgbTexture` variant, and records nothing. What a filtered sample converts is the filter's
/// value ([`PrecisionNote::HalfSampleFilter`]). Validation derives no tolerance from it.
/// value. Validation derives no tolerance from it.
///
/// Native device sampling (a texel conversion): every access with a `half` result records this
/// note, a heap element's and a depth texture's included. The recorded bound: the device's
@@ -865,15 +860,6 @@ pub enum PrecisionNote {
/// saturates to `±65504` and the rounding takes to the infinity of its sign; a NaN is the
/// device's decode ([`PrecisionNote::DeviceNanEncoding`]).
HalfTexelConversion,
/// The module samples a texture with a `half` result through a filter (linear minification
/// or magnification, a linear mip filter, anisotropy, or a runtime sampler) by Vulkan's Y′CbCr
/// model of the codes of a two-plane YCbCr texture whose planes the function reads in place
/// (`lower::sampler::in_place`), which blends the codes, not Metal's exact filter of the
/// format, on every device: recorded under the slot's bound converted 4:2:0 format and,
/// through a runtime sampler slot, the bound word's linear filter that addresses no border.
/// The `float` result's counterpart is [`PrecisionNote::FloatSampleFilter`]. Validation derives
/// no tolerance from it: the class is unbounded.
HalfSampleFilter,
/// The module reads, samples, or gathers a texture with a `half` or `float` result through
/// the device's sRGB decode, or decodes the device's filter of its codes, where the texture may
/// be bound in an 8-bit sRGB format (`metal::texel_format::srgb_coded`: the 8-bit sRGB formats
@@ -909,13 +895,6 @@ pub enum PrecisionNote {
/// it, where MoltenVK's `Pow` read within `1.83e-7` of the transfer through the alias.
/// Validation derives no tolerance from it: the class is unbounded.
SrgbTexelDecode,
/// The module samples a texture with a `float` result through a filter by Vulkan's Y′CbCr
/// model of the codes of a two-plane YCbCr texture whose planes the function reads in place
/// (`lower::sampler::in_place`), as [`PrecisionNote::HalfSampleFilter`] states for a `half`
/// result: a sample is filtered unless its sampler has nearest minification and
/// magnification, no mip filter or a nearest one, and no anisotropy. Validation derives no
/// tolerance from it: the class is unbounded.
FloatSampleFilter,
/// A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among
/// them, or constants held as `Private` variables) than the floor, 16 KiB a thread, on a device
/// whose Function storage was not measured, up to the 192 KiB a thread Metal was measured to
@@ -288,8 +288,7 @@ impl Device {
/// descriptor's color attachment formats (`LoweringInputs::tile_attachments`, the color index
/// of each attachment whose format is set), as a compute pipeline that runs one threadgroup per
/// tile of the render area and stages the attachments it reaches (`lower::access::tile`). The
/// consumer dispatches it in place of `dispatchThreadsPerTile:` with
/// `BindState::imageblock_size` set to the pass's tile size and `BindState::render_area` to its
/// consumer dispatches it in place of `dispatchThreadsPerTile:` over the pass's tile size and
/// render area, binding each attachment it reaches (`WriteSource::TileAttachment`). A
/// `Compiled` tile function must have been compiled under the same formats: one compiled
/// without tile inputs is `InvalidDescriptor(StageMismatch)`, and one that stages an attachment
@@ -964,9 +963,8 @@ impl Device {
metal = metal.min(cap);
}
// The static part of Metal's own layout, as Metal reports it: neither the emulated
// simdgroups' scratch nor a predicated walk's vote word, which are ours and which the
// planner counts in each dispatch's total (`bind::plan::compute`), refusing a threadgroup
// whose lengths fit beside this length and not beside them (`ThreadgroupMemorySize`).
// simdgroups' scratch nor a predicated walk's vote word, which are ours
// (`RuntimeFact::SimdgroupEmulation`, `RuntimeFact::PredicationVote`).
// Metal reports it rounded up to 16 bytes, its threadgroup memory's granularity
// (`threadgroup uint a[256]; threadgroup uint b;` answers 1040, not 1028, on the M3 Max,
// macOS 27.0.1).
@@ -229,21 +229,6 @@ pub fn function_key(
.bytes(format!("{:?}", inputs.srgb_textures).as_bytes());
}
// Appended only when set, as `signed_color_attachments`.
if !inputs.ycbcr_in_place.is_empty() {
h.bytes(b"ycbcr-in-place")
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
}
// Appended only when set, as `signed_color_attachments`.
if !inputs.ycbcr_planes_sampled.is_empty() {
h.bytes(b"ycbcr-planes-sampled")
.bytes(format!("{:?}", inputs.ycbcr_planes_sampled).as_bytes());
}
// Appended only when set, as `signed_color_attachments`.
if !inputs.texel_rows.is_empty() {
h.bytes(b"texel-rows")
.bytes(format!("{:?}", inputs.texel_rows).as_bytes());
}
// Appended only when set, as `signed_color_attachments`.
if !inputs.texel_buffer_parts.is_empty() {
h.bytes(b"texel-buffer-parts")
.bytes(format!("{:?}", inputs.texel_buffer_parts).as_bytes());
+116 -511
View File
@@ -649,9 +649,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", replay_bindings: false", "")
.replace(", merged_draws: false", "")
.replace(", srgb_textures: {}", "")
.replace(", ycbcr_in_place: {}", "")
.replace(", ycbcr_planes_sampled: {}", "")
.replace(", texel_rows: {}", "")
.replace(", texel_buffer_parts: {}", "")
.replace(", viewport_index_varying: false", "")
.replace(", max_call_stack_depth: None", "")
@@ -3043,461 +3040,6 @@ fn a_fragment_reading_through_a_loaded_pointer_writes_no_memory() {
}
}
/// A vertex function that writes `[[viewport_array_index]]` depends on the draw's viewport count,
/// which its push window holds and each draw writes from `BindState::viewport_count`, and writes
/// the index as written to a flat varying (`IoRole::ViewportIndex`). In its pipeline a fragment
/// function that reads the index compiles under `viewport_index_varying` and reads that varying, as
/// `render_pipeline_key` names, its push fields from the vertex function's push end
/// (`CompiledFunction::fragment_push_base`); one that does not read it compiles without
/// `viewport_index_varying`. A reading fragment compiled for the other kind of
/// vertex function is `NeedsInput(ViewportIndex)` either way. Every module passes L3.
#[test]
fn a_fragment_reads_the_viewport_index_its_vertex_function_wrote() {
use crate::bind::plan::FieldLocation;
use crate::bind::{BindState, DrawCall};
use crate::error::RuntimeInput;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::stage_io::{IoRole, StageBuiltin};
use crate::pipeline::sym::{PushField, Stage, VaryingKey};
let (Some(bc), Some(other)) = (fixture("rt6_viewports"), fixture("rt6_render_state")) else {
return;
};
let lib = Library::from_air(&bc).expect("library");
let other = Library::from_air(&other).expect("library");
let function = |lib: &Library, name: &str| {
FunctionDescriptor::new(lib.function(name).unwrap_or_else(|e| panic!("{name}: {e}")))
};
let dev = device("moltenvk-m3");
let budget = Budget::standard();
let pipeline = |vertex: StageSource, fragment: StageSource| {
let mut d = RenderPipelineDescriptor::new(vertex);
d.fragment = Some(fragment);
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA8Unorm,
));
d
};
let select = || StageSource::Function(function(&lib, "rt6_select"));
let reader = function(&lib, "rt6_viewport_read");
// The vertex function: the fact, the push field, the builtin, and the raw varying.
let vertex = dev
.compile_function(
&function(&lib, "rt6_select"),
&LoweringInputs::new(),
&budget,
)
.expect("vertex");
let a = vertex.artifact();
assert!(a.facts.contains(&RuntimeFact::ViewportCount));
assert!(a
.interface
.push
.fields
.iter()
.any(|f| f.field == PushField::ViewportCount));
assert!(a
.interface
.io
.builtins
.contains(&StageBuiltin::ViewportIndex));
let raw: Vec<_> = a
.interface
.io
.outputs
.iter()
.filter(|v| v.role == IoRole::ViewportIndex)
.collect();
assert_eq!(raw.len(), 1);
assert_eq!(raw[0].key, VaryingKey::viewport_index());
// The reading fragment in the pipeline: the field, the varying, no builtin.
let d = pipeline(select(), StageSource::Function(reader.clone()));
let keys = dev.render_pipeline_key(&d, &budget).expect("keys");
let inputs = keys.fragment_inputs.clone().expect("fragment inputs");
assert!(inputs.viewport_index_varying);
let pipe = dev.compile_render_pipeline(&d, &budget).expect("pipeline");
assert_eq!(pipe.key, keys.pipeline);
for s in &pipe.stages {
l3(&s.spirv, &pipe.requirements, &dev);
}
assert!(pipe
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::ViewportCount));
let fragment = dev
.compile_function(&reader, &inputs, &budget)
.expect("fragment");
assert_eq!(Some(*fragment.key()), keys.fragment);
let io = &fragment.artifact().interface.io;
assert!(io.inputs.iter().any(|v| v.role == IoRole::ViewportIndex));
assert!(!io.builtins.contains(&StageBuiltin::ViewportIndex));
// A fragment that does not read the index keeps its key.
let white = function(&lib, "rt6_white");
let keys = dev
.render_pipeline_key(
&pipeline(select(), StageSource::Function(white.clone())),
&budget,
)
.expect("keys");
let inputs = keys.fragment_inputs.clone().expect("fragment inputs");
assert!(!inputs.viewport_index_varying);
assert_eq!(
keys.fragment,
Some(dev.function_compile_key(&white, &inputs))
);
// Each draw writes the encoder's viewport count into the vertex push window.
let state = BindState {
viewport_count: 3,
..BindState::default()
};
let plan = pipe.plan(&dev, &state.shape()).expect("plan");
let placed = plan
.push
.fields
.iter()
.find(|f| f.stage == Stage::Vertex && f.field == PushField::ViewportCount)
.expect("placed");
let FieldLocation::PushWindow { offset } = placed.location else {
panic!("the count spilled: {placed:?}");
};
let draw = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
base_instance: 4,
};
let commands = plan.instantiate_draw(&state, &draw).expect("draw");
let write = commands
.push_constants
.iter()
.find(|w| w.stages.contains(crate::vk::ShaderStageFlags::VERTEX))
.expect("vertex push");
let at = (offset - write.offset) as usize;
assert_eq!(write.bytes[at..at + 4], 3u32.to_le_bytes());
// Compiled for the other kind of vertex function: refused, never a wrong read.
let without = dev
.compile_function(&reader, &LoweringInputs::new(), &budget)
.expect("fragment");
let mut under = LoweringInputs::new();
under.viewport_index_varying = true;
let under = dev
.compile_function(&reader, &under, &budget)
.expect("fragment");
let full = || StageSource::Function(function(&other, "rt6_full"));
for d in [
pipeline(select(), StageSource::Compiled(without)),
pipeline(full(), StageSource::Compiled(under)),
] {
assert_eq!(
dev.compile_render_pipeline(&d, &budget).err(),
Some(Error::NeedsInput(RuntimeInput::ViewportIndex))
);
}
}
/// A merged draw replay's vertex function (`VariantKey::merged_draws`) reads its command's slot
/// table from the header at its `MergedDrawAddress`, a hole of the vertex stage, in place of a
/// `RootTableAddress`, and its plan states the variant. A fragment function that reads a buffer
/// reads its command's fragment slot table from the header too, at the command its vertex wrote
/// (`IoRole::MergedCommand`): `MergedDrawAddress` is its push field, `RootTableAddress` none. One
/// that reads `[[primitive_id]]`, which Metal counts per command, is refused, as is a merged key
/// without replay bindings.
#[test]
fn a_merged_draw_reads_its_command_s_table_from_its_header() {
use crate::cache::VariantKey;
use crate::pipeline::sym::PushField;
let dev = device("moltenvk-m3");
let mut key = VariantKey::new();
key.replay_bindings = true;
key.merged_draws = true;
let compile = |vertex: (&str, &str),
fragment: Option<(&str, &str, metal::PixelFormat)>,
key: &VariantKey| {
let function = |(file, name): (&str, &str)| {
let bc = fixture(file)?;
Some(FunctionDescriptor::new(
Library::from_air(&bc)
.expect("library")
.function(name)
.expect("function"),
))
};
let mut d = RenderPipelineDescriptor::new(StageSource::Function(function(vertex)?));
match fragment {
Some((file, name, format)) => {
d.fragment = Some(StageSource::Function(function((file, name))?));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format));
}
None => d.rasterization_enabled = false,
}
Some(dev.compile_render_variant(&d, key, &Budget::standard()))
};
let Some(merged) = compile(("primitive_ids", "pi_place"), None, &key) else {
return;
};
let merged = merged.expect("merged");
let fields: Vec<PushField> = merged
.interface
.push
.iter()
.flat_map(|p| p.fields.iter().map(|f| f.field))
.collect();
assert!(fields.contains(&PushField::MergedDrawAddress), "{fields:?}");
assert!(!fields.contains(&PushField::RootTableAddress), "{fields:?}");
assert!(
!fields.contains(&PushField::BaseVertexInstance),
"{fields:?}"
);
let plan = merged
.plan(&dev, &crate::bind::BindShape::default())
.expect("plan");
assert!(plan.variant.replay_bindings && plan.variant.merged_draws);
let placed: Vec<_> = plan
.push
.fields
.iter()
.filter(|f| f.field == PushField::MergedDrawAddress)
.map(|f| f.stage)
.collect();
assert_eq!(placed, [crate::pipeline::sym::Stage::Vertex]);
let mut unreplayed = VariantKey::new();
unreplayed.merged_draws = true;
let plain = compile(("primitive_ids", "pi_place"), None, &unreplayed)
.expect("fixture")
.expect("merged alone is no variant");
assert!(!plain.interface.push.iter().any(|p| p
.fields
.iter()
.any(|f| f.field == PushField::MergedDrawAddress)));
let (vertex, fragment) = (
("primitive_ids", "pi_place"),
("primitive_ids", "pi_ids", metal::PixelFormat::RGBA32Uint),
);
compile(vertex, Some(fragment), &VariantKey::new())
.expect("fixture")
.expect("plain");
let refused = compile(vertex, Some(fragment), &key)
.expect("fixture")
.expect_err("a fragment's primitive ID under a merged draw");
assert!(
format!("{refused:?}").contains("GpuEncodedIndirectCommands"),
"{fragment:?}: {refused:?}"
);
let (vertex, fragment) = (
("a8r_targets", "a8r_vertex"),
("a8r_targets", "a8r_fill", metal::PixelFormat::RGBA8Unorm),
);
let buffered = compile(vertex, Some(fragment), &key)
.expect("fixture")
.expect("a fragment's buffer under a merged draw");
let fragment_fields: Vec<PushField> = (buffered.interface.push.iter())
.filter(|p| p.stage == crate::pipeline::sym::Stage::Fragment)
.flat_map(|p| p.fields.iter().map(|f| f.field))
.collect();
assert!(
fragment_fields.contains(&PushField::MergedDrawAddress)
&& !fragment_fields.contains(&PushField::RootTableAddress),
"{fragment_fields:?}"
);
}
/// A merged draw replay's functions find their command's slot tables before any entry hook reads
/// one: a fragment function that loads a pointer from its argument buffer reads that buffer's
/// root entry at entry (`access::dynamic::emit_entry`), from the fragment slot table the command
/// its vertex wrote names, and the merged variant of `icb_merged_arguments` (a vertex function
/// that fetches `[[stage_in]]` attributes, a fragment function whose argument buffer holds two
/// textures and a constant pointer) compiles on each device that has the replay, every stage
/// passing L3, its fragment stage reading the header at its `MergedDrawAddress`.
#[test]
fn a_merged_fragment_reads_its_argument_buffer_through_its_command_s_table() {
use crate::cache::VariantKey;
use crate::pipeline::sym::{PushField, Stage};
let Some(bc) = fixture("icb_merged_arguments") else {
return;
};
let lib = Library::from_air(&bc).expect("library");
let function = |name: &str| {
StageSource::Function(FunctionDescriptor::new(lib.function(name).expect(name)))
};
let mut d = RenderPipelineDescriptor::new(function("ica_vertex"));
d.fragment = Some(function("ica_fragment"));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA32Uint,
));
let mut input = VertexDescriptor::new();
input
.layouts
.insert(0, VertexBufferLayoutDescriptor::new(Some(8)));
input
.layouts
.insert(1, VertexBufferLayoutDescriptor::new(Some(4)));
input.attributes.insert(
0,
VertexAttributeDescriptor::new(metal::VertexFormat::Float2, 0, 0),
);
input.attributes.insert(
1,
VertexAttributeDescriptor::new(metal::VertexFormat::UInt, 0, 1),
);
d.vertex_descriptor = Some(input);
for stem in ["moltenvk-m3", "amd-780m-radv", "lavapipe"] {
let dev = device(stem);
let base = dev
.compile_render_variant(&d, &VariantKey::new(), &Budget::standard())
.unwrap_or_else(|e| panic!("{stem}: base: {e}"));
let layouts = (base.vertex_input.bindings.iter())
.map(|b| b.buffer_index)
.collect();
let shape = crate::bind::BindShape {
far_vertex_buffers: layouts,
..Default::default()
};
let mut key = base.plan(&dev, &shape).expect("base plan").variant;
key.replay_bindings = true;
key.merged_draws = true;
let merged = dev
.compile_render_variant(&d, &key, &Budget::standard())
.unwrap_or_else(|e| panic!("{stem}: merged: {e}"));
for stage in &merged.stages {
l3(&stage.spirv, &merged.requirements, &dev);
}
let fragment: Vec<PushField> = (merged.interface.push.iter())
.filter(|p| p.stage == Stage::Fragment)
.flat_map(|p| p.fields.iter().map(|f| f.field))
.collect();
assert!(
fragment.contains(&PushField::MergedDrawAddress)
&& !fragment.contains(&PushField::RootTableAddress),
"{stem}: {fragment:?}"
);
}
}
/// A render pipeline compiled as a device-replay variant (`VariantKey::replay_bindings`) reads
/// every buffer its vertex function reaches through its root entry (`BufferForm::Psb`), from the
/// slot table at the stage's own `RootTableAddress`, and needs no `SlotGuestBase`
/// (`icb_render_replay_template`); its plan states the variant. A vertex function that fetches
/// a `[[stage_in]]` attribute (`icb_render_stride_template`) in fixed function, as it does under
/// the identity domains, is refused: fixed-function input reads no slot table. Outside them the
/// attribute is pulled, so the draw binds no fixed-function layout, and its replay variant
/// compiles, one draw per command and merged, binds no layout and pulls the attribute, whose read
/// reaches the slot table; every stage passes L3, and its plan states its key.
#[test]
fn a_replayed_draw_reads_its_buffers_through_the_slot_table() {
use crate::cache::VariantKey;
use crate::pipeline::interface::{BufferForm, SlotInterface};
use crate::pipeline::sym::PushField;
let dev = device("moltenvk-m3");
let mut key = VariantKey::new();
key.replay_bindings = true;
let Some(bc) = fixture("icb_render_replay_template") else {
return;
};
let vertex = Library::from_air(&bc)
.expect("library")
.function("icb_render_replay_template")
.expect("vertex");
let mut d =
RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex)));
d.rasterization_enabled = false;
let plain = dev
.compile_render_variant(&d, &VariantKey::new(), &Budget::standard())
.expect("plain");
let replayed = dev
.compile_render_variant(&d, &key, &Budget::standard())
.expect("replayed");
let forms = |p: &crate::pipeline::artifact::RenderPipeline| -> Vec<BufferForm> {
p.interface
.slots
.values()
.filter_map(|s| match s {
SlotInterface::Buffer(b) => Some(b.form),
_ => None,
})
.collect()
};
assert_eq!(forms(&replayed).len(), 2);
assert!(forms(&replayed).iter().all(|f| *f == BufferForm::Psb));
assert!(forms(&plain).iter().any(|f| *f != BufferForm::Psb));
let fields: Vec<PushField> = replayed
.interface
.push
.iter()
.flat_map(|p| p.fields.iter().map(|f| f.field))
.collect();
assert!(fields.contains(&PushField::RootTableAddress));
assert!(!fields
.iter()
.any(|f| matches!(f, PushField::SlotGuestBase(_))));
let plan = replayed
.plan(&dev, &crate::bind::BindShape::default())
.expect("plan");
assert!(plan.variant.replay_bindings);
// A fixed-function fetch is the identity domains' alone (the runtime's): outside them every
// attribute is pulled.
let idev =
Device::from_queries(description("moltenvk-m3"), DevicePolicy::default()).expect("device");
let Some(bc) = fixture("icb_render_stride_template") else {
return;
};
let vertex = Library::from_air(&bc)
.expect("library")
.function("icb_render_stride_template")
.expect("vertex");
let mut d =
RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex)));
d.rasterization_enabled = false;
d.vertex_descriptor = Some(vertex_descriptor(&[(0, metal::VertexFormat::UInt)]));
let fetched = idev
.compile_render_variant(&d, &VariantKey::new(), &Budget::standard())
.expect("fetched");
assert_eq!(fetched.vertex_input.bindings.len(), 1);
let refused = idev
.compile_render_variant(&d, &key, &Budget::standard())
.expect_err("a fetch under replay bindings");
assert!(
format!("{refused:?}").contains("GpuEncodedIndirectCommands"),
"{refused:?}"
);
let base = dev
.compile_render_variant(&d, &VariantKey::new(), &Budget::standard())
.expect("pulled");
assert!(
base.vertex_input.bindings.is_empty(),
"{:?}",
base.vertex_input.bindings
);
for merged in [false, true] {
let mut replay = key.clone();
replay.merged_draws = merged;
let p = dev
.compile_render_variant(&d, &replay, &Budget::standard())
.unwrap_or_else(|e| panic!("merged {merged}: {e}"));
let input = &p.vertex_input;
assert!(input.bindings.is_empty(), "merged {merged}");
assert_eq!(input.pulled.len(), 1, "merged {merged}");
// The pulled layout's buffer is read through its root entry, as every other slot.
let slots = forms(&p);
assert!(
!slots.is_empty() && slots.iter().all(|f| *f == BufferForm::Psb),
"merged {merged}: {slots:?}"
);
for stage in &p.stages {
l3(&stage.spirv, &p.requirements, &dev);
}
let replayed = p
.plan(&dev, &crate::bind::BindShape::default())
.expect("the variant's plan");
assert_eq!(replayed.variant, replay, "merged {merged}");
assert!(replayed.vertex_buffers.is_empty(), "merged {merged}");
}
}
/// Under the identity domains a device-replay variant (`VariantKey::replay_bindings`), which reads
/// every buffer slot's address from its replayed command's root entry at the stage's
/// `RootTableAddress`, is refused, typed (`Unsupported{IdentityDomains}` naming the field the
@@ -3615,63 +3157,126 @@ fn a_pipeline_for_indirect_command_buffers_pulls_its_stage_in() {
}
}
/// A draw replay's variant reads every buffer through the slot table its replay's preprocess
/// writes, so inline bytes the encoder bound at a slot it reads are no refusal: commands that
/// inherit the encoder's buffers read them at the consumer's upload of them, whose address the
/// preprocess's entry takes (`bind::DrawReplayPreprocess::inherited_bytes`). Its plan for a shape
/// with inline bytes at every buffer slot plans; one with a buffer bound without a device
/// address there, which no entry can name, stays `MissingDeviceAddress`.
/// A vertex function that writes `[[viewport_array_index]]` depends on the draw's viewport count,
/// which its push window holds (`PushField::ViewportCount`), and writes the index as written to a
/// flat varying (`IoRole::ViewportIndex`). In its pipeline a fragment
/// function that reads the index compiles under `viewport_index_varying` and reads that varying, as
/// `render_pipeline_key` names, its push fields from the vertex function's push end
/// (`CompiledFunction::fragment_push_base`); one that does not read it compiles without
/// `viewport_index_varying`. A reading fragment compiled for the other kind of
/// vertex function is `NeedsInput(ViewportIndex)` either way. Every module passes L3.
#[test]
fn a_replayed_draw_plans_inline_bytes_at_its_slots() {
use crate::bind::{BindShape, BufferShape, StageShape};
use crate::cache::VariantKey;
use crate::error::BindError;
use crate::pipeline::interface::SlotInterface;
let dev = device("moltenvk-m3");
let mut key = VariantKey::new();
key.replay_bindings = true;
let Some(bc) = fixture("icb_render_replay_template") else {
fn a_fragment_reads_the_viewport_index_its_vertex_function_wrote() {
use crate::error::RuntimeInput;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::stage_io::{IoRole, StageBuiltin};
use crate::pipeline::sym::{PushField, VaryingKey};
let (Some(bc), Some(other)) = (fixture("rt6_viewports"), fixture("rt6_render_state")) else {
return;
};
let vertex = Library::from_air(&bc)
.expect("library")
.function("icb_render_replay_template")
let lib = Library::from_air(&bc).expect("library");
let other = Library::from_air(&other).expect("library");
let function = |lib: &Library, name: &str| {
FunctionDescriptor::new(lib.function(name).unwrap_or_else(|e| panic!("{name}: {e}")))
};
let dev = device("moltenvk-m3");
let budget = Budget::standard();
let pipeline = |vertex: StageSource, fragment: StageSource| {
let mut d = RenderPipelineDescriptor::new(vertex);
d.fragment = Some(fragment);
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA8Unorm,
));
d
};
let select = || StageSource::Function(function(&lib, "rt6_select"));
let reader = function(&lib, "rt6_viewport_read");
// The vertex function: the fact, the push field, the builtin, and the raw varying.
let vertex = dev
.compile_function(
&function(&lib, "rt6_select"),
&LoweringInputs::new(),
&budget,
)
.expect("vertex");
let mut d =
RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex)));
d.rasterization_enabled = false;
let replayed = dev
.compile_render_variant(&d, &key, &Budget::standard())
.expect("replayed");
let slots: Vec<_> = (replayed.interface.slots.iter())
.filter(|(_, s)| matches!(s, SlotInterface::Buffer(_)))
.map(|(slot, _)| *slot)
let a = vertex.artifact();
assert!(a.facts.contains(&RuntimeFact::ViewportCount));
assert!(a
.interface
.push
.fields
.iter()
.any(|f| f.field == PushField::ViewportCount));
assert!(a
.interface
.io
.builtins
.contains(&StageBuiltin::ViewportIndex));
let raw: Vec<_> = a
.interface
.io
.outputs
.iter()
.filter(|v| v.role == IoRole::ViewportIndex)
.collect();
assert!(!slots.is_empty());
let shape_with = |bound: BufferShape| {
let mut shape = BindShape::default();
for slot in &slots {
let stage: &mut StageShape = shape.stages.entry(slot.stage).or_default();
stage.buffers.insert(slot.index, bound);
}
shape
};
let bytes = BufferShape::Bytes {
attribute_stride: None,
};
let plan = replayed
.plan(&dev, &shape_with(bytes))
.expect("inline bytes");
assert!(plan.variant.replay_bindings);
let unaddressed = BufferShape::Buffer {
attribute_stride: None,
device_address: false,
length_class: 0,
offset_alignment: 4,
};
let refused = replayed.plan(&dev, &shape_with(unaddressed));
assert!(
matches!(refused, Err(BindError::MissingDeviceAddress { .. })),
"{refused:?}"
assert_eq!(raw.len(), 1);
assert_eq!(raw[0].key, VaryingKey::viewport_index());
// The reading fragment in the pipeline: the field, the varying, no builtin.
let d = pipeline(select(), StageSource::Function(reader.clone()));
let keys = dev.render_pipeline_key(&d, &budget).expect("keys");
let inputs = keys.fragment_inputs.clone().expect("fragment inputs");
assert!(inputs.viewport_index_varying);
let pipe = dev.compile_render_pipeline(&d, &budget).expect("pipeline");
assert_eq!(pipe.key, keys.pipeline);
for s in &pipe.stages {
l3(&s.spirv, &pipe.requirements, &dev);
}
assert!(pipe
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::ViewportCount));
let fragment = dev
.compile_function(&reader, &inputs, &budget)
.expect("fragment");
assert_eq!(Some(*fragment.key()), keys.fragment);
let io = &fragment.artifact().interface.io;
assert!(io.inputs.iter().any(|v| v.role == IoRole::ViewportIndex));
assert!(!io.builtins.contains(&StageBuiltin::ViewportIndex));
// A fragment that does not read the index keeps its key.
let white = function(&lib, "rt6_white");
let keys = dev
.render_pipeline_key(
&pipeline(select(), StageSource::Function(white.clone())),
&budget,
)
.expect("keys");
let inputs = keys.fragment_inputs.clone().expect("fragment inputs");
assert!(!inputs.viewport_index_varying);
assert_eq!(
keys.fragment,
Some(dev.function_compile_key(&white, &inputs))
);
// Compiled for the other kind of vertex function: refused, never a wrong read.
let without = dev
.compile_function(&reader, &LoweringInputs::new(), &budget)
.expect("fragment");
let mut under = LoweringInputs::new();
under.viewport_index_varying = true;
let under = dev
.compile_function(&reader, &under, &budget)
.expect("fragment");
let full = || StageSource::Function(function(&other, "rt6_full"));
for d in [
pipeline(select(), StageSource::Compiled(without)),
pipeline(full(), StageSource::Compiled(under)),
] {
assert_eq!(
dev.compile_render_pipeline(&d, &budget).err(),
Some(Error::NeedsInput(RuntimeInput::ViewportIndex))
);
}
}
+28 -73
View File
@@ -107,11 +107,10 @@ pub enum RuntimeFact {
/// whatever the bind's, and records nothing.
StageInStride { layout: u32 },
/// The kernel is a tile function (`Device::compile_tile_pipeline`): a dispatch covers the
/// render pass's render area (`BindState::render_area`, `SpecKey::RenderAreaWidth` and
/// `SpecKey::RenderAreaHeight`) in tiles of the imageblock size (`BindState::imageblock_size`),
/// one threadgroup per tile, and stages the color attachments it reaches through the
/// threadgroup's imageblock. A layered pass is not modeled: the planner refuses a render
/// target array length above 1.
/// render pass's render area (`renderTargetWidth` and `renderTargetHeight`,
/// `SpecKey::RenderAreaWidth` and `SpecKey::RenderAreaHeight`) in tiles of the pass's tile
/// size, one threadgroup per tile, and stages the color attachments it reaches through the
/// threadgroup's imageblock. A layered pass is not modeled.
TileFunction,
/// The tile function stages color attachment `color` as a storage image of pixel format
/// `format` (`LoweringInputs::tile_attachments`): its texel conversions and declared image
@@ -161,8 +160,8 @@ pub enum RuntimeFact {
/// resident everywhere, and the status word Metal returns for it is compiled in, exact on
/// every device. `sparse_arm`: the module also answers a sparse texture, with the device's
/// sparse residency (`OpImageSparse*` and `OpImageSparseTexelsResident` under
/// `shaderResourceResidency`), selected by `SpecKey::SparseTexture`. Without it the binder
/// refuses a sparse texture at the slot (`BindError::Unsupported`): naming
/// `shaderResourceResidency`), selected by `SpecKey::SparseTexture`. Without it a sparse
/// texture at the slot is refused (`Unsupported`): naming
/// `shaderResourceResidency` where the device lacks it, `NotImplemented` where one of the
/// slot's accesses has no sparse form (a bicubic sample), and `NotRepresentable` where the
/// function updates the slot atomically (`SparseTextureWrites`). A slot the function writes
@@ -214,8 +213,8 @@ pub enum RuntimeFact {
/// The vertex function writes `[[viewport_array_index]]`, which selects a viewport only below
/// the render encoder's viewport count (`setViewports:count:`): Metal draws a primitive whose
/// index is at or past the count through viewport 0, so the function stores `ViewportIndex`
/// as 0 there, reading the count from `PushField::ViewportCount`, which the binder writes per
/// draw (`BindState::viewport_count`).
/// as 0 there, reading the count from `PushField::ViewportCount`, which the consumer writes per
/// draw.
ViewportCount,
/// The tile function aliases an explicit imageblock onto its implicit one
/// (`air.alias_implicit_imageblock`), of `data_size` bytes (`air.imageblock_data_size`): a
@@ -294,10 +293,10 @@ pub enum RuntimeFact {
/// The tile function reads its threadgroup argument `index` (`[[threadgroup(index)]]`):
/// memory of its tile that the render pass keeps across its tile dispatches, at the offset
/// and in the tile memory the encoder sets (`setThreadgroupMemoryLength:offset:atIndex:` and
/// the pass's `threadgroupMemoryLength`, `BindState::tile_threadgroup`). The binder
/// the pass's `threadgroupMemoryLength`). The consumer
/// specializes `SpecKey::TgOffset(index)`, `SpecKey::TileThreadgroupLength` and
/// `SpecKey::TileGridWidth`, binds the pass's `SyntheticBinding::TileMemory`, and refuses an
/// index the encoder did not set (`BindError::MissingThreadgroupMemory`). A fragment
/// index the encoder did not set. A fragment
/// function's threadgroup arguments are the same memory: its draws read and write it in the
/// buffer, at its tile, which `SpecKey::ImageblockWidth` and `SpecKey::ImageblockHeight` (the
/// pass's tile size) place.
@@ -352,27 +351,24 @@ pub enum RuntimeFact {
/// The fragment function was compiled under `VariantKey::zeroed_colors`
/// (`LoweringInputs::zeroed_colors`): it writes zero to color attachment `color`, of pixel
/// format `format`, which its Metal pipeline lacks and the pass has, as plain Metal stores
/// zero bytes there at every sample a draw covers. Its plans state the variant the shape asks
/// for (`BindShape::zeroed_colors`).
/// zero bytes there at every sample a draw covers.
ZeroedColor {
color: u32,
format: crate::metal::PixelFormat,
},
/// The fragment function was compiled under `LoweringInputs::dropped_colors` holding
/// `color`: it keeps no output at that color attachment, which the render pass lacks and
/// whose writes plain Metal drops. A plan of a draw whose pass has the attachment asks for the
/// variant without it.
/// whose writes plain Metal drops. A draw whose pass has the attachment takes the variant
/// without it.
DroppedColor { color: u32 },
/// The fragment function was compiled under `VariantKey::depth_clamp_range`
/// (`LoweringInputs::depth_clamp_range`) and writes its depth: it clamps that depth to the
/// draw's depth clamp range itself, read from `PushField::DepthClampRange`, which the binder
/// writes from `BindState::depth_clamp_range`, a negative NaN storing 0 as Metal's does. Its
/// plans state the variant the shape asks for (`BindShape::depth_clamp_range`).
/// draw's depth clamp range itself, read from `PushField::DepthClampRange`, which the consumer
/// writes, a negative NaN storing 0 as Metal's does.
DepthClampRange,
/// The fragment function was compiled under `VariantKey::rotated_weights`
/// (`LoweringInputs::rotated_weights`) and reads `[[barycentric_coord]]`: it takes Metal's
/// weights back from a triangle drawn with Metal's last vertex first. Its plans state the
/// variant the shape asks for (`BindShape::rotated_weights`).
/// weights back from a triangle drawn with Metal's last vertex first.
RotatedWeights,
/// The function reads, samples, gathers, or fetches through a sampler the color texture
/// bound to the slot, on a profile whose sparse textures are sparse images (it enables
@@ -394,8 +390,8 @@ pub enum RuntimeFact {
/// per threadgroup or their `dispatch_` forms, its position in the grid, the threads per
/// grid, or its thread or quadgroup index in the threadgroup), and was compiled under
/// `tile_sized`, that flag (`LoweringInputs::threadgroup_size_matches_tile_size`). With
/// `tile_sized` the binder runs each dispatch with the pass's tile, its imageblock size
/// (`BindShape::imageblock_size`), as Metal's threadgroup in every region (`MultiRegion` 1),
/// `tile_sized` the consumer runs each dispatch with the pass's tile, its imageblock size,
/// as Metal's threadgroup in every region (`MultiRegion` 1),
/// the threads per tile its workgroups; a tile pipeline whose descriptor gives the flag the
/// other value is `InvalidDescriptor(TileThreadgroupSize)`.
TileThreadgroup { tile_sized: bool },
@@ -427,10 +423,9 @@ pub enum RuntimeFact {
/// not emulate there, it sets `StatusBits::CUBIC_ARGUMENT_SAMPLER` in the command buffer's
/// `ExecutionStatus` buffer (through the address the stage's `ExecutionStatus` fact asks
/// for), and a consumer that reads the bit reports the command buffer's execution as failed. A
/// run that never reaches such a sampler is Metal's exactly. The planner admits a cubic listed
/// state (`BindState::argument_samplers`) beside a stage's sampler table only where the stage
/// states this fact (a device that cannot write the buffer from the stage tests nothing, and
/// its stage is refused `NotImplemented(SamplerBicubicFilter)` there). A fragment stage never
/// run that never reaches such a sampler is Metal's exactly. A cubic argument sampler beside a
/// stage's sampler table is Metal's only where the stage states this fact (a device that
/// cannot write the buffer from the stage tests nothing). A fragment stage never
/// states it: the mark is a store, which costs a fragment function the device's hidden-surface
/// removal and early depth test although it never runs.
CubicArgumentSampler { stage: Stage },
@@ -541,49 +536,13 @@ pub enum RuntimeFact {
/// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment
/// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one
/// (`LoweringInputs::quad_primitive_ids`): for a draw of Metal's private quads or quad strip,
/// listed as two triangles a quad. Its plans state the variant the shape asks for
/// (`BindShape::quad_primitive_ids`).
/// listed as two triangles a quad.
QuadPrimitiveIds,
/// The render pipeline was compiled under `VariantKey::private_list`, and its vertex function
/// runs the consumer's list of one of Metal's private primitive types in the pulled list form
/// (`LoweringInputs::private_list`): its index and Metal's base vertex read at
/// `PushHole::CaptureIndexAddress`, each list position run once. Its plans state the variant
/// the shape asks for (`BindShape::private_list`).
/// `PushHole::CaptureIndexAddress`, each list position run once.
PrivateList,
/// The function reads the texture bound to the slot only as the in-place form of a two-plane
/// YCbCr texture reads it (`bind::YCbCrInPlace`): sampled or gathered through a constexpr sampler
/// or through the runtime sampler slots whose bits `samplers` holds (bit `n` for
/// `[[sampler(n)]]` of the slot's stage), read, or its size queried, as a 2D `float` texture.
/// Recorded on a profile that reads planes in place (`ProfileFields::ycbcr_in_place`). Where
/// the binder binds a texture whose planes are read so (`TextureShape::Texture::ycbcr_in_place`)
/// and each of those samplers states a filter the form reads (one filter for minification and
/// magnification, no anisotropy, no cubic filter, comparison or reduction), the slot joins the
/// plan's variant (`VariantKey::ycbcr_in_place`, `LoweringInputs::ycbcr_in_place`), under
/// which the slot's one binding is the planes' texel buffer (`WriteSource::YCbCrInPlace`) and
/// every access of it reads the codes and converts them as Metal does, its words in the slot's
/// push field (`PushField::YCbCrInPlace`). Elsewhere the slot binds the texture's image as
/// before. `device`: every sample of the slot is one the device's own sampler Y′CbCr
/// conversion takes (none addresses a border through a constexpr sampler or places a texel
/// offset by a parent's size, and none is a gather): where the bound texture's planes are also held as an image it
/// samples (`TextureShape::Texture::ycbcr_planes_sampler`) and each runtime sampler addresses
/// no border on either axis, the slot samples that image instead
/// (`VariantKey::ycbcr_planes_sampled`, `bind::YCbCrPlanesSampler`).
YCbCrInPlace {
slot: SlotRef,
samplers: u32,
device: bool,
},
/// The function only reads, writes or asks the size of the 2D texture bound to the slot
/// (`bind::TexelRows`): `read` at level 0 or a computed level, `write`, its width, height or
/// level count, `is_null` and a texture fence; no sample, gather, LOD query, atomic, read
/// through a sampler, imageblock slice or access of a level past the first through a storage
/// slot, and no arm of a handle that switches between slots. Where the binder binds a texture
/// whose rows are read and written in place (`TextureShape::Texture::texel_rows`), the slot
/// joins the plan's variant (`VariantKey::texel_rows`, `LoweringInputs::texel_rows`), under
/// which its one binding is a texel buffer over the rows' bytes (`WriteSource::TexelRows`),
/// texel `(x, y)` the view's `first + y · row + x`, those words in the slot's push field
/// (`PushField::TexelRows`). Elsewhere the slot binds the texture's image as before.
TexelRows { slot: SlotRef },
/// The object function runs a partial threadgroup of a `drawMeshThreads` as Metal does
/// (`lower::dispatch`'s partial object threadgroups): where its `DispatchRegion` (or a folded
/// variant's region record) carries `lower::dispatch::NONUNIFORM`, it answers its
@@ -602,8 +561,7 @@ pub enum RuntimeFact {
/// The render pipeline was compiled under `VariantKey::region_viewports`, and its vertex
/// function stores `ViewportIndex` as `DrawIndex` (`LoweringInputs::region_viewports`): each
/// draw of a multi-draw renders through the viewport and scissor at its index, the runtime's
/// draw of a rasterization-rate-mapped pass's regions several at a time. Its plans state the
/// variant the shape asks for (`BindShape::region_viewports`).
/// draw of a rasterization-rate-mapped pass's regions several at a time.
RegionViewports,
/// The kernel was compiled under `VariantKey::partial_threadgroups`
/// (`LoweringInputs::partial_threadgroups`): where its `DispatchRegion` carries
@@ -615,11 +573,10 @@ pub enum RuntimeFact {
/// The function only reads, writes, updates by a texture atomic or asks the width of the
/// texture buffer bound to the slot (`bind::texel_parts`): `read` (not through a sampler),
/// `write`, an atomic, `get_width`, `is_null` and a texture fence, on a device that indexes an
/// array of the slot's kind of texel buffer by a `NonUniform` value. Where the binder binds a
/// texture buffer of more texels than one view holds there (`TextureShape::Buffer::parts`
/// past 1), the slot joins the plan's variant (`VariantKey::texel_buffer_parts`,
/// `LoweringInputs::texel_buffer_parts`), under which its binding is an array of the texture
/// buffer's parts, one texel buffer view each. Elsewhere the slot binds one view, which
/// array of the slot's kind of texel buffer by a `NonUniform` value. Where the consumer binds a
/// texture buffer of more texels than one view holds there, the slot takes the variant
/// (`VariantKey::texel_buffer_parts`, `LoweringInputs::texel_buffer_parts`), under which its
/// binding is an array of the texture buffer's parts, one texel buffer view each. Elsewhere the slot binds one view, which
/// `maxTexelBufferElements` bounds (`TexelBufferRange`).
TexelBufferParts { slot: SlotRef },
/// Under the identity domains, the buffer slot's address, its buffer's `gpuAddress` plus the
@@ -738,8 +695,6 @@ impl RuntimeFact {
RuntimeFact::ObjectThreadgroupArena { .. } => "ObjectThreadgroupArena",
RuntimeFact::QuadPrimitiveIds => "QuadPrimitiveIds",
RuntimeFact::PrivateList => "PrivateList",
RuntimeFact::YCbCrInPlace { .. } => "YCbCrInPlace",
RuntimeFact::TexelRows { .. } => "TexelRows",
RuntimeFact::PartialObjectThreadgroups => "PartialObjectThreadgroups",
RuntimeFact::BorderTexels { .. } => "BorderTexels",
RuntimeFact::RegionViewports => "RegionViewports",
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more