Validation: the census digests each pipeline's content, and the executor's binder terms go

The authored compile census recorded, for each case, the content digest of its compiled
pipeline together with the plan the binder made for the case's bind shape (or that plan's
refusal). The runtime makes no plan, so the record now digests the content digest alone
(`CaseArtifact::record`, digest label v2), and `case_compile` takes no device. The executor
ABI moves to vulkan-engine-v213, so every census row re-records.

With the plan gone, nothing reaches the executor's binder terms, and they go:

- engine.rs: `bind_state`, `compute_shape`, `lengths_classed`, `texture_tokens`,
  `synthetic_used_addresses`, `BufferAddress`, and `ComputeRun::status` (always `None` on the
  runtime route; nothing read it);
- graphics.rs: `bind_state`, `stage_table`, `render_shape`, `texture_tokens`,
  `synthetic_address`, `synthetic_used_addresses`, `BUFFER_SLOTS` and the three per-stage
  argument-buffer iterators;
- mesh.rs: `mesh_shape`;
- argument_buffers.rs: `resource_id`, `sampler_id`, `sampler_ids`, `argument_samplers`,
  `texture_tokens`, `field_words`, `used_buffer`, `used_texture`, `synthetic_addresses` (the
  runtime route writes the runtime's own addresses and IDs through `owner_bytes`, which stays);
- resources.rs: `bound_texture`, `texture_facts`, `texel_buffer_length`, `bound_sampler`;
- variants.rs: the bound-shape module; engine/public_cases.rs, the public cases planned on
  committed profiles.

Tests: the mapping halves of the mixed tests stay (render, tessellation, slice-choosing,
argument-buffer members, the owner's bytes); their bind-state, shape and plan halves go with
the plan tests (the stencil-export, framebuffer-fetch, tessellation, owned-render and public
render plan tests, the device buffer array's table, and the executor-state plan). One check
leaves with `field_words`: it refused a texture and a sampler authored at the same field; the
runtime route's word map does not.

Verified with the cut's last commit, which names its check jobs; not built alone.
This commit is contained in:
Anees Iqbal committed 2026-11-22 10:15:18 -08:00
1 parent 25387588ea
commit fd5fcca9b0
14 files changed
+108 -3230

No files matched your search

@@ -620,7 +620,7 @@ pub fn compile_prepared(
worker: &CompileWorker,
device: &WorkerDevice,
) -> CellResult {
let planned = match case_compile(prepared, device) {
let planned = match case_compile(prepared) {
Ok(planned) => planned,
Err(error) => return CellResult::decided(executor_outcome(error, FailureClass::Case)),
};
@@ -6,8 +6,8 @@
//! draw (`platform::runtime_render`, [`graphics`]). The case's own function links the functions
//! its visible-function references name, from the modules the Metal oracle links
//! ([`linked_modules`]). Each element of a texture array is the texture at its own Metal slot
//! ([`resources::bound_textures`]), and an argument-buffer buffer is a used resource whose address
//! its owner holds ([`argument_buffers`]); an argument-buffer texture is a used texture whose
//! ([`resources::bound_textures`]), and an argument-buffer buffer is a resident buffer whose address
//! its owner holds ([`argument_buffers`]); an argument-buffer texture is a resident texture whose
//! resource id its owner holds. A draw of a structure the runtime route does not make, and an
//! object or mesh case, are typed refusals (`run_prepared`).
//!
@@ -65,14 +65,11 @@ use crate::worker::compile::{
use crate::worker::device::{DeviceInput, DeviceOutcome, DeviceRun, OpenedDevice, VenueRun};
use crate::worker::WorkerFailure;
use base64::Engine as _;
use metal2vulkan::bind::{
BindShape, BindState, BoundBuffer, BufferRanges, Dispatch, DrawCall, StageTable, StatusReport,
};
use metal2vulkan::bind::{Dispatch, DrawCall};
use metal2vulkan::cache::Hash256;
use metal2vulkan::device::DeviceProfile;
use metal2vulkan::error::Error;
use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::RenderStages;
use metal2vulkan::pipeline::Stage as ShaderStage;
use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline};
use std::borrow::Cow;
@@ -85,8 +82,6 @@ pub mod artifact;
pub mod graphics;
pub mod guards;
pub mod mesh;
#[cfg(test)]
mod public_cases;
pub mod resources;
#[cfg(test)]
pub(crate) mod tests;
@@ -99,9 +94,9 @@ pub mod variants;
/// how it decides a match. A change no recorded row can observe (a case kind no earlier executor
/// ran, or one it refused) needs no bump; its commit says why. The commit that bumps it says what
/// changed; this comment keeps no history.
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v212";
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v213";
/// One kernel case in the terms the binder takes: what this executor supports of an
/// One kernel case in the terms the runtime route takes: what this executor supports of an
/// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures,
/// textures, texture arrays, samplers, threadgroup lengths, function
/// constants, a `dispatchThreads` grid, and a buffer, argument-buffer buffer, texture or
@@ -119,20 +114,16 @@ pub struct ComputeCase {
/// Initial bytes of each argument-buffer buffer, by `(owner Metal index, field offset)`:
/// a buffer the owner's argument buffer points to (loaded pointers). The run writes its guest
/// address into the owner's bytes at the field offset, the pointer Metal's argument encoder
/// writes there ([`argument_buffers::owner_bytes`]), and lists it as a used resource
/// (`useResource`, read and write, as the oracle does), so the resident set reaches it.
/// writes there ([`argument_buffers::owner_bytes`]), and makes it resident (`useResource`,
/// read and write, as the oracle does).
pub argument_buffer_buffers: BTreeMap<(u32, u32), Vec<u8>>,
/// Each argument-buffer texture (initial contents included), by `(owner Metal index, field
/// offset)`: a used texture whose resource id the run writes into the owner at the field, the
/// `gpuResourceID` Metal's argument encoder writes there ([`argument_buffers::field_words`]),
/// resident for reading and writing, so the plan's heap holds it and the kernel's handle table
/// finds it.
/// offset)`: a texture whose `gpuResourceID` the run writes into the owner at the field, as
/// Metal's argument encoder writes it there, resident for reading and writing.
pub argument_buffer_textures: BTreeMap<(u32, u32), LiteralTexture>,
/// Each argument-buffer sampler, by `(owner Metal index, field offset)`: a sampler state whose
/// id ([`argument_buffers::sampler_ids`]) the run writes into the owner at the field, the
/// `gpuResourceID` Metal's argument encoder writes there, and lists among the bind state's
/// argument samplers, so the plan's sampler arrays hold it and the function's sampler table
/// finds it.
/// `gpuResourceID` the run writes into the owner at the field, as Metal's argument encoder
/// writes it there.
pub argument_buffer_samplers: BTreeMap<(u32, u32), ArgumentBufferSamplerResource>,
/// Each bound texture (initial contents included), by Metal texture index: the case's textures
/// and each element of its texture arrays at its own slot ([`resources::bound_textures`]).
@@ -201,9 +192,6 @@ pub struct ComputeRun {
/// for a run through the runtime.
pub translator_fingerprint: String,
pub environment: serde_json::Value,
/// The binder's execution status, read before the output; `None` for a run through the
/// runtime, whose shaders keep no status.
pub status: Option<StatusReport>,
/// Derived from the executed modules' precision notes and strategy census.
pub comparison: ComparisonClass,
/// The executed modules' census and the class of the device that ran them.
@@ -466,120 +454,6 @@ pub fn function_constants(
Ok(constants)
}
/// `state` with each stage table classing its buffers' lengths under `ranges`
/// (`StageTable::buffer_ranges`), the device's range limit (`BufferRanges::of`), as the runtime's
/// tables class them, so a buffer's shape states the length class the runtime's shape of the same
/// bind states.
pub fn lengths_classed(mut state: BindState, ranges: BufferRanges) -> BindState {
for table in state.stages.values_mut() {
table.buffer_ranges = ranges;
}
state
}
/// The `BindState` of `case`: each buffer bound at offset 0 with its length, its guest address,
/// and its host device address when the device has one (`addresses` by Metal index), each texture
/// and sampler ([`resources`]), the threadgroup lengths, each argument-buffer buffer as a used
/// buffer (`embedded` by
/// `(owner, field offset)`; its consumer token is its position in
/// [`ComputeCase::argument_buffer_buffers`]), and each argument-buffer texture as a used texture
/// with its resource id (its token follows the buffers', [`argument_buffers::texture_tokens`]),
/// each made resident for reading and writing, as the Metal oracle's `useResource` does, and each
/// argument-buffer sampler as an argument sampler with its id
/// ([`argument_buffers::argument_samplers`]); classing lengths under the device's range limit
/// `ranges` ([`lengths_classed`]).
pub fn bind_state(
case: &ComputeCase,
addresses: &BTreeMap<u32, BufferAddress>,
embedded: &BTreeMap<(u32, u32), BufferAddress>,
ranges: BufferRanges,
) -> Result<BindState, String> {
let mut table = StageTable::default();
for (&index, bytes) in &case.buffers {
let address = addresses.get(&index).copied().unwrap_or_default();
let bound = BoundBuffer::Buffer {
length: bytes.len() as u64,
offset: 0,
gpu_address: address.guest,
device_address: address.host,
attribute_stride: None,
};
table.buffers.insert(index, bound);
}
for (&index, texture) in &case.textures {
table
.textures
.insert(index, resources::bound_texture(texture)?);
}
for (&index, sampler) in &case.samplers {
table
.samplers
.insert(index, resources::bound_sampler(sampler));
}
table.threadgroup_lengths = case.threadgroup_lengths.clone();
let mut state = BindState::default();
state.stages.insert(ShaderStage::Kernel, table);
for (token, (key, bytes)) in case.argument_buffer_buffers.iter().enumerate() {
let address = embedded.get(key).copied().unwrap_or_default();
state.used_resources.push(argument_buffers::used_buffer(
token,
bytes.len(),
address,
RenderStages::empty(),
)?);
}
let tokens = texture_tokens(case)?;
for (key, texture) in &case.argument_buffer_textures {
state.used_resources.push(argument_buffers::used_texture(
tokens[key],
texture,
RenderStages::empty(),
)?);
}
state.argument_samplers =
argument_buffers::argument_samplers(case.argument_buffer_samplers.iter())?;
Ok(lengths_classed(state, ranges))
}
/// The consumer token of each argument-buffer texture of `case`, by its key
/// ([`argument_buffers::texture_tokens`]).
pub fn texture_tokens(case: &ComputeCase) -> Result<BTreeMap<(u32, u32), u32>, String> {
argument_buffers::texture_tokens(
case.argument_buffer_buffers.len(),
case.argument_buffer_textures.keys().copied(),
)
}
/// A bound buffer's addresses: the Metal `gpuAddress` the guest sees and the host Vulkan device
/// address when the buffer has one. Without device addresses the guest address is a distinct
/// synthetic base ([`BufferAddress::synthetic`], [`BufferAddress::synthetic_used`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BufferAddress {
pub guest: u64,
pub host: Option<u64>,
}
impl BufferAddress {
/// The synthetic guest base of Metal buffer `index` on a device without device addresses:
/// disjoint 4-GiB windows, never 0.
pub fn synthetic(index: u32) -> BufferAddress {
BufferAddress {
guest: (u64::from(index) + 1) << 32,
host: None,
}
}
/// The synthetic guest base of the argument-buffer buffer with consumer token `token` on a
/// device without device addresses: 4-GiB windows in the upper half of the address space,
/// disjoint from every [`BufferAddress::synthetic`] window.
pub fn synthetic_used(token: u32) -> BufferAddress {
BufferAddress {
guest: (1 << 63) | ((u64::from(token) + 1) << 32),
host: None,
}
}
}
/// The translator fingerprint of engine observations: the product and the profile the case
/// compiled for (the opened device's queried profile, policy included).
pub fn engine_fingerprint(profile: &DeviceProfile) -> String {
@@ -1275,39 +1149,6 @@ fn render_attempt(
CompileAttempt::of(compile_render_request(worker, device, libraries, request))
}
/// The `BindShape` the executor binds `case` with on a device that has device addresses exactly
/// when `addressed` and the range limits `ranges` (`BufferRanges::of`): [`bind_state`] with every
/// buffer's guest address and, when `addressed`, a host address (only whether a buffer has one is
/// part of the shape, not its value).
pub fn compute_shape(
case: &ComputeCase,
addressed: bool,
ranges: BufferRanges,
) -> Result<BindShape, String> {
let with_host = |mut address: BufferAddress| {
address.host = addressed.then_some(address.guest);
address
};
let addresses = case
.buffers
.keys()
.map(|&index| (index, with_host(BufferAddress::synthetic(index))))
.collect();
let embedded = synthetic_used_addresses(case)?
.into_iter()
.map(|(key, address)| (key, with_host(address)))
.collect();
Ok(bind_state(case, &addresses, &embedded, ranges)?.shape())
}
/// The synthetic guest address of each argument-buffer buffer of `case`, by its key
/// ([`argument_buffers::synthetic_addresses`]): its [`BufferAddress::synthetic_used`].
pub fn synthetic_used_addresses(
case: &ComputeCase,
) -> Result<BTreeMap<(u32, u32), BufferAddress>, String> {
argument_buffers::synthetic_addresses(case.argument_buffer_buffers.keys().copied())
}
/// Admit `case` for the engine candidate on `device_type`, then open that device and execute
/// it, compiling in `worker`.
pub fn execute(
@@ -1393,7 +1234,7 @@ pub fn prepare_case(
/// [`prepare_case`] for the authored compile census (`authored_compile`): a case whose only stop
/// is the mesh render pipeline the executor does not draw
/// ([`ToolingRequirement::MeshRenderPipeline`]) is prepared too, its draw mapped
/// ([`mesh::mesh_case`]), so [`case_compile`] plans the pipeline a run of it would compile. A
/// ([`mesh::mesh_case`]), so [`case_compile`] compiles the pipeline a run of it would compile. A
/// run's preparation refuses such a case before any device, its device worker's included.
pub fn prepare_compile(
device: DeviceType,
@@ -1444,113 +1285,74 @@ pub struct CaseCompile<'a> {
pipeline: PlannedPipeline<'a>,
}
/// A planned compile's request, its libraries in [`PipelineRequest::libraries`] order, and the
/// bind shape the run plans it for: a kernel's, or a draw's (a case's own, or a mesh draw's,
/// `mesh::mesh_request`).
/// A compile's request and its libraries in [`PipelineRequest::libraries`] order: a kernel's, or
/// a draw's (a case's own, or a mesh draw's, `mesh::mesh_request`).
enum PlannedPipeline<'a> {
Compute {
request: PipelineRequest,
libraries: Vec<RowSource<'a>>,
shape: BindShape,
},
Render {
request: PipelineRequest,
libraries: Vec<RowSource<'a>>,
shape: BindShape,
},
}
impl CaseCompile<'_> {
/// Compile in `worker` for `device` as the runtime compiles it and record it in `artifact` as
/// the executor's run records it (the pipeline's content and its plan for the run's bind
/// shape), keeping only whether it compiled and what the worker measured: the pipeline is
/// dropped here.
/// the executor's run records it (the pipeline's content), keeping only whether it compiled
/// and what the worker measured: the pipeline is dropped here.
pub fn compile(
&self,
worker: &CompileWorker,
device: &WorkerDevice,
artifact: &mut artifact::CaseArtifact,
) -> (Result<(), CompileFailure>, Option<crate::worker::Measured>) {
let mut record = |pipeline: &dyn artifact::Planned, shape| {
artifact
.record(pipeline, device.device(), shape)
.map_err(CompileFailure::Artifact)
};
let mut record = |content| artifact.record(content).map_err(CompileFailure::Artifact);
match &self.pipeline {
PlannedPipeline::Compute {
request,
libraries,
shape,
} => {
PlannedPipeline::Compute { request, libraries } => {
let attempt = compute_attempt(worker, device, libraries, request);
let result = attempt.result.and_then(|pipeline| record(&pipeline, shape));
let result = attempt
.result
.and_then(|pipeline| record(pipeline.content_digest()));
(result, attempt.measured)
}
PlannedPipeline::Render {
request,
libraries,
shape,
} => {
PlannedPipeline::Render { request, libraries } => {
let attempt = render_attempt(worker, device, request, libraries);
let result = attempt.result.and_then(|pipeline| record(&pipeline, shape));
let result = attempt
.result
.and_then(|pipeline| record(pipeline.content_digest()));
(result, attempt.measured)
}
}
}
}
/// The pipeline a run of `prepared` compiles on `device` before it reads any device output,
/// compiled as the runtime compiles it (through no binding plan): the case's own pipeline
/// ([`kernel_request`] for the case's dispatch, [`render_request`] with its generated companion
/// and no shape, or a mesh draw's, `mesh::mesh_request`), and the bind shape the artifact's digest
/// holds the plan of ([`compute_shape`], [`graphics::render_shape`]'s, or `mesh::mesh_shape`'s).
/// The bind shapes depend on the device only through whether it has device addresses, read from
/// `device`'s description (for an opened device, restricted to what was enabled), and through its
/// profile's range limits (`BufferRanges::of`). The authored compile census compiles it on each
/// committed profile.
pub fn case_compile<'a>(
prepared: &'a PreparedCase,
device: &WorkerDevice,
) -> Result<CaseCompile<'a>, ExecutorError> {
use metal2vulkan::device::VkFeature;
let addressed = device.description().has(VkFeature::BufferDeviceAddress);
let ranges = BufferRanges::of(device.device().profile().limits());
/// The pipeline a run of `prepared` compiles before it reads any device output, compiled as the
/// runtime compiles it: the case's own pipeline ([`kernel_request`] for the case's dispatch,
/// [`render_request`] with its generated companion, or a mesh draw's, `mesh::mesh_request`). The
/// authored compile census compiles it on each committed profile.
pub fn case_compile(prepared: &PreparedCase) -> Result<CaseCompile<'_>, ExecutorError> {
let library = RowSource::of_row(&prepared.checked.primary.source);
let linked = prepared.linked.as_slice();
let pipeline = match &prepared.mapped {
Mapped::Compute(compute) => {
let shape = compute_shape(compute, addressed, ranges).map_err(ExecutorError::Failed)?;
let (request, libraries) = kernel_request(&library, linked, compute);
PlannedPipeline::Compute {
request,
libraries,
shape,
}
PlannedPipeline::Compute { request, libraries }
}
Mapped::Render(render) => {
let shape =
graphics::render_shape(render, addressed, ranges).map_err(ExecutorError::Failed)?;
let companion = companion_source(render);
let (request, libraries) =
render_request(&library, companion.as_ref(), linked, render)?;
PlannedPipeline::Render {
request,
libraries,
shape,
}
PlannedPipeline::Render { request, libraries }
}
Mapped::Mesh(mesh) => {
let shape = mesh::mesh_shape(mesh, addressed, ranges)?;
let companion = mesh
.companion
.as_ref()
.map(|generated| RowSource::Text(Cow::Owned(generated.air_text(Spelling::Opaque))));
let (request, libraries) = mesh::mesh_request(&library, companion, mesh)?;
PlannedPipeline::Render {
request,
libraries,
shape,
}
PlannedPipeline::Render { request, libraries }
}
};
Ok(CaseCompile { pipeline })
@@ -4,30 +4,13 @@
//! A case authors each member by its owner (the Metal buffer index of the argument buffer that
//! holds it) and the byte offset of its field in the owner. The Metal oracle creates the member,
//! writes it into the owner with its argument encoder (Tier 2), and makes it resident for reading
//! and writing (`useResource:usage:`, on a render encoder with `stages: Vertex | Fragment`). The
//! executor does the same in the binder's terms: the owner, a buffer of the function's own stage,
//! is created holding at each field the 8 bytes the encoder writes there ([`field_words`],
//! [`owner_bytes`]), and each member is what the binder takes for it:
//!
//! - a buffer is its guest address in the owner and a used resource of class `Buffer`
//! ([`used_buffer`]), so the resident set reaches it and a loaded pointer is translated through
//! it;
//! - a texture is its `gpuResourceID` in the owner and a used resource of class `Texture` with
//! that resource id ([`used_texture`]): a heap member, which the plan writes into every heap
//! array whose class holds it and enters in each stage's handle table, so a handle loaded from
//! the field finds its element; a texture buffer is one of Metal's `TextureBuffer` type, which
//! the plan's heap holds no member of, so only a run through the runtime draws it;
//! - a sampler is its `gpuResourceID` in the owner and an argument sampler of the bind state with
//! that id ([`embed_samplers`], [`sampler_ids`]): the plan writes it into each sampler array
//! and enters it in each stage's sampler table, so a sampler loaded from the field finds its
//! element.
//! and writing (`useResource:usage:`, on a render encoder with `stages: Vertex | Fragment`). A run
//! through the runtime does the same: the owner, a buffer of the function's own stage, is created
//! holding at each field the 8 bytes the encoder writes there ([`owner_bytes`]): a buffer's
//! `gpuAddress`, a texture's or a sampler's `gpuResourceID`, as the runtime gives each.
use super::resources;
use super::BufferAddress;
use crate::case::ArgumentBufferSamplerResource;
use crate::literal::{LiteralArgumentBufferBuffer, LiteralArgumentBufferTexture, LiteralTexture};
use metal2vulkan::bind::{ArgumentSampler, ResourceClass, UsedResource};
use metal2vulkan::metal::{RenderStages, ResourceUsage};
use std::collections::BTreeMap;
/// An argument-buffer member's key: its owner's Metal buffer index and its field's byte offset
@@ -128,95 +111,9 @@ pub fn embed_samplers(
Ok(embedded)
}
/// The synthetic `gpuResourceID` of the used resource whose consumer token is `token`: nonzero
/// (a handle table never enters id 0, the null entry) and distinct per token.
pub fn resource_id(token: u32) -> u64 {
(1 << 62) | (u64::from(token) + 1)
}
/// The synthetic `gpuResourceID` of the argument-buffer sampler at `position` among a case's:
/// nonzero (a sampler table never enters id 0, the null entry), distinct per position, and apart
/// from every texture's [`resource_id`].
pub fn sampler_id(position: usize) -> Result<u64, String> {
u64::try_from(position)
.ok()
.and_then(|position| position.checked_add(1))
.filter(|&id| id < 1 << 61)
.map(|id| (1 << 61) | id)
.ok_or_else(|| "too many argument-buffer samplers".into())
}
/// The [`sampler_id`] of each argument-buffer sampler `keys` (in order), by key.
pub fn sampler_ids<K: Ord>(keys: impl Iterator<Item = K>) -> Result<BTreeMap<K, u64>, String> {
keys.enumerate()
.map(|(position, key)| Ok((key, sampler_id(position)?)))
.collect()
}
/// The bind state's argument samplers of `samplers`, in the order [`sampler_ids`] takes their keys:
/// each one's authored descriptor ([`resources::argument_sampler_descriptor`]) with its
/// [`sampler_id`].
pub fn argument_samplers<'a, K>(
samplers: impl Iterator<Item = (K, &'a ArgumentBufferSamplerResource)>,
) -> Result<Vec<ArgumentSampler>, String> {
samplers
.enumerate()
.map(|(position, (_, sampler))| {
Ok(ArgumentSampler::new(
resources::argument_sampler_descriptor(sampler),
sampler_id(position)?,
))
})
.collect()
}
/// The consumer token of each argument-buffer texture `keys` (in order) of a case whose
/// argument-buffer buffers number `buffers`: its position after them, so the buffers keep theirs.
pub fn texture_tokens<K: Ord>(
buffers: usize,
keys: impl Iterator<Item = K>,
) -> Result<BTreeMap<K, u32>, String> {
keys.enumerate()
.map(|(position, key)| {
let token = buffers
.checked_add(position)
.and_then(|token| u32::try_from(token).ok())
.ok_or("too many argument-buffer members")?;
Ok((key, token))
})
.collect()
}
/// The 8 bytes Metal's argument encoder writes at each member's field, as a little-endian word
/// by key: each argument-buffer buffer's guest address (`buffers`), each argument-buffer
/// texture's [`resource_id`] (`textures`, by consumer token), and each argument-buffer sampler's
/// id (`samplers`, [`sampler_ids`]). A key named by two members is refused.
pub fn field_words<K: Ord + Copy + std::fmt::Debug>(
buffers: &BTreeMap<K, BufferAddress>,
textures: &BTreeMap<K, u32>,
samplers: &BTreeMap<K, u64>,
) -> Result<BTreeMap<K, u64>, String> {
let mut words = BTreeMap::new();
let members = buffers
.iter()
.map(|(&key, address)| (key, address.guest))
.chain(
textures
.iter()
.map(|(&key, &token)| (key, resource_id(token))),
)
.chain(samplers.iter().map(|(&key, &id)| (key, id)));
for (key, word) in members {
if words.insert(key, word).is_some() {
return Err(format!("argument-buffer field {key:?} holds two members"));
}
}
Ok(words)
}
/// The bytes the buffer at Metal index `index` of a function is created with: its initial bytes
/// (`buffers`) with each of its members' words (`fields`, by key, [`field_words`]) written at
/// the member's field, little endian. Two members whose fields overlap, and a field the owner
/// (`buffers`) with each of its members' words (`fields`, by key) written at the member's field,
/// little endian. Two members whose fields overlap, and a field the owner
/// does not cover, are refused.
pub fn owner_bytes(
buffers: &BTreeMap<u32, Vec<u8>>,
@@ -244,55 +141,3 @@ pub fn owner_bytes(
}
Ok(bytes)
}
/// The used resource of the argument-buffer buffer of `length` bytes at `address` whose consumer
/// token is `token` (its position among the bind state's argument-buffer buffers), resident for
/// reading and writing in `stages`, as the Metal oracle's `useResource` makes it: no stages on a
/// compute encoder, the vertex and fragment stages on a render encoder.
pub fn used_buffer(
token: usize,
length: usize,
address: BufferAddress,
stages: RenderStages,
) -> Result<UsedResource, String> {
let token = u32::try_from(token).map_err(|_| "too many argument-buffer buffers")?;
let mut used = UsedResource::new(ResourceClass::Buffer, token);
used.gpu_address = Some(address.guest);
used.device_address = address.host;
used.length = length as u64;
used.usage = ResourceUsage::READ | ResourceUsage::WRITE;
used.stages = stages;
Ok(used)
}
/// The used resource of the argument-buffer texture `texture` whose consumer token is `token`
/// ([`texture_tokens`]): a `Texture` of its facts ([`resources::texture_facts`]), a texture
/// buffer's of Metal's `TextureBuffer` type, whose resource id is [`resource_id`] of its token,
/// resident for reading and writing in `stages` as the Metal oracle's `useResource` makes it.
/// A run through the runtime draws it, and the authored compile census compiles its pipeline for
/// this bind shape.
pub fn used_texture(
token: u32,
texture: &LiteralTexture,
stages: RenderStages,
) -> Result<UsedResource, String> {
let facts = resources::texture_facts(texture)?;
let mut used = UsedResource::new(ResourceClass::Texture(facts), token);
used.usage = ResourceUsage::READ | ResourceUsage::WRITE;
used.stages = stages;
used.resource_id = Some(resource_id(token));
Ok(used)
}
/// The guest address of each argument-buffer buffer of `keys` (in token order) on a device
/// without device addresses, by key: its [`BufferAddress::synthetic_used`].
pub fn synthetic_addresses<K: Ord>(
keys: impl Iterator<Item = K>,
) -> Result<BTreeMap<K, BufferAddress>, String> {
keys.enumerate()
.map(|(token, key)| {
let token = u32::try_from(token).map_err(|_| "too many argument-buffer buffers")?;
Ok((key, BufferAddress::synthetic_used(token)))
})
.collect()
}
@@ -1,11 +1,9 @@
//! What an engine run executed, by content.
//!
//! The pipeline a run compiles before it reads device output (the case's own, the compile
//! [`super::case_compile`] plans) contributes one compile digest: its subject (`case`), the
//! [`super::case_compile`] makes) contributes one compile digest: its subject (`case`) and the
//! pipeline's content digest (`ComputePipeline::content_digest`, every field but the cache
//! identity), the content digest of the binding plan the run makes of it for its bind shape
//! (`BindingPlan::content_digest`, or the refusal of that plan). The case's artifact is the
//! SHA-256 over the compile digests, by subject.
//! identity). The case's artifact is the SHA-256 over the compile digests, by subject.
//!
//! The executor records it ([`ExecutedArtifact`]) with the product's
//! `cache::RUNTIME_VERSION`; the authored compile census computes it the same way, device-free,
@@ -13,11 +11,7 @@
use std::collections::BTreeMap;
use metal2vulkan::bind::{BindShape, BindingPlan};
use metal2vulkan::cache::Hash256;
use metal2vulkan::device::Device;
use metal2vulkan::error::BindError;
use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@@ -57,32 +51,6 @@ impl ExecutedArtifact {
}
}
/// A pipeline whose content and binding plan a compile digest covers.
pub trait Planned {
/// The pipeline's content digest.
fn content_digest(&self) -> Hash256;
/// The pipeline's binding plan for `shape` on `device`.
fn plan_for(&self, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError>;
}
impl Planned for ComputePipeline {
fn content_digest(&self) -> Hash256 {
ComputePipeline::content_digest(self)
}
fn plan_for(&self, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
self.plan(device, shape)
}
}
impl Planned for RenderPipeline {
fn content_digest(&self) -> Hash256 {
RenderPipeline::content_digest(self)
}
fn plan_for(&self, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
self.plan(device, shape)
}
}
/// The subject of the case's own compile, as the artifact names it.
const CASE: &str = "case";
@@ -93,31 +61,14 @@ pub struct CaseArtifact {
}
impl CaseArtifact {
/// Record the case's compile: `pipeline` planned for `shape` on `device`. A plan the binder
/// refuses is part of the digest as its refusal. Compiled twice, it must be the same compile.
pub fn record(
&mut self,
pipeline: &dyn Planned,
device: &Device,
shape: &BindShape,
) -> Result<(), ExecutorError> {
/// Record the case's compile, a pipeline of content digest `content`. Compiled twice, it must
/// be the same compile.
pub fn record(&mut self, content: Hash256) -> Result<(), ExecutorError> {
let label = CASE.to_owned();
let mut h = Sha256::new();
h.update(b"metal2vulkan C3 compile digest v1\0");
h.update(b"metal2vulkan C3 compile digest v2\0");
put(&mut h, label.as_bytes());
h.update(pipeline.content_digest());
match pipeline.plan_for(device, shape) {
Ok(plan) => {
h.update([1]);
h.update(plan.content_digest().map_err(|error| {
ExecutorError::Failed(format!("the binding plan has no digest: {error}"))
})?);
}
Err(refusal) => {
h.update([0]);
put(&mut h, format!("{refusal:?}").as_bytes());
}
}
h.update(content);
self.insert(label, h.finalize().into())
}
@@ -4,9 +4,8 @@
//! `Library` → `Function` → `compile_render_pipeline` with the Metal oracle's descriptor
//! ([`RenderTemplate`], compiled in the tools' compile worker as
//! `acceptance::PipelineRequest::VertexDraw`, or as `PipelineRequest::Draw` with both stages'
//! libraries), then `RenderPipeline::plan` and `BindingPlan::instantiate_draw`. This module is the
//! device-free half (case mapping, the bind state, the descriptor, and output selection); the
//! Vulkan half is `platform::render`.
//! libraries), then drawn through the runtime. This module is the device-free half (case mapping,
//! the descriptor, and output selection); the Vulkan half is `platform::runtime_render`.
//!
//! What an authored case maps to ([`render_case`]):
//!
@@ -33,10 +32,7 @@
//! functions of two libraries through one pipeline with derived expectations.
use super::argument_buffers::{self, FieldKey};
use super::{
function_constants, lengths_classed, require_case_families, resources, select_range,
BufferAddress,
};
use super::{function_constants, require_case_families, resources, select_range};
use crate::case::out_of_bounds::OutOfBoundsTarget;
use crate::case::{
ArgumentBufferSamplerResource, AttributeFormat, AuthoredCase, OutputSelection, Primitive,
@@ -50,13 +46,10 @@ use crate::executor_contract::render_target_array::render_target_array_length;
use crate::executor_contract::tessellation as patches;
use crate::executor_contract::DrawDepthStencil;
use crate::literal::{LiteralDepthStencil, LiteralResources, LiteralStageInput, LiteralTexture};
use metal2vulkan::bind::{
BindShape, BindState, BoundBuffer, BufferRanges, DrawCall, IndexBufferRef, StageTable,
TessellationFactorBuffer, TessellationFactors,
};
use metal2vulkan::bind::{DrawCall, IndexBufferRef};
use metal2vulkan::error::{DescriptorError, Error, MetalAnswer};
use metal2vulkan::library::FunctionConstantValues;
use metal2vulkan::metal::{self, RenderStages};
use metal2vulkan::metal;
use metal2vulkan::pipeline::Stage as ShaderStage;
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, FunctionDescriptor, RenderPipeline, RenderPipelineDescriptor,
@@ -65,9 +58,6 @@ use metal2vulkan::pipeline::{
};
use std::collections::BTreeMap;
/// The Metal buffer slots are `0..31`.
const BUFFER_SLOTS: u32 = 31;
/// What one stage binds, by Metal index.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StageResources {
@@ -190,7 +180,7 @@ pub enum Assembly {
},
}
/// One draw through one render pipeline, in the terms the binder takes.
/// One draw through one render pipeline, in the terms the runtime route takes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RenderCase {
pub vertex: RenderFunction,
@@ -208,7 +198,7 @@ pub struct RenderCase {
pub depth_stencil_state: DrawDepthStencil,
/// The render pass's `renderTargetArrayLength`: the Metal oracle's, 1 when the case's own
/// function's stage metadata declares its render target slice and 0 otherwise
/// ([`render_target_array_length`]), bound as `BindState::render_target_array_length`.
/// ([`render_target_array_length`]).
pub render_target_array_length: u32,
pub assembly: Assembly,
pub draw: DrawCall,
@@ -251,48 +241,6 @@ impl RenderCase {
.map(|(_, function)| function)
}
/// Each argument-buffer buffer of each stage, by `(stage, owner, field offset)`, in stage
/// order: its position is its consumer token in the bind state ([`bind_state`]).
pub fn argument_buffer_buffers(
&self,
) -> impl Iterator<Item = ((ShaderStage, u32, u32), &Vec<u8>)> {
self.stages().flat_map(|(stage, function)| {
function
.resources
.argument_buffer_buffers
.iter()
.map(move |(&(owner, field), bytes)| ((stage, owner, field), bytes))
})
}
/// Each argument-buffer texture of each stage, by `(stage, owner, field offset)`, in stage
/// order ([`texture_tokens`] gives its consumer token).
pub fn argument_buffer_textures(
&self,
) -> impl Iterator<Item = ((ShaderStage, u32, u32), &LiteralTexture)> {
self.stages().flat_map(|(stage, function)| {
function
.resources
.argument_buffer_textures
.iter()
.map(move |(&(owner, field), texture)| ((stage, owner, field), texture))
})
}
/// Each argument-buffer sampler of each stage, by `(stage, owner, field offset)`, in stage
/// order ([`argument_buffers::sampler_ids`] gives its id).
pub fn argument_buffer_samplers(
&self,
) -> impl Iterator<Item = ((ShaderStage, u32, u32), &ArgumentBufferSamplerResource)> {
self.stages().flat_map(|(stage, function)| {
function
.resources
.argument_buffer_samplers
.iter()
.map(move |(&(owner, field), sampler)| ((stage, owner, field), sampler))
})
}
/// The stage of the generated companion's function, which links nothing: the vertex stage of a
/// passthrough vertex, the fragment stage of an observer fragment, none without a companion
/// (a render case's is never a mesh render pipeline's stages, which [`render_case`] refuses).
@@ -905,172 +853,6 @@ pub fn pipeline_descriptor(
)
}
/// The guest-visible slot of a stage's buffer: disjoint 4-GiB windows per stage and index, never
/// 0 (see [`BufferAddress::synthetic`]).
pub fn synthetic_address(stage: ShaderStage, index: u32) -> BufferAddress {
let base = if stage == ShaderStage::Fragment {
BUFFER_SLOTS
} else {
0
};
BufferAddress::synthetic(base + index)
}
/// The `BindState` of `case`: each stage's buffers at offset 0 with their lengths and addresses
/// (`addresses` by stage and Metal index), textures, and samplers; the vertex buffers bound to the
/// vertex stage at their slots (their strides come from the descriptor); each argument-buffer
/// buffer as a used buffer at its address (`embedded` by stage, owner, and field offset; its
/// consumer token is its position in [`RenderCase::argument_buffer_buffers`]) and each
/// argument-buffer texture as a used texture with its resource id (its token follows the buffers',
/// [`texture_tokens`]), each resident for reading and writing in the vertex and fragment stages, as
/// the Metal oracle's `useResource:usage:stages:` makes it; the pass's render target array length;
/// and a patch draw's factor buffer, its whole length at the shared offset and instance stride,
/// with Metal's default scale (`executor_contract::tessellation`); and the draw's depth/stencil
/// descriptor, the one the Metal oracle sets (`RenderCase::depth_stencil_state`), which a
/// pipeline's shader-side stencil reads as push data; classing lengths under the device's range
/// limit `ranges` ([`lengths_classed`]).
pub fn bind_state(
case: &RenderCase,
addresses: &BTreeMap<(ShaderStage, u32), BufferAddress>,
embedded: &BTreeMap<(ShaderStage, u32, u32), BufferAddress>,
ranges: BufferRanges,
) -> Result<BindState, String> {
let bound = |stage: ShaderStage, index: u32, length: u64| {
let address = addresses.get(&(stage, index)).copied().unwrap_or_default();
BoundBuffer::Buffer {
length,
offset: 0,
gpu_address: address.guest,
device_address: address.host,
attribute_stride: None,
}
};
let mut state = BindState::default();
state.render_target_array_length = case.render_target_array_length;
if let Assembly::Patches { factors, .. } = &case.assembly {
state.tessellation_factors = TessellationFactors::new(
Some(TessellationFactorBuffer::new(
factors.len() as u64,
patches::FACTOR_OFFSET,
patches::FACTOR_INSTANCE_STRIDE,
)),
patches::FACTOR_SCALE,
);
}
for (stage, function) in case.stages() {
let table = stage_table(function, |index, length| bound(stage, index, length))?;
state.stages.insert(stage, table);
}
let table = state.stages.entry(ShaderStage::Vertex).or_default();
for buffer in &case.vertex_buffers {
let slot = bound(
ShaderStage::Vertex,
buffer.buffer_index,
buffer.bytes.len() as u64,
);
if table.buffers.insert(buffer.buffer_index, slot).is_some() {
return Err(format!(
"vertex buffer {} is also a bound buffer",
buffer.buffer_index
));
}
}
for (token, (key, bytes)) in case.argument_buffer_buffers().enumerate() {
let address = embedded.get(&key).copied().unwrap_or_default();
state.used_resources.push(argument_buffers::used_buffer(
token,
bytes.len(),
address,
RenderStages::VERTEX | RenderStages::FRAGMENT,
)?);
}
let tokens = texture_tokens(case)?;
for (key, texture) in case.argument_buffer_textures() {
state.used_resources.push(argument_buffers::used_texture(
tokens[&key],
texture,
RenderStages::VERTEX | RenderStages::FRAGMENT,
)?);
}
state.argument_samplers = argument_buffers::argument_samplers(case.argument_buffer_samplers())?;
state.depth_stencil = case.depth_stencil_state.descriptor;
Ok(lengths_classed(state, ranges))
}
/// The bind table of `function`'s own resources: its buffers, each bound as `bound` binds a buffer
/// of its index and length, its textures and its samplers.
pub fn stage_table(
function: &RenderFunction,
bound: impl Fn(u32, u64) -> BoundBuffer,
) -> Result<StageTable, String> {
let mut table = StageTable::default();
for (&index, bytes) in &function.resources.buffers {
table
.buffers
.insert(index, bound(index, bytes.len() as u64));
}
for (&index, texture) in &function.resources.textures {
table
.textures
.insert(index, resources::bound_texture(texture)?);
}
for (&index, sampler) in &function.resources.samplers {
table
.samplers
.insert(index, resources::bound_sampler(sampler));
}
Ok(table)
}
/// The consumer token of each argument-buffer texture of `case`, by `(stage, owner, field
/// offset)`: its position after every argument-buffer buffer
/// ([`argument_buffers::texture_tokens`]).
pub fn texture_tokens(case: &RenderCase) -> Result<BTreeMap<(ShaderStage, u32, u32), u32>, String> {
argument_buffers::texture_tokens(
case.argument_buffer_buffers().count(),
case.argument_buffer_textures().map(|(key, _)| key),
)
}
/// The synthetic guest address of each argument-buffer buffer of `case`, by its key
/// ([`argument_buffers::synthetic_addresses`]): its [`BufferAddress::synthetic_used`].
pub fn synthetic_used_addresses(
case: &RenderCase,
) -> Result<BTreeMap<(ShaderStage, u32, u32), BufferAddress>, String> {
argument_buffers::synthetic_addresses(case.argument_buffer_buffers().map(|(key, _)| key))
}
/// The `BindShape` the render executor binds `case` with on a device that has device addresses
/// exactly when `addressed` and the range limits `ranges` ([`bind_state`] with every buffer's and
/// argument-buffer buffer's synthetic guest address and, when `addressed`, a host address; only
/// whether a buffer has one is part of the shape): the shape the census's artifact digest plans the
/// draw's pipeline for.
pub fn render_shape(
case: &RenderCase,
addressed: bool,
ranges: BufferRanges,
) -> Result<BindShape, String> {
let with_host = |mut address: BufferAddress| {
address.host = addressed.then_some(address.guest);
address
};
let addresses = case
.stages()
.flat_map(|(stage, f)| f.resources.buffers.keys().map(move |&index| (stage, index)))
.chain(
case.vertex_buffers
.iter()
.map(|buffer| (ShaderStage::Vertex, buffer.buffer_index)),
)
.map(|(stage, index)| ((stage, index), with_host(synthetic_address(stage, index))))
.collect();
let embedded = synthetic_used_addresses(case)?
.into_iter()
.map(|(key, address)| (key, with_host(address)))
.collect();
Ok(bind_state(case, &addresses, &embedded, ranges)?.shape())
}
/// The final contents of a render run, by stage and Metal index (color targets by index).
#[derive(Debug, Default)]
pub struct RenderFinals {
File diff suppressed because it is too large. Load diff
@@ -13,18 +13,16 @@
//!
//! The compile worker compiles its pipeline device-free as the runtime compiles it
//! ([`mesh_request`]): the oracle's descriptor ([`MeshTemplate`]) of its functions, each from the
//! case's library or its companion's (`Device::compile_mesh_pipeline`); the artifact of the
//! compile digests its plan for the bind shape of its own stage's resources ([`mesh_shape`]).
//! case's library or its companion's (`Device::compile_mesh_pipeline`).
use super::graphics::{self, ColorTarget, RenderFunction, RenderOutput, StageResources};
use super::{function_constants, lengths_classed, require_case_families, resources, BufferAddress};
use super::{function_constants, require_case_families, resources};
use crate::acceptance::{MeshFunction, PipelineRequest, RequestFunction};
use crate::case::{AuthoredCase, MeshGrid, OutputSelection, Stage};
use crate::check::admission::{ExecutorError, NotSupported};
use crate::companion::Companion;
use crate::engine::RowSource;
use crate::literal::LiteralResources;
use metal2vulkan::bind::{BindShape, BindState, BoundBuffer, BufferRanges};
use metal2vulkan::error::{DescriptorError, Error, MetalAnswer};
use metal2vulkan::library::FunctionConstantValues;
use metal2vulkan::pipeline::Stage as ShaderStage;
@@ -238,49 +236,6 @@ impl MeshTemplate {
}
}
/// The `BindShape` the runtime binds `mesh`'s draw with on a device that has device addresses
/// exactly when `addressed` and the range limits `ranges`: its own stage's buffers at their
/// synthetic guest addresses (and, when `addressed`, a host address), textures and samplers
/// ([`graphics::stage_table`]); a partner binds none; classing lengths under `ranges`
/// ([`lengths_classed`]), so its plan is the runtime's
/// of the same binds. What the compile's artifact plans the draw's pipeline for
/// (`artifact::CaseArtifact::record`).
/// A case whose own function takes an argument buffer is not built here (`NotImplemented`).
pub fn mesh_shape(
mesh: &MeshCase,
addressed: bool,
ranges: BufferRanges,
) -> Result<BindShape, ExecutorError> {
let mut state = BindState::default();
for (stage, function) in mesh.stages() {
let resources = &function.resources;
if !(resources.argument_buffer_buffers.is_empty()
&& resources.argument_buffer_textures.is_empty()
&& resources.argument_buffer_samplers.is_empty())
{
return Err(NotSupported::NotImplemented(
"engine candidate: a device-free compile of a mesh draw whose function takes an \
argument buffer"
.into(),
)
.into());
}
let bound = |index: u32, length: u64| {
let address: BufferAddress = graphics::synthetic_address(stage, index);
BoundBuffer::Buffer {
length,
offset: 0,
gpu_address: address.guest,
device_address: addressed.then_some(address.guest),
attribute_stride: None,
}
};
let table = graphics::stage_table(function, bound).map_err(ExecutorError::Failed)?;
state.stages.insert(stage, table);
}
Ok(lengths_classed(state, ranges).shape())
}
/// The compile request for `mesh`'s pipeline, and its libraries in
/// `PipelineRequest::libraries` order: `library`, the case's, then `companion`, its generated
/// stages' source, where a stage is generated (`MeshCase::generated`). No function links any.
@@ -1,521 +0,0 @@
//! The committed public kernel cases with textures or samplers through the engine's
//! device-free half: each is mapped, compiled for committed profiles with the inputs its bind state
//! decides (`variants`), and planned by the binder, or refused typed. No device is opened.
use super::*;
use crate::source::public_sources;
use metal2vulkan::bind::{ImageSource, WriteSource};
use metal2vulkan::device::FormatUsage;
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::error::{BindError, Capability, Feature, Needs, Unsupported};
use metal2vulkan::library::Library;
use metal2vulkan::metal::format::vk_format;
use metal2vulkan::pipeline::FunctionDescriptor;
use metal2vulkan::Budget;
use metal2vulkan_devtools::{llvm_assemble, AssembleError};
use std::collections::{BTreeMap, BTreeSet};
pub(super) fn device(stem: &str) -> Device {
let path = crate::engine::profiles_dir().join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).unwrap();
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
Device::from_queries(description, DevicePolicy::RESIDENT_TABLES).unwrap()
}
/// The committed cases whose AIR is a public fixture, with that fixture's source row.
fn public_cases() -> Vec<(AuthoredCase, crate::source::SourceRow)> {
let root = metal2vulkan_devtools::validation_dir().join("corpus");
let store = CorpusStore::new(&root);
let sources = public_sources().unwrap();
let mut out = Vec::new();
for shard in 0..64 {
for case in store.read_case_shard(shard).unwrap() {
// The row of the case's module and entry.
if let Some(row) = sources
.iter()
.find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry)
{
out.push((case, row.clone()));
}
}
}
out
}
/// How one case ended in the device-free half.
enum Planned {
/// Refused typed before a device was involved (the mapping or the product's compile).
Refused,
/// No `llvm-as` is installed (the only reason the test skips).
NoAssembler(String),
/// The installed `llvm-as` rejected the fixture's text (an older LLVM than the one it was
/// written for): that one case is skipped, with a printed line.
Unassembled(String),
/// Planned: the families of its descriptor writes, and "pipeline variant" when its plan
/// needed one.
Writes(BTreeSet<&'static str>),
}
/// Whether every alternative of `sets` needs some format's support, and `device`'s profile
/// cannot use one of the formats `case` binds a texture in as `sets` names (or sample it).
fn lacks_a_bound_format(device: &Device, case: &AuthoredCase, sets: &[Vec<Capability>]) -> bool {
// The usages the refusal names (linear filtering, say), and sampling itself.
let usages: BTreeSet<FormatUsage> = sets
.iter()
.flatten()
.filter_map(|capability| match capability {
Capability::Format { usage, .. } => Some(*usage),
_ => None,
})
.chain([FormatUsage::SampledImage])
.collect();
sets.iter().all(|set| {
set.iter()
.any(|capability| matches!(capability, Capability::Format { .. }))
}) && case.textures.iter().any(|texture| {
usages.iter().any(|&usage| {
vk_format(
resources::pixel_format(texture.format),
&BTreeSet::from([usage]),
device.profile(),
)
.is_err()
})
})
}
fn plan_case(device: &Device, case: &AuthoredCase, row: &crate::source::SourceRow) -> Planned {
let scratch = crate::ScratchDir::new("public-texture-case").unwrap();
let ll = scratch.path().join("case.ll");
std::fs::write(&ll, &row.air_ll).unwrap();
let bitcode = match llvm_assemble(&ll) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => return Planned::NoAssembler(why),
Err(AssembleError::Rejected(why)) => return Planned::Unassembled(why),
};
let Ok(compute) = compute_case(case) else {
return Planned::Refused;
};
let library = Library::from_air(&bitcode).unwrap();
let mut function = FunctionDescriptor::new(library.function(&compute.entry).unwrap());
function.constants = compute.constants.clone();
let shape = compute_shape(&compute, true, BufferRanges::default()).unwrap();
let (pipeline, inputs) = match variants::bound::compile_compute_for_shape(
device,
&function,
&shape,
Some(&compute.dispatch),
&Budget::standard(),
) {
Ok(compiled) => compiled,
Err(error) if !Outcome::from(&error).is_defect() => return Planned::Refused,
Err(error) => panic!("{}: compile: {error:?}", case.name),
};
let addresses = compute
.buffers
.keys()
.map(|&index| {
let address = 0x1000_0000 * u64::from(index + 1);
(
index,
BufferAddress {
guest: address,
host: Some(address),
},
)
})
.collect();
let embedded = compute
.argument_buffer_buffers
.keys()
.enumerate()
.map(|(token, &key)| {
let address = 0x8000_0000_0000 + 0x1000_0000 * token as u64;
(
key,
BufferAddress {
guest: address,
host: Some(address),
},
)
})
.collect();
let state = bind_state(&compute, &addresses, &embedded, BufferRanges::default()).unwrap();
// The executor's shape is the one it compiles for.
assert_eq!(state.shape(), shape, "{}", case.name);
let plan = match pipeline.plan(device, &state.shape()) {
Ok(plan) => plan,
// A sparse texture whose residency the function observes plans only where the device
// states shader residency: elsewhere the binder refuses it typed, as the executor reports
// it.
Err(BindError::Unsupported(Unsupported {
feature: Feature::SparseTexture { slot },
..
})) if case
.textures
.iter()
.any(|texture| texture.sparse.is_some() && texture.binding == slot.index) =>
{
return Planned::Refused;
}
// A texture of a format the profile cannot sample, or filter as the case's sampler
// does, is refused typed as the device's gap (`Feature::Format`, needing that format's
// support): the case's literal binds it, and no
// other mapping of the case changes it (the sRGB and packed formats).
Err(BindError::Unsupported(Unsupported {
feature: Feature::Format,
needs: Needs::AnyOf(sets),
..
})) if lacks_a_bound_format(device, case, &sets) => {
return Planned::Refused;
}
Err(error) => panic!("{}: plan: {error}", case.name),
};
// The dispatch plans the variant its pipeline was compiled for; the executor refuses
// diagnostics, and no public case has one.
assert!(
variants::bound::compiled_for(&inputs, &plan.variant),
"{}: planned variant {:?}, compiled {inputs:?}",
case.name,
plan.variant
);
assert!(
plan.diagnostics.is_empty(),
"{}: {:?}",
case.name,
plan.diagnostics
);
// A plan that needed a variant counts as its own family, so the lowering-input path is
// known to run.
let variant = (!plan.variant.is_empty()).then_some("pipeline variant");
Planned::Writes(
plan.descriptors
.iter()
.map(|write| match &write.source {
WriteSource::Texture { .. }
if write.ty == metal2vulkan::vk::DescriptorType::STORAGE_IMAGE =>
{
"storage texture"
}
WriteSource::Texture { .. } => "texture",
WriteSource::CombinedImageSampler { .. } => "combined image sampler",
WriteSource::Sampler { .. } => "sampler",
WriteSource::Neutral(_) => "neutral",
_ => "buffer-like",
})
.chain(variant)
.collect(),
)
}
/// Every public kernel case with textures or samplers that maps and compiles for its bind state
/// plans the variant it was compiled for and no plan diagnostic (which the executor refuses), and
/// together they write a sampled texture, a storage texture and a sampler. On a profile that needs
/// storage formats as inputs, some of them plan a variant. At least one case plans on every
/// profile; the test skips only when no
/// `llvm-as` is installed, and a case whose fixture the installed `llvm-as` rejects is skipped
/// alone, with a printed line.
#[test]
fn public_texture_cases_plan_their_compiled_variant_without_diagnostics() {
let cases = public_cases();
for stem in ["lavapipe", "moltenvk-m3", "runtime-floor"] {
let device = device(stem);
let mut families = BTreeSet::new();
let mut planned = 0;
for (case, row) in &cases {
if case.stage != Stage::Kernel || (case.textures.is_empty() && case.samplers.is_empty())
{
continue;
}
match plan_case(&device, case, row) {
Planned::Refused => {}
Planned::Unassembled(why) => {
eprintln!("SKIPPED {}: llvm-as rejected its fixture: {why}", case.name);
}
Planned::NoAssembler(why) => {
eprintln!("SKIPPED: {why}");
return;
}
Planned::Writes(writes) => {
planned += 1;
families.extend(writes);
}
}
}
// Refusing every case would pass the checks below vacuously.
assert!(planned > 0, "{stem}: no public texture case planned");
for family in ["texture", "storage texture"] {
assert!(families.contains(family), "{stem}: no {family} write");
}
assert!(
families.contains("sampler") || families.contains("combined image sampler"),
"{stem}: no sampler write"
);
// The runtime floor reads storage images only with a format: its storage cases compile
// with an input and plan that variant.
if stem == "runtime-floor" {
assert!(families.contains("pipeline variant"), "{stem}: no variant");
}
}
}
/// Every public kernel case over texture arrays maps each element to the texture at its slot
/// and, compiled for its bind state, plans a texture write of exactly the element slots its
/// function reads, with no neutral and no diagnostic: the product reads an element through its
/// slot's own binding, which the executor binds as the Metal oracle does. The elements each case's
/// function reads, as positions in the element slots of its arrays in binding order, are stated per
/// entry, so a new such case must say which:
/// - `texture_array_width` (`array<texture2d<float>, 2> [[texture(0)]]`) reads `textures[1]`;
/// - `a4_texture_array_dynamic` (`array<texture2d<float>, 4> [[texture(0)]]`) reads
/// `ts[gid & 3]`, every element;
/// - `ob3_texture_array` (two `array<texture2d<uint>, 2>` at `[[texture(0)]]` and
/// `[[texture(2)]]`) reads `tex[idx[t]]`, clamped onto both of its elements, and `spare[t & 1]`,
/// every element of both;
/// - `smp_runtime_array` (`array<texture2d<float>, 32> [[texture(0)]]`) samples `t[gid & 31]`,
/// every element, each through a combined image sampler or, on `moltenvk-m3`, whose 16
/// samplers per stage the 32 pairs exceed, a separate texture. A sampled element's texture is the
/// image of its combined write, or its separate texture's write.
#[test]
fn public_texture_array_cases_plan_their_elements_at_their_slots() {
const EVERY_32: [u32; 32] = {
let mut every = [0; 32];
let mut i = 0;
while i < 32 {
every[i] = i as u32;
i += 1;
}
every
};
let read_elements = |entry: &str| -> Option<&'static [u32]> {
match entry {
"texture_array_width" => Some(&[1]),
"a4_texture_array_dynamic" | "ob3_texture_array" => Some(&[0, 1, 2, 3]),
"smp_runtime_array" => Some(&EVERY_32),
_ => None,
}
};
let cases = public_cases();
let arrays = cases
.iter()
.filter(|(case, _)| case.stage == Stage::Kernel && !case.texture_arrays.is_empty())
.collect::<Vec<_>>();
assert!(
arrays.len() >= 2,
"the public kernel cases with a texture array"
);
for (case, row) in arrays {
let read = read_elements(&case.entry).unwrap_or_else(|| {
panic!(
"{}: state which texture-array elements {} reads",
case.name, case.entry
)
});
let scratch = crate::ScratchDir::new("public-texture-array-case").unwrap();
let ll = scratch.path().join("case.ll");
std::fs::write(&ll, &row.air_ll).unwrap();
let bitcode = match llvm_assemble(&ll) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => {
panic!("{}: llvm-as rejected it: {why}", case.name)
}
};
let compute = compute_case(case).unwrap();
let slots = case
.texture_arrays
.iter()
.flat_map(|array| {
(0..array.elements.len() as u32).map(move |element| array.binding + element)
})
.collect::<Vec<_>>();
assert_eq!(
compute.textures.keys().copied().collect::<Vec<_>>(),
slots,
"{}",
case.name
);
let library = Library::from_air(&bitcode).unwrap();
let mut function = FunctionDescriptor::new(library.function(&compute.entry).unwrap());
function.constants = compute.constants.clone();
for stem in ["lavapipe", "moltenvk-m3", "runtime-floor"] {
let device = device(stem);
let shape = compute_shape(&compute, true, BufferRanges::default()).unwrap();
let compiled = variants::bound::compile_compute_for_shape(
&device,
&function,
&shape,
None,
&Budget::standard(),
);
let sampled = device
.profile()
.limits()
.max_per_stage_descriptor_sampled_images;
let (pipeline, inputs) = match compiled {
// More elements than the stage's sampled images (the runtime floor's 16): refused
// typed, naming the limit.
Err(error) if slots.len() > sampled as usize => {
let text = format!("{error:?}");
assert!(
text.contains("MaxPerStageDescriptorSampledImages"),
"{} {stem}: {text}",
case.name
);
continue;
}
compiled => compiled
.unwrap_or_else(|error| panic!("{} {stem}: compile: {error:?}", case.name)),
};
let plan = pipeline.plan(&device, &shape).unwrap();
assert!(
variants::bound::compiled_for(&inputs, &plan.variant),
"{} {stem}",
case.name
);
assert!(
plan.diagnostics.is_empty(),
"{} {stem}: {:?}",
case.name,
plan.diagnostics
);
let textures = plan
.descriptors
.iter()
.filter_map(|write| match &write.source {
WriteSource::Texture { slot, .. }
| WriteSource::CombinedImageSampler {
image: ImageSource::Texture { slot, .. },
..
} => Some(slot.index),
WriteSource::Neutral(neutral)
| WriteSource::CombinedImageSampler {
image: ImageSource::Neutral(neutral),
..
} => {
panic!("{} {stem}: a neutral {neutral:?}", case.name)
}
_ => None,
})
.collect::<Vec<_>>();
let expected = read
.iter()
.map(|&element| slots[element as usize])
.collect::<Vec<_>>();
assert_eq!(textures, expected, "{} {stem}", case.name);
}
}
}
/// Each public kernel case whose root argument points to further nodes (argument-buffer buffers)
/// maps, compiles for its bind state, and plans on devices with device addresses; its dispatch's
/// root table holds each pointee's resident entry (host and guest address), which is what a loaded
/// pointer is translated through. The case is the one-member case: the rate-map case whose maps are
/// members is the runtime's limit (`ToolingRequirement::RasterizationRateMap`).
#[test]
fn the_public_argument_buffer_cases_plan_their_pointees_resident() {
let cases = public_cases();
let selected = cases
.iter()
.filter(|(case, _)| {
case.stage == Stage::Kernel
&& !case.argument_buffer_buffers.is_empty()
&& crate::executor_contract::case_requirements(case).is_empty()
})
.collect::<Vec<_>>();
assert!(
!selected.is_empty(),
"the public kernel cases with argument-buffer buffers"
);
for (case, row) in selected {
let scratch = crate::ScratchDir::new("public-argument-buffer-case").unwrap();
let ll = scratch.path().join("case.ll");
std::fs::write(&ll, &row.air_ll).unwrap();
let bitcode = match llvm_assemble(&ll) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => {
panic!("{}: llvm-as rejected it: {why}", case.name)
}
};
let compute = compute_case(case).unwrap();
assert_eq!(
compute.argument_buffer_buffers.len(),
case.argument_buffer_buffers.len(),
"{}",
case.name
);
let library = Library::from_air(&bitcode).unwrap();
let mut function = FunctionDescriptor::new(library.function(&compute.entry).unwrap());
function.constants = compute.constants.clone();
let address = |guest: u64| BufferAddress {
guest,
host: Some(guest + 0x10_0000_0000),
};
let addresses = compute
.buffers
.keys()
.map(|&index| (index, address(0x1000_0000 * u64::from(index + 1))))
.collect();
// Each member's pointee at its own address.
let embedded = compute
.argument_buffer_buffers
.keys()
.zip(0u64..)
.map(|(&key, ordinal)| (key, address(0x7000_0000 + 0x100_0000 * ordinal)))
.collect::<BTreeMap<_, _>>();
let state = bind_state(&compute, &addresses, &embedded, BufferRanges::default()).unwrap();
for stem in ["lavapipe", "moltenvk-m3"] {
let device = device(stem);
let shape = compute_shape(&compute, true, BufferRanges::default()).unwrap();
assert_eq!(state.shape(), shape);
let (pipeline, inputs) = variants::bound::compile_compute_for_shape(
&device,
&function,
&shape,
Some(&compute.dispatch),
&Budget::standard(),
)
.unwrap_or_else(|error| panic!("{} {stem}: compile: {error:?}", case.name));
let plan = pipeline.plan(&device, &shape).unwrap();
assert!(
variants::bound::compiled_for(&inputs, &plan.variant),
"{stem}"
);
assert!(
plan.diagnostics.is_empty(),
"{} {stem}: {:?}",
case.name,
plan.diagnostics
);
let commands = plan
.instantiate_dispatch(&state, &compute.dispatch)
.unwrap();
let table = commands
.root_table
.expect("a loaded pointer reads the root table");
// A root-table entry is 32 bytes: host, guest, size, and bind offset.
let word =
|entry: &[u8], at: usize| u64::from_le_bytes(entry[at..at + 8].try_into().unwrap());
let entries: Vec<[u64; 2]> = table
.bytes
.as_chunks::<32>()
.0
.iter()
.map(|entry| [word(entry, 0), word(entry, 8)])
.collect();
for (key, pointee) in &embedded {
assert!(
entries.contains(&[pointee.host.unwrap(), pointee.guest]),
"{} {stem}: the pointee of {key:?} is not resident",
case.name
);
}
}
}
}
@@ -1,4 +1,4 @@
//! Textures and samplers of an engine case in the binder's terms.
//! Textures and samplers of an engine case as the Metal oracle creates them.
//!
//! The executor binds exactly what the Metal oracle binds: each authored texture is a Metal
//! texture of the same type, pixel format, extent, and sample count (one mip level), a texture
@@ -7,15 +7,15 @@
//! address, filter, and coordinate modes. Element `k` of a texture array at `[[texture(n)]]` is
//! the texture bound at slot `n + k` ([`bound_textures`]): the Metal oracle binds it there, and the
//! product reads that element through that slot's own binding (a handle-array element is the slot
//! `n + k`, `memory::handles`), so the binder needs no descriptor array. Everything here is
//! device-free; the Vulkan objects are `platform::plan_resources`.
//! `n + k`, `memory::handles`). Everything here is device-free; a run through the runtime makes
//! the objects (`platform::runtime_textures`).
use crate::case::{
ArgumentBufferSamplerResource, SamplerAddressMode, SamplerCompareFunction, SamplerFilter,
SamplerMipFilter, SamplerResource, TextureFormat, TextureType,
};
use crate::literal::{LiteralTexture, LiteralTextureArray};
use metal2vulkan::bind::{BoundSampler, BoundTexture, SamplerDescriptor, TextureFacts};
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::metal::{self, PixelFormat};
use std::collections::{BTreeMap, BTreeSet};
@@ -136,72 +136,6 @@ pub fn bound_textures(
Ok(bound)
}
/// The bytes a texture buffer's view covers: its width in texels (the Metal oracle's
/// `newTextureWithDescriptor:offset:bytesPerRow:` view of the authored bytes at offset 0).
pub fn texel_buffer_length(texture: &LiteralTexture) -> Result<u64, String> {
let length = u64::from(texture.dimensions[0])
.checked_mul(texture.format.bytes_per_pixel() as u64)
.ok_or_else(|| format!("texture buffer {} length overflows", texture.binding))?;
if length == 0 || length > texture.bytes.len() as u64 {
return Err(format!(
"texture buffer {} is {length} bytes wide but authors {} bytes",
texture.binding,
texture.bytes.len()
));
}
Ok(length)
}
/// What the binder sees bound for an authored texture: a texture buffer's view (offset 0, its
/// width in texels), or an image texture's facts ([`texture_facts`]).
pub fn bound_texture(texture: &LiteralTexture) -> Result<BoundTexture, String> {
if texture.texture_type == TextureType::Buffer {
let length = texel_buffer_length(texture)?;
return Ok(BoundTexture::Buffer {
pixel_format: pixel_format(texture.format),
offset: 0,
length,
bytes_per_row: length,
resource_id: None,
swizzle: metal2vulkan::metal::TextureSwizzleChannels::DEFAULT,
parts: 1,
});
}
Ok(BoundTexture::Texture {
facts: texture_facts(texture)?,
resource_id: None,
})
}
/// The facts of an authored texture, as the binder sees an image texture bound and a used
/// resource (`useResource`) names any texture: its type, its pixel format, and shader read and
/// write usage; an image texture's sample count, Metal's `arrayLength` (which counts cubes for a
/// cube array), its levels, and `isSparse` for a sparse texture. A texture buffer is one sample,
/// level and slice of Metal's `TextureBuffer` type, its width checked ([`texel_buffer_length`]).
pub fn texture_facts(texture: &LiteralTexture) -> Result<TextureFacts, String> {
let mut facts = TextureFacts::new(
self::texture_type(texture.texture_type),
pixel_format(texture.format),
);
facts.usage = metal::TextureUsage::SHADER_READ | metal::TextureUsage::SHADER_WRITE;
if texture.texture_type == TextureType::Buffer {
texel_buffer_length(texture)?;
return Ok(facts);
}
let layout = texture.layout()?;
facts.sample_count = layout.sample_count;
facts.array_length = match texture.texture_type {
TextureType::D1Array | TextureType::D2Array | TextureType::D2MultisampleArray => {
layout.array_layers
}
TextureType::CubeArray => layout.array_layers / 6,
_ => 1,
};
facts.sparse = texture.sparse.is_some();
facts.mipmap_level_count = texture.mip_levels;
Ok(facts)
}
/// The `MTLSamplerDescriptor` the Metal oracle creates for `sampler`: the defaults, with the
/// authored address mode on every axis, the filters, and the coordinate mode.
pub fn sampler_descriptor(sampler: &SamplerResource) -> SamplerDescriptor {
@@ -255,11 +189,6 @@ pub fn argument_sampler_descriptor(sampler: &ArgumentBufferSamplerResource) -> S
desc
}
/// The bound sampler of an authored sampler.
pub fn bound_sampler(sampler: &SamplerResource) -> BoundSampler {
BoundSampler::new(sampler_descriptor(sampler))
}
/// The observed bytes of a texture output: the `(origin, dimensions)` selection, in the case's
/// spelling, of `texture` whose `bytes` are its final contents packed like the authored literal
/// (slice-major rows). A multisampled texture has no such packing on either executor.
@@ -326,30 +255,6 @@ mod tests {
}
}
#[test]
fn authored_textures_bind_what_the_metal_oracle_creates() {
match bound_texture(&texture(TextureType::CubeArray, [2, 2, 12], vec![0; 48])).unwrap() {
BoundTexture::Texture { facts, .. } => {
assert_eq!(facts.texture_type, metal::TextureType::CubeArray);
assert_eq!(facts.pixel_format, PixelFormat::R8Unorm);
assert_eq!((facts.array_length, facts.sample_count), (2, 1));
assert_eq!(facts.mipmap_level_count, 1);
}
other => panic!("{other:?}"),
}
match bound_texture(&texture(TextureType::D1Array, [4, 3, 1], vec![0; 12])).unwrap() {
BoundTexture::Texture { facts, .. } => assert_eq!(facts.array_length, 3),
other => panic!("{other:?}"),
}
// A texture buffer's view is its width, not every authored byte.
match bound_texture(&texture(TextureType::Buffer, [5, 1, 1], vec![0; 8])).unwrap() {
BoundTexture::Buffer { offset, length, .. } => assert_eq!((offset, length), (0, 5)),
other => panic!("{other:?}"),
}
assert!(bound_texture(&texture(TextureType::Buffer, [9, 1, 1], vec![0; 8])).is_err());
assert!(bound_texture(&texture(TextureType::Cube, [2, 3, 6], vec![0; 36])).is_err());
}
#[test]
fn samplers_are_metals_defaults_with_the_authored_modes() {
let desc = sampler_descriptor(&SamplerResource {
@@ -1,19 +1,12 @@
//! Device-free tests of the engine candidate: the status and output rules, the case mapping,
//! and the binder accepting the executor's bind state for a looping kernel that reaches no status
//! buffer. No device is opened.
//! Device-free tests of the engine candidate: the status and output rules and the case mapping.
//! No device is opened.
use super::*;
use crate::case::ScalarType;
use crate::check::admission::NotSupported;
use crate::requirement::ToolingRequirement;
use metal2vulkan::bind::{PushHole, ResourceClass, WriteSource};
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::library::Library;
use metal2vulkan::metal::{DataType, ResourceUsage};
use metal2vulkan::pipeline::{
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource,
};
use metal2vulkan::Budget;
use metal2vulkan::metal::DataType;
use metal2vulkan_devtools::{llvm_assemble, AssembleError};
mod argument_buffer_members;
@@ -64,20 +57,6 @@ fn device(stem: &str, policy: DevicePolicy) -> Device {
Device::from_queries(description, policy).unwrap()
}
fn compile(device: &Device, bitcode: &[u8], entry: &str) -> ComputePipeline {
let function = Library::from_air(bitcode)
.and_then(|library| library.function(entry))
.unwrap();
device
.compile_compute_pipeline(
&ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(
function,
))),
&Budget::standard(),
)
.unwrap()
}
/// A difference under notes is a noted difference unless the C3 reviewed list holds its case under
/// an answer gap the case's structure meets: then it stays a mismatch naming the gap. Judged over
/// the committed list's every answer gap over a public fixture and its committed case, and a
@@ -136,7 +115,7 @@ fn kernel_case() -> AuthoredCase {
}
#[test]
fn the_case_maps_onto_the_binder_or_names_the_gap() {
fn the_case_maps_or_names_the_gap() {
let mut case = kernel_case();
case.threadgroup_memory
.push(crate::case::ThreadgroupMemoryResource {
@@ -161,38 +140,6 @@ fn the_case_maps_onto_the_binder_or_names_the_gap() {
case.fuel = Some(9);
assert_eq!(map_kernel(&case).unwrap(), mapped);
let state = bind_state(
&mapped,
&BTreeMap::from([(
0,
BufferAddress {
guest: 0x1000,
host: Some(0x1000),
},
)]),
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
assert!(state.used_resources.is_empty());
let table = &state.stages[&ShaderStage::Kernel];
assert_eq!(table.threadgroup_lengths, mapped.threadgroup_lengths);
for (index, bytes) in &mapped.buffers {
let expected_host = (*index == 0).then_some(0x1000);
match table.buffers[index] {
BoundBuffer::Buffer {
length,
offset,
device_address,
..
} => {
assert_eq!((length, offset), (bytes.len() as u64, 0));
assert_eq!(device_address, expected_host);
}
other => panic!("{other:?}"),
}
}
// An explicit imageblock is the runtime's limit.
let mut imageblock = kernel_case();
imageblock.imageblock = Some(crate::case::ImageblockResource {
@@ -604,12 +551,12 @@ fn b64(bytes: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(bytes)
}
/// Device buffer array elements bind at consecutive Metal slots (the oracle's and the buffer
/// table's `first + k`); an argument-buffer buffer is a used resource whose guest address the
/// owner holds at its field, the owner covering that field; each maps its output, and a
/// collision, an owner that is not bound, or an element slot that overflows is a gap.
/// Device buffer array elements bind at consecutive Metal slots (the oracle's `first + k`); an
/// argument-buffer buffer's guest address is held by its owner at its field, the owner covering
/// that field; each maps its output, and a collision, an owner that is not bound, or an element
/// slot that overflows is a gap.
#[test]
fn arrays_and_argument_buffers_map_onto_the_binder() {
fn arrays_and_argument_buffers_map() {
use crate::case::{
ArgumentBufferBufferResource, DeviceBufferArrayElementResource, DeviceBufferArrayResource,
ResourceRole,
@@ -660,66 +607,8 @@ fn arrays_and_argument_buffers_map_onto_the_binder() {
}
);
let host = |guest| BufferAddress {
guest,
host: Some(guest),
};
let addresses = mapped
.buffers
.keys()
.map(|&index| (index, host(0x1000 * u64::from(index + 1))))
.collect();
let embedded = BTreeMap::from([((0, 8), host(0xdead_0000))]);
let state = bind_state(&mapped, &addresses, &embedded, BufferRanges::default()).unwrap();
assert_eq!(
state.stages[&ShaderStage::Kernel]
.buffers
.keys()
.copied()
.collect::<Vec<_>>(),
[0, 4, 5]
);
let [used] = state.used_resources.as_slice() else {
panic!("{:?}", state.used_resources);
};
assert_eq!(used.class, ResourceClass::Buffer);
assert_eq!(used.token, 0);
assert_eq!(
(used.gpu_address, used.device_address, used.length),
(Some(0xdead_0000), Some(0xdead_0000), 12)
);
assert_eq!(used.usage, ResourceUsage::READ | ResourceUsage::WRITE);
// The executor's shape is the one it compiles for, with and without device addresses.
for addressed in [false, true] {
let shape = compute_shape(&mapped, addressed, BufferRanges::default()).unwrap();
assert_eq!(shape.used.len(), 1);
let addresses = mapped
.buffers
.keys()
.map(|&index| {
let mut address = BufferAddress::synthetic(index);
address.host = addressed.then_some(0x9000);
(index, address)
})
.collect();
let mut used = BufferAddress::synthetic_used(0);
used.host = addressed.then_some(0xa000);
let embedded = BTreeMap::from([((0, 8), used)]);
assert_eq!(
bind_state(&mapped, &addresses, &embedded, BufferRanges::default())
.unwrap()
.shape(),
shape
);
}
assert_ne!(
BufferAddress::synthetic_used(0).guest,
BufferAddress::synthetic(0).guest
);
// The owner is created holding the pointer, little endian, at its field.
let fields =
argument_buffers::field_words(&embedded, &BTreeMap::new(), &BTreeMap::new()).unwrap();
let fields = BTreeMap::from([((0, 8), 0xdead_0000)]);
let owner_bytes = |index| argument_buffers::owner_bytes(&mapped.buffers, index, &fields);
let owner = owner_bytes(0).unwrap();
assert_eq!(&owner[..4], &[0xab; 4]);
@@ -786,8 +675,7 @@ fn texture_array(
/// Element `k` of a texture array at `[[texture(n)]]` is the texture bound at slot `n + k`, as
/// the Metal oracle binds it and the product reads it: the case maps each element there beside its
/// textures, its bind state binds each as a texture of the array's type and format, and an element
/// output is that texture's region. Element 0 of an array that overrides the texture at its base
/// textures, and an element output is that texture's region. Element 0 of an array that overrides the texture at its base
/// slot replaces it (Metal binds arrays last); any other collision and a slot that overflows are
/// gaps.
#[test]
@@ -838,24 +726,6 @@ fn texture_arrays_bind_each_element_at_its_slot() {
dimensions: [1, 1, 1],
}
);
let state = bind_state(
&mapped,
&BTreeMap::new(),
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
let table = &state.stages[&ShaderStage::Kernel];
assert_eq!(
table.textures.keys().copied().collect::<Vec<_>>(),
[0, 2, 3, 4]
);
for slot in [2, 3, 4] {
assert_eq!(
table.textures[&slot],
resources::bound_texture(&mapped.textures[&slot]).unwrap()
);
}
// The final element texture is the observation.
let mut finals = mapped.textures.clone();
finals.get_mut(&3).unwrap().bytes = 99u32.to_le_bytes().to_vec();
@@ -935,154 +805,6 @@ entry:\n\
)
}
/// A case with a device buffer array maps its elements onto consecutive slots, and the binder
/// plans and instantiates the executor's state for a buffer-table kernel compiled for that
/// shape, with and without device addresses, with no diagnostic.
#[test]
fn a_device_buffer_array_plans_as_the_functions_buffer_table() {
use crate::case::{DeviceBufferArrayElementResource, DeviceBufferArrayResource, ResourceRole};
let Some(bitcode) = assemble(&buffer_table_kernel()) else {
return;
};
let mut case = kernel_case();
case.entry = "table".into();
case.buffers[0].initial_bytes_b64 = Some(b64(&[0; 8]));
case.device_buffer_arrays.push(DeviceBufferArrayResource {
binding: 1,
length: 2,
elements: (0..2)
.map(|index| DeviceBufferArrayElementResource {
index,
role: ResourceRole::Input,
bytes_b64: Some(b64(&[index as u8 + 1; 8])),
initial_bytes_b64: None,
})
.collect(),
});
let compute = map_kernel(&case).unwrap();
assert_eq!(
compute.buffers.keys().copied().collect::<Vec<_>>(),
[0, 1, 2]
);
let library = Library::from_air(&bitcode).unwrap();
let function = FunctionDescriptor::new(library.function("table").unwrap());
for (stem, addressed) in [
("lavapipe", true),
("moltenvk-m3", true),
("runtime-floor", false),
] {
let device = device(stem, DevicePolicy::RESIDENT_TABLES);
let shape = compute_shape(&compute, addressed, BufferRanges::default()).unwrap();
let (pipeline, inputs) = variants::bound::compile_compute_for_shape(
&device,
&function,
&shape,
Some(&compute.dispatch),
&Budget::standard(),
)
.unwrap_or_else(|error| panic!("{stem}: compile: {error:?}"));
let plan = pipeline.plan(&device, &shape).unwrap();
assert!(
variants::bound::compiled_for(&inputs, &plan.variant),
"{stem}"
);
assert!(
plan.diagnostics.is_empty(),
"{stem}: {:?}",
plan.diagnostics
);
let addresses = compute
.buffers
.keys()
.map(|&index| {
let mut address = BufferAddress::synthetic(index);
address.host = addressed.then_some(address.guest);
(index, address)
})
.collect();
let state = bind_state(
&compute,
&addresses,
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
assert_eq!(state.shape(), shape, "{stem}");
let commands = plan
.instantiate_dispatch(&state, &compute.dispatch)
.unwrap_or_else(|error| panic!("{stem}: instantiate: {error}"));
assert!(!commands.regions.is_empty(), "{stem}");
}
}
/// The binder accepts the executor's bind state for a compiled looping kernel, with and without
/// device addresses, and plans every buffer write the executor handles; the loop reaches no
/// status buffer.
#[test]
fn the_binder_plans_the_executors_state() {
let Some(bitcode) = assemble(&counting_kernel()) else {
return;
};
let case = ComputeCase {
out_of_bounds: Vec::new(),
creation_bound: crate::budgets::PIPELINE_CREATION_CEILING,
entry: "count".into(),
constants: FunctionConstantValues::defaults(),
buffers: BTreeMap::from([(0, vec![0; 4])]),
argument_buffer_buffers: BTreeMap::new(),
argument_buffer_textures: BTreeMap::new(),
argument_buffer_samplers: BTreeMap::new(),
textures: BTreeMap::new(),
samplers: BTreeMap::new(),
threadgroup_lengths: BTreeMap::new(),
dispatch: Dispatch::Threads {
threads: [5, 1, 1],
threads_per_group: [2, 1, 1],
},
output: ComputeOutput::Buffer {
binding: 0,
offset: 0,
length: 4,
},
};
for stem in ["lavapipe", "moltenvk-m3", "runtime-floor"] {
let device = device(stem, DevicePolicy::RESIDENT_TABLES);
let pipeline = compile(&device, &bitcode, "count");
for address in [
BufferAddress::synthetic(0),
BufferAddress {
guest: 0x10_0000,
host: Some(0x10_0000),
},
] {
let state = bind_state(
&case,
&BTreeMap::from([(0, address)]),
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
let plan = pipeline.plan(&device, &state.shape()).unwrap();
let commands = plan.instantiate_dispatch(&state, &case.dispatch).unwrap();
assert!(!commands.regions.is_empty(), "{stem}");
assert!(plan.descriptors.iter().all(|write| matches!(
write.source,
WriteSource::Buffer { .. }
| WriteSource::Neutral(_)
| WriteSource::ArgumentTable { .. }
| WriteSource::ConstantBlob { .. }
)));
assert!(
!commands
.push_holes
.iter()
.any(|hole| matches!(hole, PushHole::ExecutionStatusAddress { .. })),
"{stem}: the loop reaches no status buffer"
);
}
}
}
#[test]
fn identity_is_per_profile_and_per_engine_slot() {
let a = engine_fingerprint(device("lavapipe", DevicePolicy::RESIDENT_TABLES).profile());
@@ -1,32 +1,15 @@
//! Argument-buffer textures and samplers in the engine executor: a texture is a used texture whose
//! resource id its owner holds at its field, a member of the plan's heap that the kernel's handle
//! table finds; a sampler is an argument sampler whose id its owner holds, an element of the plan's
//! sampler arrays that the kernel's sampler table finds. No device is opened.
//! Argument-buffer textures and samplers in the engine executor's mapping: a texture's resource id
//! and a sampler's id are what its owner holds at its field. No device is opened.
use super::{b64, device, kernel_case, map_kernel};
use crate::candidate::engine::argument_buffers::{
field_words, owner_bytes, resource_id, sampler_id, sampler_ids,
};
use crate::candidate::engine::resources::argument_sampler_descriptor;
use crate::candidate::engine::{
bind_state, compute_shape, require_case_families, texture_tokens, variants, BufferAddress,
ComputeOutput,
};
use super::{b64, kernel_case, map_kernel};
use crate::candidate::engine::argument_buffers::owner_bytes;
use crate::candidate::engine::{require_case_families, ComputeOutput};
use crate::case::{
ArgumentBufferBufferResource, ArgumentBufferSamplerResource, ArgumentBufferTextureResource,
AuthoredCase, BufferResource, OutputSelection, ResourceRole, SamplerAddressMode, SamplerFilter,
SamplerMipFilter, TextureFormat, TextureType,
};
use crate::check::admission::NotSupported;
use metal2vulkan::bind::{BufferRanges, HeapSource, NeutralResource, ResourceClass, WriteSource};
use metal2vulkan::device::DevicePolicy;
use metal2vulkan::library::Library;
use metal2vulkan::metal::{
PixelFormat, RenderStages, ResourceUsage, SamplerMinMagFilter, TextureType as MetalType,
};
use metal2vulkan::pipeline::FunctionDescriptor;
use metal2vulkan::Budget;
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
use std::collections::BTreeMap;
/// An argument-buffer texture of `format` and `dimensions` at `field_offset` of buffer 0, holding
@@ -63,13 +46,10 @@ fn gap(case: &AuthoredCase, expected: &str) {
}
/// Every member of buffer 0's argument buffer maps into its owner: the owner (4 authored bytes)
/// grows to cover each 8-byte field; each texture is a used texture (its token after the
/// argument-buffer buffers', its resource id nonzero and its own), resident for reading and
/// writing like the oracle's `useResource`; the owner is created holding the buffer's address and
/// each texture's resource id at their fields; a texture's region is an output; and an owner that
/// is not bound, a key authored twice, a field named twice, and overlapping fields are refused. A
/// texture buffer maps, as a run through the runtime makes it, and binds as a used texture of
/// Metal's `TextureBuffer` type, in the shape the authored compile census compiles for.
/// grows to cover each 8-byte field; the owner is created holding the buffer's address and each
/// texture's resource id at their fields; a texture's region is an output; and an owner that is
/// not bound, a key authored twice, overlapping fields, and a field past the owner are refused. A
/// texture buffer maps, as a run through the runtime makes it.
#[test]
fn argument_buffer_members_are_written_into_their_owner() {
let mut case = kernel_case();
@@ -145,62 +125,13 @@ fn argument_buffer_members_are_written_into_their_owner() {
}
);
// The bind state: the buffer is token 0, the textures follow it with their resource ids.
let tokens = texture_tokens(&mapped).unwrap();
assert_eq!(tokens, BTreeMap::from([((0, 16), 1), ((0, 24), 2)]));
let host = |guest| BufferAddress {
guest,
host: Some(guest),
};
let addresses = BTreeMap::from([(0, host(0x1000))]);
let embedded = BTreeMap::from([((0, 8), host(0xdead_0000))]);
let state = bind_state(&mapped, &addresses, &embedded, BufferRanges::default()).unwrap();
let [buffer, first, second] = state.used_resources.as_slice() else {
panic!("{:?}", state.used_resources);
};
assert_eq!((buffer.class, buffer.token), (ResourceClass::Buffer, 0));
for (used, token, format) in [
(first, 1, PixelFormat::RGBA8Unorm),
(second, 2, PixelFormat::R32Uint),
] {
let ResourceClass::Texture(facts) = used.class else {
panic!("{used:?}");
};
assert_eq!(
(facts.texture_type, facts.pixel_format),
(MetalType::Type2D, format)
);
assert_eq!(used.token, token);
assert_eq!(used.resource_id, Some(resource_id(token)));
assert_eq!(used.usage, ResourceUsage::READ | ResourceUsage::WRITE);
assert_eq!(used.stages, RenderStages::empty());
assert_eq!((used.gpu_address, used.device_address), (None, None));
}
for addressed in [false, true] {
let shape = compute_shape(&mapped, addressed, BufferRanges::default()).unwrap();
assert_eq!(shape.used.len(), 3);
if addressed {
assert_eq!(state.shape(), shape);
}
}
// The owner holds, at each field, the word Metal's argument encoder writes there.
let fields = field_words(&embedded, &tokens, &BTreeMap::new()).unwrap();
let fields = BTreeMap::from([((0, 8), 0xdead_0000), ((0, 16), 0x11), ((0, 24), 0x22)]);
let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap();
let word = |at: usize| u64::from_le_bytes(owner[at..at + 8].try_into().unwrap());
assert_eq!(&owner[..8], &[0xab, 0xab, 0xab, 0xab, 0, 0, 0, 0]);
assert_eq!(
[word(8), word(16), word(24)],
[0xdead_0000, resource_id(1), resource_id(2)]
);
// Ids are nonzero (a handle table never enters id 0) and distinct.
let ids = (0..64)
.map(resource_id)
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(ids.len(), 64);
assert!(!ids.contains(&0));
// A field named by two members, overlapping fields, and a field past the owner are refused.
assert!(field_words(&embedded, &BTreeMap::from([((0, 8), 1)]), &BTreeMap::new(),).is_err());
assert_eq!([word(8), word(16), word(24)], [0xdead_0000, 0x11, 0x22]);
// Overlapping fields and a field past the owner are refused.
let overlapping = BTreeMap::from([((0, 8), 1), ((0, 12), 2)]);
assert!(owner_bytes(&mapped.buffers, 0, &overlapping).is_err());
assert!(owner_bytes(&mapped.buffers, 0, &BTreeMap::from([((0, 32), 1)])).is_err());
@@ -218,147 +149,6 @@ fn argument_buffer_members_are_written_into_their_owner() {
texel.argument_buffer_textures[&(0, 16)].texture_type,
TextureType::Buffer
);
let state = bind_state(&texel, &addresses, &embedded, BufferRanges::default()).unwrap();
let ResourceClass::Texture(facts) = state.used_resources[1].class else {
panic!("{:?}", state.used_resources);
};
assert_eq!(
(facts.texture_type, facts.pixel_format),
(MetalType::TextureBuffer, PixelFormat::RGBA8Unorm)
);
assert_eq!(
(
state.used_resources[1].token,
state.used_resources[1].resource_id
),
(1, Some(resource_id(1)))
);
assert_eq!(
compute_shape(&texel, true, BufferRanges::default()).unwrap(),
state.shape()
);
}
/// End to end without a device: `argument_buffer_read` of the owned `handles` fixture on
/// `moltenvk-m3`, bound as the executor binds it, plans its argument-buffer texture as a heap
/// member (`HeapEntry` of its token) with the kernel's handle table, whose bytes the dispatch
/// fills to their planned length, and the resource id the owner holds at the field is the one
/// the bind state names for that member. That the table resolves each used resource's id to its
/// member's element is the binder's contract, which the crate's own tests check by decoding the
/// table (`a_sampled_heap_writes_each_member_and_its_table`).
#[test]
fn an_argument_buffer_texture_is_the_heap_member_its_owner_names() {
let mut case = kernel_case();
case.entry = "argument_buffer_read".into();
case.buffers = vec![
BufferResource {
binding: 0,
role: ResourceRole::Input,
bytes_b64: Some(b64(&[0; 8])),
initial_bytes_b64: None,
rasterization_rate_map: None,
},
BufferResource {
binding: 1,
role: ResourceRole::Output,
bytes_b64: None,
initial_bytes_b64: Some(b64(&[0xab; 16])),
rasterization_rate_map: None,
},
];
case.argument_buffer_textures.push(member(
0,
TextureFormat::Rgba32Float,
[1, 1, 1],
ResourceRole::Input,
&[0x3f; 16],
));
case.output = OutputSelection::Buffer {
binding: 1,
offset: 0,
length: 16,
};
let mapped = map_kernel(&case).unwrap();
let bitcode = match llvm_assemble(&engine_dir().join("handles.ll")) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected handles.ll: {why}"),
};
let device = device("moltenvk-m3", DevicePolicy::RESIDENT_TABLES);
let library = Library::from_air(&bitcode).unwrap();
let function = FunctionDescriptor::new(library.function(&mapped.entry).unwrap());
let shape = compute_shape(&mapped, true, BufferRanges::default()).unwrap();
let (pipeline, _) = variants::bound::compile_compute_for_shape(
&device,
&function,
&shape,
Some(&mapped.dispatch),
&Budget::standard(),
)
.unwrap();
let addresses = mapped
.buffers
.keys()
.map(|&index| {
let mut address = BufferAddress::synthetic(index);
address.host = Some(address.guest);
(index, address)
})
.collect();
let state = bind_state(
&mapped,
&addresses,
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
assert_eq!(state.shape(), shape);
let plan = pipeline.plan(&device, &shape).unwrap();
assert!(plan.diagnostics.is_empty(), "{:?}", plan.diagnostics);
let token = texture_tokens(&mapped).unwrap()[&(0, 0)];
let elements = plan
.descriptors
.iter()
.filter_map(|write| match write.source {
WriteSource::HeapEntry {
source, element, ..
} => Some((source, element)),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(elements, [(HeapSource::Used(token), 1)]);
let table = plan
.descriptors
.iter()
.find(|write| matches!(write.source, WriteSource::HandleTable { .. }))
.expect("the kernel's handle table");
let commands = plan.instantiate_dispatch(&state, &mapped.dispatch).unwrap();
let bytes = &commands
.descriptor_bytes
.iter()
.find(|bytes| (bytes.set, bytes.binding) == (table.set, table.binding))
.expect("the handle table's bytes")
.bytes;
let WriteSource::HandleTable { bytes_len, .. } = table.source else {
unreachable!()
};
assert_eq!(bytes.len(), bytes_len as usize);
let fields = field_words(
&BTreeMap::new(),
&texture_tokens(&mapped).unwrap(),
&BTreeMap::new(),
)
.unwrap();
let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap();
let id = u64::from_le_bytes(owner[..8].try_into().unwrap());
assert_eq!(id, resource_id(token));
assert!(state
.used_resources
.iter()
.any(|used| used.token == token && used.resource_id == Some(id)));
}
/// The material `{ texture2d<float> t; sampler s; }` of `argument_sampler_sample` (the owned
@@ -430,131 +220,4 @@ fn an_argument_buffer_sampler_maps_by_its_field() {
&ownerless,
"argument-buffer sampler 3+8 without its owner buffer",
);
// Its field cannot also hold another member.
let mut shared = case;
shared.argument_buffer_textures[0].field_offset = 8;
let mapped = map_kernel(&shared).unwrap();
assert!(field_words(
&BTreeMap::new(),
&texture_tokens(&mapped).unwrap(),
&sampler_ids(mapped.argument_buffer_samplers.keys().copied()).unwrap(),
)
.is_err());
}
/// End to end without a device: `argument_sampler_sample` of the owned `tail_argument_samplers`
/// fixture on `moltenvk-m3`, bound as the executor binds it. The bind state lists the sampler with
/// its authored descriptor and the id the owner holds at the field; the plan fills the sampler
/// array with it after the neutral element, and the dispatch fills each of the kernel's tables to
/// its planned length. That the sampler table resolves the listed id to its element is the binder's
/// contract, which the crate's own tests check by decoding the table
/// (`src/tests/engine_heap_binder.rs`).
#[test]
fn an_argument_buffer_sampler_is_the_sampler_table_entry_its_owner_names() {
let mapped = map_kernel(&sampler_case()).unwrap();
let bitcode = match llvm_assemble(&engine_dir().join("tail_argument_samplers.ll")) {
Ok(bitcode) => bitcode,
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
return;
}
Err(AssembleError::Rejected(why)) => {
panic!("llvm-as rejected tail_argument_samplers.ll: {why}")
}
};
let device = device("moltenvk-m3", DevicePolicy::RESIDENT_TABLES);
let library = Library::from_air(&bitcode).unwrap();
let function = FunctionDescriptor::new(library.function(&mapped.entry).unwrap());
let shape = compute_shape(&mapped, true, BufferRanges::default()).unwrap();
let (pipeline, _) = variants::bound::compile_compute_for_shape(
&device,
&function,
&shape,
Some(&mapped.dispatch),
&Budget::standard(),
)
.unwrap();
let addresses = mapped
.buffers
.keys()
.map(|&index| {
let mut address = BufferAddress::synthetic(index);
address.host = Some(address.guest);
(index, address)
})
.collect();
let state = bind_state(
&mapped,
&addresses,
&BTreeMap::new(),
BufferRanges::default(),
)
.unwrap();
assert_eq!(state.shape(), shape);
let id = sampler_ids(mapped.argument_buffer_samplers.keys().copied()).unwrap()[&(0, 8)];
assert_eq!(id, sampler_id(0).unwrap());
assert_ne!(id, resource_id(texture_tokens(&mapped).unwrap()[&(0, 0)]));
assert_eq!(state.argument_samplers.len(), 1);
let listed = &state.argument_samplers[0];
assert_eq!(listed.resource_id, id);
assert_eq!(
listed.desc,
argument_sampler_descriptor(&sampler_case().argument_buffer_samplers[0])
);
assert_eq!(listed.desc.min_filter, SamplerMinMagFilter::Linear);
let plan = pipeline.plan(&device, &shape).unwrap();
assert!(plan.diagnostics.is_empty(), "{:?}", plan.diagnostics);
// One sampled, non-comparing float use: one array of twice the class's 16 entries, the
// neutral sampler first (every plan's sampler arrays and tables hold twice their class,
// whatever filter the states listed have, for states made late).
let mut elements = plan
.descriptors
.iter()
.filter_map(|write| match write.source {
WriteSource::ArgumentSampler {
index,
compare,
integer,
} => Some((write.array_element, index, compare, integer)),
_ => None,
})
.collect::<Vec<_>>();
elements.sort();
assert_eq!(
elements,
(1..32)
.map(|e| (e, e - 1, false, false))
.collect::<Vec<_>>()
);
assert!(plan.descriptors.iter().any(|write| write.array_element == 0
&& write.source == WriteSource::Neutral(NeutralResource::Sampler { compare: false })));
let commands = plan.instantiate_dispatch(&state, &mapped.dispatch).unwrap();
let fields = field_words(
&BTreeMap::new(),
&texture_tokens(&mapped).unwrap(),
&sampler_ids(mapped.argument_buffer_samplers.keys().copied()).unwrap(),
)
.unwrap();
let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap();
assert_eq!(u64::from_le_bytes(owner[8..16].try_into().unwrap()), id);
let tables = plan
.descriptors
.iter()
.filter_map(|write| match write.source {
WriteSource::HandleTable { bytes_len, .. } => {
Some((write.set, write.binding, bytes_len))
}
_ => None,
})
.collect::<Vec<_>>();
assert!(!tables.is_empty(), "the kernel's sampler table");
for (set, binding, bytes_len) in tables {
let bytes = &commands
.descriptor_bytes
.iter()
.find(|bytes| (bytes.set, bytes.binding) == (set, binding))
.expect("a table's bytes")
.bytes;
assert_eq!(bytes.len(), bytes_len as usize);
}
}
@@ -52,7 +52,14 @@ pub fn compile_kernel(
#[cfg(test)]
mod tests {
use super::*;
use crate::candidate::engine::public_cases::device;
use metal2vulkan::device::{DeviceDescription, DevicePolicy};
fn device(stem: &str) -> Device {
let path = crate::engine::profiles_dir().join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).unwrap();
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
Device::from_queries(description, DevicePolicy::default()).unwrap()
}
/// A dispatch whose threadgroup has a partial simdgroup runs the kernel's emulated-simdgroups
/// variant on a device whose subgroups run whole simdgroups (moltenvk-m3); a full threadgroup
@@ -93,274 +100,3 @@ mod tests {
assert_eq!(kernel, plain);
}
}
/// The binder's loop of a kernel's compile and its plan for a bind shape: what the binder's own
/// tests compile a case with until the binder goes.
#[cfg(test)]
pub(crate) mod bound {
use metal2vulkan::bind::{BindShape, Dispatch, TextureShape};
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::{Device, DeviceProfile};
use metal2vulkan::error::{Error, InternalError, InternalKind, RuntimeInput};
use metal2vulkan::metal::format::storage_image_choice;
use metal2vulkan::metal::PixelFormat;
use metal2vulkan::pipeline::{
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, SlotClass, SlotRef, Stage,
StageSource,
};
use metal2vulkan::Budget;
/// Whether a pipeline compiled under `compiled` is the one `variant` asks for.
pub fn compiled_for(compiled: &VariantKey, variant: &VariantKey) -> bool {
compiled == variant
}
/// The pixel format of the texture or texture buffer `shape` binds at texture slot `slot`.
pub fn bound_format(shape: &BindShape, slot: SlotRef) -> Option<PixelFormat> {
if slot.class != SlotClass::Texture {
return None;
}
match shape.stages.get(&slot.stage)?.textures.get(&slot.index)? {
TextureShape::Texture { pixel_format, .. }
| TextureShape::Buffer { pixel_format, .. } => Some(*pixel_format),
_ => None,
}
}
/// Compile with the variant a bind decides: `compile` under the empty key first; each
/// `NeedsInput(StorageTextureFormat{slot})` adds the storage-image choice of the format
/// `bound_format` reports at that slot (of whichever stage) and compiles again; then `variant`
/// plans the pipeline (`None` when the plan refuses the bind, which the caller's own plan then
/// reports), and a plan asking for a different key compiles once more under that key. Returns
/// the pipeline and the key it was compiled under.
///
/// Every retry adds a slot the key did not have, or is the one recompile for the plan's key, so
/// the loop ends.
pub fn compile_for_bind_state<P>(
bound_format: impl Fn(SlotRef) -> Option<PixelFormat>,
profile: &DeviceProfile,
mut compile: impl FnMut(&VariantKey) -> Result<P, Error>,
mut variant: impl FnMut(&P) -> Option<VariantKey>,
) -> Result<(P, VariantKey), Error> {
let mut key = VariantKey::new();
let mut recompiled = false;
loop {
let pipeline = match compile(&key) {
Ok(pipeline) => pipeline,
Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat { slot }))
if !key.storage_images.contains_key(&slot) =>
{
let Some(format) = bound_format(slot) else {
return Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat {
slot,
}));
};
key.storage_images
.insert(slot, storage_image_choice(format, profile)?);
continue;
}
Err(error) => return Err(error),
};
let Some(wanted) = variant(&pipeline) else {
return Ok((pipeline, key));
};
if compiled_for(&key, &wanted) {
return Ok((pipeline, key));
}
if recompiled {
return Err(Error::Internal(InternalError::new(
InternalKind::Invariant,
format!("the plan asks for variant {wanted:?} of the pipeline compiled for it"),
)));
}
recompiled = true;
key = wanted;
}
}
/// Compile `function` into a compute pipeline for `device` under `budget` with the inputs the
/// bind shape `shape` decides, and those `dispatch` runs on when given (its plan's
/// `dispatch_variant`) ([`compile_for_bind_state`], the key's kernel inputs); returns the pipeline
/// and that key.
pub fn compile_compute_for_shape(
device: &Device,
function: &FunctionDescriptor,
shape: &BindShape,
dispatch: Option<&Dispatch>,
budget: &Budget,
) -> Result<(ComputePipeline, VariantKey), Error> {
compile_kernel_for_shape(device, shape, dispatch, |key| {
let inputs = key.lowering_inputs(Stage::Kernel);
let compiled = device.compile_function(function, &inputs, budget)?;
let descriptor = ComputePipelineDescriptor::new(StageSource::Compiled(compiled));
device.compile_compute_pipeline(&descriptor, budget)
})
}
/// [`compile_for_bind_state`] of a kernel pipeline `compile` builds under a key, settling on the
/// variant the plan of `shape` asks for, or the one `dispatch` runs on when given (its plan's
/// `dispatch_variant`).
fn compile_kernel_for_shape(
device: &Device,
shape: &BindShape,
dispatch: Option<&Dispatch>,
compile: impl FnMut(&VariantKey) -> Result<ComputePipeline, Error>,
) -> Result<(ComputePipeline, VariantKey), Error> {
compile_for_bind_state(
|slot| bound_format(shape, slot),
device.profile(),
compile,
// A dispatch the plan refuses leaves the plan's own key: the caller's instantiation of
// the same dispatch reports the refusal.
|pipeline| {
let plan = pipeline.plan(device, shape).ok()?;
Some(match dispatch {
Some(dispatch) => plan.dispatch_variant(dispatch).unwrap_or(plan.variant),
None => plan.variant,
})
},
)
}
mod tests {
use super::*;
use crate::candidate::engine::public_cases::device;
use std::cell::Cell;
fn texture(index: u32) -> SlotRef {
SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index,
}
}
fn buffer(index: u32) -> SlotRef {
SlotRef {
stage: Stage::Kernel,
class: SlotClass::Buffer,
index,
}
}
/// A compile that needs a format for `needed` and otherwise returns the key it ran under.
fn needing(
needed: SlotRef,
calls: &Cell<u32>,
) -> impl FnMut(&VariantKey) -> Result<VariantKey, Error> + '_ {
move |key| {
calls.set(calls.get() + 1);
if key.storage_images.contains_key(&needed) {
Ok(key.clone())
} else {
Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat {
slot: needed,
}))
}
}
}
/// The plan of a pipeline compiled under `key` asks for exactly that key.
fn settled(key: &VariantKey) -> Option<VariantKey> {
Some(key.clone())
}
#[test]
fn a_needed_storage_format_is_the_bound_textures_choice() {
let device = device("lavapipe");
let calls = Cell::new(0);
let (_, inputs) = compile_for_bind_state(
|slot| (slot == texture(2)).then_some(PixelFormat::R32Uint),
device.profile(),
needing(texture(2), &calls),
settled,
)
.unwrap();
let choice = storage_image_choice(PixelFormat::R32Uint, device.profile()).unwrap();
assert_eq!(inputs.storage_images.get(&texture(2)), Some(&choice));
assert_eq!(calls.get(), 2);
}
#[test]
fn an_unbound_storage_slot_keeps_the_products_needs_input() {
let device = device("lavapipe");
let calls = Cell::new(0);
let error = compile_for_bind_state(
|_| None,
device.profile(),
needing(texture(0), &calls),
settled,
)
.unwrap_err();
assert_eq!(
error,
Error::NeedsInput(RuntimeInput::StorageTextureFormat { slot: texture(0) })
);
assert_eq!(calls.get(), 1);
}
#[test]
fn a_plan_variant_recompiles_once_under_its_key() {
let device = device("lavapipe");
let mut wanted = VariantKey::new();
wanted.psb_slots.insert(buffer(1));
let calls = Cell::new(0);
let (pipeline, inputs) = compile_for_bind_state(
|_| None,
device.profile(),
|inputs| {
calls.set(calls.get() + 1);
Ok(inputs.clone())
},
|_| Some(wanted.clone()),
)
.unwrap();
assert!(compiled_for(&inputs, &wanted));
assert_eq!(pipeline, inputs);
assert_eq!(calls.get(), 2);
}
#[test]
fn a_variant_that_does_not_settle_is_internal() {
let device = device("lavapipe");
let calls = Cell::new(0);
let error = compile_for_bind_state(
|_| None,
device.profile(),
|inputs| {
calls.set(calls.get() + 1);
Ok(inputs.clone())
},
|compiled: &VariantKey| {
let mut key = VariantKey::new();
key.psb_slots
.insert(buffer(compiled.psb_slots.len() as u32));
Some(key)
},
)
.unwrap_err();
assert!(matches!(error, Error::Internal(_)), "{error:?}");
assert_eq!(calls.get(), 2);
}
/// A plan that refuses the bind ends the loop with the pipeline compiled so far; the caller's
/// own plan of the same shape reports the refusal.
#[test]
fn a_refused_plan_returns_the_pipeline_for_the_callers_plan() {
let device = device("lavapipe");
let calls = Cell::new(0);
let (_, inputs) = compile_for_bind_state(
|_| None,
device.profile(),
|inputs| {
calls.set(calls.get() + 1);
Ok(inputs.clone())
},
|_| None,
)
.unwrap();
assert_eq!(inputs, VariantKey::new());
assert_eq!(calls.get(), 1);
}
}
}
@@ -626,7 +626,6 @@ pub(super) fn ran(
spv_sha256: None,
translator_fingerprint: runtime_fingerprint(),
environment: environment.clone(),
status: None,
comparison: census.comparison_class(),
census,
}
@@ -346,7 +346,7 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() {
);
let prepared = prepare_compile(device, admitted())
.unwrap_or_else(|error| panic!("{name}: preparation: {error}"));
case_compile(&prepared, &lavapipe).unwrap();
case_compile(&prepared).unwrap();
let cells = compile_case(scratch.path(), &worker, &case, &[&lavapipe]);
assert_eq!(cells.len(), 1, "{name}");
assert_eq!(
@@ -359,10 +359,8 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() {
}
/// A case whose argument buffer holds a texture buffer, which a run draws through the runtime,
/// compiles in the census under the identity domains (the runtime's): the member is a used
/// texture of Metal's `TextureBuffer` type in the bind shape the census compiles for
/// (`argument_buffers::used_texture`), where the census failed the case. Each committed case that
/// holds one, on lavapipe, whose profile holds a texel-buffer heap array.
/// compiles in the census as the runtime compiles it: each committed case that holds one, on
/// lavapipe.
#[test]
fn the_census_compiles_a_texture_buffer_an_argument_buffer_holds() {
use metal2vulkan_validation::authored_compile::compile_case;