diff --git a/crates/metal2vulkan-validation/src/authored_compile.rs b/crates/metal2vulkan-validation/src/authored_compile.rs index e000e4478..f65e96a01 100644 --- a/crates/metal2vulkan-validation/src/authored_compile.rs +++ b/crates/metal2vulkan-validation/src/authored_compile.rs @@ -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)), }; diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index ce0aab717..dc3e4efb5 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -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>, /// 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, /// 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, - embedded: &BTreeMap<(u32, u32), BufferAddress>, - ranges: BufferRanges, -) -> Result { - 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, 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, -} - -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 { - 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, 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>, - shape: BindShape, }, Render { request: PipelineRequest, libraries: Vec>, - 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) { - 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, 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, 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 }) diff --git a/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs b/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs index 13d290b3e..904836f32 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs @@ -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::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(keys: impl Iterator) -> Result, 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, -) -> Result, 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( - buffers: usize, - keys: impl Iterator, -) -> Result, 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( - buffers: &BTreeMap, - textures: &BTreeMap, - samplers: &BTreeMap, -) -> Result, 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>, @@ -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 { - 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 { - 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( - keys: impl Iterator, -) -> Result, 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() -} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs index aeb6c1a89..63ba1d59a 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs @@ -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; -} - -impl Planned for ComputePipeline { - fn content_digest(&self) -> Hash256 { - ComputePipeline::content_digest(self) - } - fn plan_for(&self, device: &Device, shape: &BindShape) -> Result { - 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 { - 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()) } diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs index 6410b8088..9287b3335 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs @@ -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)> { - 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 { - 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 { - 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 { - 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 { - 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, 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, 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 { - 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 { diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs index 0649b7a15..30506adfb 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs @@ -1,6 +1,6 @@ //! Device-free tests of the engine render candidate: case mapping, companion refusals, the //! oracle's vertex-buffer slots, output selection, and the owned and public graphics pipelines -//! compiled and planned for committed profiles. No device is opened. +//! compiled for committed profiles. No device is opened. use super::*; use crate::case::{AttributeFormat, VertexObservation}; @@ -10,8 +10,6 @@ use crate::source::public_sources; use crate::store::CorpusStore; use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; use metal2vulkan::library::FunctionConstantValues; -use metal2vulkan::pipeline::PrecisionNote; -use metal2vulkan::vk; use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError}; use std::path::Path; @@ -180,149 +178,6 @@ fn a_fragment_cases_depth_stencil_attachment_and_state_are_the_oracles() { ); } -/// A fragment case's `[[stencil]]` output plans through stencil export: on lavapipe, which has -/// the extension, the pipeline requires it and the bind state carries the draw's descriptor, the -/// one the Metal oracle sets. On nvidia-rtx50-linux, which lacks it, the compile refuses naming -/// the extension. -#[test] -fn a_stencil_output_case_plans_through_stencil_export() { - use metal2vulkan::device::VkExtension; - use metal2vulkan::error::{Capability, Feature, Needs}; - let Some(bitcode) = assembled(&fixtures_dir().join("fragment_depth_stencil.ll")) else { - return; - }; - let mut authored = crate::companion::tests::case( - Stage::Fragment, - "fragment_depth_stencil", - TextureFormat::Rgba32Float, - ); - authored.render_targets.clear(); - authored.depth_stencil = Some(crate::case::DepthStencilResource { - dimensions: [1, 1], - initial_depth_b64: None, - initial_stencil_b64: Some("qw==".into()), - state: None, - }); - authored.output = OutputSelection::Stencil { - origin: [0, 0], - dimensions: [1, 1], - }; - let (interface, companion) = checked_companion(&authored, &bitcode); - let mut render = render_case(&authored, &interface, WITHOUT_SLICE, companion.as_ref()).unwrap(); - // Both aspects are the runtime's limit (`SeparateDepthStencil`), which stops such a case - // before the engine plans it; the plan below is the translator's for both, so the case maps - // with its stencil and takes its depth after. - render.depth_stencil.as_mut().unwrap().depth = Some(1.0f32.to_le_bytes().to_vec()); - let companion_bitcode = render.companion.as_ref().unwrap().opaque_bitcode().unwrap(); - let libraries = RenderLibraries { - vertex: &companion_bitcode, - fragment: Some(&bitcode), - }; - let (pipeline, _, _) = planned_draw(&device("lavapipe"), &render, libraries).unwrap(); - assert!(pipeline - .requirements - .extensions - .contains(&VkExtension::ExtShaderStencilExport)); - let state = bind_state( - &render, - &BTreeMap::new(), - &BTreeMap::new(), - BufferRanges::default(), - ) - .unwrap(); - assert_eq!(state.depth_stencil, render.depth_stencil_state.descriptor); - - match planned_draw(&device("nvidia-rtx50-linux"), &render, libraries) { - Err(Error::Unsupported(u)) => assert_eq!( - (u.feature, u.needs), - ( - Feature::StencilExport, - Needs::AnyOf(vec![vec![Capability::Extension( - VkExtension::ExtShaderStencilExport - )]]) - ) - ), - other => panic!("a stencil output without export: {:?}", other.map(|_| ())), - } -} - -/// A fragment case that reads its color attachment maps like any fragment case (its render target -/// is the attachment it reads; no requirement stops the engine's candidate) and plans, on lavapipe -/// (which has `rasterizationOrderColorAttachmentAccess`) and on moltenvk-m3 alike, color attachment -/// 0 read through an input-attachment write, which the consumer orders between draws alone (its -/// barriers, `platform::graphics_pipeline::fetch_between_draws`), the fragment stage noting -/// `PrecisionNote::UnorderedFetchWithinDraw`, and requires no ordered form. -#[test] -fn a_framebuffer_fetch_case_plans_its_ordered_input_attachment() { - use metal2vulkan::bind::WriteSource; - use metal2vulkan::device::VkFeature; - let Some(bitcode) = assembled(&metal2vulkan_devtools::engine_dir().join("fragment_fetch.ll")) - else { - return; - }; - let mut authored = - crate::companion::tests::case(Stage::Fragment, "fetch_scalar", TextureFormat::R32Float); - authored.render_targets[0].initial_bytes_b64 = b64(&3.0f32.to_le_bytes()); - authored.output = OutputSelection::RenderTarget { - index: 0, - origin: [0, 0], - dimensions: [1, 1], - }; - let (interface, companion) = checked_companion(&authored, &bitcode); - let render = render_case(&authored, &interface, WITHOUT_SLICE, companion.as_ref()).unwrap(); - assert_eq!(render.color_targets[&0].bytes, 3.0f32.to_le_bytes()); - let companion_bitcode = render.companion.as_ref().unwrap().opaque_bitcode().unwrap(); - let libraries = RenderLibraries { - vertex: &companion_bitcode, - fragment: Some(&bitcode), - }; - let (pipeline, plan, _) = planned_draw(&device("lavapipe"), &render, libraries).unwrap(); - assert_eq!(pipeline.graphics.input_attachments.len(), 1); - assert!(unordered_within_draw(&pipeline)); - assert!(!pipeline - .requirements - .features - .contains(&VkFeature::RasterizationOrderColorAttachmentAccess)); - assert_eq!( - plan.descriptors - .iter() - .filter(|write| matches!(write.source, WriteSource::Attachment { color_index: 0 })) - .count(), - 1 - ); - // Moltenvk-m3: the input attachment ordered between draws alone, noted. - let (pipeline, plan, _) = planned_draw(&device("moltenvk-m3"), &render, libraries).unwrap(); - let read: Vec = (pipeline.graphics.input_attachments.iter()) - .map(|input| input.color_index) - .collect(); - assert_eq!(read, [0]); - assert!(pipeline.graphics.color_attachments[0].is_some()); - assert!(!pipeline - .requirements - .features - .contains(&VkFeature::RasterizationOrderColorAttachmentAccess)); - assert_eq!( - plan.descriptors - .iter() - .filter(|write| matches!(write.source, WriteSource::Attachment { color_index: 0 })) - .count(), - 1 - ); - assert!(unordered_within_draw(&pipeline)); -} - -/// Whether `pipeline`'s fragment stage records `PrecisionNote::UnorderedFetchWithinDraw`: its -/// fetch is ordered between draws alone. -fn unordered_within_draw(pipeline: &metal2vulkan::pipeline::RenderPipeline) -> bool { - (pipeline.stages.iter()) - .filter(|stage| stage.stage == vk::ShaderStage::FRAGMENT) - .any(|stage| { - stage - .precision_notes - .contains(&PrecisionNote::UnorderedFetchWithinDraw) - }) -} - /// A fragment case draws through its passthrough vertex companion with its own resources on the /// fragment stage, its render targets attached, and a render-target output; an observed vertex /// case draws into its observer with its resources, attributes, and target on the vertex side. @@ -484,26 +339,6 @@ fn a_rasterization_disabled_vertex_case_maps_onto_the_oracles_draw() { length: 4 } ); - let addresses = BTreeMap::from([( - (ShaderStage::Vertex, 0), - synthetic_address(ShaderStage::Vertex, 0), - )]); - let state = bind_state( - &render, - &addresses, - &BTreeMap::new(), - BufferRanges::default(), - ) - .unwrap(); - let vertex = &state.stages[&ShaderStage::Vertex]; - assert_eq!( - vertex.buffers.keys().copied().collect::>(), - [0, 29, 30] - ); - assert_ne!( - synthetic_address(ShaderStage::Vertex, 3).guest, - synthetic_address(ShaderStage::Fragment, 3).guest - ); } #[test] @@ -651,83 +486,10 @@ pub(crate) fn two_stage_case( } } -/// Compile and plan `case` on `device`: no variant, no diagnostic, and one direct draw; or the -/// product's compile refusal. -fn plan_render( - device: &Device, - case: &RenderCase, - libraries: RenderLibraries<'_>, -) -> Result<(), Error> { - planned_draw(device, case, libraries).map(|_| ()) -} - -/// [`plan_render`]'s pipeline, plan, and instantiated draw. -fn planned_draw( - device: &Device, - case: &RenderCase, - libraries: RenderLibraries<'_>, -) -> Result< - ( - metal2vulkan::pipeline::RenderPipeline, - metal2vulkan::bind::BindingPlan, - metal2vulkan::bind::DrawCommands, - ), - Error, -> { - // Every buffer the case binds, vertex buffers and argument-buffer buffers included, with a - // device address equal to its guest base, as the render executor binds them on a device with - // buffer device addresses: a slot the pipeline reaches through a physical pointer needs one - // to plan. - let shape = render_shape(case, true, BufferRanges::default()).unwrap(); - let pipeline = compile_in_process(device, case, libraries)?; - assert_eq!( - pipeline.graphics.rasterizer_discard, - case.fragment.is_none() - ); - let own = |guest| BufferAddress { - guest, - host: Some(guest), - }; - 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), own(synthetic_address(stage, index).guest))) - .collect(); - let embedded = synthetic_used_addresses(case) - .unwrap() - .into_iter() - .map(|(key, address)| (key, own(address.guest))) - .collect(); - let state = bind_state(case, &addresses, &embedded, BufferRanges::default()).unwrap(); - assert_eq!(state.shape(), shape); - let plan = pipeline.plan(device, &shape).unwrap(); - assert!(plan.variant.is_empty(), "{}", case.vertex.entry); - assert!(plan.diagnostics.is_empty(), "{:?}", plan.diagnostics); - let commands = plan.instantiate_draw(&state, &case.draw).unwrap(); - // An indexed case's draw instantiates indexed, every other one direct. - match (&case.index_buffer, commands.draw) { - (None, vk::DrawCommand::Draw { .. }) | (Some(_), vk::DrawCommand::DrawIndexed { .. }) => {} - (_, other) => panic!("{}: {other:?}", case.vertex.entry), - } - assert!(!commands.indirect_needs_arguments); - assert_eq!( - commands.buffer_offsets.len(), - pipeline.vertex_input.bindings.len() - ); - Ok((pipeline, plan, commands)) -} - /// A tessellation case maps onto the Metal oracle's patch draw: its tessellation state and factor /// bytes (`executor_contract::tessellation`), its control points per patch control point and its -/// patch attribute per patch at the oracle's slots, one patch draw of the function's control points -/// over every patch and instance through the observer, and the factor buffer in the bind state. It -/// compiles to a tessellation pipeline and plans on committed profiles: the control stage reads the -/// factors over exactly the draw's bytes, and the draw is one vertex per patch. +/// patch attribute per patch at the oracle's slots, and one patch draw of the function's control +/// points over every patch and instance through the observer. #[test] fn a_tessellation_case_maps_onto_the_oracles_patch_draw() { use crate::case::{ @@ -841,129 +603,15 @@ fn a_tessellation_case_maps_onto_the_oracles_patch_draw() { layouts[&28].step_function, metal::VertexStepFunction::PerPatch ); - let shape = render_shape(&render, true, BufferRanges::default()).unwrap(); - assert!(shape.tessellation_factor_buffer); - - let companion = observer.as_ref().unwrap().opaque_bitcode().unwrap(); - let libraries = RenderLibraries { - vertex: &bitcode, - fragment: Some(&companion), - }; - for stem in ["lavapipe", "moltenvk-m3"] { - let (pipeline, plan, commands) = planned_draw(&device(stem), &render, libraries).unwrap(); - let tessellation = pipeline - .graphics - .tessellation - .expect("a tessellation pipeline"); - assert_eq!(tessellation.control_points, 3, "{stem}"); - let factors = plan - .descriptors - .iter() - .find(|write| write.source == metal2vulkan::bind::WriteSource::TessellationFactors) - .unwrap_or_else(|| panic!("{stem}: no factor write")); - let range = commands - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == (factors.set, factors.binding)) - .unwrap_or_else(|| panic!("{stem}: no factor range")); - assert_eq!(range.range.offset, 0, "{stem}"); - assert!(range.range.range >= bytes.len() as u64, "{stem}"); - assert_eq!( - commands.draw, - vk::DrawCommand::Draw { - vertex_count: 2, - instance_count: 3, - first_vertex: 0, - first_instance: 0, - }, - "{stem}" - ); - // The control stage's push range: no residual offset, no instance stride, scale 1, no - // patch index buffer, and no control-point index buffer. - let control = commands - .push_constants - .iter() - .find(|w| w.stages == vk::ShaderStageFlags::TESSELLATION_CONTROL) - .unwrap_or_else(|| panic!("{stem}: no control push")); - let words = [0u32, 0, 1.0f32.to_bits(), 0, 0, 0] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect::>(); - assert_eq!(control.bytes, words, "{stem}"); - } } -/// The owned vertex/fragment pairs the device tests draw compile into one pipeline and plan -/// cleanly on committed profiles. +/// A render case's argument-buffer buffers are its own stage's: its owner covers the pointer field +/// and its final range is an output. The public raster-ordered argument-buffer fragment case maps +/// so. A texture array's elements are the stage's textures at their slots, and an element output is +/// that texture's region. An argument-buffer texture and sampler are the stage's members at their +/// fields, and the texture's region is an output. #[test] -fn owned_render_pipelines_plan_without_variants_or_diagnostics() { - let public = fixtures_dir(); - let (Some(triangle), Some(constant), Some(varying)) = ( - assembled(&public.join("vertex_varying_triangle.ll")), - assembled(&public.join("fragment_constant_color.ll")), - assembled(&public.join("fragment_varying_color.ll")), - ) else { - return; - }; - let target = ColorTarget { - format: TextureFormat::Rgba32Float, - dimensions: [4, 4], - samples: 1, - bytes: vec![0; 256], - }; - let vertices = vec![ - VertexBuffer { - location: 0, - buffer_index: 30, - format: AttributeFormat::Float2, - stride: 8, - step: metal::VertexStepFunction::PerVertex, - bytes: vec![0; 24], - }, - VertexBuffer { - location: 1, - buffer_index: 29, - format: AttributeFormat::Float2, - stride: 8, - step: metal::VertexStepFunction::PerVertex, - bytes: vec![0; 24], - }, - ]; - for stem in ["lavapipe", "moltenvk-m3"] { - let device = device(stem); - for (fragment, bitcode) in [ - ("fragment_constant_color", &constant), - ("fragment_varying_color", &varying), - ] { - let case = two_stage_case( - "vertex_varying_triangle", - fragment, - vertices.clone(), - BTreeMap::from([(0, target.clone())]), - 3, - ); - plan_render( - &device, - &case, - RenderLibraries { - vertex: &triangle, - fragment: Some(bitcode), - }, - ) - .unwrap_or_else(|error| panic!("{stem} {fragment}: {error}")); - } - } -} - -/// A render case's argument-buffer buffers are its own stage's: its owner covers the pointer field, -/// each is a used buffer resident for reading and writing in the vertex and fragment stages (the -/// Metal oracle's `useResource:usage:stages:`), and its final range is an output. The public -/// raster-ordered argument-buffer fragment case maps so, compiles for the shape the executor binds, -/// and plans with its pointee in the root table, host and guest address (what a loaded pointer is -/// translated through). A texture array's elements are the stage's textures at their slots, and an -/// element output is that texture's region. -#[test] -fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { +fn render_cases_map_argument_buffer_buffers_and_texture_arrays() { let root = metal2vulkan_devtools::validation_dir().join("corpus"); let store = CorpusStore::new(&root); let sources = public_sources().unwrap(); @@ -1040,84 +688,6 @@ fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { } assert!(select_render_output(vertex_side, &finals).is_err()); - // The bind state: the owner at its address, the pointee a used buffer of both stages. - let address = |guest: u64| BufferAddress { - guest, - host: Some(guest + 0x10_0000_0000), - }; - let addresses = own - .resources - .buffers - .keys() - .map(|&index| { - ( - (ShaderStage::Fragment, index), - address(0x1000_0000 * u64::from(index + 1)), - ) - }) - .collect(); - let pointee = address(0x7000_0000); - let embedded = BTreeMap::from([((ShaderStage::Fragment, key.0, key.1), pointee)]); - let state = bind_state(&render, &addresses, &embedded, BufferRanges::default()).unwrap(); - let [used] = state.used_resources.as_slice() else { - panic!("{:?}", state.used_resources); - }; - assert_eq!(used.token, 0); - assert_eq!( - (used.gpu_address, used.device_address, used.length), - (Some(pointee.guest), pointee.host, pointee_length as u64) - ); - assert_eq!( - used.usage, - metal::ResourceUsage::READ | metal::ResourceUsage::WRITE - ); - assert_eq!(used.stages, RenderStages::VERTEX | RenderStages::FRAGMENT); - - // It compiles for the shape the executor binds, and plans with the pointee resident. - let scratch = crate::ScratchDir::new("public-render-argument-buffer").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - let generated = render - .companion - .as_ref() - .expect("a fragment case draws with its companion") - .opaque_bitcode() - .unwrap(); - let libraries = RenderLibraries { - vertex: &generated, - fragment: Some(&bitcode), - }; - for stem in ["lavapipe", "moltenvk-m3"] { - let device = device(stem); - let shape = render_shape(&render, true, BufferRanges::default()).unwrap(); - assert_eq!(state.shape(), shape, "{stem}"); - let pipeline = compile_in_process(&device, &render, libraries) - .unwrap_or_else(|error| panic!("{stem}: compile: {error}")); - let plan = pipeline.plan(&device, &shape).unwrap(); - assert!( - plan.diagnostics.is_empty(), - "{stem}: {:?}", - plan.diagnostics - ); - let commands = plan.instantiate_draw(&state, &render.draw).unwrap(); - // 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()); - assert!( - commands.root_tables.iter().any(|(_, table)| table - .bytes - .as_chunks::<32>() - .0 - .iter() - .any(|entry| [word(entry, 0), word(entry, 8)] - == [pointee.host.unwrap(), pointee.guest])), - "{stem}: the pointee is not resident" - ); - } - // A texture array's elements are the fragment stage's textures at their slots. let mut arrays = case.clone(); arrays @@ -1164,11 +734,8 @@ fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { } ); - // An argument-buffer texture of the fragment stage is a used texture of both stages whose token - // follows the buffers' and whose resource id its owner holds at its field; the texture's region - // is an output. An argument-buffer sampler is an argument sampler of the bind state whose id - // its owner holds at its field. - use crate::candidate::engine::argument_buffers::{field_words, resource_id, sampler_id}; + // An argument-buffer texture and sampler of the fragment stage are its members at their fields; + // the texture's region is an output. let mut members = case.clone(); let texture_field = key.1 + 64; let sampler_field = key.1 + 88; @@ -1223,54 +790,6 @@ fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { [(key.0, texture_field)] ); let member = (ShaderStage::Fragment, key.0, texture_field); - let tokens = texture_tokens(&render).unwrap(); - assert_eq!(tokens, BTreeMap::from([(member, 1)])); - let embedded = BTreeMap::from([((ShaderStage::Fragment, key.0, key.1), pointee)]); - let state = bind_state(&render, &addresses, &embedded, BufferRanges::default()).unwrap(); - let [_, used] = state.used_resources.as_slice() else { - panic!("{:?}", state.used_resources); - }; - assert!( - matches!(used.class, metal2vulkan::bind::ResourceClass::Texture(_)), - "{used:?}" - ); - assert_eq!( - (used.token, used.resource_id, used.stages), - ( - 1, - Some(resource_id(1)), - RenderStages::VERTEX | RenderStages::FRAGMENT - ) - ); - assert_eq!( - render_shape(&render, true, BufferRanges::default()).unwrap(), - state.shape() - ); - let sampler = (ShaderStage::Fragment, key.0, sampler_field); - let samplers = - argument_buffers::sampler_ids(render.argument_buffer_samplers().map(|(key, _)| key)) - .unwrap(); - assert_eq!( - samplers, - BTreeMap::from([(sampler, sampler_id(0).unwrap())]) - ); - let [listed] = state.argument_samplers.as_slice() else { - panic!("{:?}", state.argument_samplers); - }; - assert_eq!(listed.resource_id, sampler_id(0).unwrap()); - assert_eq!( - listed.desc, - resources::argument_sampler_descriptor(&members.argument_buffer_samplers[0]) - ); - let words = field_words(&embedded, &tokens, &samplers).unwrap(); - assert_eq!( - words, - BTreeMap::from([ - ((ShaderStage::Fragment, key.0, key.1), pointee.guest), - (member, resource_id(1)), - (sampler, sampler_id(0).unwrap()), - ]) - ); let finals = RenderFinals { argument_buffer_textures: BTreeMap::from([( member, @@ -1283,10 +802,10 @@ fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { /// The public case whose vertex function chooses its render target slice /// (`vertex_amplification_id_layer`) is drawn in the one-layer pass the Metal oracle draws it in: -/// its render case and bind state carry the length the shared derivation gives, and the -/// pipeline compiled for that shape writes `Layer` (0 for every index in that pass). +/// its render case carries the length the shared derivation gives, and its pipeline writes `Layer` +/// (0 for every index in that pass). #[test] -fn a_slice_choosing_case_binds_the_oracles_one_layer_pass() { +fn a_slice_choosing_case_maps_the_oracles_one_layer_pass() { let root = metal2vulkan_devtools::validation_dir().join("corpus"); let store = CorpusStore::new(&root); let sources = public_sources().unwrap(); @@ -1318,8 +837,6 @@ fn a_slice_choosing_case_binds_the_oracles_one_layer_pass() { ) ); assert_eq!(render.render_target_array_length, 1); - let shape = render_shape(&render, true, BufferRanges::default()).unwrap(); - assert_eq!(shape.render_target_array_length, 1); let scratch = crate::ScratchDir::new("slice-choosing-case").unwrap(); let ll = scratch.path().join("case.ll"); @@ -1358,482 +875,6 @@ fn b64(bytes: &[u8]) -> String { base64::engine::general_purpose::STANDARD.encode(bytes) } -/// Every committed public vertex or fragment case either maps onto a draw (with its generated -/// companion when it needs one) that compiles and plans cleanly on committed profiles, or is -/// refused typed. -#[test] -fn public_render_cases_plan_or_refuse_typed() { - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let store = CorpusStore::new(&root); - let sources = public_sources().unwrap(); - let mut planned = 0; - let mut with_companion = 0; - for shard in 0..64 { - for case in store.read_case_shard(shard).unwrap() { - let Some(row) = sources - .iter() - .find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry) - else { - continue; - }; - // A kernel case is no draw, and an object or mesh case is a mesh draw, which - // `engine::mesh` maps (`mesh_case`), never `render_case`. - if !matches!(case.stage, Stage::Vertex | Stage::Fragment) { - continue; - } - let scratch = crate::ScratchDir::new("public-render-case").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - // The interface and companion the prepare path maps with: the checked entry's, under - // the case's constants. - let checked = crate::check::check_case_against_source(&root, case.clone(), row) - .unwrap_or_else(|errors| panic!("{}: {errors:?}", case.name)); - let render = match render_case( - &case, - &checked.primary.interface, - &row.air_ll, - checked.primary.companion.as_ref(), - ) { - Ok(render) => render, - Err(ExecutorError::NotSupported( - NotSupported::NotImplemented(_) | NotSupported::Requirements(_), - )) => continue, - Err(other) => panic!("{}: {other:?}", case.name), - }; - let companion = render - .companion - .as_ref() - .map(|companion| companion.opaque_bitcode().unwrap()); - let libraries = match (&render.companion, &companion) { - (None, _) => RenderLibraries { - vertex: &bitcode, - fragment: None, - }, - (Some(Companion::PassthroughVertex(_)), Some(generated)) => RenderLibraries { - vertex: generated, - fragment: Some(&bitcode), - }, - (Some(Companion::ObserverFragment(_)), Some(generated)) => RenderLibraries { - vertex: &bitcode, - fragment: Some(generated), - }, - (Some(Companion::MeshStages(_)), Some(_)) => { - unreachable!("a render case's companion is no mesh render pipeline's stages") - } - (Some(_), None) => unreachable!("the companion's bitcode was assembled"), - }; - with_companion += usize::from(render.companion.is_some()); - for stem in ["lavapipe", "moltenvk-m3"] { - match plan_render(&device(stem), &render, libraries) { - Ok(()) => planned += 1, - // The product's typed refusal of the function, not the executor's. - Err(error) => assert!( - !crate::engine::Outcome::from(&error).is_defect(), - "{stem} {}: {error}", - case.name - ), - } - } - } - } - assert!(planned >= 1, "{planned} public render cases planned"); - assert!(with_companion > 0, "no public case drew with a companion"); -} - -/// Every installed public tessellation case maps onto the oracle's patch draw in its authored state -/// (partition mode, output winding, cull mode) and plans on lavapipe and moltenvk-m3: a -/// tessellation pipeline of the function's control points, the factor write over the case's factor -/// bytes, and one vertex per patch. A case without a vertex observation draws its patches with -/// rasterization disabled and no observer, and at least one (the domain-point cases) does. -#[test] -fn public_tessellation_cases_plan_their_patch_draws() { - use crate::executor_contract::tessellation as shared; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let store = CorpusStore::new(&root); - let sources = public_sources().unwrap(); - let mut planned = 0; - let mut unrasterized = 0; - for shard in 0..64 { - for case in store.read_case_shard(shard).unwrap() { - let Some(draw) = case.tessellation.as_ref() else { - continue; - }; - let Some(row) = sources - .iter() - .find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry) - else { - continue; - }; - let scratch = crate::ScratchDir::new("public-tessellation-case").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - let checked = crate::check::check_case_against_source(&root, case.clone(), row) - .unwrap_or_else(|errors| panic!("{}: {errors:?}", case.name)); - let render = render_case( - &case, - &checked.primary.interface, - &row.air_ll, - checked.primary.companion.as_ref(), - ) - .unwrap_or_else(|error| panic!("{}: {error:?}", case.name)); - let factors = shared::factor_bytes(&draw.factors); - assert_eq!( - render.assembly, - Assembly::Patches { - tessellation: shared::descriptor(draw), - factors: factors.clone(), - }, - "{}", - case.name - ); - assert_eq!(render.cull_mode, shared::cull_mode(draw), "{}", case.name); - let companion = match render.companion.as_ref() { - Some(companion) => Some(companion.opaque_bitcode().unwrap()), - None => { - assert!( - case.is_rasterization_disabled_vertex(), - "{}: no observer", - case.name - ); - unrasterized += 1; - None - } - }; - let libraries = RenderLibraries { - vertex: &bitcode, - fragment: companion.as_deref(), - }; - for stem in ["lavapipe", "moltenvk-m3"] { - let (pipeline, plan, commands) = planned_draw(&device(stem), &render, libraries) - .unwrap_or_else(|error| panic!("{stem} {}: {error}", case.name)); - let control_points = shared::control_points(&checked.primary.interface).unwrap(); - assert_eq!( - pipeline.graphics.tessellation.map(|t| t.control_points), - Some(control_points), - "{stem} {}", - case.name - ); - let write = plan - .descriptors - .iter() - .find(|write| { - write.source == metal2vulkan::bind::WriteSource::TessellationFactors - }) - .unwrap_or_else(|| panic!("{stem} {}: no factor write", case.name)); - let range = commands - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == (write.set, write.binding)) - .unwrap_or_else(|| panic!("{stem} {}: no factor range", case.name)); - assert!( - range.range.range >= factors.len() as u64, - "{stem} {}", - case.name - ); - assert_eq!( - commands.draw, - vk::DrawCommand::Draw { - vertex_count: draw.factors.len() as u32, - instance_count: draw.instance_count, - first_vertex: 0, - first_instance: 0, - }, - "{stem} {}", - case.name - ); - planned += 1; - } - } - } - assert!(planned > 0, "no public tessellation case planned"); - assert!( - unrasterized > 0, - "no public patch draw with rasterization disabled" - ); -} - -/// Every installed public framebuffer-fetch case maps onto its fullscreen triangle drawn as its -/// instances, with each read render target attached, and plans on lavapipe (one input-attachment -/// write per color input, ordered between draws alone, noted). Every case carries -/// no requirement, at least one of them drawing more than one instance (overlapping fragments). -/// The lavapipe pipeline masks every write to a color attachment the function reads but has no -/// output for, which at least one case does. A case of a multisampled pass, which at least one -/// is, reads its colors as input attachments at each invocation's own sample (sample-rate -/// shading, the pipeline's sample count), at least one so; or it is refused, typed: the pixel's -/// coverage read beside it (`[[sample_mask]]` in, on no device), or a sample count the device's -/// attachments lack. -#[test] -fn public_framebuffer_fetch_cases_plan_their_ordered_input_attachments() { - use std::collections::BTreeSet; - - use crate::air::reflect::ResourceKind; - use metal2vulkan::bind::WriteSource; - use metal2vulkan::device::VkFeature; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let store = CorpusStore::new(&root); - let sources = public_sources().unwrap(); - let mut planned = 0; - let mut overlapping = 0; - let mut unwritten = 0; - let mut multisampled = 0; - let mut per_sample = 0; - for shard in 0..64 { - for case in store.read_case_shard(shard).unwrap() { - let Some(row) = sources - .iter() - .find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry) - else { - continue; - }; - if case.stage != Stage::Fragment { - continue; - } - let checked = crate::check::check_case_against_source(&root, case.clone(), row) - .unwrap_or_else(|errors| panic!("{}: {errors:?}", case.name)); - let colors: Vec = checked - .primary - .reflection - .bindings - .iter() - .filter(|binding| binding.kind == ResourceKind::ColorInput) - .map(|binding| binding.metal_index) - .collect(); - if colors.is_empty() { - continue; - } - let draw = case.draw.as_ref().expect("a fragment case's draw"); - assert!(checked.requirements().is_empty(), "{}", case.name); - overlapping += usize::from(draw.instance_count > 1); - let scratch = crate::ScratchDir::new("public-fetch-case").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - let render = render_case( - &case, - &checked.primary.interface, - &row.air_ll, - checked.primary.companion.as_ref(), - ) - .unwrap_or_else(|error| panic!("{}: {error:?}", case.name)); - for color in &colors { - assert!(render.color_targets.contains_key(color), "{}", case.name); - } - let companion = render - .companion - .as_ref() - .map(|companion| companion.opaque_bitcode().unwrap()) - .unwrap_or_else(|| panic!("{}: no passthrough vertex", case.name)); - let libraries = RenderLibraries { - vertex: &companion, - fragment: Some(&bitcode), - }; - // Each invocation reads its own sample. - if let Some(samples) = case.raster_sample_count { - let mut expected = colors.clone(); - expected.sort_unstable(); - match planned_draw(&device("lavapipe"), &render, libraries) { - Ok((pipeline, _, _)) => { - let g = &pipeline.graphics; - assert_eq!(g.rasterization_samples.as_raw(), samples, "{}", case.name); - let required = &pipeline.requirements; - assert!(required.features.contains(&VkFeature::SampleRateShading)); - let mut fetched: Vec = - g.input_attachments.iter().map(|a| a.color_index).collect(); - fetched.sort_unstable(); - assert_eq!(fetched, expected, "{}", case.name); - per_sample += 1; - } - Err(Error::Unsupported(refusal)) => { - use metal2vulkan::error::{Feature, Needs}; - match (&refusal.feature, &refusal.needs) { - (Feature::PixelCoverageAtSampleRate, Needs::NotRepresentable) - | (Feature::RasterSampleCount, Needs::AnyOf(_)) => {} - _ => panic!("lavapipe {}: {refusal:?}", case.name), - } - } - Err(other) => panic!("lavapipe {}: {other:?}", case.name), - } - multisampled += 1; - continue; - } - let (pipeline, plan, commands) = planned_draw(&device("lavapipe"), &render, libraries) - .unwrap_or_else(|error| panic!("lavapipe {}: {error}", case.name)); - assert!(unordered_within_draw(&pipeline), "{}", case.name); - // A color attachment the fragment function reads but has no output for keeps its - // contents, as Metal kept it in case f39cf462: the pipeline the executor builds from - // the artifact masks every write to it, and keeps the descriptor's mask on the others. - let written: BTreeSet = checked - .primary - .reflection - .render_targets - .iter() - .map(|target| target.location) - .collect(); - for (index, state) in pipeline.graphics.color_attachments.iter().enumerate() { - let Some(state) = state else { continue }; - let index = index as u32; - assert_eq!( - state.write_mask.is_empty(), - !written.contains(&index), - "{} attachment {index}", - case.name - ); - unwritten += usize::from(!written.contains(&index)); - } - let mut read: Vec = plan - .descriptors - .iter() - .filter_map(|write| match write.source { - WriteSource::Attachment { color_index } => Some(color_index), - _ => None, - }) - .collect(); - read.sort_unstable(); - let mut expected = colors.clone(); - expected.sort_unstable(); - assert_eq!(read, expected, "{}", case.name); - assert_eq!( - commands.draw, - vk::DrawCommand::Draw { - vertex_count: 3, - instance_count: draw.instance_count, - first_vertex: 0, - first_instance: 0, - }, - "{}", - case.name - ); - planned += 1; - } - } - assert!(planned > 0, "no public framebuffer-fetch case planned"); - assert!( - overlapping > 0, - "no public framebuffer-fetch case overlaps its fragments" - ); - assert!( - unwritten > 0, - "no public framebuffer-fetch case reads an attachment it does not write" - ); - assert!( - multisampled > 0, - "no public framebuffer-fetch case draws a multisampled pass" - ); - assert!( - per_sample > 0, - "no multisampled public framebuffer-fetch case plans" - ); -} - -/// On every committed profile, every installed public framebuffer-fetch case plans its color -/// inputs as input attachments, which the consumer orders between draws alone, and its fragment -/// stage notes `PrecisionNote::UnorderedFetchWithinDraw`; or, a multisampled pass, is refused as on -/// every device (the coverage read beside it, or a sample count the attachments lack), or for the -/// sample-rate shading each invocation's read of its own sample needs, where the device lacks it. -#[test] -fn public_framebuffer_fetch_cases_plan_input_attachments_without_an_ordered_form() { - use crate::air::reflect::ResourceKind; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let store = CorpusStore::new(&root); - let sources = public_sources().unwrap(); - for stem in crate::engine::committed_profiles().unwrap() { - let stem = stem.as_str(); - let dev = device(stem); - let mut fetches = 0; - for shard in 0..64 { - for case in store.read_case_shard(shard).unwrap() { - let Some(row) = sources - .iter() - .find(|row| row.air_sha256 == case.air_sha256 && row.entry == case.entry) - else { - continue; - }; - if case.stage != Stage::Fragment { - continue; - } - let checked = crate::check::check_case_against_source(&root, case.clone(), row) - .unwrap_or_else(|errors| panic!("{}: {errors:?}", case.name)); - let colors: Vec = checked - .primary - .reflection - .bindings - .iter() - .filter(|binding| binding.kind == ResourceKind::ColorInput) - .map(|binding| binding.metal_index) - .collect(); - if colors.is_empty() { - continue; - } - fetches += 1; - let scratch = crate::ScratchDir::new("public-fetch-unordered").unwrap(); - let ll = scratch.path().join("case.ll"); - std::fs::write(&ll, &row.air_ll).unwrap(); - let Some(bitcode) = assembled(&ll) else { - return; - }; - let render = render_case( - &case, - &checked.primary.interface, - &row.air_ll, - checked.primary.companion.as_ref(), - ) - .unwrap_or_else(|error| panic!("{}: {error:?}", case.name)); - let companion = render - .companion - .as_ref() - .map(|companion| companion.opaque_bitcode().unwrap()) - .unwrap_or_else(|| panic!("{}: no passthrough vertex", case.name)); - let libraries = RenderLibraries { - vertex: &companion, - fragment: Some(&bitcode), - }; - let pipeline = match planned_draw(&dev, &render, libraries) { - Ok((pipeline, _, _)) => pipeline, - // A multisampled pass's refusals of every device's form (the lavapipe - // test's), and its fetch on a device without sample-rate shading, which each - // invocation's read of its own sample needs. - Err(Error::Unsupported(refusal)) if case.raster_sample_count.is_some() => { - use metal2vulkan::device::VkFeature; - use metal2vulkan::error::{Capability, Feature, Needs}; - let shading = [vec![Capability::Feature(VkFeature::SampleRateShading)]]; - match (&refusal.feature, &refusal.needs) { - (Feature::PixelCoverageAtSampleRate, Needs::NotRepresentable) - | (Feature::RasterSampleCount, Needs::AnyOf(_)) => continue, - (Feature::FramebufferFetch, Needs::AnyOf(needs)) - if needs[..] == shading - && !crate::engine::load_description(stem) - .unwrap() - .has(VkFeature::SampleRateShading) => - { - continue - } - _ => panic!("{stem} {}: {refusal:?}", case.name), - } - } - Err(other) => panic!("{stem} {}: {other:?}", case.name), - }; - let mut read: Vec = (pipeline.graphics.input_attachments.iter()) - .map(|input| input.color_index) - .collect(); - read.sort_unstable(); - let mut colors = colors; - colors.sort_unstable(); - assert_eq!(read, colors, "{stem} {}", case.name); - assert!(unordered_within_draw(&pipeline), "{stem} {}", case.name); - } - } - assert!(fetches > 0, "{stem}: no public framebuffer-fetch case"); - } -} - /// A render case of one sample draws as before: its template names no sample count (so the pipeline /// keeps Metal's default of one, and the template crosses the compile worker's exchange in the /// bytes it always did). A multisampled case's template carries its count. diff --git a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs index 7469ded5c..b3f00e839 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs @@ -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 { - 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. diff --git a/crates/metal2vulkan-validation/src/candidate/engine/public_cases.rs b/crates/metal2vulkan-validation/src/candidate/engine/public_cases.rs deleted file mode 100644 index 0be753335..000000000 --- a/crates/metal2vulkan-validation/src/candidate/engine/public_cases.rs +++ /dev/null @@ -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]) -> bool { - // The usages the refusal names (linear filtering, say), and sampling itself. - let usages: BTreeSet = 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, 2> [[texture(0)]]`) reads `textures[1]`; -/// - `a4_texture_array_dynamic` (`array, 4> [[texture(0)]]`) reads -/// `ts[gid & 3]`, every element; -/// - `ob3_texture_array` (two `array, 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, 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::>(); - 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::>(); - assert_eq!( - compute.textures.keys().copied().collect::>(), - 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::>(); - let expected = read - .iter() - .map(|&element| slots[element as usize]) - .collect::>(); - 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::>(); - 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::>(); - 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 - ); - } - } - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/resources.rs b/crates/metal2vulkan-validation/src/candidate/engine/resources.rs index 52a35e6e5..f206efb2b 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/resources.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/resources.rs @@ -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 { - 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 { - 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 { - 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 { diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index a083bf631..b4bc76e15 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -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::>(), - [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::>(), - [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::>(), - [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()); diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs index 768c9b3ce..ca81008d2 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs @@ -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::>(); - 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::>(); - 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 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::>(); - elements.sort(); - assert_eq!( - elements, - (1..32) - .map(|e| (e, e - 1, false, false)) - .collect::>() - ); - 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::>(); - 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); - } } diff --git a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs index 595e4ae03..c9eeb1c0a 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs @@ -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 { - 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

( - bound_format: impl Fn(SlotRef) -> Option, - profile: &DeviceProfile, - mut compile: impl FnMut(&VariantKey) -> Result, - mut variant: impl FnMut(&P) -> Option, - ) -> 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, - ) -> 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, - ) -> impl FnMut(&VariantKey) -> Result + '_ { - 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 { - 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); - } - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs index 3d1e06136..630bd04d9 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs @@ -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, } diff --git a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs index d5c21ccc1..ea492162f 100644 --- a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs +++ b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs @@ -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;